From 35d12024766dbde43403407076fb168dfcb8ef82 Mon Sep 17 00:00:00 2001 From: GLDRoger <130458023+GLDRoger@users.noreply.github.com> Date: Sun, 8 Nov 2026 19:17:15 +0530 Subject: [PATCH 1/3] fix(kin): revocation covers expired sessions Individual revoke now cascades to same-key siblings that are unexpired or still connected, since upstream keeps a connected session active past its expiry. Bulk "sign out other devices" now blocks every other mapped proof key until owner repair, even when its last session expired offline, while still excluding the caller's exact key across renewals. Bulk blocks are recorded as individually_revoked = 2, so no new migration is needed. Co-Authored-By: Claude Opus 5.5 --- .../src/kin/auth/ProofKeySessions.test.ts | 70 +++++++++++++++++-- apps/server/src/kin/auth/ProofKeySessions.ts | 25 +++++-- docs/kin/specs/approvals.md | 6 +- 3 files changed, 84 insertions(+), 17 deletions(-) diff --git a/apps/server/src/kin/auth/ProofKeySessions.test.ts b/apps/server/src/kin/auth/ProofKeySessions.test.ts index 26a092953cbb0..09b1c8763f41d 100644 --- a/apps/server/src/kin/auth/ProofKeySessions.test.ts +++ b/apps/server/src/kin/auth/ProofKeySessions.test.ts @@ -186,8 +186,10 @@ it.layer(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))("Kin proof key se "other-devices", "other-devices-live", "other-key", + "other-key-expired", "expired-revocation", "individual", + "individual-connected-expired", "insert-race", ] as const)("%s", (action) => Effect.gen(function* () { @@ -203,9 +205,17 @@ it.layer(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))("Kin proof key se ); const first = yield* exchange(); const original = yield* sessions.verify(first.access_token); - if (action === "other-key") { - const other = yield* sessions.issue({ proofKeyThumbprint: "other" }); - yield* auth.revokeOtherClientSessions(original.sessionId); + if (action === "other-key" || action === "other-key-expired") { + const other = yield* sessions.issue({ + proofKeyThumbprint: "other", + ttl: Duration.hours(1), + }); + let caller = original; + if (action === "other-key-expired") { + yield* TestClock.adjust(Duration.minutes(61)); + caller = yield* sessions.verify((yield* exchange()).access_token); + } + yield* auth.revokeOtherClientSessions(caller.sessionId); const link = yield* auth.createPairingLink({ proofKeyThumbprint: "other" }); expect( (yield* auth @@ -216,6 +226,9 @@ it.layer(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))("Kin proof key se ).toBe("ServerAuthInvalidCredentialError"); expect(Exit.isFailure(yield* sessions.verify(other.token).pipe(Effect.exit))).toBe(true); yield* exchange(); + expect((yield* sessions.verify((yield* exchange()).access_token)).proofKeyThumbprint).toBe( + "device", + ); } else if (action === "other-devices" || action === "other-devices-live") { if (action === "other-devices") yield* TestClock.adjust(Duration.minutes(61)); const current = yield* sessions.verify((yield* exchange()).access_token); @@ -233,6 +246,31 @@ it.layer(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))("Kin proof key se expect(Exit.isFailure(yield* sessions.verify(sibling.access_token).pipe(Effect.exit))).toBe( true, ); + } else if (action === "individual-connected-expired") { + yield* sessions.markConnected(original.sessionId); + yield* TestClock.adjust(Duration.minutes(61)); + const renewed = yield* sessions.verify((yield* exchange()).access_token); + const changes = yield* Queue.unbounded(); + yield* sessions.streamChanges.pipe( + Stream.runForEach((change) => Queue.offer(changes, change)), + Effect.forkScoped({ startImmediately: true }), + ); + yield* sessions.revoke(renewed.sessionId); + const sql = yield* SqlClient.SqlClient; + expect( + yield* sql`SELECT revoked_at FROM auth_sessions WHERE session_id = ${original.sessionId}`, + ).toEqual([{ revoked_at: expect.any(String) }]); + expect([yield* Queue.take(changes), yield* Queue.take(changes)]).toEqual( + expect.arrayContaining([ + { type: "clientRemoved", sessionId: original.sessionId }, + { type: "clientRemoved", sessionId: renewed.sessionId }, + ]), + ); + expect( + (yield* sessions.listActive()).some( + (session) => session.sessionId === original.sessionId, + ), + ).toBe(false); } else { yield* (yield* SessionHooks).checkExchange("device", { method: "one-time-token" }); yield* sessions.revoke(original.sessionId); @@ -390,9 +428,9 @@ it.layer(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))("Kin proof key se }).pipe(Effect.provide(layer)), ); - it.effect( - "blocks fresh cloud mints after revoke until an owner uses a bound repair pairing", - () => + it.effect.each(["individual", "bulk-expired"] as const)( + "blocks fresh cloud mints after %s revoke until an owner uses a bound repair pairing", + (revocation) => Effect.gen(function* () { const auth = yield* EnvironmentAuth.EnvironmentAuth; const sessions = yield* SessionStore.SessionStore; @@ -411,7 +449,25 @@ it.layer(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))("Kin proof key se }); const first = yield* exchange((yield* mint()).credential); const issued = yield* sessions.verify(first.access_token); - yield* sessions.revoke(issued.sessionId); + if (revocation === "individual") yield* sessions.revoke(issued.sessionId); + else { + yield* TestClock.adjust(Duration.minutes(61)); + const desktop = yield* exchange( + (yield* mint("cloud-connect", "desktop")).credential, + "desktop", + ); + const caller = yield* exchange( + (yield* mint("cloud-connect", "desktop")).credential, + "desktop", + ); + yield* auth.revokeOtherClientSessions( + (yield* sessions.verify(caller.access_token)).sessionId, + ); + expect( + Exit.isFailure(yield* sessions.verify(desktop.access_token).pipe(Effect.exit)), + ).toBe(true); + yield* exchange((yield* mint("cloud-connect", "desktop")).credential, "desktop"); + } const denied = yield* exchange((yield* mint()).credential).pipe(Effect.exit); expect(Exit.isFailure(denied)).toBe(true); const unboundRepair = yield* auth.createPairingLink({ subject: "one-time-token" }); diff --git a/apps/server/src/kin/auth/ProofKeySessions.ts b/apps/server/src/kin/auth/ProofKeySessions.ts index 618af604a4741..dfc7adfdf2bf1 100644 --- a/apps/server/src/kin/auth/ProofKeySessions.ts +++ b/apps/server/src/kin/auth/ProofKeySessions.ts @@ -11,6 +11,11 @@ import * as KinEnabled from "../KinEnabled.ts"; import * as KinPersistence from "../persistence/KinPersistence.ts"; import { SessionHooks } from "./sessionHooks.ts"; +// `individually_revoked` values: an individual revoke blocks only if it landed before expiry; +// an explicit bulk sign-out blocks the key even when its last session had already expired. +const INDIVIDUAL_BLOCK = 1; +const BULK_BLOCK = 2; + const enabled = Layer.effect( SessionHooks, Effect.gen(function* () { @@ -19,8 +24,8 @@ const enabled = Layer.effect( function* (thumbprint: string) { const rows = yield* sql`SELECT 1 FROM kin_auth_session_keys m JOIN auth_sessions s ON s.session_id = m.session_id - WHERE m.proof_key_thumbprint = ${thumbprint} AND m.individually_revoked = 1 AND m.repaired_at IS NULL - AND s.revoked_at IS NOT NULL AND s.revoked_at <= s.expires_at LIMIT 1`; + WHERE m.proof_key_thumbprint = ${thumbprint} AND m.repaired_at IS NULL AND s.revoked_at IS NOT NULL + AND (m.individually_revoked = ${BULK_BLOCK} OR (m.individually_revoked = ${INDIVIDUAL_BLOCK} AND s.revoked_at <= s.expires_at)) LIMIT 1`; return rows.length > 0; }, Effect.mapError(toPersistenceSqlError("ProofKeySessions.blocked")), @@ -91,7 +96,7 @@ const enabled = Layer.effect( AND consumed_at IS NULL RETURNING pairing_link_id`; if (repairs.length > 0) yield* sql`UPDATE kin_auth_session_keys SET repaired_at = ${now.epochMilliseconds} - WHERE proof_key_thumbprint = ${thumbprint} AND individually_revoked = 1 + WHERE proof_key_thumbprint = ${thumbprint} AND individually_revoked != 0 AND session_id IN (SELECT session_id FROM auth_sessions WHERE revoked_at IS NOT NULL)`; } return !(yield* blocked(thumbprint)); @@ -115,6 +120,11 @@ const enabled = Layer.effect( .withTransaction( Effect.gen(function* () { const now = yield* DateTime.now; + // Upstream keeps an expired session active while it stays connected. + const connected = sql.in([ + ...(yield* Ref.get(notifications.connectedSessionsRef)).keys(), + ]); + const callerKey = sql`SELECT proof_key_thumbprint FROM kin_auth_session_keys WHERE session_id = ${sessionId}`; const selected = bulk ? sql<{ session_id: AuthSessionId; @@ -122,12 +132,13 @@ const enabled = Layer.effect( : sql<{ session_id: AuthSessionId; }>`SELECT s.session_id FROM auth_sessions s LEFT JOIN kin_auth_session_keys m ON m.session_id = s.session_id - WHERE s.revoked_at IS NULL AND (s.session_id = ${sessionId} OR (s.expires_at > ${DateTime.formatIso(now)} AND m.proof_key_thumbprint = (SELECT proof_key_thumbprint FROM kin_auth_session_keys WHERE session_id = ${sessionId})))`; + WHERE s.revoked_at IS NULL AND (s.session_id = ${sessionId} OR (m.proof_key_thumbprint = (${callerKey}) + AND (s.expires_at > ${DateTime.formatIso(now)} OR s.session_id IN ${connected})))`; if (bulk) { - yield* sql`UPDATE kin_auth_session_keys SET individually_revoked = 1 WHERE session_id IN (SELECT session_id FROM auth_sessions WHERE session_id != ${sessionId} AND revoked_at IS NULL AND expires_at > ${DateTime.formatIso(now)}) - AND proof_key_thumbprint != COALESCE((SELECT proof_key_thumbprint FROM kin_auth_session_keys WHERE session_id = ${sessionId}), '')`; + yield* sql`UPDATE kin_auth_session_keys SET individually_revoked = ${BULK_BLOCK}, repaired_at = NULL + WHERE session_id != ${sessionId} AND proof_key_thumbprint != COALESCE((${callerKey}), '')`; } else { - yield* sql`UPDATE kin_auth_session_keys SET individually_revoked = 1 WHERE session_id = ${sessionId} AND EXISTS (SELECT 1 FROM auth_sessions WHERE session_id = ${sessionId} AND revoked_at IS NULL)`; + yield* sql`UPDATE kin_auth_session_keys SET individually_revoked = ${INDIVIDUAL_BLOCK} WHERE session_id = ${sessionId} AND EXISTS (SELECT 1 FROM auth_sessions WHERE session_id = ${sessionId} AND revoked_at IS NULL)`; } return yield* sql<{ session_id: AuthSessionId; diff --git a/docs/kin/specs/approvals.md b/docs/kin/specs/approvals.md index 3bc67a21b99c5..1fc2a53db3218 100644 --- a/docs/kin/specs/approvals.md +++ b/docs/kin/specs/approvals.md @@ -215,11 +215,11 @@ WHERE k.state != 'revoked' AND s.revoked_at IS NOT NULL There is no backfill: historical `jkt` values exist only in signed tokens, not stored sessions. The mapping is environment-local, not org-owned; the approver table supplies org isolation. K015_AuthSessionKeys owns this environment-local exception; these auth tables intentionally have no org_id. -With Kin enabled, an individually revoked mapped session blocks fresh exchanges for that exact proof key, including cloud re-mints; revocations after expiry do not block. Individual revocation also revokes all live sessions sharing the key. Session insertion, mapping and a second block check share a transaction with individual revocation, so either race ordering leaves the new session revoked and issuance fails rather than returning a dead token. Revoke notifications and connected-session removals run only after commit. Upstream issue still updates in-memory state and emits an upsert inside the transaction: a DPoP issue that rolls back can leave a stale upsert. Bulk “sign out other devices” blocks the other devices' live mapped keys, but excludes the caller's exact key, including earlier renewals. With Kin disabled the server hooks are no-ops; the CLI uses a read-only sqlite_master check to enable hooks against existing Kin auth tables without running Kin migrations, and remains a no-op when the table is absent; enabled-store initialization failure fails closed. Managed-policy revocations ("no remote clients") are individual revocations too, so those keys stay blocked after remote access is turned back on until the owner repairs them. A revoke that lands between insert and commit fails the exchange with a server-side issue error rather than a credential rejection; a retry is harmless because the bootstrap credential is already spent. +With Kin enabled, an individually revoked mapped session blocks fresh exchanges for that exact proof key, including cloud re-mints; an individual revocation that lands after the session expired does not block. Individual revocation also revokes every session sharing the key that is unexpired or still connected, because upstream treats a connected session as active past its expiry; expired, disconnected siblings are left alone. Session insertion, mapping and a second block check share a transaction with individual revocation, so either race ordering leaves the new session revoked and issuance fails rather than returning a dead token. Revoke notifications and connected-session removals run only after commit. Upstream issue still updates in-memory state and emits an upsert inside the transaction: a DPoP issue that rolls back can leave a stale upsert. Bulk “sign out other devices” is an explicit decision: it blocks every other proof key mapped in this environment, even one whose last session had already expired offline, until the owner repairs it. It excludes the caller's exact key, including earlier renewals. The mapping's `individually_revoked` column records which rule applies (1 individual, 2 bulk). With Kin disabled the server hooks are no-ops; the CLI uses a read-only sqlite_master check to enable hooks against existing Kin auth tables without running Kin migrations, and remains a no-op when the table is absent; enabled-store initialization failure fails closed. Managed-policy revocations ("no remote clients") are individual revocations too, so those keys stay blocked after remote access is turned back on until the owner repairs them. A revoke that lands between insert and commit fails the exchange with a server-side issue error rather than a credential rejection; a retry is harmless because the bootstrap credential is already spent. -The server owner can deliberately re-pair the same key with `t3 auth pairing create --repair-proof-key ` against the target environment's home directory, with Kin enabled or with Kin off when that database already has the Kin auth tables; the repair is consumed once Kin is on. The flag accepts only canonical 43-character base64url SHA-256 thumbprints. The CLI preserves upstream's `one-time-token` subject and records a key-bound repair in `kin_auth_key_repairs` with its pairing link id and integer-millisecond creation/consumption timestamps. Exchanges atomically consume that exact repair and acknowledge existing individual revocations; cloud mints, unbound links, another key and replay cannot acknowledge them. A later individual revocation blocks again. Repair consumption and acknowledgement precede session insertion in a separate transaction because upstream resolves/consumes bootstrap grants before issuing a session; the post-insert check covers intervening revocation. If session issuance fails after consumption, the repair is spent and the key is already unblocked; a fresh ordinary pairing can retry unless a later revocation blocks it again. Repair never restores sessions or approver keys or bypasses registration/confirmation. +The server owner can deliberately re-pair the same key with `t3 auth pairing create --repair-proof-key ` against the target environment's home directory, with Kin enabled or with Kin off when that database already has the Kin auth tables; the repair is consumed once Kin is on. The flag accepts only canonical 43-character base64url SHA-256 thumbprints. The CLI preserves upstream's `one-time-token` subject and records a key-bound repair in `kin_auth_key_repairs` with its pairing link id and integer-millisecond creation/consumption timestamps. Exchanges atomically consume that exact repair and acknowledge existing individual and bulk blocks; cloud mints, unbound links, another key and replay cannot acknowledge them. A later individual revocation or bulk sign-out blocks again. Repair consumption and acknowledgement precede session insertion in a separate transaction because upstream resolves/consumes bootstrap grants before issuing a session; the post-insert check covers intervening revocation. If session issuance fails after consumption, the repair is spent and the key is already unblocked; a fresh ordinary pairing can retry unless a later revocation blocks it again. Repair never restores sessions or approver keys or bypasses registration/confirmation. -Lane B (#42) must keep the registering-session reconcile and exact-key fallback, but exclude sessions whose mapped thumbprint matches the caller's during `revokeAllExcept`, and sessions revoked after expiry. Its historical join still sees repaired revocations: use a fresh proof key for new approver registration unless lane B implements repair-aware registration. These approver-key reconciliation changes remain lane B's responsibility, not #54. Nishchay's sign-off on the environment-local auth-table exception is still required. +Lane B (#42) must keep the registering-session reconcile and exact-key fallback, but exclude sessions whose mapped thumbprint matches the caller's during `revokeAllExcept`, and sessions an individual revoke reached after expiry; bulk sign-out reaches other devices' keys even when their sessions had expired. Its historical join still sees repaired revocations: use a fresh proof key for new approver registration unless lane B implements repair-aware registration. These approver-key reconciliation changes remain lane B's responsibility, not #54. Nishchay's sign-off on the environment-local auth-table exception is still required. A key's role isn't stored on the key. It is read at verify time from org membership (chat spec), so demoting a person takes effect at once. From 543a8684ed56e52f84a4b5c5588228e9dbc73040 Mon Sep 17 00:00:00 2001 From: GLDRoger <130458023+GLDRoger@users.noreply.github.com> Date: Sun, 8 Nov 2026 19:54:00 +0530 Subject: [PATCH 2/3] fix(kin): revoking an active session always blocks its key An individual revoke now flags every session it kills, writing 2 (unconditional block) for sessions that were active (unexpired or still connected) and 1 (expiry-guarded) otherwise. Revoking a device that stays connected past expiry, with or without a renewal, now blocks the key. Revokes and bulk sign-outs that block a key also void its unconsumed repairs, so a repair link issued before the block cannot lift it. The spec states how lane B must read individually_revoked. Co-Authored-By: Claude Opus 5.5 --- .../src/kin/auth/ProofKeySessions.test.ts | 45 +++++++++++++++++-- apps/server/src/kin/auth/ProofKeySessions.ts | 31 +++++++++---- docs/kin/specs/approvals.md | 6 +-- 3 files changed, 67 insertions(+), 15 deletions(-) diff --git a/apps/server/src/kin/auth/ProofKeySessions.test.ts b/apps/server/src/kin/auth/ProofKeySessions.test.ts index 09b1c8763f41d..fc5f750cf752d 100644 --- a/apps/server/src/kin/auth/ProofKeySessions.test.ts +++ b/apps/server/src/kin/auth/ProofKeySessions.test.ts @@ -188,8 +188,11 @@ it.layer(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))("Kin proof key se "other-key", "other-key-expired", "expired-revocation", + "expired-revocation-live-sibling", "individual", "individual-connected-expired", + "individual-connected-expired-original", + "individual-connected-expired-alone", "insert-race", ] as const)("%s", (action) => Effect.gen(function* () { @@ -240,6 +243,27 @@ it.layer(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))("Kin proof key se yield* TestClock.adjust(Duration.minutes(61)); yield* sessions.revoke(original.sessionId); yield* exchange(); + } else if ( + action === "expired-revocation-live-sibling" || + action === "individual-connected-expired-original" || + action === "individual-connected-expired-alone" + ) { + if (action !== "expired-revocation-live-sibling") + yield* sessions.markConnected(original.sessionId); + yield* TestClock.adjust(Duration.minutes(61)); + if (action !== "individual-connected-expired-alone") yield* exchange(); + yield* sessions.revoke(original.sessionId); + const link = yield* auth.createPairingLink({ + subject: "cloud-connect", + proofKeyThumbprint: "device", + }); + expect( + (yield* auth + .exchangeBootstrapCredentialForAccessToken(link.credential, undefined, metadata, { + proofKeyThumbprint: "device", + }) + .pipe(Effect.flip))._tag, + ).toBe("ServerAuthInvalidCredentialError"); } else if (action === "individual") { const sibling = yield* exchange(); yield* sessions.revoke(original.sessionId); @@ -297,7 +321,13 @@ it.layer(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))("Kin proof key se }).pipe(Effect.scoped, Effect.provide(layer)), ); - it.effect.each(["wrong-link", "spent"] as const)("repair guard: %s", (guard) => + it.effect.each([ + "wrong-link", + "spent", + "bulk-after-repair", + "issued-before-revoke", + "issued-before-bulk", + ] as const)("repair guard: %s", (guard) => Effect.gen(function* () { const sessions = yield* SessionStore.SessionStore; const sql = yield* SqlClient.SqlClient; @@ -313,14 +343,23 @@ it.layer(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))("Kin proof key se ), ), ); + const bulkFromDesktop = sessions + .issue({ proofKeyThumbprint: "desktop" }) + .pipe(Effect.flatMap((desktop) => sessions.revokeAllExcept(desktop.sessionId))); const first = yield* sessions.issue({ proofKeyThumbprint: "device" }); - yield* sessions.revoke(first.sessionId); - yield* hooks.recordRepair("device", "A"); + const issuedBefore = guard === "issued-before-revoke" || guard === "issued-before-bulk"; + if (issuedBefore) yield* hooks.recordRepair("device", "A"); + if (guard === "issued-before-bulk") yield* bulkFromDesktop; + else yield* sessions.revoke(first.sessionId); + if (!issuedBefore) yield* hooks.recordRepair("device", "A"); const grant = { method: "one-time-token", proofKeyThumbprint: "device", pairingLinkId: "A" }; if (guard === "spent") { expect(yield* hooks.checkExchange("device", grant)).toBe(true); const next = yield* sessions.issue({ proofKeyThumbprint: "device" }); yield* sessions.revoke(next.sessionId); + } else if (guard === "bulk-after-repair") { + expect(yield* hooks.checkExchange("device", grant)).toBe(true); + yield* bulkFromDesktop; } expect( yield* hooks.checkExchange("device", { diff --git a/apps/server/src/kin/auth/ProofKeySessions.ts b/apps/server/src/kin/auth/ProofKeySessions.ts index dfc7adfdf2bf1..8da5d47026062 100644 --- a/apps/server/src/kin/auth/ProofKeySessions.ts +++ b/apps/server/src/kin/auth/ProofKeySessions.ts @@ -11,10 +11,10 @@ import * as KinEnabled from "../KinEnabled.ts"; import * as KinPersistence from "../persistence/KinPersistence.ts"; import { SessionHooks } from "./sessionHooks.ts"; -// `individually_revoked` values: an individual revoke blocks only if it landed before expiry; -// an explicit bulk sign-out blocks the key even when its last session had already expired. -const INDIVIDUAL_BLOCK = 1; -const BULK_BLOCK = 2; +// `individually_revoked`: 0 none; 1 blocks only if `revoked_at <= expires_at`; 2 blocks unconditionally +// (bulk sign-out, or a revoke that killed an active session). +const GUARDED_BLOCK = 1; +const UNCONDITIONAL_BLOCK = 2; const enabled = Layer.effect( SessionHooks, @@ -22,10 +22,12 @@ const enabled = Layer.effect( const sql = yield* SqlClient.SqlClient; const blocked = Effect.fn("ProofKeySessions.blocked")( function* (thumbprint: string) { + // Readers of `individually_revoked` test `!= 0` and apply the expiry guard only to 1. const rows = yield* sql`SELECT 1 FROM kin_auth_session_keys m JOIN auth_sessions s ON s.session_id = m.session_id WHERE m.proof_key_thumbprint = ${thumbprint} AND m.repaired_at IS NULL AND s.revoked_at IS NOT NULL - AND (m.individually_revoked = ${BULK_BLOCK} OR (m.individually_revoked = ${INDIVIDUAL_BLOCK} AND s.revoked_at <= s.expires_at)) LIMIT 1`; + AND m.individually_revoked != 0 + AND (m.individually_revoked != ${GUARDED_BLOCK} OR s.revoked_at <= s.expires_at) LIMIT 1`; return rows.length > 0; }, Effect.mapError(toPersistenceSqlError("ProofKeySessions.blocked")), @@ -124,6 +126,7 @@ const enabled = Layer.effect( const connected = sql.in([ ...(yield* Ref.get(notifications.connectedSessionsRef)).keys(), ]); + const active = sql`SELECT session_id FROM auth_sessions WHERE expires_at > ${DateTime.formatIso(now)} OR session_id IN ${connected}`; const callerKey = sql`SELECT proof_key_thumbprint FROM kin_auth_session_keys WHERE session_id = ${sessionId}`; const selected = bulk ? sql<{ @@ -133,13 +136,23 @@ const enabled = Layer.effect( session_id: AuthSessionId; }>`SELECT s.session_id FROM auth_sessions s LEFT JOIN kin_auth_session_keys m ON m.session_id = s.session_id WHERE s.revoked_at IS NULL AND (s.session_id = ${sessionId} OR (m.proof_key_thumbprint = (${callerKey}) - AND (s.expires_at > ${DateTime.formatIso(now)} OR s.session_id IN ${connected})))`; + AND s.session_id IN (${active})))`; + const blockedKeys = bulk + ? sql`SELECT proof_key_thumbprint FROM kin_auth_session_keys + WHERE session_id != ${sessionId} AND proof_key_thumbprint != COALESCE((${callerKey}), '')` + : sql`SELECT proof_key_thumbprint FROM kin_auth_session_keys + WHERE session_id IN (${selected}) AND individually_revoked = ${UNCONDITIONAL_BLOCK}`; if (bulk) { - yield* sql`UPDATE kin_auth_session_keys SET individually_revoked = ${BULK_BLOCK}, repaired_at = NULL - WHERE session_id != ${sessionId} AND proof_key_thumbprint != COALESCE((${callerKey}), '')`; + yield* sql`UPDATE kin_auth_session_keys SET individually_revoked = ${UNCONDITIONAL_BLOCK}, repaired_at = NULL + WHERE proof_key_thumbprint IN (${blockedKeys})`; } else { - yield* sql`UPDATE kin_auth_session_keys SET individually_revoked = ${INDIVIDUAL_BLOCK} WHERE session_id = ${sessionId} AND EXISTS (SELECT 1 FROM auth_sessions WHERE session_id = ${sessionId} AND revoked_at IS NULL)`; + yield* sql`UPDATE kin_auth_session_keys SET individually_revoked = + CASE WHEN session_id IN (${active}) THEN ${UNCONDITIONAL_BLOCK} ELSE ${GUARDED_BLOCK} END + WHERE session_id IN (${selected})`; } + // A repair link issued before this block must not lift it. + yield* sql`UPDATE kin_auth_key_repairs SET consumed_at = ${now.epochMilliseconds} + WHERE consumed_at IS NULL AND thumbprint IN (${blockedKeys})`; return yield* sql<{ session_id: AuthSessionId; }>`UPDATE auth_sessions SET revoked_at = ${DateTime.formatIso(now)} WHERE session_id IN (${selected}) AND revoked_at IS NULL RETURNING session_id`; diff --git a/docs/kin/specs/approvals.md b/docs/kin/specs/approvals.md index 1fc2a53db3218..1c3004509a933 100644 --- a/docs/kin/specs/approvals.md +++ b/docs/kin/specs/approvals.md @@ -215,11 +215,11 @@ WHERE k.state != 'revoked' AND s.revoked_at IS NOT NULL There is no backfill: historical `jkt` values exist only in signed tokens, not stored sessions. The mapping is environment-local, not org-owned; the approver table supplies org isolation. K015_AuthSessionKeys owns this environment-local exception; these auth tables intentionally have no org_id. -With Kin enabled, an individually revoked mapped session blocks fresh exchanges for that exact proof key, including cloud re-mints; an individual revocation that lands after the session expired does not block. Individual revocation also revokes every session sharing the key that is unexpired or still connected, because upstream treats a connected session as active past its expiry; expired, disconnected siblings are left alone. Session insertion, mapping and a second block check share a transaction with individual revocation, so either race ordering leaves the new session revoked and issuance fails rather than returning a dead token. Revoke notifications and connected-session removals run only after commit. Upstream issue still updates in-memory state and emits an upsert inside the transaction: a DPoP issue that rolls back can leave a stale upsert. Bulk “sign out other devices” is an explicit decision: it blocks every other proof key mapped in this environment, even one whose last session had already expired offline, until the owner repairs it. It excludes the caller's exact key, including earlier renewals. The mapping's `individually_revoked` column records which rule applies (1 individual, 2 bulk). With Kin disabled the server hooks are no-ops; the CLI uses a read-only sqlite_master check to enable hooks against existing Kin auth tables without running Kin migrations, and remains a no-op when the table is absent; enabled-store initialization failure fails closed. Managed-policy revocations ("no remote clients") are individual revocations too, so those keys stay blocked after remote access is turned back on until the owner repairs them. A revoke that lands between insert and commit fails the exchange with a server-side issue error rather than a credential rejection; a retry is harmless because the bootstrap credential is already spent. +With Kin enabled, an individually revoked mapped session blocks fresh exchanges for that exact proof key, including cloud re-mints; an individual revocation that reaches only an expired, disconnected session does not block. A revoke that kills an active session (unexpired, or connected past expiry, since upstream treats a connected session as active) blocks the key unconditionally, whether that session is the target or a same-key sibling, so revoking an expired target that has a live renewal blocks the key. Individual revocation also revokes every session sharing the key that is unexpired or still connected, because upstream treats a connected session as active past its expiry; expired, disconnected siblings are left alone. Session insertion, mapping and a second block check share a transaction with individual revocation, so either race ordering leaves the new session revoked and issuance fails rather than returning a dead token. Revoke notifications and connected-session removals run only after commit. Upstream issue still updates in-memory state and emits an upsert inside the transaction: a DPoP issue that rolls back can leave a stale upsert. Bulk “sign out other devices” is an explicit decision: it blocks every other proof key mapped in this environment, even one whose last session had already expired offline, until the owner repairs it. It excludes the caller's exact key, including earlier renewals. With Kin disabled the server hooks are no-ops; the CLI uses a read-only sqlite_master check to enable hooks against existing Kin auth tables without running Kin migrations, and remains a no-op when the table is absent; enabled-store initialization failure fails closed. Managed-policy revocations ("no remote clients") are individual revocations too, so those keys stay blocked after remote access is turned back on until the owner repairs them. A revoke that lands between insert and commit fails the exchange with a server-side issue error rather than a credential rejection; a retry is harmless because the bootstrap credential is already spent. -The server owner can deliberately re-pair the same key with `t3 auth pairing create --repair-proof-key ` against the target environment's home directory, with Kin enabled or with Kin off when that database already has the Kin auth tables; the repair is consumed once Kin is on. The flag accepts only canonical 43-character base64url SHA-256 thumbprints. The CLI preserves upstream's `one-time-token` subject and records a key-bound repair in `kin_auth_key_repairs` with its pairing link id and integer-millisecond creation/consumption timestamps. Exchanges atomically consume that exact repair and acknowledge existing individual and bulk blocks; cloud mints, unbound links, another key and replay cannot acknowledge them. A later individual revocation or bulk sign-out blocks again. Repair consumption and acknowledgement precede session insertion in a separate transaction because upstream resolves/consumes bootstrap grants before issuing a session; the post-insert check covers intervening revocation. If session issuance fails after consumption, the repair is spent and the key is already unblocked; a fresh ordinary pairing can retry unless a later revocation blocks it again. Repair never restores sessions or approver keys or bypasses registration/confirmation. +The server owner can deliberately re-pair the same key with `t3 auth pairing create --repair-proof-key ` against the target environment's home directory, with Kin enabled or with Kin off when that database already has the Kin auth tables; the repair is consumed once Kin is on. The flag accepts only canonical 43-character base64url SHA-256 thumbprints. The CLI preserves upstream's `one-time-token` subject and records a key-bound repair in `kin_auth_key_repairs` with its pairing link id and integer-millisecond creation/consumption timestamps. Exchanges atomically consume that exact repair and acknowledge existing individual and bulk blocks; cloud mints, unbound links, another key and replay cannot acknowledge them. A later individual revocation or bulk sign-out blocks again and voids that key's unconsumed repairs, so a repair link issued before the block cannot lift it. Repair consumption and acknowledgement precede session insertion in a separate transaction because upstream resolves/consumes bootstrap grants before issuing a session; the post-insert check covers intervening revocation. If session issuance fails after consumption, the repair is spent and the key is already unblocked; a fresh ordinary pairing can retry unless a later revocation blocks it again. Repair never restores sessions or approver keys or bypasses registration/confirmation. -Lane B (#42) must keep the registering-session reconcile and exact-key fallback, but exclude sessions whose mapped thumbprint matches the caller's during `revokeAllExcept`, and sessions an individual revoke reached after expiry; bulk sign-out reaches other devices' keys even when their sessions had expired. Its historical join still sees repaired revocations: use a fresh proof key for new approver registration unless lane B implements repair-aware registration. These approver-key reconciliation changes remain lane B's responsibility, not #54. Nishchay's sign-off on the environment-local auth-table exception is still required. +Lane B (#42) must keep the registering-session reconcile and exact-key fallback, and exclude sessions whose mapped thumbprint matches the caller's during `revokeAllExcept`. It must read the mapping's `individually_revoked` column by this rule: 0 means not revoked, 1 means a revoke that blocks only if `s.revoked_at <= s.expires_at`, and 2 means an unconditional block (bulk sign-out, or a revoke that killed an active session). Test `individually_revoked != 0` and apply the expiry guard only to 1, as in `m.individually_revoked != 0 AND (m.individually_revoked != 1 OR s.revoked_at <= s.expires_at)`; a partial index uses `WHERE individually_revoked != 0`. Reading `= 1` treats every unconditional block as not revoked. Its historical join still sees repaired revocations: use a fresh proof key for new approver registration unless lane B implements repair-aware registration. These approver-key reconciliation changes remain lane B's responsibility, not #54. Nishchay's sign-off on the environment-local auth-table exception is still required. A key's role isn't stored on the key. It is read at verify time from org membership (chat spec), so demoting a person takes effect at once. From b61db83420003f647e2c5a1a74d8d4eae8596363 Mon Sep 17 00:00:00 2001 From: GLDRoger <130458023+GLDRoger@users.noreply.github.com> Date: Sun, 8 Nov 2026 20:39:18 +0530 Subject: [PATCH 3/3] fix(kin): a client revoke never locks out the caller's own key Revoking another session from Settings passed no caller, so the same-key cascade signed the caller out and blocked its key until a CLI repair. SessionStore.revoke now takes an optional caller: the cascade skips the caller's session, and a same-key caller neither blocks the key nor voids its repairs. Managed-policy, CLI and other-key revokes still block. A session expiring at exactly the revoke instant now counts as active, matching the guard's revoked_at <= expires_at, so its repairs are voided. Co-Authored-By: Claude Opus 5.5 --- apps/server/src/auth/EnvironmentAuth.ts | 6 ++-- apps/server/src/auth/SessionStore.ts | 1 + .../src/kin/auth/ProofKeySessions.test.ts | 36 +++++++++++++++++-- apps/server/src/kin/auth/ProofKeySessions.ts | 24 +++++++------ docs/kin/specs/approvals.md | 2 +- 5 files changed, 53 insertions(+), 16 deletions(-) diff --git a/apps/server/src/auth/EnvironmentAuth.ts b/apps/server/src/auth/EnvironmentAuth.ts index 84e84b52023d5..3978c44b38de9 100644 --- a/apps/server/src/auth/EnvironmentAuth.ts +++ b/apps/server/src/auth/EnvironmentAuth.ts @@ -1121,8 +1121,8 @@ export const make = Effect.gen(function* () { Effect.withSpan("EnvironmentAuth.listSessions"), ); - const revokeSession: EnvironmentAuth["Service"]["revokeSession"] = (sessionId) => - sessions.revoke(sessionId).pipe( + const revokeSession = (sessionId: AuthSessionId, callerSessionId?: AuthSessionId) => + sessions.revoke(sessionId, callerSessionId).pipe( Effect.mapError((cause) => new ServerAuthSessionRevocationError({ cause })), Effect.withSpan("EnvironmentAuth.revokeSession"), ); @@ -1191,7 +1191,7 @@ export const make = Effect.gen(function* () { if (currentSessionId === targetSessionId) { return yield* new ServerAuthForbiddenOperationError({}); } - return yield* revokeSession(targetSessionId); + return yield* revokeSession(targetSessionId, currentSessionId); }); const revokeOtherClientSessions: EnvironmentAuth["Service"]["revokeOtherClientSessions"] = ( diff --git a/apps/server/src/auth/SessionStore.ts b/apps/server/src/auth/SessionStore.ts index ec86bf6fa1db0..19197a02a5695 100644 --- a/apps/server/src/auth/SessionStore.ts +++ b/apps/server/src/auth/SessionStore.ts @@ -416,6 +416,7 @@ export class SessionStore extends Context.Service< ) => Effect.Effect; readonly revoke: ( sessionId: AuthSessionId, + callerSessionId?: AuthSessionId, ) => Effect.Effect; readonly revokeAllExcept: ( sessionId: AuthSessionId, diff --git a/apps/server/src/kin/auth/ProofKeySessions.test.ts b/apps/server/src/kin/auth/ProofKeySessions.test.ts index fc5f750cf752d..b763b63724f05 100644 --- a/apps/server/src/kin/auth/ProofKeySessions.test.ts +++ b/apps/server/src/kin/auth/ProofKeySessions.test.ts @@ -193,6 +193,10 @@ it.layer(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))("Kin proof key se "individual-connected-expired", "individual-connected-expired-original", "individual-connected-expired-alone", + "same-key-caller", + "same-key-caller-connected-expired", + "same-key-caller-expired", + "other-key-caller", "insert-race", ] as const)("%s", (action) => Effect.gen(function* () { @@ -264,6 +268,32 @@ it.layer(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))("Kin proof key se }) .pipe(Effect.flip))._tag, ).toBe("ServerAuthInvalidCredentialError"); + } else if (action.startsWith("same-key-caller") || action === "other-key-caller") { + if (action === "same-key-caller-connected-expired") + yield* sessions.markConnected(original.sessionId); + if (action.endsWith("expired")) yield* TestClock.adjust(Duration.minutes(61)); + const callerToken = + action === "other-key-caller" + ? (yield* sessions.issue({ proofKeyThumbprint: "desktop" })).token + : (yield* exchange()).access_token; + const caller = yield* sessions.verify(callerToken); + expect(yield* auth.revokeClientSession(caller.sessionId, original.sessionId)).toBe(true); + const sql = yield* SqlClient.SqlClient; + expect( + yield* sql`SELECT revoked_at FROM auth_sessions WHERE session_id = ${original.sessionId}`, + ).toEqual([{ revoked_at: expect.any(String) }]); + const link = yield* auth.createPairingLink({ + subject: "cloud-connect", + proofKeyThumbprint: "device", + }); + const mint = yield* auth + .exchangeBootstrapCredentialForAccessToken(link.credential, undefined, metadata, { + proofKeyThumbprint: "device", + }) + .pipe(Effect.exit); + expect(Exit.isSuccess(mint)).toBe(action !== "other-key-caller"); + if (action !== "other-key-caller") + expect((yield* sessions.verify(callerToken)).sessionId).toBe(caller.sessionId); } else if (action === "individual") { const sibling = yield* exchange(); yield* sessions.revoke(original.sessionId); @@ -326,6 +356,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))("Kin proof key se "spent", "bulk-after-repair", "issued-before-revoke", + "issued-before-revoke-at-expiry", "issued-before-bulk", ] as const)("repair guard: %s", (guard) => Effect.gen(function* () { @@ -346,9 +377,10 @@ it.layer(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))("Kin proof key se const bulkFromDesktop = sessions .issue({ proofKeyThumbprint: "desktop" }) .pipe(Effect.flatMap((desktop) => sessions.revokeAllExcept(desktop.sessionId))); - const first = yield* sessions.issue({ proofKeyThumbprint: "device" }); - const issuedBefore = guard === "issued-before-revoke" || guard === "issued-before-bulk"; + const first = yield* sessions.issue({ proofKeyThumbprint: "device", ttl: Duration.hours(1) }); + const issuedBefore = guard.startsWith("issued-before"); if (issuedBefore) yield* hooks.recordRepair("device", "A"); + if (guard === "issued-before-revoke-at-expiry") yield* TestClock.adjust(Duration.hours(1)); if (guard === "issued-before-bulk") yield* bulkFromDesktop; else yield* sessions.revoke(first.sessionId); if (!issuedBefore) yield* hooks.recordRepair("device", "A"); diff --git a/apps/server/src/kin/auth/ProofKeySessions.ts b/apps/server/src/kin/auth/ProofKeySessions.ts index 8da5d47026062..880e4ca452c34 100644 --- a/apps/server/src/kin/auth/ProofKeySessions.ts +++ b/apps/server/src/kin/auth/ProofKeySessions.ts @@ -117,7 +117,7 @@ const enabled = Layer.effect( next.delete(sessionId); return next; }).pipe(Effect.andThen(notifications.emitRemoved(sessionId))); - const revoke = (sessionId: AuthSessionId, bulk: boolean) => + const revoke = (sessionId: AuthSessionId, bulk: boolean, callerSessionId?: AuthSessionId) => sql .withTransaction( Effect.gen(function* () { @@ -126,8 +126,12 @@ const enabled = Layer.effect( const connected = sql.in([ ...(yield* Ref.get(notifications.connectedSessionsRef)).keys(), ]); - const active = sql`SELECT session_id FROM auth_sessions WHERE expires_at > ${DateTime.formatIso(now)} OR session_id IN ${connected}`; - const callerKey = sql`SELECT proof_key_thumbprint FROM kin_auth_session_keys WHERE session_id = ${sessionId}`; + const active = sql`SELECT session_id FROM auth_sessions WHERE expires_at >= ${DateTime.formatIso(now)} OR session_id IN ${connected}`; + const keyOf = (id: AuthSessionId | null) => + sql`SELECT proof_key_thumbprint FROM kin_auth_session_keys WHERE session_id = ${id}`; + const caller = bulk ? sessionId : (callerSessionId ?? null); + // A caller never signs itself out or blocks the key it is signed in with. + const notCallerKey = sql`proof_key_thumbprint IS NOT (${keyOf(caller)})`; const selected = bulk ? sql<{ session_id: AuthSessionId; @@ -135,20 +139,20 @@ const enabled = Layer.effect( : sql<{ session_id: AuthSessionId; }>`SELECT s.session_id FROM auth_sessions s LEFT JOIN kin_auth_session_keys m ON m.session_id = s.session_id - WHERE s.revoked_at IS NULL AND (s.session_id = ${sessionId} OR (m.proof_key_thumbprint = (${callerKey}) - AND s.session_id IN (${active})))`; + WHERE s.revoked_at IS NULL AND s.session_id IS NOT ${caller} AND (s.session_id = ${sessionId} + OR (m.proof_key_thumbprint = (${keyOf(sessionId)}) AND s.session_id IN (${active})))`; const blockedKeys = bulk ? sql`SELECT proof_key_thumbprint FROM kin_auth_session_keys - WHERE session_id != ${sessionId} AND proof_key_thumbprint != COALESCE((${callerKey}), '')` + WHERE session_id != ${sessionId} AND ${notCallerKey}` : sql`SELECT proof_key_thumbprint FROM kin_auth_session_keys - WHERE session_id IN (${selected}) AND individually_revoked = ${UNCONDITIONAL_BLOCK}`; + WHERE session_id IN (${selected}) AND individually_revoked = ${UNCONDITIONAL_BLOCK} AND ${notCallerKey}`; if (bulk) { yield* sql`UPDATE kin_auth_session_keys SET individually_revoked = ${UNCONDITIONAL_BLOCK}, repaired_at = NULL WHERE proof_key_thumbprint IN (${blockedKeys})`; } else { yield* sql`UPDATE kin_auth_session_keys SET individually_revoked = CASE WHEN session_id IN (${active}) THEN ${UNCONDITIONAL_BLOCK} ELSE ${GUARDED_BLOCK} END - WHERE session_id IN (${selected})`; + WHERE session_id IN (${selected}) AND ${notCallerKey}`; } // A repair link issued before this block must not lift it. yield* sql`UPDATE kin_auth_key_repairs SET consumed_at = ${now.epochMilliseconds} @@ -203,8 +207,8 @@ const enabled = Layer.effect( ), ); }), - revoke: Effect.fn("ProofKeySessions.revoke")((sessionId) => - revoke(sessionId, false).pipe( + revoke: Effect.fn("ProofKeySessions.revoke")((sessionId, callerSessionId) => + revoke(sessionId, false, callerSessionId).pipe( Effect.map((ids) => ids.some((row) => row.session_id === sessionId)), Effect.mapError( (cause) => diff --git a/docs/kin/specs/approvals.md b/docs/kin/specs/approvals.md index 1c3004509a933..e0273e6425856 100644 --- a/docs/kin/specs/approvals.md +++ b/docs/kin/specs/approvals.md @@ -215,7 +215,7 @@ WHERE k.state != 'revoked' AND s.revoked_at IS NOT NULL There is no backfill: historical `jkt` values exist only in signed tokens, not stored sessions. The mapping is environment-local, not org-owned; the approver table supplies org isolation. K015_AuthSessionKeys owns this environment-local exception; these auth tables intentionally have no org_id. -With Kin enabled, an individually revoked mapped session blocks fresh exchanges for that exact proof key, including cloud re-mints; an individual revocation that reaches only an expired, disconnected session does not block. A revoke that kills an active session (unexpired, or connected past expiry, since upstream treats a connected session as active) blocks the key unconditionally, whether that session is the target or a same-key sibling, so revoking an expired target that has a live renewal blocks the key. Individual revocation also revokes every session sharing the key that is unexpired or still connected, because upstream treats a connected session as active past its expiry; expired, disconnected siblings are left alone. Session insertion, mapping and a second block check share a transaction with individual revocation, so either race ordering leaves the new session revoked and issuance fails rather than returning a dead token. Revoke notifications and connected-session removals run only after commit. Upstream issue still updates in-memory state and emits an upsert inside the transaction: a DPoP issue that rolls back can leave a stale upsert. Bulk “sign out other devices” is an explicit decision: it blocks every other proof key mapped in this environment, even one whose last session had already expired offline, until the owner repairs it. It excludes the caller's exact key, including earlier renewals. With Kin disabled the server hooks are no-ops; the CLI uses a read-only sqlite_master check to enable hooks against existing Kin auth tables without running Kin migrations, and remains a no-op when the table is absent; enabled-store initialization failure fails closed. Managed-policy revocations ("no remote clients") are individual revocations too, so those keys stay blocked after remote access is turned back on until the owner repairs them. A revoke that lands between insert and commit fails the exchange with a server-side issue error rather than a credential rejection; a retry is harmless because the bootstrap credential is already spent. +With Kin enabled, an individually revoked mapped session blocks fresh exchanges for that exact proof key, including cloud re-mints; an individual revocation that reaches only an expired, disconnected session does not block. A revoke that kills an active session (`expires_at >= now`, matching the guard's `revoked_at <= expires_at`, or connected past expiry, since upstream treats a connected session as active) blocks the key unconditionally, whether that session is the target or a same-key sibling, so revoking an expired target that has a live renewal blocks the key. Individual revocation also revokes every active session sharing the key; expired, disconnected siblings are left alone. A client revoke from Settings passes the caller: the cascade never revokes the caller's own session, and when the caller holds the target's key the revoke signs out the target and its other same-key sessions without blocking the key or voiding its repairs, so an owner clearing a stale entry of their own phone keeps access. A caller on another key, managed policy and the CLI block as above. Session insertion, mapping and a second block check share a transaction with individual revocation, so either race ordering leaves the new session revoked and issuance fails rather than returning a dead token. Revoke notifications and connected-session removals run only after commit. Upstream issue still updates in-memory state and emits an upsert inside the transaction: a DPoP issue that rolls back can leave a stale upsert. Bulk “sign out other devices” is an explicit decision: it blocks every other proof key mapped in this environment, even one whose last session had already expired offline, until the owner repairs it. It excludes the caller's exact key, including earlier renewals. With Kin disabled the server hooks are no-ops; the CLI uses a read-only sqlite_master check to enable hooks against existing Kin auth tables without running Kin migrations, and remains a no-op when the table is absent; enabled-store initialization failure fails closed. Managed-policy revocations ("no remote clients") are individual revocations too, so those keys stay blocked after remote access is turned back on until the owner repairs them. A revoke that lands between insert and commit fails the exchange with a server-side issue error rather than a credential rejection; a retry is harmless because the bootstrap credential is already spent. The server owner can deliberately re-pair the same key with `t3 auth pairing create --repair-proof-key ` against the target environment's home directory, with Kin enabled or with Kin off when that database already has the Kin auth tables; the repair is consumed once Kin is on. The flag accepts only canonical 43-character base64url SHA-256 thumbprints. The CLI preserves upstream's `one-time-token` subject and records a key-bound repair in `kin_auth_key_repairs` with its pairing link id and integer-millisecond creation/consumption timestamps. Exchanges atomically consume that exact repair and acknowledge existing individual and bulk blocks; cloud mints, unbound links, another key and replay cannot acknowledge them. A later individual revocation or bulk sign-out blocks again and voids that key's unconsumed repairs, so a repair link issued before the block cannot lift it. Repair consumption and acknowledgement precede session insertion in a separate transaction because upstream resolves/consumes bootstrap grants before issuing a session; the post-insert check covers intervening revocation. If session issuance fails after consumption, the repair is spent and the key is already unblocked; a fresh ordinary pairing can retry unless a later revocation blocks it again. Repair never restores sessions or approver keys or bypasses registration/confirmation.