diff --git a/README.md b/README.md index 1b135fc..d00fd1f 100644 --- a/README.md +++ b/README.md @@ -14,8 +14,20 @@ handling, no CSRF defense. Your host owns its login flow and its HTTP surface; this store remembers the result. > [!IMPORTANT] -> `@pegma/sessions` is published as `0.1.0`. It remains early `0.x`: the -> public API is not stable, and it is not ready for production use. +> `@pegma/sessions` remains early `0.x`: the public API is not stable, and +> it is not ready for production use. Published versions are listed on +> [npm](https://www.npmjs.com/package/@pegma/sessions). + +The `0.2.1` change observes the default clock after awaited reads and sweeps. +With a consistent advancing clock, a concurrent touch observed in that snapshot +is no longer mistaken for a future timestamp merely because the operation +started earlier. Explicit caller-supplied timestamps keep their semantics. + +Clock rollback and skew between hosts remain fail-closed: an idle anchor ahead +of the observing clock is dead under the single liveness predicate and may be +conditionally deleted. This change adds no clock-skew tolerance or coordination. +Source versions describe behavior; publication is recorded in +[GitHub releases](https://github.com/pegma-dev/sessions/releases). Current status: the record-store package is published on npm, the first consumer migration is merged in diff --git a/RELEASE_NOTES.md b/RELEASE_NOTES.md index 6a6991f..e9a1a2f 100644 --- a/RELEASE_NOTES.md +++ b/RELEASE_NOTES.md @@ -1,3 +1,22 @@ +# @pegma/sessions v0.2.1 + +Fix default clock observation around awaited session reads and expiry sweeps. +Default read time is observed after hashing and the initial storage read; +default sweep time is observed after the versioned list snapshot. With a +consistent advancing clock, a concurrent touch in that snapshot is no longer +misclassified as a future idle anchor merely because the operation began +before the touch. Sessions that expire during these awaits are rejected or +purged using the later observation. + +Explicit caller-supplied instants retain their existing semantics. Clock +rollback or skew between hosts can still produce a future idle anchor, which +fails closed and may be conditionally deleted. There is no skew tolerance or +clock-coordination API. The single liveness predicate, malformed timestamp +refusal, conditional hygiene deletion, unconditional revocation and best-effort +non-resurrecting touch remain in place. No storage call, schema, runtime +dependency or public method is added. Memory and Azurite regressions cover the +concurrent touches, awaited expiry, clock observation and explicit-time behavior. + # @pegma/sessions v0.2.0 A dependency-alignment release: `@pegma/storage-core` advances from `0.3.0` to diff --git a/docs/PROJECT_PLAN.md b/docs/PROJECT_PLAN.md index 9321e77..878173e 100644 --- a/docs/PROJECT_PLAN.md +++ b/docs/PROJECT_PLAN.md @@ -2,10 +2,13 @@ ## Status -**Stage:** Phases 1–4 are complete. `@pegma/sessions@0.1.1` is published; -RetireGolden is the first integrated consumer and pegma.dev is the second, -live consumer. `0.2.0` is prepared, aligning `@pegma/storage-core` at `0.4.0` -across the stack. The public API remains unstable. +**Stage:** Phases 1–4 are complete. The published `0.2.0` release aligned +`@pegma/storage-core` at `0.4.0`. RetireGolden is the first integrated consumer +and pegma.dev is the second, live consumer. The `0.2.1` patch moves default +clock observations after awaited reads and sweep snapshots. Publication is +recorded in [GitHub releases](https://github.com/pegma-dev/sessions/releases) +and [npm](https://www.npmjs.com/package/@pegma/sessions); source metadata alone +does not publish a version. The public API remains unstable. Phase 1 is merged on `main` ([PR #1](https://github.com/pegma-dev/sessions/pull/1), `f5ea435`, diff --git a/docs/RELEASING.md b/docs/RELEASING.md index 64136a6..6bc212e 100644 --- a/docs/RELEASING.md +++ b/docs/RELEASING.md @@ -10,7 +10,7 @@ There is no npm-token or manual-dispatch fallback. ## Historical `v0.1.0` exception -`@pegma/sessions@0.1.0` is published and is the current `latest` version. It +`@pegma/sessions@0.1.0` was the first published version. It is immutable, but it predates the hardened release path: - the GitHub release used a lightweight tag at @@ -110,7 +110,10 @@ After the first OIDC release succeeds, set npm Publishing access to Prepare every version from `0.1.1` onward through an ordinary pull request that updates the root, workspace, and lockfile versions together and adds -reviewed release notes. Run the complete gate and a local release pack on +reviewed release notes. Keep README and project-plan status factual, using +release checkpoints and registry links for publication status. Release notes +describe version behavior without a candidate/publication label that would +become stale after release. Run the complete gate and a local release pack on Node 22 and 24. Node 25 and later do not bundle Corepack, so install it first if `corepack` is missing: @@ -127,7 +130,8 @@ pnpm run release:pack -- -- --output .release ``` After merge, create and verify the tag before creating the GitHub release. -For example, for the next patch release: +For example, for the next patch release. The final command sends only the +current version's section to GitHub; older sections stay in the changelog: ```sh git fetch origin @@ -135,12 +139,13 @@ git switch --detach origin/main git config gpg.format ssh git config user.signingkey ~/.ssh/pegma-release-signing-key git config gpg.ssh.allowedSignersFile ~/.config/pegma/release-allowed-signers -git tag --sign v0.2.0 --message "Sessions v0.2.0" HEAD -git verify-tag v0.2.0 -git push origin refs/tags/v0.2.0 -git fetch origin tag v0.2.0 --force -git verify-tag v0.2.0 -gh release create v0.2.0 --verify-tag --title "@pegma/sessions v0.2.0" --notes-file RELEASE_NOTES.md +git tag --sign v0.2.1 --message "Sessions v0.2.1" HEAD +git verify-tag v0.2.1 +git push origin refs/tags/v0.2.1 +git fetch origin tag v0.2.1 --force +git verify-tag v0.2.1 +node --input-type=module -e 'import { readFileSync } from "node:fs"; process.stdout.write(readFileSync("RELEASE_NOTES.md", "utf8").split("\n# @pegma/sessions ")[0]);' | + gh release create v0.2.1 --verify-tag --title "@pegma/sessions v0.2.1" --notes-file - ``` Do not let `gh release create` create a tag. Never move or recreate a release diff --git a/package.json b/package.json index b3ea6e4..54ad74b 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "sessions", - "version": "0.2.0", + "version": "0.2.1", "private": true, "description": "Server-side session records for Pegma components.", "license": "MIT", diff --git a/packages/sessions/package.json b/packages/sessions/package.json index 79be7f3..407064f 100644 --- a/packages/sessions/package.json +++ b/packages/sessions/package.json @@ -1,6 +1,6 @@ { "name": "@pegma/sessions", - "version": "0.2.0", + "version": "0.2.1", "description": "Hashed server-side session records with absolute and idle expiry.", "license": "MIT", "type": "module", diff --git a/packages/sessions/src/index.test.ts b/packages/sessions/src/index.test.ts index 0d2c6b4..6cedcdf 100644 --- a/packages/sessions/src/index.test.ts +++ b/packages/sessions/src/index.test.ts @@ -129,6 +129,50 @@ function wrapSessionCollection( }; } +function pauseSessionRead(base: Store) { + let next: "getVersioned" | "listVersioned" | undefined; + let reached!: () => void; + let release!: () => void; + const entered = new Promise((resolve) => { + reached = resolve; + }); + const resume = new Promise((resolve) => { + release = resolve; + }); + async function before(method: "getVersioned" | "listVersioned") { + if (next !== method) return; + next = undefined; + reached(); + await resume; + } + const store = wrapSessionCollection(base, (collection) => { + const getVersioned: typeof collection.getVersioned = async (...args) => { + await before("getVersioned"); + return collection.getVersioned(...args); + }; + const listVersioned: typeof collection.listVersioned = async (...args) => { + await before("listVersioned"); + return collection.listVersioned(...args); + }; + return new Proxy(collection, { + get(target, property) { + if (property === "getVersioned") return getVersioned; + if (property === "listVersioned") return listVersioned; + const value = Reflect.get(target, property, target); + return typeof value === "function" ? value.bind(target) : value; + }, + }); + }); + return { + store, + entered, + release, + arm(method: typeof next) { + next = method; + }, + }; +} + function recordingLogger() { const entries: { readonly level: string; @@ -230,6 +274,167 @@ for (const backend of backends) { ).toThrow(/positive finite/); }); + it("observes the default clock after an overlapping read has touched the live session", async () => { + const inspected = inspectStorage(backend.freshStore()); + const paused = pauseSessionRead(inspected.store); + let milliseconds = Date.parse(NOW); + const clock = { now: () => new Date(milliseconds).toISOString() }; + const sessions = createSessionStore(paused.store, { clock }); + await sessions.create("overlapping-default-read", NEW_SESSION); + + paused.arm("getVersioned"); + const earlier = sessions.get("overlapping-default-read"); + await paused.entered; + milliseconds += 1; + try { + // This actual SDK read, not a forged storage row, advances lastSeenAt. + expect(await sessions.get("overlapping-default-read")).not.toBeNull(); + } finally { + paused.release(); + } + + expect((await earlier)?.lastSeenAt).toBe(clock.now()); + expect(await sessions.get("overlapping-default-read")).not.toBeNull(); + expect( + storedSessions(await inspected.records().list("session")), + ).toHaveLength(1); + }); + + it("observes the default sweep clock after an overlapping read has touched the live session", async () => { + const inspected = inspectStorage(backend.freshStore()); + const paused = pauseSessionRead(inspected.store); + let milliseconds = Date.parse(NOW); + const clock = { now: () => new Date(milliseconds).toISOString() }; + const sessions = createSessionStore(paused.store, { clock }); + await sessions.create("overlapping-default-sweep", NEW_SESSION); + + paused.arm("listVersioned"); + const sweeping = sessions.purgeExpired(); + await paused.entered; + milliseconds += 1; + try { + expect(await sessions.get("overlapping-default-sweep")).not.toBeNull(); + } finally { + paused.release(); + } + + expect(await sweeping).toBe(0); + expect(await sessions.get("overlapping-default-sweep")).not.toBeNull(); + expect( + storedSessions(await inspected.records().list("session")), + ).toHaveLength(1); + }); + + it("observes expiry at the default clock after the awaited session read", async () => { + const inspected = inspectStorage(backend.freshStore()); + const paused = pauseSessionRead(inspected.store); + let milliseconds = Date.parse(NOW); + const clock = { now: () => new Date(milliseconds).toISOString() }; + const sessions = createSessionStore(paused.store, { + clock, + absoluteLifetimeMs: 1_000, + }); + await sessions.create("delayed-default-expiry", NEW_SESSION); + + paused.arm("getVersioned"); + const reading = sessions.get("delayed-default-expiry"); + await paused.entered; + try { + milliseconds += 1_000; + } finally { + paused.release(); + } + + expect(await reading).toBeNull(); + expect( + storedSessions(await inspected.records().list("session")), + ).toHaveLength(0); + }); + + it("observes expiry at the default clock after the awaited sweep list", async () => { + const inspected = inspectStorage(backend.freshStore()); + const paused = pauseSessionRead(inspected.store); + let milliseconds = Date.parse(NOW); + const clock = { now: () => new Date(milliseconds).toISOString() }; + const sessions = createSessionStore(paused.store, { + clock, + absoluteLifetimeMs: 1_000, + }); + await sessions.create("delayed-sweep-expiry", NEW_SESSION); + + paused.arm("listVersioned"); + const sweeping = sessions.purgeExpired(); + await paused.entered; + try { + milliseconds += 1_000; + } finally { + paused.release(); + } + + expect(await sweeping).toBe(1); + expect( + storedSessions(await inspected.records().list("session")), + ).toHaveLength(0); + }); + + it("observes one default clock after a missing read and an empty sweep", async () => { + const paused = pauseSessionRead(backend.freshStore()); + let observations = 0; + const sessions = createSessionStore(paused.store, { + clock: { + now() { + ++observations; + return NOW; + }, + }, + }); + paused.arm("getVersioned"); + const missing = sessions.get("unknown-session"); + await paused.entered; + try { + expect(observations).toBe(0); + } finally { + paused.release(); + } + + expect(await missing).toBeNull(); + expect(observations).toBe(1); + expect(await sessions.purgeExpired()).toBe(0); + expect(observations).toBe(2); + expect(await sessions.get("unknown-session", NOW)).toBeNull(); + expect(await sessions.purgeExpired(NOW)).toBe(0); + expect(observations).toBe(2); + }); + + it("preserves explicit read and sweep instants after awaited storage", async () => { + const inspected = inspectStorage(backend.freshStore()); + const paused = pauseSessionRead(inspected.store); + let milliseconds = Date.parse(NOW); + const clock = { now: () => new Date(milliseconds).toISOString() }; + const sessions = createSessionStore(paused.store, { + clock, + absoluteLifetimeMs: 1_000, + }); + await sessions.create("explicit-read-instant", NEW_SESSION); + const explicitNow = "2026-07-27T12:00:00.500Z"; + + paused.arm("getVersioned"); + const reading = sessions.get("explicit-read-instant", explicitNow); + await paused.entered; + try { + milliseconds += 1_000; + } finally { + paused.release(); + } + + expect(await reading).not.toBeNull(); + expect(await sessions.purgeExpired(explicitNow)).toBe(0); + expect( + storedSessions(await inspected.records().list("session")), + ).toHaveLength(1); + expect(await sessions.get("explicit-read-instant")).toBeNull(); + }); + it("returns the initially validated record without claiming its touch", async () => { const sessions = createSessionStore(backend.freshStore(), { clock: fixedClock(NOW), @@ -336,6 +541,20 @@ for (const backend of backends) { await sessions.create("invalid-purge-now", NEW_SESSION); expect(await sessions.purgeExpired("still-not-a-time")).toBe(1); + + // JavaScript callers can supply malformed values despite the TS type. + // Only undefined selects the default clock; null must still fail closed. + await sessions.create("invalid-null-read", NEW_SESSION); + expect( + await Reflect.apply(sessions.get, sessions, [ + "invalid-null-read", + null, + ]), + ).toBeNull(); + await sessions.create("invalid-null-purge", NEW_SESSION); + expect(await Reflect.apply(sessions.purgeExpired, sessions, [null])).toBe( + 1, + ); }); it("fails closed on a future idle anchor", async () => { diff --git a/packages/sessions/src/index.ts b/packages/sessions/src/index.ts index 1833368..ea6535f 100644 --- a/packages/sessions/src/index.ts +++ b/packages/sessions/src/index.ts @@ -60,7 +60,8 @@ export interface SessionStore { * Returns the initially validated record when live, otherwise null. * * The idle touch is best-effort. The returned record deliberately does not - * claim that touch succeeded. + * claim that touch succeeded. An omitted `now` is observed after the initial + * storage read; an explicit instant is used unchanged. */ get(sessionId: string, now?: IsoTimestamp): Promise; @@ -70,7 +71,7 @@ export interface SessionStore { /** Revokes every session owned by `principalId`. */ destroyAllForPrincipal(principalId: PrincipalId): Promise; - /** Conditionally removes records that are dead at `now`. */ + /** Conditionally removes records dead at `now`, defaulting to after the list. */ purgeExpired(now?: IsoTimestamp): Promise; } @@ -537,15 +538,18 @@ export function createSessionStore( throwRevocationTransactionLimit(); }, - async get(sessionId, now = clock.now()) { + async get(sessionId, now) { const key = sessionKey(await hashSessionId(sessionId)); const versioned = await sessions.getVersioned(key); + // A concurrent read can touch lastSeenAt during hashing or storage I/O. + // Observe the default clock after that snapshot, keeping explicit times. + const observedNow = now === undefined ? clock.now() : now; if (versioned === null || !isSessionRecord(versioned.value)) { return null; } const initiallyRead = versioned.value; - if (!isLive(initiallyRead, now, idleTimeoutMs)) { + if (!isLive(initiallyRead, observedNow, idleTimeoutMs)) { await sessions .deleteIfUnchanged(key, versioned.version) .catch(() => undefined); @@ -557,12 +561,12 @@ export function createSessionStore( if ( current === null || !isSessionRecord(current) || - !isLive(current, now, idleTimeoutMs) + !isLive(current, observedNow, idleTimeoutMs) ) { return { action: "keep" }; } const currentLastSeen = timestamp(current.lastSeenAt); - const at = timestamp(now); + const at = timestamp(observedNow); if (at <= currentLastSeen) { return { action: "keep" }; } @@ -704,13 +708,16 @@ export function createSessionStore( return destroyed; }, - async purgeExpired(now = clock.now()) { + async purgeExpired(now) { let purged = 0; - for (const versioned of await sessions.listVersioned(SESSION_PARTITION)) { + const snapshot = await sessions.listVersioned(SESSION_PARTITION); + // The list can include a touch newer than the sweep invocation itself. + const observedNow = now === undefined ? clock.now() : now; + for (const versioned of snapshot) { if (!isSessionRecord(versioned.value)) { continue; } - if (isLive(versioned.value, now, idleTimeoutMs)) { + if (isLive(versioned.value, observedNow, idleTimeoutMs)) { continue; } if (