From 6829ea2589d12392c42eb8beb91f9485d7767ab7 Mon Sep 17 00:00:00 2001 From: Nathan Rover Date: Thu, 12 Nov 2026 22:09:31 -0500 Subject: [PATCH 1/2] Add read-only live session observations for closing checks --- README.md | 11 +- RELEASE_NOTES.md | 23 ++ docs/PROJECT_PLAN.md | 18 +- docs/RELEASING.md | 14 +- package.json | 2 +- packages/sessions/README.md | 39 +++ packages/sessions/package.json | 2 +- packages/sessions/src/index.test.ts | 383 +++++++++++++++++++++++++++- packages/sessions/src/index.ts | 28 +- 9 files changed, 496 insertions(+), 24 deletions(-) diff --git a/README.md b/README.md index d00fd1f..a6d6619 100644 --- a/README.md +++ b/README.md @@ -29,6 +29,13 @@ 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). +The `0.3.0` API adds `observe(sessionId, now?)`: a fresh liveness-checked read +without an idle touch or cleanup write. Hosts can keep `get` for initial +admission and use `observe` for closing checks that must not count as activity. +Both use the same expiry predicate and clock semantics. Each result is a +snapshot; later revocation or expiry is still possible. See the +[package README](packages/sessions/README.md) for usage. + Current status: the record-store package is published on npm, the first consumer migration is merged in [RetireGolden/retiregolden.org#54](https://github.com/RetireGolden/retiregolden.org/pull/54). @@ -60,8 +67,8 @@ What it does own, it owns opinionatedly: The hygiene sweep is the opposite — version-conditional, so a session that came back to life mid-sweep survives. Keeping those two rules opposite is the design. -- **Reads that garbage-collect and never resurrect** — a dead row found on - read is lazily purged; the idle-anchor touch declines to write back a +- **Activity reads that garbage-collect and never resurrect** — a dead row found + by `get` is lazily purged; the idle-anchor touch declines to write back a session a concurrent destroy just removed, and a failed touch never fails the request. diff --git a/RELEASE_NOTES.md b/RELEASE_NOTES.md index e9a1a2f..4b18a7c 100644 --- a/RELEASE_NOTES.md +++ b/RELEASE_NOTES.md @@ -1,3 +1,26 @@ +# @pegma/sessions v0.3.0 + +Add `SessionStore.observe(sessionId, now?)` for fresh liveness and identity +checks that must not extend activity. It hashes the raw session id and performs +one keyed backend read, then applies the existing liveness predicate. It returns +the public record when live and null when missing, revoked, expired, idle, or +malformed. It never touches the idle anchor or lazily deletes a dead row; backend +read failures propagate. + +The default clock is observed after the awaited read, matching `get`; explicit +instants retain their existing semantics. Use `get` for activity such as initial +request admission and `observe` for later closing checks. Each observation reads +the backend afresh, but its result is a snapshot, not a lock against subsequent +revocation or expiry. Hosts still own current identity and permission checks. + +The `0.3.0` minor version reflects the public `SessionStore` interface expansion +under `0.x`. Existing `get`, revocation, expiry cleanup, storage schema, and +runtime dependency pins retain their behavior. Memory and real Azure Tables +tests cover read-only operation, exact expiry, clock observation, fresh +revocation, concurrent touches, and snapshot limits. An initialized Azure Tables +adapter sends one physical GET per observation, including dead and missing +records. + # @pegma/sessions v0.2.1 Fix default clock observation around awaited session reads and expiry sweeps. diff --git a/docs/PROJECT_PLAN.md b/docs/PROJECT_PLAN.md index 878173e..46e4d0f 100644 --- a/docs/PROJECT_PLAN.md +++ b/docs/PROJECT_PLAN.md @@ -117,6 +117,10 @@ same function, so the two can never disagree. idle anchor through a decider that declines to resurrect a session a concurrent destroy just removed; a failed touch never fails the request. - `destroy(sessionId)` — delete; already-gone is success, not an error. +- `observe(sessionId, now?)` — one fresh keyed read with the same liveness and + clock semantics as `get`, without an idle touch or lazy delete. Use it for + closing checks after the activity-bearing admission read. Backend failures + propagate; the result is a snapshot, not a lock against later revocation. - `destroyAllForPrincipal(principalId)` — sign out everywhere. Lists the partition and filters on the record's principal; deletes are deliberately **unconditional**, because a session touched concurrently must still die. @@ -199,8 +203,8 @@ counts, revocation counts) report through the spine `Logger` port. ### In scope -- The session record store: create, liveness-checked reads with idle - touch, destroy, principal-wide revocation, expiry sweep. +- The session record store: create, liveness-checked activity reads with idle + touch, read-only observation, destroy, principal-wide revocation, expiry sweep. - Mandatory id hashing, dual expiry, the single liveness predicate. - The host data field with a host-supplied codec fragment. - Conformance-style tests over `createMemoryStore()` and against the Azure @@ -313,11 +317,11 @@ principal exists. `PrincipalId` would become nullable and needs it yet, and nullable-principal is a one-way door better opened by a real requirement. -**Touch write amplification.** Every live `get` writes the idle anchor. The -reference application accepts this (its traffic is modest); a busier host -might want a touch floor ("don't re-touch within N minutes"), trading idle -precision for writes. Cheap to add behind a config default of 0; decide when -a consumer measures it. +**Touch write amplification.** Every live `get` still writes the idle anchor. +The `0.3.0` `observe` API addresses a measured pegma.dev Support Desk need: +closing checks require fresh session authority but should not renew activity. +Initial admission retains `get`, and later checks can use `observe` without +changing idle precision. This is not a touch floor or an authority cache. ## Near-term backlog diff --git a/docs/RELEASING.md b/docs/RELEASING.md index 6bc212e..85916e9 100644 --- a/docs/RELEASING.md +++ b/docs/RELEASING.md @@ -130,7 +130,7 @@ 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. The final command sends only the +For example, for the next release. The final command sends only the current version's section to GitHub; older sections stay in the changelog: ```sh @@ -139,13 +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.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 +git tag --sign v0.3.0 --message "Sessions v0.3.0" HEAD +git verify-tag v0.3.0 +git push origin refs/tags/v0.3.0 +git fetch origin tag v0.3.0 --force +git verify-tag v0.3.0 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 - + gh release create v0.3.0 --verify-tag --title "@pegma/sessions v0.3.0" --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 54ad74b..42315b0 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "sessions", - "version": "0.2.1", + "version": "0.3.0", "private": true, "description": "Server-side session records for Pegma components.", "license": "MIT", diff --git a/packages/sessions/README.md b/packages/sessions/README.md index cde8d74..f51d212 100644 --- a/packages/sessions/README.md +++ b/packages/sessions/README.md @@ -33,6 +33,45 @@ thousands, not millions, of live sessions. Session data must never contain IdP access tokens, refresh tokens, or any other credential re-presentable to another service. +## Activity reads and read-only checks + +Use `get(rawSessionId)` when the request should count as activity. It reads a +live session and touches its idle anchor best-effort; a dead row is lazily +deleted best-effort. The returned record describes the initial validated +snapshot and does not claim that the touch succeeded. + +Use `observe(rawSessionId)` when a later check needs current session identity +and liveness without extending activity: + +```ts +const admitted = await sessions.get(rawSessionId); +if (admitted === null) return refuseRequest(); + +// Before a later protected step, read current session state again. +const current = await sessions.observe(rawSessionId); +if (current === null) return refuseRequest(); +// The host must also revalidate current identity and permissions. +``` + +`observe` hashes the id and performs one fresh keyed backend read per call. It +returns a `SessionRecord` when live or null when missing, revoked, expired, +idle, or malformed, using the same liveness predicate as `get` and the sweep. +It does not touch the idle anchor, delete dead rows, or cache earlier results. +Backend read failures reject so the host can fail closed. Keep `get` for the +activity that should renew idle expiry; repeated observations alone will not +keep a session alive. + +Both methods observe the default clock after the awaited storage read. An +explicit `now` is used unchanged; hosts seeking current liveness should omit +it. Absolute and idle boundaries are exclusive: a session is dead at either +boundary. Invalid timestamps and idle anchors ahead of the observing clock +fail closed, including clock rollback or host skew. + +A returned record is a snapshot, not a lock or a cross-store transaction. +Revocation after that backend snapshot can overlap a successful result, and +the session may expire before later work completes. Hosts retain their +closing checks and any required identity, permission, and commit-time fences. + ## Development Node.js 22 or 24 is required for local development (the same versions CI diff --git a/packages/sessions/package.json b/packages/sessions/package.json index 407064f..518eac4 100644 --- a/packages/sessions/package.json +++ b/packages/sessions/package.json @@ -1,6 +1,6 @@ { "name": "@pegma/sessions", - "version": "0.2.1", + "version": "0.3.0", "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 6cedcdf..ea054f8 100644 --- a/packages/sessions/src/index.test.ts +++ b/packages/sessions/src/index.test.ts @@ -28,11 +28,23 @@ const CONNECTION_STRING = [ let tableCounter = 0; -function freshAzureStore(): Store { +function freshAzureStore(requests?: string[]): Store { tableCounter += 1; const table = `sessions${tableCounter}t${process.pid}`; const client = TableClient.fromConnectionString(CONNECTION_STRING, table, { allowInsecureConnection: true, + additionalPolicies: [ + { + position: "perRetry", + policy: { + name: "record-session-test-requests", + sendRequest(request, next) { + requests?.push(`${request.method} ${request.url}`); + return next(request); + }, + }, + }, + ], }); return createAzureTablesStore({ client }); } @@ -129,7 +141,7 @@ function wrapSessionCollection( }; } -function pauseSessionRead(base: Store) { +function pauseSessionRead(base: Store, phase: "before" | "after" = "before") { let next: "getVersioned" | "listVersioned" | undefined; let reached!: () => void; let release!: () => void; @@ -147,8 +159,10 @@ function pauseSessionRead(base: Store) { } const store = wrapSessionCollection(base, (collection) => { const getVersioned: typeof collection.getVersioned = async (...args) => { - await before("getVersioned"); - return collection.getVersioned(...args); + if (phase === "before") await before("getVersioned"); + const result = await collection.getVersioned(...args); + if (phase === "after") await before("getVersioned"); + return result; }; const listVersioned: typeof collection.listVersioned = async (...args) => { await before("listVersioned"); @@ -449,6 +463,344 @@ for (const backend of backends) { expect(second?.lastSeenAt).toBe(touchedAt); }); + describe("read-only observation", () => { + it("uses one fresh hashed-key read without any mutation for live, dead, or missing sessions", async () => { + const inspected = inspectStorage(backend.freshStore()); + let readOnly = false; + const calls: unknown[] = []; + const wrapped = wrapSessionCollection( + inspected.store, + (collection) => + new Proxy(collection, { + get(target, property) { + const value: unknown = Reflect.get(target, property, target); + if (typeof value !== "function") return value; + if (!readOnly) return value.bind(target); + if (property !== "getVersioned") { + throw new Error( + `Unexpected observation operation: ${String(property)}`, + ); + } + return (...args: unknown[]) => { + calls.push(args); + return Reflect.apply(value, target, args); + }; + }, + }), + ); + const { logger, entries } = recordingLogger(); + const sessions = createSessionStore(wrapped, { + clock: fixedClock(NOW), + logger, + idleTimeoutMs: 1_000, + }); + const rawId = "observe-raw-session-secret"; + const created = await sessions.create(rawId, NEW_SESSION); + const key = { + partition: "session", + id: `session:${await sha256(rawId)}`, + }; + const before = await inspected.records().getVersioned(key); + + readOnly = true; + expect(await sessions.observe(rawId, NOW)).toEqual(created); + expect( + await sessions.observe(rawId, "2026-07-27T12:00:01.000Z"), + ).toBeNull(); + expect(await sessions.observe("observe-missing", NOW)).toBeNull(); + await expect(sessions.observe("")).rejects.toThrow( + "Session id must be a non-empty string.", + ); + readOnly = false; + + expect(calls).toEqual([ + [key], + [key], + [ + { + partition: "session", + id: `session:${await sha256("observe-missing")}`, + }, + ], + ]); + expect(await inspected.records().getVersioned(key)).toEqual(before); + expect(JSON.stringify(calls)).not.toContain(rawId); + expect(entries).toEqual([]); + }); + + it("does not prolong idle expiry while get still advances the anchor", async () => { + const sessions = createSessionStore(backend.freshStore(), { + clock: fixedClock(NOW), + idleTimeoutMs: 500, + absoluteLifetimeMs: 2_000, + }); + await sessions.create("observe-idle", NEW_SESSION); + await sessions.create("get-idle", NEW_SESSION); + const later = "2026-07-27T12:00:00.499Z"; + + expect( + (await sessions.observe("observe-idle", later))?.lastSeenAt, + ).toBe(NOW); + expect(await sessions.get("get-idle", later)).not.toBeNull(); + expect( + await sessions.observe("observe-idle", "2026-07-27T12:00:00.500Z"), + ).toBeNull(); + expect( + (await sessions.observe("get-idle", "2026-07-27T12:00:00.998Z")) + ?.lastSeenAt, + ).toBe(later); + expect( + await sessions.observe("get-idle", "2026-07-27T12:00:00.999Z"), + ).toBeNull(); + }); + + it("rejects the absolute boundary even after activity advances idle expiry", async () => { + const sessions = createSessionStore(backend.freshStore(), { + clock: fixedClock(NOW), + absoluteLifetimeMs: 1_000, + idleTimeoutMs: 2_000, + }); + await sessions.create("observe-absolute", NEW_SESSION); + await sessions.get("observe-absolute", "2026-07-27T12:00:00.999Z"); + expect( + await sessions.observe( + "observe-absolute", + "2026-07-27T12:00:00.999Z", + ), + ).not.toBeNull(); + expect( + await sessions.observe( + "observe-absolute", + "2026-07-27T12:00:01.000Z", + ), + ).toBeNull(); + }); + + it("observes the default clock after a concurrent get touches the session", async () => { + const paused = pauseSessionRead(backend.freshStore()); + let milliseconds = Date.parse(NOW); + const clock = { now: () => new Date(milliseconds).toISOString() }; + const sessions = createSessionStore(paused.store, { clock }); + await sessions.create("observe-touch-race", NEW_SESSION); + paused.arm("getVersioned"); + const observing = sessions.observe("observe-touch-race"); + await paused.entered; + try { + milliseconds += 1; + expect(await sessions.get("observe-touch-race")).not.toBeNull(); + } finally { + paused.release(); + } + expect((await observing)?.lastSeenAt).toBe(clock.now()); + }); + + it.each(["absolute", "idle"] as const)( + "checks %s expiry after the awaited snapshot without deleting it", + async (boundary) => { + const inspected = inspectStorage(backend.freshStore()); + const paused = pauseSessionRead(inspected.store, "after"); + let milliseconds = Date.parse(NOW); + const sessions = createSessionStore(paused.store, { + clock: { now: () => new Date(milliseconds).toISOString() }, + absoluteLifetimeMs: boundary === "absolute" ? 1_000 : 2_000, + idleTimeoutMs: boundary === "idle" ? 1_000 : 2_000, + }); + await sessions.create("observe-awaited-expiry", NEW_SESSION); + paused.arm("getVersioned"); + const observing = sessions.observe("observe-awaited-expiry"); + await paused.entered; + try { + milliseconds += 1_000; + } finally { + paused.release(); + } + expect(await observing).toBeNull(); + expect( + storedSessions(await inspected.records().list("session")), + ).toHaveLength(1); + }, + ); + + it("preserves explicit instants and never consults the clock for them", async () => { + const paused = pauseSessionRead(backend.freshStore(), "after"); + let observations = 0; + let milliseconds = Date.parse(NOW); + const sessions = createSessionStore(paused.store, { + clock: { + now() { + observations += 1; + return new Date(milliseconds).toISOString(); + }, + }, + absoluteLifetimeMs: 1_000, + }); + await sessions.create("observe-explicit", NEW_SESSION); + observations = 0; + paused.arm("getVersioned"); + const observing = sessions.observe( + "observe-explicit", + "2026-07-27T12:00:00.999Z", + ); + await paused.entered; + try { + milliseconds += 1_000; + expect(observations).toBe(0); + } finally { + paused.release(); + } + expect(await observing).not.toBeNull(); + expect( + await sessions.observe( + "observe-explicit", + "2026-07-27T12:00:01.000Z", + ), + ).toBeNull(); + expect(observations).toBe(0); + }); + + it("consults the default clock once after a missing read", async () => { + const paused = pauseSessionRead(backend.freshStore()); + let observations = 0; + const sessions = createSessionStore(paused.store, { + clock: { + now() { + observations += 1; + return NOW; + }, + }, + }); + paused.arm("getVersioned"); + const observing = sessions.observe("observe-unknown"); + await paused.entered; + try { + expect(observations).toBe(0); + } finally { + paused.release(); + } + expect(await observing).toBeNull(); + expect(observations).toBe(1); + expect(await sessions.observe("observe-unknown", NOW)).toBeNull(); + expect(observations).toBe(1); + }); + + it.each([ + ["createdAt", "not-a-time"], + ["expiresAt", "Infinity"], + ["lastSeenAt", "NaN"], + ["expiresAt", "2026-07-32T12:00:00.000Z"], + ["createdAt", "2026-07-27T12:00:00.001Z"], + ["lastSeenAt", "2026-07-27T12:00:00.001Z"], + ] as const)( + "fails closed without deleting malformed %s %s", + async (field, value) => { + const inspected = inspectStorage(backend.freshStore()); + const sessions = createSessionStore(inspected.store, { + clock: fixedClock(NOW), + }); + await sessions.create("observe-malformed", NEW_SESSION); + const records = inspected.records(); + const [record] = storedSessions(await records.list("session")); + await records.put({ + ...(record as StoredSessionFixture), + [field]: value, + }); + expect(await sessions.observe("observe-malformed", NOW)).toBeNull(); + expect(storedSessions(await records.list("session"))).toHaveLength(1); + }, + ); + + it("fails closed for invalid explicit times and an invalid default clock", async () => { + const base = backend.freshStore(); + const sessions = createSessionStore(base, { clock: fixedClock(NOW) }); + await sessions.create("observe-invalid-now", NEW_SESSION); + for (const now of [null, "not-a-time", "2026-07-27T11:59:59.999Z"]) { + expect( + await Reflect.apply(sessions.observe, sessions, [ + "observe-invalid-now", + now, + ]), + ).toBeNull(); + } + const badClock = createSessionStore(base, { + clock: { now: () => "NaN" }, + }); + expect(await badClock.observe("observe-invalid-now")).toBeNull(); + expect( + await sessions.observe("observe-invalid-now", NOW), + ).not.toBeNull(); + }); + + it.each(["individual", "principal"] as const)( + "freshly refuses %s revocation during an awaited read", + async (mode) => { + const paused = pauseSessionRead(backend.freshStore()); + const sessions = createSessionStore(paused.store, { + clock: fixedClock(NOW), + }); + await sessions.create("observe-revoke-race", NEW_SESSION); + expect(await sessions.observe("observe-revoke-race")).not.toBeNull(); + paused.arm("getVersioned"); + const observing = sessions.observe("observe-revoke-race"); + await paused.entered; + try { + if (mode === "individual") + await sessions.destroy("observe-revoke-race"); + else + expect(await sessions.destroyAllForPrincipal(PRINCIPAL)).toBe(1); + } finally { + paused.release(); + } + expect(await observing).toBeNull(); + expect(await sessions.observe("observe-revoke-race")).toBeNull(); + }, + ); + + it("does not claim to lock a snapshot against later revocation or resurrect it", async () => { + const paused = pauseSessionRead(backend.freshStore(), "after"); + const sessions = createSessionStore(paused.store, { + clock: fixedClock(NOW), + }); + const created = await sessions.create( + "observe-snapshot-race", + NEW_SESSION, + ); + paused.arm("getVersioned"); + const observing = sessions.observe("observe-snapshot-race"); + await paused.entered; + try { + await sessions.destroy("observe-snapshot-race"); + } finally { + paused.release(); + } + expect(await observing).toEqual(created); + expect(await sessions.observe("observe-snapshot-race")).toBeNull(); + }); + + it("propagates a fresh backend read failure instead of returning an earlier live result", async () => { + let unavailable = false; + const failure = new Error("observation backend unavailable"); + const wrapped = wrapSessionCollection( + backend.freshStore(), + (collection) => ({ + ...collection, + async getVersioned(key) { + if (unavailable) throw failure; + return collection.getVersioned(key); + }, + }), + ); + const sessions = createSessionStore(wrapped, { + clock: fixedClock(NOW), + }); + await sessions.create("observe-read-error", NEW_SESSION); + expect(await sessions.observe("observe-read-error")).not.toBeNull(); + unavailable = true; + await expect(sessions.observe("observe-read-error")).rejects.toBe( + failure, + ); + }); + }); + it("refuses a collision and preserves the first record", async () => { const sessions = createSessionStore(backend.freshStore(), { clock: fixedClock(NOW), @@ -834,6 +1186,7 @@ for (const backend of backends) { collision = error; } await sessions.get(rawId, NOW); + await sessions.observe(rawId, NOW); await sessions.destroy(rawId); await sessions.destroyAllForPrincipal(PRINCIPAL); await sessions.purgeExpired(NOW); @@ -1191,3 +1544,25 @@ for (const backend of backends) { }); }); } + +it("sends one physical Azure GET and no write for each observation after table initialization", async () => { + const requests: string[] = []; + const sessions = createSessionStore(freshAzureStore(requests), { + clock: fixedClock(NOW), + idleTimeoutMs: 1_000, + }); + const rawId = "physical-observation-secret"; + await sessions.create(rawId, NEW_SESSION); + for (const [sessionId, now, live] of [ + [rawId, NOW, true], + [rawId, "2026-07-27T12:00:01.000Z", false], + ["physical-missing", NOW, false], + ] as const) { + requests.length = 0; + expect((await sessions.observe(sessionId, now)) !== null).toBe(live); + expect(requests).toHaveLength(1); + expect(requests[0]).toMatch(/^GET /u); + expect(requests[0]).toContain(await sha256(sessionId)); + expect(requests[0]).not.toContain(sessionId); + } +}); diff --git a/packages/sessions/src/index.ts b/packages/sessions/src/index.ts index ea6535f..e4b8aba 100644 --- a/packages/sessions/src/index.ts +++ b/packages/sessions/src/index.ts @@ -47,7 +47,7 @@ export interface SessionRecord extends NewSession { readonly createdAt: IsoTimestamp; /** Absolute boundary. The session is dead at this instant, not after it. */ readonly expiresAt: IsoTimestamp; - /** Idle-timeout anchor, advanced best-effort by successful reads. */ + /** Idle-timeout anchor, advanced best-effort by successful `get` calls. */ readonly lastSeenAt: IsoTimestamp; } @@ -65,6 +65,16 @@ export interface SessionStore { */ get(sessionId: string, now?: IsoTimestamp): Promise; + /** + * Reads a fresh record and returns it when live, otherwise null. + * + * Does not touch the idle anchor or delete dead records. An omitted `now` + * is observed after the storage read; an explicit instant is used unchanged. + * Storage read failures propagate. The returned snapshot is not a lock: + * revocation or expiry can occur after the read. + */ + observe(sessionId: string, now?: IsoTimestamp): Promise; + /** Idempotently revokes one session. */ destroy(sessionId: string): Promise; @@ -303,7 +313,7 @@ function throwRevocationTransactionLimit(): never { /** * The only liveness predicate. * - * Both the hot read and the hygiene sweep call this function. Invalid time + * Both read operations and the hygiene sweep call this function. Invalid time * from either the clock or storage fails closed. */ function isLive( @@ -583,6 +593,20 @@ export function createSessionStore( return publicRecord(initiallyRead); }, + async observe(sessionId, now) { + const key = sessionKey(await hashSessionId(sessionId)); + const versioned = await sessions.getVersioned(key); + const observedNow = now === undefined ? clock.now() : now; + if ( + versioned === null || + !isSessionRecord(versioned.value) || + !isLive(versioned.value, observedNow, idleTimeoutMs) + ) { + return null; + } + return publicRecord(versioned.value); + }, + async destroy(sessionId) { await sessions.delete(sessionKey(await hashSessionId(sessionId))); }, From 13724e4171571bd50702f12abaf5c710b76a6a19 Mon Sep 17 00:00:00 2001 From: Nathan Rover Date: Thu, 12 Nov 2026 22:23:01 -0500 Subject: [PATCH 2/2] Clarify session observation guarantees and release documentation --- README.md | 14 +++++++------- RELEASE_NOTES.md | 14 ++++++++------ docs/PROJECT_PLAN.md | 12 +++++++----- packages/sessions/README.md | 7 ++++--- 4 files changed, 26 insertions(+), 21 deletions(-) diff --git a/README.md b/README.md index a6d6619..5a0ed1e 100644 --- a/README.md +++ b/README.md @@ -18,6 +18,13 @@ surface; this store remembers the result. > it is not ready for production use. Published versions are listed on > [npm](https://www.npmjs.com/package/@pegma/sessions). +The `0.3.0` API adds `observe(sessionId, now?)`: a fresh liveness-checked read +without an idle touch or cleanup write. Hosts can keep `get` for initial +admission and use `observe` for closing checks that must not count as activity. +Both use the same expiry predicate and clock semantics. Each result is a +snapshot; later revocation or expiry is still possible. See the +[package README](packages/sessions/README.md) for usage. + 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 @@ -29,13 +36,6 @@ 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). -The `0.3.0` API adds `observe(sessionId, now?)`: a fresh liveness-checked read -without an idle touch or cleanup write. Hosts can keep `get` for initial -admission and use `observe` for closing checks that must not count as activity. -Both use the same expiry predicate and clock semantics. Each result is a -snapshot; later revocation or expiry is still possible. See the -[package README](packages/sessions/README.md) for usage. - Current status: the record-store package is published on npm, the first consumer migration is merged in [RetireGolden/retiregolden.org#54](https://github.com/RetireGolden/retiregolden.org/pull/54). diff --git a/RELEASE_NOTES.md b/RELEASE_NOTES.md index 4b18a7c..6821869 100644 --- a/RELEASE_NOTES.md +++ b/RELEASE_NOTES.md @@ -3,9 +3,10 @@ Add `SessionStore.observe(sessionId, now?)` for fresh liveness and identity checks that must not extend activity. It hashes the raw session id and performs one keyed backend read, then applies the existing liveness predicate. It returns -the public record when live and null when missing, revoked, expired, idle, or -malformed. It never touches the idle anchor or lazily deletes a dead row; backend -read failures propagate. +the public record when live and null when missing, revoked, or rejected by the +shared timestamp and expiry checks. Those checks validate lifecycle timestamps, +not principal claims or host data. It never touches the idle anchor or lazily +deletes a dead row; backend read failures propagate. The default clock is observed after the awaited read, matching `get`; explicit instants retain their existing semantics. Use `get` for activity such as initial @@ -17,9 +18,10 @@ The `0.3.0` minor version reflects the public `SessionStore` interface expansion under `0.x`. Existing `get`, revocation, expiry cleanup, storage schema, and runtime dependency pins retain their behavior. Memory and real Azure Tables tests cover read-only operation, exact expiry, clock observation, fresh -revocation, concurrent touches, and snapshot limits. An initialized Azure Tables -adapter sends one physical GET per observation, including dead and missing -records. +revocation, concurrent touches, and snapshot limits. On the initialized Azure +Tables adapter's no-retry path, the tests observe one physical GET per +observation, including dead and missing records. Adapter retries can issue +additional physical requests. # @pegma/sessions v0.2.1 diff --git a/docs/PROJECT_PLAN.md b/docs/PROJECT_PLAN.md index 46e4d0f..7e55c95 100644 --- a/docs/PROJECT_PLAN.md +++ b/docs/PROJECT_PLAN.md @@ -317,11 +317,13 @@ principal exists. `PrincipalId` would become nullable and needs it yet, and nullable-principal is a one-way door better opened by a real requirement. -**Touch write amplification.** Every live `get` still writes the idle anchor. -The `0.3.0` `observe` API addresses a measured pegma.dev Support Desk need: -closing checks require fresh session authority but should not renew activity. -Initial admission retains `get`, and later checks can use `observe` without -changing idle precision. This is not a touch floor or an authority cache. +**Touch write amplification.** A live `get` attempts a best-effort idle touch. +Its decider keeps the existing anchor when the observed instant is no later +than the current `lastSeenAt`, including after a concurrent touch. The `0.3.0` +`observe` API supports hosts whose closing checks need fresh session liveness +without renewing activity. A host can retain `get` for initial admission and +use `observe` for later checks without changing idle precision. This is not a +touch floor or an authority cache. ## Near-term backlog diff --git a/packages/sessions/README.md b/packages/sessions/README.md index f51d212..ad7be09 100644 --- a/packages/sessions/README.md +++ b/packages/sessions/README.md @@ -36,7 +36,7 @@ credential re-presentable to another service. ## Activity reads and read-only checks Use `get(rawSessionId)` when the request should count as activity. It reads a -live session and touches its idle anchor best-effort; a dead row is lazily +live session and attempts a best-effort idle touch; a dead row is lazily deleted best-effort. The returned record describes the initial validated snapshot and does not claim that the touch succeeded. @@ -54,8 +54,9 @@ if (current === null) return refuseRequest(); ``` `observe` hashes the id and performs one fresh keyed backend read per call. It -returns a `SessionRecord` when live or null when missing, revoked, expired, -idle, or malformed, using the same liveness predicate as `get` and the sweep. +returns a `SessionRecord` when live or null when missing, revoked, or rejected +by the timestamp and expiry checks shared with `get` and the sweep. These +checks validate lifecycle timestamps, not principal claims or host data. It does not touch the idle anchor, delete dead rows, or cache earlier results. Backend read failures reject so the host can fail closed. Keep `get` for the activity that should renew idle expiry; repeated observations alone will not