From e29b46f35f09192b1e633b2d5e5642a3e6dbf266 Mon Sep 17 00:00:00 2001 From: Surajsm60720 <1ds22is166@dsce.edu.in> Date: Sun, 8 Nov 2026 07:12:51 +0530 Subject: [PATCH 01/16] chore(kin): claim APPR-5 approver keys Co-Authored-By: Claude Opus 5.5 From 22d6135fc5ba9963d35463f5c379cedac8cb81ad Mon Sep 17 00:00:00 2001 From: Surajsm60720 <1ds22is166@dsce.edu.in> Date: Sun, 8 Nov 2026 07:29:40 +0530 Subject: [PATCH 02/16] feat(kin): approver key registry with attestation (APPR-5) Co-Authored-By: Claude Opus 5.5 --- apps/server/src/kin/KinServer.ts | 3 +- .../src/kin/approvals/ApproverKeys.test.ts | 377 +++++++++++++ apps/server/src/kin/approvals/ApproverKeys.ts | 520 ++++++++++++++++++ .../approvals/attestation/AttestationTrust.ts | 110 ++++ .../src/kin/approvals/attestation/der.ts | 159 ++++++ .../src/kin/approvals/attestation/roots.ts | 64 +++ .../kin/approvals/attestation/testFixtures.ts | 367 ++++++++++++ .../kin/approvals/attestation/verify.test.ts | 147 +++++ .../src/kin/approvals/attestation/verify.ts | 361 ++++++++++++ .../approvals/handlers/registerApproverKey.ts | 59 ++ apps/server/src/kin/approvals/layer.ts | 13 + apps/server/src/kin/approvals/rpcHandlers.ts | 67 ++- apps/server/src/kin/layer.ts | 7 +- packages/contracts/src/kinApprovals.ts | 30 +- packages/shared/src/kinGrant.test.ts | 11 +- 15 files changed, 2268 insertions(+), 27 deletions(-) create mode 100644 apps/server/src/kin/approvals/ApproverKeys.test.ts create mode 100644 apps/server/src/kin/approvals/ApproverKeys.ts create mode 100644 apps/server/src/kin/approvals/attestation/AttestationTrust.ts create mode 100644 apps/server/src/kin/approvals/attestation/der.ts create mode 100644 apps/server/src/kin/approvals/attestation/roots.ts create mode 100644 apps/server/src/kin/approvals/attestation/testFixtures.ts create mode 100644 apps/server/src/kin/approvals/attestation/verify.test.ts create mode 100644 apps/server/src/kin/approvals/attestation/verify.ts create mode 100644 apps/server/src/kin/approvals/handlers/registerApproverKey.ts create mode 100644 apps/server/src/kin/approvals/layer.ts diff --git a/apps/server/src/kin/KinServer.ts b/apps/server/src/kin/KinServer.ts index b81fde1c88621..288d392666633 100644 --- a/apps/server/src/kin/KinServer.ts +++ b/apps/server/src/kin/KinServer.ts @@ -3,8 +3,9 @@ import * as Option from "effect/Option"; import { KinIdentity } from "./chat/KinIdentity.ts"; import { KinChatService } from "./chat/KinChatService.ts"; import { KinChatHub } from "./chat/KinChatHub.ts"; +import { ApproverKeys } from "./approvals/ApproverKeys.ts"; -export type Services = KinIdentity | KinChatService; +export type Services = KinIdentity | KinChatService | ApproverKeys; export class KinServer extends Context.Service< KinServer, diff --git a/apps/server/src/kin/approvals/ApproverKeys.test.ts b/apps/server/src/kin/approvals/ApproverKeys.test.ts new file mode 100644 index 0000000000000..b6da7d3213faa --- /dev/null +++ b/apps/server/src/kin/approvals/ApproverKeys.test.ts @@ -0,0 +1,377 @@ +import { assert, describe, it } from "@effect/vitest"; +import { + AuthSessionId, + KinEventId, + KinOrgId, + KinPersonId, + type KinApprovalError, + type KinApprovalsRegisterKeyInput, + type KinPendingAction, +} from "@t3tools/contracts"; +import * as Effect from "effect/Effect"; +import * as Exit from "effect/Exit"; +import * as Layer from "effect/Layer"; +import * as Option from "effect/Option"; +import * as Schema from "effect/Schema"; +import * as SqlClient from "effect/sql/SqlClient"; +import * as TestClock from "effect/testing/TestClock"; + +import * as Sqlite from "../../persistence/Sqlite.ts"; +import * as KinPersistence from "../persistence/KinPersistence.ts"; +import { + ApproverKeys, + kinKeyConfirmationCode, + layer as approverKeysLayer, + type KinKeyCaller, + type KinKeyConnection, +} from "./ApproverKeys.ts"; +import { KinAttestationTrust } from "./attestation/AttestationTrust.ts"; +import { androidChain, makeTrustFixture } from "./attestation/testFixtures.ts"; +import { makeRegisterApproverKeyHandler } from "./handlers/registerApproverKey.ts"; +import { + KinPendingActions, + layer as pendingActionsLayer, + type KinPendingActionCreateInput, +} from "./PendingActions.ts"; + +const NOW = Date.parse("2026-11-08T00:00:00Z"); +const fixture = makeTrustFixture(); +const trustLayer = Layer.succeed(KinAttestationTrust, { + load: () => Effect.succeed(fixture.trust), +}); +const database = Layer.provideMerge(KinPersistence.layer, Sqlite.layerMemory); +const layer = approverKeysLayer.pipe( + Layer.provideMerge(pendingActionsLayer), + Layer.provide(trustLayer), + Layer.provideMerge(database), +); + +const orgId = Schema.decodeSync(KinOrgId)("org_01"); +const owner = Schema.decodeSync(KinPersonId)("h_owner"); +const sessionId = Schema.decodeSync(AuthSessionId); +const decodeEventId = Schema.decodeSync(KinEventId); +const loopback: KinKeyConnection = { remoteAddress: "127.0.0.1", headers: {} }; + +const caller = (id: string, subject: string, connection?: KinKeyConnection): KinKeyCaller => ({ + session: { sessionId: sessionId(id), subject, method: "bearer-access-token", scopes: [] }, + people: [{ _tag: "person", orgId, personId: owner }], + connection: Option.fromUndefinedOr(connection), +}); +const phone = caller("sess-phone", "phone", { remoteAddress: "192.168.1.20", headers: {} }); +const desktop = caller("sess-desktop", "desktop-bootstrap", loopback); + +const seed = Effect.gen(function* () { + yield* TestClock.setTime(NOW); + const sql = yield* SqlClient.SqlClient; + yield* sql`INSERT INTO kin_orgs (org_id, name, created_at) + VALUES ('org_01', 'Kin', '2026-11-07T00:00:00.000Z')`; + for (const [id, subject, ip] of [ + ["sess-phone", "phone", "192.168.1.20"], + ["sess-desktop", "desktop-bootstrap", "127.0.0.1"], + ["sess-desktop-remote", "desktop-bootstrap", "100.101.102.103"], + // A browser, or a tunnel's local process, on the Kin host itself. + ["sess-local-browser", "browser", "127.0.0.1"], + ] as const) { + yield* sql`INSERT INTO auth_sessions (session_id, subject, scopes, method, client_ip_address, + issued_at, expires_at) + VALUES (${id}, ${subject}, '[]', 'bearer-access-token', ${ip}, + '2026-11-07T00:00:00.000Z', '2026-12-07T00:00:00.000Z')`; + } + return { keys: yield* ApproverKeys, actions: yield* KinPendingActions, sql }; +}); + +const registerAndroid = ( + keys: ApproverKeys["Service"], + from: KinKeyCaller = phone, + spec: Partial[1]> = {}, +) => + Effect.gen(function* () { + const { challenge } = yield* keys.keyChallenge(from); + const bytes = new Uint8Array(Buffer.from(challenge, "base64url")); + const chain = androidChain(fixture, { challenge: bytes, ...spec }); + const input = { + orgId, + publicJwk: chain.publicJwk, + platform: "android", + challenge, + attestation: { format: "android-key", certificateChain: chain.certificateChain }, + deviceLabel: "Pixel 9", + } satisfies KinApprovalsRegisterKeyInput; + return { ...(yield* keys.registerKey(from, input)), input }; + }); + +const reasonOf = (exit: Exit.Exit) => + Exit.isFailure(exit) && exit.cause.reasons[0]?._tag === "Fail" + ? (exit.cause.reasons[0].error as KinApprovalError).reason + : "success"; + +const mergeRequest = (source: string) => + ({ + orgId: "org_01", + kind: "merge_pull_request", + target: { + _tag: "pull_request", + host: "github.com", + repo: "GLDRoger/t3code", + number: 212, + mergeMethod: "squash", + deleteBranchAfter: false, + }, + resolved: { + _tag: "pull_request", + headSha: "a".repeat(40), + base: "main", + head: "kin/fix-212", + title: "Fix 212", + additions: 3, + deletions: 1, + files: 1, + checks: [], + }, + targetDigest: "1".repeat(64), + reason: "CI is green.", + requestedBy: { agentId: "lead", threadId: "thread-lead" }, + provenance: { startedBy: "github", startedByRole: "none", chain: [] }, + source: decodeEventId(source), + }) as unknown as KinPendingActionCreateInput; + +const approveWith = ( + actions: KinPendingActions["Service"], + action: KinPendingAction, + thumbprint: KinPendingAction["targetDigest"], + jti: string, +) => + actions.approve({ + orgId: action.orgId, + actionId: action.id, + revision: action.revision, + nonce: action.nonce, + jti, + approverHumanId: owner, + keyThumbprint: thumbprint as never, + compact: `compact-${jti}`, + iat: NOW / 1000, + exp: NOW / 1000 + 600, + }); + +const confirmFirst = (keys: ApproverKeys["Service"]) => + Effect.gen(function* () { + const registered = yield* registerAndroid(keys); + yield* keys.confirmKey(desktop, { + orgId, + thumbprint: registered.key.thumbprint, + code: registered.code, + }); + return registered; + }); + +describe("ApproverKeys", () => { + it.effect("the first approver key can't be confirmed from a remote session", () => + Effect.gen(function* () { + const { keys } = yield* seed; + const { key, code } = yield* registerAndroid(keys); + assert.strictEqual(key.state, "pending"); + assert.strictEqual(key.hardware, "strongbox"); + assert.isTrue(key.attested); + const input = { orgId, thumbprint: key.thumbprint, code }; + const remote: ReadonlyArray = [ + phone, + caller("sess-phone", "phone", loopback), + caller("sess-local-browser", "browser", loopback), + caller("sess-desktop", "desktop-bootstrap", { remoteAddress: "100.64.0.9", headers: {} }), + caller("sess-desktop", "desktop-bootstrap", { + remoteAddress: "127.0.0.1", + headers: { "x-forwarded-for": "100.64.0.9" }, + }), + caller("sess-desktop", "desktop-bootstrap", { + remoteAddress: "127.0.0.1", + headers: { "tailscale-user-login": "someone@example.com" }, + }), + caller("sess-desktop", "desktop-bootstrap"), + caller("sess-desktop-remote", "desktop-bootstrap", loopback), + ]; + for (const from of remote) { + assert.strictEqual(reasonOf(yield* Effect.exit(keys.confirmKey(from, input))), "not_local"); + } + const wrong = code === "000000" ? "000001" : "000000"; + assert.strictEqual( + reasonOf(yield* Effect.exit(keys.confirmKey(desktop, { ...input, code: wrong }))), + "bad_code", + ); + const confirmed = yield* keys.confirmKey(desktop, input); + assert.strictEqual(confirmed.state, "active"); + assert.deepStrictEqual(yield* keys.requireActive(key), confirmed); + }).pipe(Effect.provide(layer)), + ); + + it.effect( + "a grant signed by a revoked key is rejected, and revoking voids approved actions it signed", + () => + Effect.gen(function* () { + const { keys, actions } = yield* seed; + const { key } = yield* confirmFirst(keys); + const signed = (yield* actions.create(mergeRequest("evt-1"))).action; + const waiting = (yield* actions.create(mergeRequest("evt-2"))).action; + assert.strictEqual( + (yield* approveWith(actions, signed, key.thumbprint, "jti-1"))._tag, + "approved", + ); + + const revoked = yield* keys.revokeKey(phone, key); + assert.strictEqual(revoked.state, "revoked"); + assert.strictEqual(reasonOf(yield* Effect.exit(keys.requireActive(key))), "revoked_key"); + const voided = yield* actions.get({ orgId, actionId: signed.id }); + assert.strictEqual(Option.getOrThrow(voided).state, "voided"); + assert.strictEqual(Option.getOrThrow(voided).stateReason, "key_revoked"); + const untouched = yield* actions.get({ orgId, actionId: waiting.id }); + assert.strictEqual(Option.getOrThrow(untouched).state, "awaiting_approval"); + // Revoking is idempotent and never brings a key back. + assert.strictEqual((yield* keys.revokeKey(phone, key)).state, "revoked"); + }).pipe(Effect.provide(layer)), + ); + + it.effect("revoking the T3 session a key was registered from revokes the key", () => + Effect.gen(function* () { + const { keys, actions, sql } = yield* seed; + const { key } = yield* confirmFirst(keys); + const signed = (yield* actions.create(mergeRequest("evt-1"))).action; + yield* approveWith(actions, signed, key.thumbprint, "jti-1"); + yield* sql`UPDATE auth_sessions SET revoked_at = '2026-11-08T00:00:00.000Z' + WHERE session_id = 'sess-phone'`; + + assert.strictEqual(reasonOf(yield* Effect.exit(keys.requireActive(key))), "revoked_key"); + const { keys: listed } = yield* keys.listKeys(desktop, { orgId }); + assert.deepStrictEqual( + listed.map((listedKey) => listedKey.state), + ["revoked"], + ); + const voided = Option.getOrThrow(yield* actions.get({ orgId, actionId: signed.id })); + assert.strictEqual(voided.stateReason, "session_revoked"); + }).pipe(Effect.provide(layer)), + ); + + it.effect("the server never activates an unattested key", () => + Effect.gen(function* () { + const { keys } = yield* seed; + const { challenge } = yield* keys.keyChallenge(phone); + const ios = yield* keys.registerKey(phone, { + orgId, + publicJwk: androidChain(fixture, { challenge: new Uint8Array(32) }).publicJwk, + platform: "ios", + challenge, + deviceLabel: "iPhone", + }); + assert.strictEqual(ios.key.attested, false); + assert.strictEqual(ios.key.hardware, "software"); + const failed = yield* registerAndroid(keys, phone, { deviceLocked: false }); + assert.strictEqual(failed.key.attested, false); + for (const { key, code } of [ios, failed]) { + const exit = yield* Effect.exit( + keys.confirmKey(desktop, { orgId, thumbprint: key.thumbprint, code }), + ); + assert.strictEqual(reasonOf(exit), "unattested"); + assert.isFalse(yield* keys.activateByGrant(key)); + } + }).pipe(Effect.provide(layer)), + ); + + it.effect("a key challenge is single-use, bound to its session and expires in 5 minutes", () => + Effect.gen(function* () { + const { keys } = yield* seed; + const { challenge } = yield* keys.keyChallenge(desktop); + const other = yield* Effect.exit(registerAndroidWith(keys, phone, challenge)); + assert.strictEqual(reasonOf(other), "bad_challenge"); + + const first = yield* keys.keyChallenge(phone); + yield* registerAndroidWith(keys, phone, first.challenge); + const reused = yield* Effect.exit(registerAndroidWith(keys, phone, first.challenge)); + assert.strictEqual(reasonOf(reused), "bad_challenge"); + + const late = yield* keys.keyChallenge(phone); + yield* TestClock.adjust("5 minutes"); + const expired = yield* Effect.exit(registerAndroidWith(keys, phone, late.challenge)); + assert.strictEqual(reasonOf(expired), "bad_challenge"); + }).pipe(Effect.provide(layer)), + ); + + it.effect("five wrong codes end the confirmation", () => + Effect.gen(function* () { + const { keys } = yield* seed; + const { key, code, input } = yield* registerAndroid(keys); + assert.strictEqual( + code, + kinKeyConfirmationCode( + key.thumbprint, + new Uint8Array(Buffer.from(input.challenge, "base64url")), + ), + ); + const wrong = code === "000000" ? "000001" : "000000"; + for (let attempt = 0; attempt < 5; attempt++) { + yield* Effect.exit( + keys.confirmKey(desktop, { orgId, thumbprint: key.thumbprint, code: wrong }), + ); + } + const exit = yield* Effect.exit( + keys.confirmKey(desktop, { orgId, thumbprint: key.thumbprint, code }), + ); + assert.strictEqual(reasonOf(exit), "bad_code"); + }).pipe(Effect.provide(layer)), + ); + + it.effect("a later key needs a register_approver_key grant from an active key", () => + Effect.gen(function* () { + const { keys, actions, sql } = yield* seed; + const first = yield* confirmFirst(keys); + const second = yield* registerAndroid(keys, phone, { attestationLevel: 1, keyMintLevel: 1 }); + const desktopConfirm = yield* Effect.exit( + keys.confirmKey(desktop, { orgId, thumbprint: second.key.thumbprint, code: second.code }), + ); + assert.strictEqual(reasonOf(desktopConfirm), "invalid_state"); + + const [row] = yield* sql<{ action_id: string }>`SELECT action_id FROM kin_pending_actions + WHERE kind = 'register_approver_key' AND state = 'awaiting_approval'`; + const action = Option.getOrThrow( + yield* actions.get({ orgId, actionId: row!.action_id as KinPendingAction["id"] }), + ); + assert.deepStrictEqual(action.target, { + _tag: "device_key", + thumbprint: second.key.thumbprint, + hardware: "tee", + attested: true, + }); + assert.deepStrictEqual(action.provenance.startedBy, { humanId: owner }); + + const approved = yield* approveWith(actions, action, first.key.thumbprint, "jti-key"); + assert.strictEqual(approved._tag, "approved"); + if (approved._tag !== "approved") return; + const handler = yield* makeRegisterApproverKeyHandler; + assert.strictEqual(yield* handler.reconcile(action), "not_done"); + assert.strictEqual(yield* handler.run(action, approved.grant), "succeeded"); + assert.strictEqual(yield* handler.reconcile(action), "done"); + assert.strictEqual((yield* keys.requireActive(second.key)).state, "active"); + // A second run finds nothing pending. + assert.isTrue(Exit.isFailure(yield* Effect.exit(handler.run(action, approved.grant)))); + + const third = yield* registerAndroid(keys); + yield* keys.revokeKey(phone, third.key); + const [cancelled] = yield* sql<{ state: string }>`SELECT state FROM kin_pending_actions + WHERE kind = 'register_approver_key' + AND json_extract(target_json, '$.thumbprint') = ${third.key.thumbprint}`; + assert.strictEqual(cancelled?.state, "cancelled"); + }).pipe(Effect.provide(layer)), + ); +}); + +function registerAndroidWith(keys: ApproverKeys["Service"], from: KinKeyCaller, challenge: string) { + const chain = androidChain(fixture, { + challenge: new Uint8Array(Buffer.from(challenge, "base64url")), + }); + return keys.registerKey(from, { + orgId, + publicJwk: chain.publicJwk, + platform: "android", + challenge, + attestation: { format: "android-key", certificateChain: chain.certificateChain }, + deviceLabel: "Pixel 9", + }); +} diff --git a/apps/server/src/kin/approvals/ApproverKeys.ts b/apps/server/src/kin/approvals/ApproverKeys.ts new file mode 100644 index 0000000000000..3a626255e2b62 --- /dev/null +++ b/apps/server/src/kin/approvals/ApproverKeys.ts @@ -0,0 +1,520 @@ +// @effect-diagnostics nodeBuiltinImport:off -- synchronous SHA-256 and constant-time compares. +import * as NodeCrypto from "node:crypto"; + +import { + KinActionTarget, + KinAgentId, + KinApprovalError, + KinApproverKey, + KinEventId, + ThreadId, + type AuthSessionId, + type Hex64, + type KinActionKind, + type KinApprovalsConfirmKeyInput, + type KinApprovalsKeyChallengeResult, + type KinApprovalsKeyInput, + type KinApprovalsListKeysResult, + type KinApprovalsOrgInput, + type KinApprovalsRegisterKeyInput, + type KinApprovalsRegisterKeyResult, + type KinKeyThumbprint, + type KinOrgId, +} from "@t3tools/contracts"; +import { computeDpopJwkThumbprint } from "@t3tools/shared/dpop"; +import { isLocalLoopbackHost } from "@t3tools/shared/hostClassification"; +import { stableStringify } from "@t3tools/shared/relaySigning"; +import * as Clock from "effect/Clock"; +import * as Context from "effect/Context"; +import * as DateTime from "effect/DateTime"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; +import * as Option from "effect/Option"; +import * as Schema from "effect/Schema"; +import * as SecureRandom from "effect/crypto/SecureRandom"; +import * as Base64Url from "effect/encoding/Base64Url"; +import * as SqlClient from "effect/sql/SqlClient"; + +import type { AuthenticatedSession } from "../../auth/EnvironmentAuth.ts"; +import type { PersonIdentity } from "../chat/KinIdentity.ts"; +import { KinAttestationTrust } from "./attestation/AttestationTrust.ts"; +import { + verifyAndroidKeyAttestation, + verifyAppleAppAttest, + type AttestationResult, +} from "./attestation/verify.ts"; +import { KinPendingActions } from "./PendingActions.ts"; + +const CHALLENGE_TTL_MS = 5 * 60 * 1000; +const CONFIRM_TTL_MS = 10 * 60 * 1000; +const MAX_CODE_ATTEMPTS = 5; +// The desktop app's own credential; CloudLink trusts the same subject as "this machine". +const DESKTOP_SUBJECT = "desktop-bootstrap"; +const FORWARDING_HEADERS = [ + "forwarded", + "x-forwarded-for", + "x-forwarded-host", + "x-forwarded-proto", + "x-real-ip", + "cf-connecting-ip", + "tailscale-user-login", +]; + +/** The live socket a call arrived on, read when the WS connection was set up. */ +export type KinKeyConnection = { + readonly remoteAddress: string | undefined; + readonly headers: Readonly>; +}; + +export type KinKeyCaller = { + readonly session: AuthenticatedSession; + readonly people: ReadonlyArray; + readonly connection: Option.Option; +}; + +type KeyRef = { readonly orgId: KinOrgId; readonly thumbprint: KinKeyThumbprint }; + +type KeyRow = { + readonly thumbprint: string; + readonly org_id: string; + readonly public_jwk_json: string; + readonly human_id: string; + readonly device_label: string; + readonly platform: string; + readonly hardware: string; + readonly attested: number; + readonly session_id: string | null; + readonly state: string; + readonly created_at: number; + readonly confirmed_at: number | null; + readonly revoked_at: number | null; +}; + +const iso = (ms: number) => DateTime.formatIso(DateTime.makeUnsafe(ms)); +const decodeKey = Schema.decodeUnknownEffect(KinApproverKey); +const decodeEventId = Schema.decodeEffect(KinEventId); +const decodeTarget = Schema.decodeUnknownEffect(KinActionTarget); +const isKinApprovalError = Schema.is(KinApprovalError); + +// Not an agent: the phone asked for this action, and the approver signs it on an existing key. +const SERVER_REQUESTER = { + agentId: Schema.decodeSync(KinAgentId)("kin-approver-keys"), + threadId: Schema.decodeSync(ThreadId)("kin-approver-keys"), +}; + +const fail = (reason: KinApprovalError["reason"], message: string) => + Effect.fail(new KinApprovalError({ reason, message })); + +const sameBytes = (a: string, b: string) => { + const left = Buffer.from(a); + const right = Buffer.from(b); + return left.length === right.length && NodeCrypto.timingSafeEqual(left, right); +}; + +/** Spec section 4: six digits from `sha256(thumbprint ‖ serverNonce)`; the nonce is the challenge. */ +export const kinKeyConfirmationCode = (thumbprint: string, challenge: Uint8Array) => { + const digest = NodeCrypto.createHash("sha256").update(thumbprint).update(challenge).digest(); + return String(digest.readUInt32BE(0) % 1_000_000).padStart(6, "0"); +}; + +/** `sha256(stableStringify({kind, target, headSha?, base?}))`, approvals spec section 3. */ +const kinTargetDigest = (kind: KinActionKind, target: KinActionTarget): Hex64 => + NodeCrypto.createHash("sha256").update(stableStringify({ kind, target })).digest("hex"); + +const toKey = (row: KeyRow) => + decodeKey({ + orgId: row.org_id, + thumbprint: row.thumbprint, + publicJwk: JSON.parse(row.public_jwk_json), + humanId: row.human_id, + deviceLabel: row.device_label, + platform: row.platform, + hardware: row.hardware, + attested: row.attested === 1, + ...(row.session_id === null ? {} : { sessionId: row.session_id }), + state: row.state, + createdAt: iso(row.created_at), + ...(row.confirmed_at === null ? {} : { confirmedAt: iso(row.confirmed_at) }), + ...(row.revoked_at === null ? {} : { revokedAt: iso(row.revoked_at) }), + }); + +/** Only `ws` connections from this machine with no proxy in between. */ +const isLoopbackConnection = (connection: KinKeyConnection) => + connection.remoteAddress !== undefined && + isLocalLoopbackHost(connection.remoteAddress.replace(/^::ffff:/i, "")) && + FORWARDING_HEADERS.every((name) => connection.headers[name] === undefined); + +export class ApproverKeys extends Context.Service< + ApproverKeys, + { + readonly keyChallenge: ( + caller: KinKeyCaller, + ) => Effect.Effect; + readonly registerKey: ( + caller: KinKeyCaller, + input: KinApprovalsRegisterKeyInput, + ) => Effect.Effect; + /** The first key in an org, on the desktop app on this machine, with the phone's code. */ + readonly confirmKey: ( + caller: KinKeyCaller, + input: KinApprovalsConfirmKeyInput, + ) => Effect.Effect; + readonly listKeys: ( + caller: KinKeyCaller, + input: KinApprovalsOrgInput, + ) => Effect.Effect; + readonly revokeKey: ( + caller: KinKeyCaller, + input: KinApprovalsKeyInput, + ) => Effect.Effect; + /** What grant verification and the executor trust: the key, after session revocations. */ + readonly get: (ref: KeyRef) => Effect.Effect, KinApprovalError>; + /** Grant check 2: an `active` key in the org, else `unknown_key` or `revoked_key`. */ + readonly requireActive: (ref: KeyRef) => Effect.Effect; + /** The `register_approver_key` handler's step, only after a verified grant. */ + readonly activateByGrant: (ref: KeyRef) => Effect.Effect; + /** Revokes keys whose T3 session was revoked. Returns how many. */ + readonly reconcileSessions: () => Effect.Effect; + } +>()("t3/kin/approvals/ApproverKeys") {} + +const make = Effect.gen(function* () { + const sql = yield* SqlClient.SqlClient; + const trust = yield* KinAttestationTrust; + const actions = yield* KinPendingActions; + // Single-use, session-bound, short-lived: memory is enough, and a restart only means retrying. + const challenges = new Map< + AuthSessionId, + { readonly challenge: string; readonly expiresAt: number } + >(); + const confirmations = new Map< + string, + { readonly code: string; readonly expiresAt: number; attempts: number } + >(); + const slot = (ref: KeyRef) => `${ref.orgId}\u0000${ref.thumbprint}`; + + const internal = (operation: string) => (cause: unknown) => + isKinApprovalError(cause) + ? cause + : new KinApprovalError({ reason: "unavailable", message: `${operation} failed.` }); + + const personIn = (caller: KinKeyCaller, orgId: KinOrgId) => { + const person = caller.people.find((candidate) => candidate.orgId === orgId); + return person === undefined + ? fail("not_owner", "Only a person in this org can manage its approver keys.") + : Effect.succeed(person); + }; + + const select = (ref: KeyRef) => + sql`SELECT * FROM kin_approver_keys + WHERE org_id = ${ref.orgId} AND thumbprint = ${ref.thumbprint}`.pipe( + Effect.map((rows) => rows[0]), + ); + + const hasActiveKey = (orgId: KinOrgId) => + sql`SELECT 1 FROM kin_approver_keys WHERE org_id = ${orgId} AND state = 'active' LIMIT 1`.pipe( + Effect.map((rows) => rows.length > 0), + ); + + /** Sets `revoked`, voids approved actions this key signed, cancels its pending registration. */ + const revokeRow = (ref: KeyRef, reason: string) => + sql.withTransaction( + Effect.gen(function* () { + const now = yield* Clock.currentTimeMillis; + const [row] = yield* sql`UPDATE kin_approver_keys + SET state = 'revoked', revoked_at = ${now} + WHERE org_id = ${ref.orgId} AND thumbprint = ${ref.thumbprint} AND state != 'revoked' + RETURNING *`; + if (row === undefined) return undefined; + yield* sql`UPDATE kin_pending_actions + SET state = 'voided', state_reason = ${reason}, updated_at = ${now} + WHERE org_id = ${ref.orgId} AND state = 'approved' AND EXISTS ( + SELECT 1 FROM kin_grants g + WHERE g.action_id = kin_pending_actions.action_id + AND g.revision = kin_pending_actions.revision + AND g.key_thumbprint = ${ref.thumbprint} AND g.consumed_at IS NULL)`; + yield* sql`UPDATE kin_pending_actions + SET state = 'cancelled', state_reason = ${reason}, updated_at = ${now} + WHERE org_id = ${ref.orgId} AND kind = 'register_approver_key' + AND state = 'awaiting_approval' + AND json_extract(target_json, '$.thumbprint') = ${ref.thumbprint}`; + confirmations.delete(slot(ref)); + return row; + }), + ); + + // T3 revokes sessions in SessionStore (revokeClient, revokeOtherClients, managed policy). + // Reading its table here keeps auth free of Kin hooks, and runs before every key is trusted. + const reconcileSessions = Effect.fn("ApproverKeys.reconcileSessions")( + function* () { + const rows = yield* sql<{ org_id: KinOrgId; thumbprint: KinKeyThumbprint }>` + SELECT k.org_id, k.thumbprint FROM kin_approver_keys k + JOIN auth_sessions s ON s.session_id = k.session_id + WHERE k.state != 'revoked' AND s.revoked_at IS NOT NULL`; + for (const row of rows) { + yield* revokeRow({ orgId: row.org_id, thumbprint: row.thumbprint }, "session_revoked"); + } + return rows.length; + }, + Effect.mapError(internal("ApproverKeys.reconcileSessions")), + ); + + const keyChallenge = Effect.fn("ApproverKeys.keyChallenge")(function* (caller: KinKeyCaller) { + if (caller.people.length === 0) + return yield* fail("not_owner", "Only a person can register an approver key."); + const now = yield* Clock.currentTimeMillis; + for (const [sessionId, entry] of challenges) { + if (entry.expiresAt <= now) challenges.delete(sessionId); + } + const challenge = Base64Url.encode(SecureRandom.randomBytesUnsafe(32)); + const expiresAt = now + CHALLENGE_TTL_MS; + challenges.set(caller.session.sessionId, { challenge, expiresAt }); + return { challenge, expiresAt: DateTime.makeUnsafe(expiresAt) }; + }); + + const attest = Effect.fn("ApproverKeys.attest")(function* ( + input: KinApprovalsRegisterKeyInput, + challenge: Uint8Array, + ) { + const attestation = input.attestation; + const format = input.platform === "android" ? "android-key" : "apple-app-attest"; + if (attestation === undefined || attestation.format !== format) + return { attested: false, reason: `no ${format} attestation` } satisfies AttestationResult; + const loaded = yield* trust + .load(input.platform) + .pipe( + Effect.mapError( + (error) => new KinApprovalError({ reason: "unavailable", message: error.message }), + ), + ); + const now = yield* Clock.currentTimeMillis; + const common = { challenge, publicJwk: input.publicJwk, trust: loaded, now }; + return attestation.format === "android-key" + ? verifyAndroidKeyAttestation({ ...common, certificateChain: attestation.certificateChain }) + : verifyAppleAppAttest({ + ...common, + keyId: attestation.keyId, + attestationObject: attestation.attestationObject, + }); + }); + + const registerKey = Effect.fn("ApproverKeys.registerKey")( + function* (caller: KinKeyCaller, input: KinApprovalsRegisterKeyInput) { + const person = yield* personIn(caller, input.orgId); + const now = yield* Clock.currentTimeMillis; + const issued = challenges.get(caller.session.sessionId); + challenges.delete(caller.session.sessionId); + if ( + issued === undefined || + issued.expiresAt <= now || + !sameBytes(issued.challenge, input.challenge) + ) + return yield* fail("bad_challenge", "Ask for a new key challenge on this connection."); + const challenge = new Uint8Array(Buffer.from(input.challenge, "base64url")); + yield* reconcileSessions(); + + const thumbprint = computeDpopJwkThumbprint(input.publicJwk) as KinKeyThumbprint; + const ref = { orgId: input.orgId, thumbprint }; + const result = yield* attest(input, challenge); + if (!result.attested) { + yield* Effect.logWarning("Kin approver key isn't attested; it can't be activated.", { + platform: input.platform, + reason: result.reason, + }); + } + const existing = yield* select(ref); + if ( + existing !== undefined && + (existing.state !== "pending" || existing.human_id !== person.personId) + ) + return yield* fail("invalid_state", "This key is already registered."); + const row = { + thumbprint, + org_id: input.orgId, + public_jwk_json: stableStringify(input.publicJwk), + human_id: person.personId, + device_label: input.deviceLabel, + platform: input.platform, + hardware: result.attested ? result.hardware : "software", + attested: result.attested ? 1 : 0, + session_id: caller.session.sessionId, + state: "pending", + created_at: now, + confirmed_at: null, + revoked_at: null, + }; + const key = yield* toKey(row); + yield* sql`INSERT INTO kin_approver_keys ${sql.insert(row)} + ON CONFLICT (org_id, thumbprint) DO UPDATE SET + public_jwk_json = excluded.public_jwk_json, device_label = excluded.device_label, + platform = excluded.platform, hardware = excluded.hardware, attested = excluded.attested, + session_id = excluded.session_id, created_at = excluded.created_at + WHERE kin_approver_keys.state = 'pending'`; + const code = kinKeyConfirmationCode(thumbprint, challenge); + if (!result.attested) return { key, code }; + + confirmations.set(slot(ref), { code, expiresAt: now + CONFIRM_TTL_MS, attempts: 0 }); + if (yield* hasActiveKey(input.orgId)) { + // Later keys need a grant from an existing key (spec section 4, step 3). + const target = yield* decodeTarget({ + _tag: "device_key", + thumbprint, + hardware: result.hardware, + attested: true, + }); + yield* actions.create({ + orgId: input.orgId, + kind: "register_approver_key", + target, + resolved: { _tag: "none" }, + targetDigest: kinTargetDigest("register_approver_key", target), + reason: `Add approver key for "${input.deviceLabel}".`, + requestedBy: SERVER_REQUESTER, + provenance: { + startedBy: { humanId: person.personId }, + startedByRole: "owner", + chain: [{ kind: "approver_key", id: thumbprint, authorRole: "owner" }], + }, + source: yield* decodeEventId(`approver_key:${thumbprint}:${input.challenge}`), + }); + } + return { key, code }; + }, + Effect.mapError(internal("ApproverKeys.registerKey")), + ); + + const isLocalDesktop = Effect.fn("ApproverKeys.isLocalDesktop")(function* (caller: KinKeyCaller) { + if (caller.session.subject !== DESKTOP_SUBJECT) return false; + if (Option.isNone(caller.connection) || !isLoopbackConnection(caller.connection.value)) + return false; + const [issued] = yield* sql<{ client_ip_address: string | null }>` + SELECT client_ip_address FROM auth_sessions + WHERE session_id = ${caller.session.sessionId} AND revoked_at IS NULL`; + return ( + issued?.client_ip_address != null && + isLocalLoopbackHost(issued.client_ip_address.replace(/^::ffff:/i, "")) + ); + }); + + const confirmKey = Effect.fn("ApproverKeys.confirmKey")( + function* (caller: KinKeyCaller, input: KinApprovalsConfirmKeyInput) { + const person = yield* personIn(caller, input.orgId); + if (!(yield* isLocalDesktop(caller))) + return yield* fail( + "not_local", + "Confirm the first approver key in the desktop app on the Kin host.", + ); + yield* reconcileSessions(); + const ref = { orgId: input.orgId, thumbprint: input.thumbprint }; + const row = yield* select(ref); + if (row === undefined) return yield* fail("not_found", "No such approver key."); + if (row.state !== "pending") + return yield* fail("invalid_state", "This key isn't waiting for confirmation."); + if (row.attested !== 1) + return yield* fail( + "unattested", + "This device couldn't prove its key is in secure hardware.", + ); + if (row.human_id !== person.personId) + return yield* fail("not_owner", "Only the key's owner can confirm it."); + if (yield* hasActiveKey(input.orgId)) + return yield* fail("invalid_state", "Approve this key from a device that already has one."); + const now = yield* Clock.currentTimeMillis; + const pending = confirmations.get(slot(ref)); + if (pending === undefined || pending.expiresAt <= now) + return yield* fail("bad_code", "The code expired; register the key again."); + if (!sameBytes(pending.code, input.code)) { + pending.attempts += 1; + if (pending.attempts >= MAX_CODE_ATTEMPTS) confirmations.delete(slot(ref)); + return yield* fail("bad_code", "The code doesn't match the phone."); + } + const [active] = yield* sql`UPDATE kin_approver_keys + SET state = 'active', confirmed_at = ${now} + WHERE org_id = ${ref.orgId} AND thumbprint = ${ref.thumbprint} + AND state = 'pending' AND attested = 1 + AND NOT EXISTS (SELECT 1 FROM kin_approver_keys + WHERE org_id = ${ref.orgId} AND state = 'active') + RETURNING *`; + if (active === undefined) + return yield* fail("invalid_state", "Another key was confirmed first."); + confirmations.delete(slot(ref)); + return yield* toKey(active); + }, + Effect.mapError(internal("ApproverKeys.confirmKey")), + ); + + const listKeys = Effect.fn("ApproverKeys.listKeys")( + function* (caller: KinKeyCaller, input: KinApprovalsOrgInput) { + yield* personIn(caller, input.orgId); + yield* reconcileSessions(); + const rows = yield* sql`SELECT * FROM kin_approver_keys + WHERE org_id = ${input.orgId} ORDER BY created_at, thumbprint`; + return { keys: yield* Effect.forEach(rows, toKey) }; + }, + Effect.mapError(internal("ApproverKeys.listKeys")), + ); + + const revokeKey = Effect.fn("ApproverKeys.revokeKey")( + function* (caller: KinKeyCaller, input: KinApprovalsKeyInput) { + const person = yield* personIn(caller, input.orgId); + const row = yield* select(input); + if (row === undefined) return yield* fail("not_found", "No such approver key."); + if (row.human_id !== person.personId) + return yield* fail("not_owner", "Only the key's owner can revoke it."); + const revoked = yield* revokeRow(input, "key_revoked"); + return yield* toKey(revoked ?? row); + }, + Effect.mapError(internal("ApproverKeys.revokeKey")), + ); + + const get = Effect.fn("ApproverKeys.get")( + function* (ref: KeyRef) { + yield* reconcileSessions(); + const row = yield* select(ref); + return row === undefined ? Option.none() : Option.some(yield* toKey(row)); + }, + Effect.mapError(internal("ApproverKeys.get")), + ); + + const requireActive = Effect.fn("ApproverKeys.requireActive")(function* (ref: KeyRef) { + const key = yield* get(ref); + if (Option.isNone(key) || key.value.state === "pending") + return yield* fail("unknown_key", "No active approver key with this id."); + if (key.value.state === "revoked") + return yield* fail("revoked_key", "This approver key was revoked."); + return key.value; + }); + + const activateByGrant = Effect.fn("ApproverKeys.activateByGrant")( + function* (ref: KeyRef) { + yield* reconcileSessions(); + const now = yield* Clock.currentTimeMillis; + const rows = yield* sql`UPDATE kin_approver_keys + SET state = 'active', confirmed_at = ${now} + WHERE org_id = ${ref.orgId} AND thumbprint = ${ref.thumbprint} + AND state = 'pending' AND attested = 1 + RETURNING thumbprint`; + if (rows.length > 0) confirmations.delete(slot(ref)); + return rows.length > 0; + }, + Effect.mapError(internal("ApproverKeys.activateByGrant")), + ); + + yield* reconcileSessions().pipe( + Effect.catch((error) => Effect.logError("Kin approver key reconciliation failed.", error)), + ); + + return ApproverKeys.of({ + keyChallenge, + registerKey, + confirmKey, + listKeys, + revokeKey, + get, + requireActive, + activateByGrant, + reconcileSessions, + }); +}); + +export const layer = Layer.effect(ApproverKeys, make); diff --git a/apps/server/src/kin/approvals/attestation/AttestationTrust.ts b/apps/server/src/kin/approvals/attestation/AttestationTrust.ts new file mode 100644 index 0000000000000..dc72e2fe9168c --- /dev/null +++ b/apps/server/src/kin/approvals/attestation/AttestationTrust.ts @@ -0,0 +1,110 @@ +// @effect-diagnostics nodeBuiltinImport:off -- X509Certificate for the pinned roots. +import * as NodeCrypto from "node:crypto"; + +import type { KinApproverKeyPlatform } from "@t3tools/contracts"; +import * as Clock from "effect/Clock"; +import * as Config from "effect/Config"; +import * as Context from "effect/Context"; +import * as Duration from "effect/Duration"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; +import * as Option from "effect/Option"; +import * as Ref from "effect/Ref"; +import * as Schema from "effect/Schema"; +import * as HttpClient from "effect/http/HttpClient"; +import * as HttpClientResponse from "effect/http/HttpClientResponse"; + +import { APPLE_APP_ATTEST_ROOT, GOOGLE_HARDWARE_ATTESTATION_ROOTS } from "./roots.ts"; +import type { AttestationTrust } from "./verify.ts"; + +const STATUS_URL = "https://android.googleapis.com/attestation/status"; +const STATUS_TTL = Duration.hours(1); +const StatusList = Schema.Struct({ + entries: Schema.Record(Schema.String, Schema.Struct({ status: Schema.String })), +}); + +export class KinAttestationTrustError extends Schema.TaggedError()( + "KinAttestationTrustError", + { message: Schema.String }, +) {} + +export class KinAttestationTrust extends Context.Service< + KinAttestationTrust, + { + /** Android fails rather than trust a chain it couldn't check for revocation. */ + readonly load: ( + platform: KinApproverKeyPlatform, + ) => Effect.Effect; + } +>()("t3/kin/approvals/attestation/AttestationTrust/KinAttestationTrust") {} + +const hexList = (name: string) => + Config.String(name).pipe( + Config.withDefault(""), + Config.map((value) => + value + .split(",") + .map((entry) => entry.trim().toLowerCase().replaceAll(":", "")) + .filter((entry) => entry.length > 0), + ), + ); + +/** Production trust: pinned roots, the release app identity from config, Google's status list. */ +export const layer = Layer.effect( + KinAttestationTrust, + Effect.gen(function* () { + const config = yield* Config.all({ + androidPackage: Config.String("KIN_ANDROID_PACKAGE").pipe(Config.option), + androidSigners: hexList("KIN_ANDROID_SIGNING_CERT_SHA256"), + appleAppId: Config.String("KIN_IOS_APP_ID").pipe(Config.option), + appleDevelopment: Config.Boolean("KIN_IOS_APP_ATTEST_DEVELOPMENT").pipe( + Config.withDefault(false), + ), + }); + const http = (yield* HttpClient.HttpClient).pipe(HttpClient.filterStatusOk); + const cache = yield* Ref.make(Option.none<{ at: number; serials: ReadonlySet }>()); + const fixed = { + googleRoots: GOOGLE_HARDWARE_ATTESTATION_ROOTS.map( + (pem) => new NodeCrypto.X509Certificate(pem), + ), + appleRoot: new NodeCrypto.X509Certificate(APPLE_APP_ATTEST_ROOT), + androidApps: Option.isSome(config.androidPackage) + ? [{ packageName: config.androidPackage.value, signingCertSha256: config.androidSigners }] + : [], + appleAppIds: Option.isSome(config.appleAppId) ? [config.appleAppId.value] : [], + appleEnvironments: config.appleDevelopment + ? (["production", "development"] as const) + : (["production"] as const), + }; + const revoked = Effect.gen(function* () { + const now = yield* Clock.currentTimeMillis; + const cached = yield* Ref.get(cache); + if (Option.isSome(cached) && now - cached.value.at < Duration.toMillis(STATUS_TTL)) + return cached.value.serials; + const list = yield* http + .get(STATUS_URL) + .pipe(Effect.flatMap(HttpClientResponse.schemaBodyJson(StatusList)), Effect.scoped); + const serials = new Set( + Object.entries(list.entries) + .filter(([, entry]) => entry.status === "REVOKED" || entry.status === "SUSPENDED") + .map(([serial]) => serial.toLowerCase().replace(/^0+(?=.)/, "")), + ); + yield* Ref.set(cache, Option.some({ at: now, serials })); + return serials as ReadonlySet; + }).pipe( + Effect.timeout(Duration.seconds(10)), + Effect.mapError( + () => + new KinAttestationTrustError({ + message: "Couldn't load Google's attestation revocation list.", + }), + ), + ); + return KinAttestationTrust.of({ + load: Effect.fn("KinAttestationTrust.load")(function* (platform: KinApproverKeyPlatform) { + const androidRevokedSerials = platform === "ios" ? new Set() : yield* revoked; + return { ...fixed, androidRevokedSerials }; + }), + }); + }), +); diff --git a/apps/server/src/kin/approvals/attestation/der.ts b/apps/server/src/kin/approvals/attestation/der.ts new file mode 100644 index 0000000000000..1c9fc0c21628a --- /dev/null +++ b/apps/server/src/kin/approvals/attestation/der.ts @@ -0,0 +1,159 @@ +// @effect-diagnostics extendsNativeError:off -- thrown and caught inside the pure parsers only. +/** + * A strict DER reader for the few structures attestation needs. Node's X509Certificate verifies + * signatures but doesn't expose extensions. Anything not canonical DER throws. + */ +export class DerError extends Error {} + +export type Tlv = { + /** 0 universal, 1 application, 2 context, 3 private. */ + readonly cls: number; + readonly constructed: boolean; + readonly tag: number; + readonly value: Uint8Array; + /** The whole element, header included. */ + readonly raw: Uint8Array; +}; + +const UNIVERSAL = 0; +export const CONTEXT = 2; +const T_BOOLEAN = 1; +const T_INTEGER = 2; +const T_OCTET_STRING = 4; +const T_OID = 6; +const T_ENUMERATED = 10; +const T_SEQUENCE = 16; +export const T_SET = 17; + +const fail = (message: string): never => { + throw new DerError(message); +}; + +function readOne(bytes: Uint8Array, start: number): { tlv: Tlv; end: number } { + let offset = start; + const next = () => (offset < bytes.length ? bytes[offset++]! : fail("truncated DER")); + const first = next(); + const cls = first >> 6; + const constructed = (first & 0x20) !== 0; + let tag = first & 0x1f; + if (tag === 0x1f) { + tag = 0; + let byte = next(); + if (byte === 0x80) fail("non-minimal tag"); + for (;;) { + tag = tag * 128 + (byte & 0x7f); + if (tag > 0xffff) fail("tag too large"); + if ((byte & 0x80) === 0) break; + byte = next(); + } + if (tag < 0x1f) fail("non-minimal tag"); + } + const lengthByte = next(); + let length = lengthByte; + if (lengthByte === 0x80) fail("indefinite length"); + if (lengthByte > 0x80) { + const count = lengthByte & 0x7f; + if (count > 4) fail("length too large"); + length = 0; + for (let i = 0; i < count; i++) length = length * 256 + next(); + if (length < 0x80 || (count > 1 && length < 256 ** (count - 1))) fail("non-minimal length"); + } + const end = offset + length; + if (end > bytes.length) fail("truncated DER"); + return { + tlv: { + cls, + constructed, + tag, + value: bytes.subarray(offset, end), + raw: bytes.subarray(start, end), + }, + end, + }; +} + +/** Exactly one element filling `bytes`. */ +export function parse(bytes: Uint8Array): Tlv { + const { tlv, end } = readOne(bytes, 0); + if (end !== bytes.length) fail("trailing bytes after DER"); + return tlv; +} + +export function children(tlv: Tlv): ReadonlyArray { + if (!tlv.constructed) fail("expected a constructed element"); + const out: Tlv[] = []; + let offset = 0; + while (offset < tlv.value.length) { + const { tlv: child, end } = readOne(tlv.value, offset); + out.push(child); + offset = end; + } + return out; +} + +export function expect(tlv: Tlv | undefined, tag: number, cls = UNIVERSAL): Tlv { + if (tlv === undefined) return fail(`missing element with tag ${tag}`); + if (tlv.cls !== cls || tlv.tag !== tag) + fail(`expected tag ${cls}:${tag}, got ${tlv.cls}:${tlv.tag}`); + return tlv; +} + +export function sequence(tlv: Tlv | undefined): ReadonlyArray { + return children(expect(tlv, T_SEQUENCE)); +} + +/** INTEGER or ENUMERATED as a safe non-negative number. */ +export function integer(tlv: Tlv | undefined, tag = T_INTEGER): number { + const { value, constructed } = expect(tlv, tag); + if (constructed || value.length === 0) fail("bad integer"); + if (value.length > 1 && value[0] === 0 && (value[1]! & 0x80) === 0) fail("non-minimal integer"); + if (value.length > 1 && value[0] === 0xff && (value[1]! & 0x80) !== 0) + fail("non-minimal integer"); + if ((value[0]! & 0x80) !== 0) fail("negative integer"); + let n = 0; + for (const byte of value) n = n * 256 + byte; + if (!Number.isSafeInteger(n)) fail("integer too large"); + return n; +} + +export function enumerated(tlv: Tlv | undefined): number { + return integer(tlv, T_ENUMERATED); +} + +export function octets(tlv: Tlv | undefined): Uint8Array { + const element = expect(tlv, T_OCTET_STRING); + if (element.constructed) fail("constructed octet string"); + return element.value; +} + +export function boolean(tlv: Tlv | undefined): boolean { + const { value } = expect(tlv, T_BOOLEAN); + if (value.length !== 1 || (value[0] !== 0 && value[0] !== 0xff)) fail("bad boolean"); + return value[0] === 0xff; +} + +/** An OID's content bytes in hex, for comparison with constants. */ +function oidHex(tlv: Tlv | undefined): string { + return Buffer.from(expect(tlv, T_OID).value).toString("hex"); +} + +export type Extension = { readonly critical: boolean; readonly value: Uint8Array }; + +/** `tbsCertificate.extensions` keyed by OID content hex. Duplicate OIDs throw. */ +export function certificateExtensions(certificateDer: Uint8Array): ReadonlyMap { + const [tbs] = sequence(parse(certificateDer)); + const fields = sequence(tbs); + const wrapper = fields.find((field) => field.cls === CONTEXT && field.tag === 3); + const out = new Map(); + if (wrapper === undefined) return out; + const [list] = children(wrapper); + for (const extension of sequence(list)) { + const parts = sequence(extension); + const oid = oidHex(parts[0]); + const critical = parts.length === 3 ? boolean(parts[1]) : false; + if (parts.length !== 2 && parts.length !== 3) fail("bad extension"); + if (out.has(oid)) fail("duplicate extension"); + out.set(oid, { critical, value: octets(parts[parts.length - 1]) }); + } + return out; +} diff --git a/apps/server/src/kin/approvals/attestation/roots.ts b/apps/server/src/kin/approvals/attestation/roots.ts new file mode 100644 index 0000000000000..a10258c2fe858 --- /dev/null +++ b/apps/server/src/kin/approvals/attestation/roots.ts @@ -0,0 +1,64 @@ +// Fetched 2026-11-08 from https://android.googleapis.com/attestation/root and +// https://www.apple.com/certificateauthority/Apple_App_Attestation_Root_CA.pem. SHA-256: Google RSA +// CE:DB:1C:B6…80:0D:FC, Google EC (Key Attestation CA1) 6D:9D:B4:CE…A4:BC:C0, Apple 1C:B9:82:3B…C9:32. +export const GOOGLE_HARDWARE_ATTESTATION_ROOTS = [ + `-----BEGIN CERTIFICATE----- +MIIFHDCCAwSgAwIBAgIJAPHBcqaZ6vUdMA0GCSqGSIb3DQEBCwUAMBsxGTAXBgNV +BAUTEGY5MjAwOWU4NTNiNmIwNDUwHhcNMjIwMzIwMTgwNzQ4WhcNNDIwMzE1MTgw +NzQ4WjAbMRkwFwYDVQQFExBmOTIwMDllODUzYjZiMDQ1MIICIjANBgkqhkiG9w0B +AQEFAAOCAg8AMIICCgKCAgEAr7bHgiuxpwHsK7Qui8xUFmOr75gvMsd/dTEDDJdS +Sxtf6An7xyqpRR90PL2abxM1dEqlXnf2tqw1Ne4Xwl5jlRfdnJLmN0pTy/4lj4/7 +tv0Sk3iiKkypnEUtR6WfMgH0QZfKHM1+di+y9TFRtv6y//0rb+T+W8a9nsNL/ggj +nar86461qO0rOs2cXjp3kOG1FEJ5MVmFmBGtnrKpa73XpXyTqRxB/M0n1n/W9nGq +C4FSYa04T6N5RIZGBN2z2MT5IKGbFlbC8UrW0DxW7AYImQQcHtGl/m00QLVWutHQ +oVJYnFPlXTcHYvASLu+RhhsbDmxMgJJ0mcDpvsC4PjvB+TxywElgS70vE0XmLD+O +JtvsBslHZvPBKCOdT0MS+tgSOIfga+z1Z1g7+DVagf7quvmag8jfPioyKvxnK/Eg +sTUVi2ghzq8wm27ud/mIM7AY2qEORR8Go3TVB4HzWQgpZrt3i5MIlCaY504LzSRi +igHCzAPlHws+W0rB5N+er5/2pJKnfBSDiCiFAVtCLOZ7gLiMm0jhO2B6tUXHI/+M +RPjy02i59lINMRRev56GKtcd9qO/0kUJWdZTdA2XoS82ixPvZtXQpUpuL12ab+9E +aDK8Z4RHJYYfCT3Q5vNAXaiWQ+8PTWm2QgBR/bkwSWc+NpUFgNPN9PvQi8WEg5Um +AGMCAwEAAaNjMGEwHQYDVR0OBBYEFDZh4QB8iAUJUYtEbEf/GkzJ6k8SMB8GA1Ud +IwQYMBaAFDZh4QB8iAUJUYtEbEf/GkzJ6k8SMA8GA1UdEwEB/wQFMAMBAf8wDgYD +VR0PAQH/BAQDAgIEMA0GCSqGSIb3DQEBCwUAA4ICAQB8cMqTllHc8U+qCrOlg3H7 +174lmaCsbo/bJ0C17JEgMLb4kvrqsXZs01U3mB/qABg/1t5Pd5AORHARs1hhqGIC +W/nKMav574f9rZN4PC2ZlufGXb7sIdJpGiO9ctRhiLuYuly10JccUZGEHpHSYM2G +tkgYbZba6lsCPYAAP83cyDV+1aOkTf1RCp/lM0PKvmxYN10RYsK631jrleGdcdkx +oSK//mSQbgcWnmAEZrzHoF1/0gso1HZgIn0YLzVhLSA/iXCX4QT2h3J5z3znluKG +1nv8NQdxei2DIIhASWfu804CA96cQKTTlaae2fweqXjdN1/v2nqOhngNyz1361mF +mr4XmaKH/ItTwOe72NI9ZcwS1lVaCvsIkTDCEXdm9rCNPAY10iTunIHFXRh+7KPz +lHGewCq/8TOohBRn0/NNfh7uRslOSZ/xKbN9tMBtw37Z8d2vvnXq/YWdsm1+JLVw +n6yYD/yacNJBlwpddla8eaVMjsF6nBnIgQOf9zKSe06nSTqvgwUHosgOECZJZ1Eu +zbH4yswbt02tKtKEFhx+v+OTge/06V+jGsqTWLsfrOCNLuA8H++z+pUENmpqnnHo +vaI47gC+TNpkgYGkkBT6B/m/U01BuOBBTzhIlMEZq9qkDWuM2cA5kW5V3FJUcfHn +w1IdYIg2Wxg7yHcQZemFQg== +-----END CERTIFICATE-----`, + `-----BEGIN CERTIFICATE----- +MIICIjCCAaigAwIBAgIRAISp0Cl7DrWK5/8OgN52BgUwCgYIKoZIzj0EAwMwUjEc +MBoGA1UEAwwTS2V5IEF0dGVzdGF0aW9uIENBMTEQMA4GA1UECwwHQW5kcm9pZDET +MBEGA1UECgwKR29vZ2xlIExMQzELMAkGA1UEBhMCVVMwHhcNMjUwNzE3MjIzMjE4 +WhcNMzUwNzE1MjIzMjE4WjBSMRwwGgYDVQQDDBNLZXkgQXR0ZXN0YXRpb24gQ0Ex +MRAwDgYDVQQLDAdBbmRyb2lkMRMwEQYDVQQKDApHb29nbGUgTExDMQswCQYDVQQG +EwJVUzB2MBAGByqGSM49AgEGBSuBBAAiA2IABCPaI3FO3z5bBQo8cuiEas4HjqCt +G/mLFfRT0MsIssPBEEU5Cfbt6sH5yOAxqEi5QagpU1yX4HwnGb7OtBYpDTB57uH5 +Eczm34A5FNijV3s0/f0UPl7zbJcTx6xwqMIRq6NCMEAwDwYDVR0TAQH/BAUwAwEB +/zAOBgNVHQ8BAf8EBAMCAQYwHQYDVR0OBBYEFFIyuyz7RkOb3NaBqQ5lZuA0QepA +MAoGCCqGSM49BAMDA2gAMGUCMETfjPO/HwqReR2CS7p0ZWoD/LHs6hDi422opifH +EUaYLxwGlT9SLdjkVpz0UUOR5wIxAIoGyxGKRHVTpqpGRFiJtQEOOTp/+s1GcxeY +uR2zh/80lQyu9vAFCj6E4AXc+osmRg== +-----END CERTIFICATE-----`, +] as const; + +export const APPLE_APP_ATTEST_ROOT = `-----BEGIN CERTIFICATE----- +MIICITCCAaegAwIBAgIQC/O+DvHN0uD7jG5yH2IXmDAKBggqhkjOPQQDAzBSMSYw +JAYDVQQDDB1BcHBsZSBBcHAgQXR0ZXN0YXRpb24gUm9vdCBDQTETMBEGA1UECgwK +QXBwbGUgSW5jLjETMBEGA1UECAwKQ2FsaWZvcm5pYTAeFw0yMDAzMTgxODMyNTNa +Fw00NTAzMTUwMDAwMDBaMFIxJjAkBgNVBAMMHUFwcGxlIEFwcCBBdHRlc3RhdGlv +biBSb290IENBMRMwEQYDVQQKDApBcHBsZSBJbmMuMRMwEQYDVQQIDApDYWxpZm9y +bmlhMHYwEAYHKoZIzj0CAQYFK4EEACIDYgAERTHhmLW07ATaFQIEVwTtT4dyctdh +NbJhFs/Ii2FdCgAHGbpphY3+d8qjuDngIN3WVhQUBHAoMeQ/cLiP1sOUtgjqK9au +Yen1mMEvRq9Sk3Jm5X8U62H+xTD3FE9TgS41o0IwQDAPBgNVHRMBAf8EBTADAQH/ +MB0GA1UdDgQWBBSskRBTM72+aEH/pwyp5frq5eWKoTAOBgNVHQ8BAf8EBAMCAQYw +CgYIKoZIzj0EAwMDaAAwZQIwQgFGnByvsiVbpTKwSga0kP0e8EeDS4+sQmTvb7vn +53O5+FRXgeLhpJ06ysC5PrOyAjEAp5U4xDgEgllF7En3VcE3iexZZtKeYnpqtijV +oyFraWVIyd/dganmrduC1bmTBGwD +-----END CERTIFICATE-----`; diff --git a/apps/server/src/kin/approvals/attestation/testFixtures.ts b/apps/server/src/kin/approvals/attestation/testFixtures.ts new file mode 100644 index 0000000000000..47f6290896759 --- /dev/null +++ b/apps/server/src/kin/approvals/attestation/testFixtures.ts @@ -0,0 +1,367 @@ +// @effect-diagnostics nodeBuiltinImport:off -- test certificates are built and signed with node:crypto. +import * as NodeCrypto from "node:crypto"; + +import type { KinApproverPublicJwk } from "@t3tools/contracts"; + +import type { AttestationTrust } from "./verify.ts"; + +const length = (n: number) => + n < 0x80 + ? [n] + : n < 0x100 + ? [0x81, n] + : n < 0x10000 + ? [0x82, n >> 8, n & 0xff] + : [0x83, n >> 16, (n >> 8) & 0xff, n & 0xff]; +const tlv = (identifier: ReadonlyArray, content: Uint8Array) => + new Uint8Array([...identifier, ...length(content.length), ...content]); +const concat = (parts: ReadonlyArray) => + new Uint8Array(parts.flatMap((part) => [...part])); + +const der = { + seq: (...parts: ReadonlyArray) => tlv([0x30], concat(parts)), + set: (...parts: ReadonlyArray) => tlv([0x31], concat(parts)), + int: (n: number) => { + const bytes: number[] = []; + let rest = n; + do { + bytes.unshift(rest % 256); + rest = Math.floor(rest / 256); + } while (rest > 0); + if (bytes[0]! & 0x80) bytes.unshift(0); + return tlv([0x02], new Uint8Array(bytes)); + }, + serial: (bytes: Uint8Array) => + tlv([0x02], bytes[0]! & 0x80 ? new Uint8Array([0, ...bytes]) : bytes), + enumerated: (n: number) => tlv([0x0a], new Uint8Array([n])), + bool: (value: boolean) => tlv([0x01], new Uint8Array([value ? 0xff : 0])), + null: () => tlv([0x05], new Uint8Array()), + octet: (bytes: Uint8Array) => tlv([0x04], bytes), + utf8: (text: string) => tlv([0x0c], new Uint8Array(Buffer.from(text))), + bits: (bytes: Uint8Array) => tlv([0x03], new Uint8Array([0, ...bytes])), + utcTime: (text: string) => tlv([0x17], new Uint8Array(Buffer.from(text))), + oid: (dotted: string) => { + const [a, b, ...rest] = dotted.split(".").map(Number); + const out = [a! * 40 + b!]; + for (const arc of rest) { + const chunk = [arc & 0x7f]; + let value = arc >> 7; + while (value > 0) { + chunk.unshift((value & 0x7f) | 0x80); + value >>= 7; + } + out.push(...chunk); + } + return tlv([0x06], new Uint8Array(out)); + }, + /** `[tag] EXPLICIT`, high tag numbers included. */ + explicit: (tag: number, inner: Uint8Array) => { + if (tag < 31) return tlv([0xa0 | tag], inner); + const digits = [tag & 0x7f]; + for (let value = tag >> 7; value > 0; value >>= 7) digits.unshift((value & 0x7f) | 0x80); + return tlv([0xbf, ...digits], inner); + }, +}; + +type KeyPair = { + readonly publicKey: NodeCrypto.KeyObject; + readonly privateKey: NodeCrypto.KeyObject; +}; +export const newKey = (): KeyPair => NodeCrypto.generateKeyPairSync("ec", { namedCurve: "P-256" }); + +const name = (cn: string) => der.seq(der.set(der.seq(der.oid("2.5.4.3"), der.utf8(cn)))); +const ECDSA_SHA256 = der.seq(der.oid("1.2.840.10045.4.3.2")); + +export type CertificateSpec = { + readonly subject: string; + readonly issuer: string; + readonly subjectKey: NodeCrypto.KeyObject; + readonly issuerKey: NodeCrypto.KeyObject; + readonly ca?: boolean; + readonly extensions?: ReadonlyArray<{ readonly oid: string; readonly value: Uint8Array }>; + readonly notBefore?: string; + readonly notAfter?: string; + readonly serial?: Uint8Array; +}; + +function certificate(spec: CertificateSpec): Uint8Array { + const extensions = [ + ...(spec.ca + ? [der.seq(der.oid("2.5.29.19"), der.bool(true), der.octet(der.seq(der.bool(true))))] + : []), + ...(spec.extensions ?? []).map((extension) => + der.seq(der.oid(extension.oid), der.octet(extension.value)), + ), + ]; + const tbs = der.seq( + der.explicit(0, der.int(2)), + der.serial(spec.serial ?? new Uint8Array(NodeCrypto.randomBytes(8))), + ECDSA_SHA256, + name(spec.issuer), + der.seq( + der.utcTime(spec.notBefore ?? "250101000000Z"), + der.utcTime(spec.notAfter ?? "400101000000Z"), + ), + name(spec.subject), + new Uint8Array(spec.subjectKey.export({ type: "spki", format: "der" })), + ...(extensions.length > 0 ? [der.explicit(3, der.seq(...extensions))] : []), + ); + const signature = NodeCrypto.sign("sha256", tbs, spec.issuerKey); + return der.seq(tbs, ECDSA_SHA256, der.bits(new Uint8Array(signature))); +} + +const publicJwkOf = (key: NodeCrypto.KeyObject): KinApproverPublicJwk => { + const jwk = key.export({ format: "jwk" }); + return { kty: "EC", crv: "P-256", x: jwk.x!, y: jwk.y! }; +}; +const point = (key: NodeCrypto.KeyObject) => { + const jwk = key.export({ format: "jwk" }); + return new Uint8Array([ + 4, + ...Buffer.from(jwk.x!, "base64url"), + ...Buffer.from(jwk.y!, "base64url"), + ]); +}; +const sha256 = (...parts: ReadonlyArray) => { + const hash = NodeCrypto.createHash("sha256"); + for (const part of parts) hash.update(part); + return new Uint8Array(hash.digest()); +}; +const b64 = (bytes: Uint8Array) => Buffer.from(bytes).toString("base64"); + +const ANDROID_PACKAGE = "com.gldroger.kin"; +const ANDROID_SIGNER = "ab".repeat(32); +const APPLE_APP_ID = "TEAM123456.com.gldroger.kin"; + +export function makeTrustFixture() { + const googleRoot = newKey(); + const appleRoot = newKey(); + const googleRootDer = certificate({ + subject: "Test Google Root", + issuer: "Test Google Root", + subjectKey: googleRoot.publicKey, + issuerKey: googleRoot.privateKey, + ca: true, + }); + const appleRootDer = certificate({ + subject: "Test Apple Root", + issuer: "Test Apple Root", + subjectKey: appleRoot.publicKey, + issuerKey: appleRoot.privateKey, + ca: true, + }); + const trust: AttestationTrust = { + googleRoots: [new NodeCrypto.X509Certificate(googleRootDer)], + androidRevokedSerials: new Set(), + androidApps: [{ packageName: ANDROID_PACKAGE, signingCertSha256: [ANDROID_SIGNER] }], + appleRoot: new NodeCrypto.X509Certificate(appleRootDer), + appleAppIds: [APPLE_APP_ID], + appleEnvironments: ["production"], + }; + return { trust, googleRoot, googleRootDer, appleRoot }; +} +export type TrustFixture = ReturnType; + +export type KeyDescriptionSpec = { + readonly attestationLevel?: number; + readonly keyMintLevel?: number; + readonly challenge: Uint8Array; + readonly purposes?: ReadonlyArray; + readonly algorithm?: number; + readonly ecCurve?: number; + readonly digests?: ReadonlyArray; + readonly userAuthType?: number; + readonly authTimeout?: number; + readonly noAuthRequiredInSoftware?: boolean; + readonly origin?: number; + readonly deviceLocked?: boolean; + readonly bootState?: number; + readonly packages?: ReadonlyArray; + readonly signers?: ReadonlyArray; +}; + +function keyDescription(spec: KeyDescriptionSpec): Uint8Array { + const appId = der.seq( + der.set( + ...(spec.packages ?? [ANDROID_PACKAGE]).map((pkg) => + der.seq(der.octet(new Uint8Array(Buffer.from(pkg))), der.int(7)), + ), + ), + der.set( + ...(spec.signers ?? [ANDROID_SIGNER]).map((hex) => + der.octet(new Uint8Array(Buffer.from(hex, "hex"))), + ), + ), + ); + const software = der.seq( + ...(spec.noAuthRequiredInSoftware ? [der.explicit(503, der.null())] : []), + der.explicit(709, der.octet(appId)), + ); + const hardware = der.seq( + der.explicit(1, der.set(...(spec.purposes ?? [2]).map(der.int))), + der.explicit(2, der.int(spec.algorithm ?? 3)), + der.explicit(3, der.int(256)), + der.explicit(5, der.set(...(spec.digests ?? [4]).map(der.int))), + der.explicit(10, der.int(spec.ecCurve ?? 1)), + der.explicit(504, der.int(spec.userAuthType ?? 2)), + ...(spec.authTimeout === undefined ? [] : [der.explicit(505, der.int(spec.authTimeout))]), + der.explicit(702, der.int(spec.origin ?? 0)), + der.explicit( + 704, + der.seq( + der.octet(new Uint8Array(32)), + der.bool(spec.deviceLocked ?? true), + der.enumerated(spec.bootState ?? 0), + der.octet(new Uint8Array(32)), + ), + ), + ); + return der.seq( + der.int(300), + der.enumerated(spec.attestationLevel ?? 2), + der.int(300), + der.enumerated(spec.keyMintLevel ?? 2), + der.octet(spec.challenge), + der.octet(new Uint8Array()), + software, + hardware, + ); +} + +export type AndroidChainSpec = KeyDescriptionSpec & { + /** The approval key the leaf certifies; a fresh one when omitted. */ + readonly approvalKey?: KeyPair; + readonly descriptionInIntermediate?: boolean; + readonly leafSignedByStranger?: boolean; + readonly leafNotAfter?: string; + readonly leafSerial?: Uint8Array; + readonly root?: KeyPair; +}; + +export function androidChain(fixture: TrustFixture, spec: AndroidChainSpec) { + const approvalKey = spec.approvalKey ?? newKey(); + const root = spec.root ?? fixture.googleRoot; + const rootDer = spec.root + ? certificate({ + subject: "Other Root", + issuer: "Other Root", + subjectKey: root.publicKey, + issuerKey: root.privateKey, + ca: true, + }) + : fixture.googleRootDer; + const intermediate = newKey(); + const description = { oid: "1.3.6.1.4.1.11129.2.1.17", value: keyDescription(spec) }; + const intermediateDer = certificate({ + subject: "Test Attestation Intermediate", + issuer: spec.root ? "Other Root" : "Test Google Root", + subjectKey: intermediate.publicKey, + issuerKey: root.privateKey, + ca: true, + ...(spec.descriptionInIntermediate ? { extensions: [description] } : {}), + }); + const leafDer = certificate({ + subject: "Android Keystore Key", + issuer: "Test Attestation Intermediate", + subjectKey: approvalKey.publicKey, + issuerKey: spec.leafSignedByStranger ? newKey().privateKey : intermediate.privateKey, + extensions: [description], + ...(spec.leafNotAfter ? { notAfter: spec.leafNotAfter } : {}), + ...(spec.leafSerial ? { serial: spec.leafSerial } : {}), + }); + return { + publicJwk: publicJwkOf(approvalKey.publicKey), + approvalKey, + certificateChain: [leafDer, intermediateDer, rootDer].map(b64), + }; +} + +const cborHead = (major: number, n: number) => + n < 24 + ? [(major << 5) | n] + : n < 0x100 + ? [(major << 5) | 24, n] + : [(major << 5) | 25, n >> 8, n & 0xff]; +const cbor = { + bytes: (value: Uint8Array) => new Uint8Array([...cborHead(2, value.length), ...value]), + text: (value: string) => { + const bytes = Buffer.from(value); + return new Uint8Array([...cborHead(3, bytes.length), ...bytes]); + }, + array: (items: ReadonlyArray) => + new Uint8Array([...cborHead(4, items.length), ...concat(items)]), + map: (entries: ReadonlyArray) => + new Uint8Array([ + ...cborHead(5, entries.length), + ...concat(entries.flatMap(([key, value]) => [cbor.text(key), value])), + ]), +}; + +export type AppleSpec = { + readonly challenge: Uint8Array; + readonly approvalKey?: KeyPair; + /** The key the nonce binds, when it differs from the registered one. */ + readonly boundKey?: KeyPair; + readonly appId?: string; + readonly counter?: number; + readonly aaguid?: string; + readonly wrongKeyId?: boolean; + readonly root?: KeyPair; +}; + +export function appleAttestation(fixture: TrustFixture, spec: AppleSpec) { + const approvalKey = spec.approvalKey ?? newKey(); + const appAttestKey = newKey(); + const keyId = sha256(point(appAttestKey.publicKey)); + const aaguid = Buffer.alloc(16); + Buffer.from(spec.aaguid ?? "appattest").copy(aaguid); + const counter = Buffer.alloc(4); + counter.writeUInt32BE(spec.counter ?? 0); + const authData = new Uint8Array([ + ...sha256(Buffer.from(spec.appId ?? APPLE_APP_ID)), + 0x40, + ...counter, + ...aaguid, + 0, + 32, + ...keyId, + 0xa0, + ]); + const clientDataHash = sha256(spec.challenge, point((spec.boundKey ?? approvalKey).publicKey)); + const nonce = sha256(authData, clientDataHash); + const root = spec.root ?? fixture.appleRoot; + const intermediate = newKey(); + const intermediateDer = certificate({ + subject: "Test App Attest CA", + issuer: "Test Apple Root", + subjectKey: intermediate.publicKey, + issuerKey: root.privateKey, + ca: true, + }); + const credCert = certificate({ + subject: "App Attest Key", + issuer: "Test App Attest CA", + subjectKey: appAttestKey.publicKey, + issuerKey: intermediate.privateKey, + extensions: [ + { oid: "1.2.840.113635.100.8.2", value: der.seq(der.explicit(1, der.octet(nonce))) }, + ], + }); + const attestationObject = cbor.map([ + ["fmt", cbor.text("apple-appattest")], + [ + "attStmt", + cbor.map([ + ["x5c", cbor.array([cbor.bytes(credCert), cbor.bytes(intermediateDer)])], + ["receipt", cbor.bytes(new Uint8Array([1]))], + ]), + ], + ["authData", cbor.bytes(authData)], + ]); + return { + publicJwk: publicJwkOf(approvalKey.publicKey), + approvalKey, + keyId: b64(spec.wrongKeyId ? sha256(keyId) : keyId), + attestationObject: b64(attestationObject), + }; +} diff --git a/apps/server/src/kin/approvals/attestation/verify.test.ts b/apps/server/src/kin/approvals/attestation/verify.test.ts new file mode 100644 index 0000000000000..5d6f80a671a82 --- /dev/null +++ b/apps/server/src/kin/approvals/attestation/verify.test.ts @@ -0,0 +1,147 @@ +// @effect-diagnostics nodeBuiltinImport:off -- random challenges for fixtures. +import * as NodeCrypto from "node:crypto"; + +import { assert, describe, it } from "@effect/vitest"; + +import { + androidChain, + appleAttestation, + makeTrustFixture, + newKey, + type AndroidChainSpec, + type AppleSpec, +} from "./testFixtures.ts"; +import { verifyAndroidKeyAttestation, verifyAppleAppAttest } from "./verify.ts"; + +const NOW = Date.parse("2026-11-08T00:00:00Z"); +const challenge = new Uint8Array(NodeCrypto.randomBytes(32)); + +describe("Android key attestation", () => { + const fixture = makeTrustFixture(); + const verify = (spec: Partial = {}, trust = fixture.trust) => { + const chain = androidChain(fixture, { challenge, ...spec }); + return verifyAndroidKeyAttestation({ + certificateChain: chain.certificateChain, + challenge, + publicJwk: chain.publicJwk, + trust, + now: NOW, + }); + }; + + it("accepts a StrongBox key and reads the hardware from the attestation", () => { + assert.deepStrictEqual(verify(), { attested: true, hardware: "strongbox" }); + assert.deepStrictEqual(verify({ attestationLevel: 1, keyMintLevel: 1 }), { + attested: true, + hardware: "tee", + }); + }); + + const rejections: ReadonlyArray, string]> = [ + ["another root", { root: newKey() }, "Google hardware attestation root"], + ["a forged leaf", { leafSignedByStranger: true }, "isn't signed by the next one"], + ["an expired leaf", { leafNotAfter: "260101000000Z" }, "outside its validity"], + ["another challenge", { challenge: new Uint8Array(32) }, "challenge mismatch"], + ["a software key", { attestationLevel: 0 }, "secure hardware"], + ["software KeyMint", { keyMintLevel: 0 }, "secure hardware"], + ["an encrypting key", { purposes: [0, 2] }, "SIGN only"], + ["an RSA key", { algorithm: 1 }, "algorithm"], + ["another curve", { ecCurve: 2 }, "P-256"], + ["a SHA-1 digest", { digests: [2] }, "SHA-256"], + ["a PIN-gated key", { userAuthType: 1 }, "biometric only"], + ["an auth timeout", { authTimeout: 30 }, "auth timeout"], + ["no auth required", { noAuthRequiredInSoftware: true }, "needs no auth"], + ["an imported key", { origin: 2 }, "generated in hardware"], + ["an unlocked bootloader", { deviceLocked: false }, "unlocked"], + ["unverified boot", { bootState: 2 }, "Verified"], + ["another app", { packages: ["com.evil.app"] }, "package"], + ["two apps", { packages: ["com.gldroger.kin", "com.evil.app"] }, "more than one package"], + ["another signer", { signers: ["cd".repeat(32)] }, "signing certificate"], + ["a key description above the leaf", { descriptionInIntermediate: true }, "outside the leaf"], + ]; + it.each(rejections)("refuses %s", (_name, spec, reason) => { + const result = verify(spec); + assert.isFalse(result.attested); + assert.include(result.attested ? "" : result.reason, reason); + }); + + it("refuses a chain with a revoked certificate", () => { + const serial = new Uint8Array([0x0f, 0x1e, 0x2d]); + const result = verify( + { leafSerial: serial }, + { ...fixture.trust, androidRevokedSerials: new Set(["f1e2d"]) }, + ); + assert.deepStrictEqual(result, { + attested: false, + reason: "a certificate in the chain is revoked", + }); + }); + + it("refuses a chain for another key and malformed input", () => { + const chain = androidChain(fixture, { challenge }); + const other = androidChain(fixture, { challenge }); + const base = { challenge, trust: fixture.trust, now: NOW }; + const swapped = verifyAndroidKeyAttestation({ + ...base, + certificateChain: chain.certificateChain, + publicJwk: other.publicJwk, + }); + assert.deepStrictEqual(swapped, { + attested: false, + reason: "attested key isn't the registered key", + }); + const garbage = verifyAndroidKeyAttestation({ + ...base, + certificateChain: ["bm90IGEgY2VydA==", chain.certificateChain[1]!], + publicJwk: chain.publicJwk, + }); + assert.isFalse(garbage.attested); + const short = verifyAndroidKeyAttestation({ + ...base, + certificateChain: chain.certificateChain.slice(0, 1), + publicJwk: chain.publicJwk, + }); + assert.deepStrictEqual(short, { attested: false, reason: "attestation chain is too short" }); + }); +}); + +describe("Apple App Attest", () => { + const fixture = makeTrustFixture(); + const verify = (spec: Partial = {}, trust = fixture.trust) => { + const attestation = appleAttestation(fixture, { challenge, ...spec }); + return verifyAppleAppAttest({ + keyId: attestation.keyId, + attestationObject: attestation.attestationObject, + challenge, + publicJwk: attestation.publicJwk, + trust, + now: NOW, + }); + }; + + it("accepts an attestation over the challenge and the new key", () => { + assert.deepStrictEqual(verify(), { attested: true, hardware: "secure_enclave" }); + assert.deepStrictEqual( + verify( + { aaguid: "appattestdevelop" }, + { ...fixture.trust, appleEnvironments: ["development"] }, + ), + { attested: true, hardware: "secure_enclave" }, + ); + }); + + const rejections: ReadonlyArray, string]> = [ + ["another root", { root: newKey() }, "Apple App Attest root"], + ["another challenge", { challenge: new Uint8Array(32) }, "nonce"], + ["a nonce over another approval key", { boundKey: newKey() }, "nonce"], + ["another app", { appId: "TEAM999999.com.evil" }, "allowlist"], + ["a used App Attest key", { counter: 1 }, "counter"], + ["a development build", { aaguid: "appattestdevelop" }, "environment"], + ["a keyId for another key", { wrongKeyId: true }, "keyId"], + ]; + it.each(rejections)("refuses %s", (_name, spec, reason) => { + const result = verify(spec); + assert.isFalse(result.attested); + assert.include(result.attested ? "" : result.reason, reason); + }); +}); diff --git a/apps/server/src/kin/approvals/attestation/verify.ts b/apps/server/src/kin/approvals/attestation/verify.ts new file mode 100644 index 0000000000000..27eb59c29dc41 --- /dev/null +++ b/apps/server/src/kin/approvals/attestation/verify.ts @@ -0,0 +1,361 @@ +// @effect-diagnostics nodeBuiltinImport:off extendsNativeError:off -- node:crypto X.509; errors stay inside `run`. +import * as NodeCrypto from "node:crypto"; + +import type { KinApproverKeyHardware, KinApproverPublicJwk } from "@t3tools/contracts"; + +import * as Der from "./der.ts"; + +/** Pinned roots, allowlists and Google's revocation list (approvals spec section 4). */ +export type AttestationTrust = { + readonly googleRoots: ReadonlyArray; + /** Lowercase hex serials without leading zeros, as Google's status list keys them. */ + readonly androidRevokedSerials: ReadonlySet; + readonly androidApps: ReadonlyArray<{ + readonly packageName: string; + /** Lowercase hex SHA-256 of each release signing certificate. */ + readonly signingCertSha256: ReadonlyArray; + }>; + readonly appleRoot: NodeCrypto.X509Certificate; + /** `.`. */ + readonly appleAppIds: ReadonlyArray; + readonly appleEnvironments: ReadonlyArray<"production" | "development">; +}; + +export type AttestationResult = + | { readonly attested: true; readonly hardware: Exclude } + | { readonly attested: false; readonly reason: string }; + +class Refused extends Error {} +const refuse = (reason: string): never => { + throw new Refused(reason); +}; +const check = (condition: boolean, reason: string) => { + if (!condition) refuse(reason); +}; + +const run = (body: () => AttestationResult): AttestationResult => { + try { + return body(); + } catch (error) { + if (error instanceof Refused) return { attested: false, reason: error.message }; + if (error instanceof Der.DerError) + return { attested: false, reason: `malformed: ${error.message}` }; + return { attested: false, reason: "malformed attestation" }; + } +}; + +const sha256 = (...parts: ReadonlyArray) => { + const hash = NodeCrypto.createHash("sha256"); + for (const part of parts) hash.update(part); + return new Uint8Array(hash.digest()); +}; +const equalBytes = (a: Uint8Array, b: Uint8Array) => + a.length === b.length && NodeCrypto.timingSafeEqual(a, b); +const spki = (certificate: NodeCrypto.X509Certificate) => + new Uint8Array(certificate.publicKey.export({ type: "spki", format: "der" })); +const decodeBase64 = (value: string) => { + check(/^[A-Za-z0-9+/]+={0,2}$/.test(value) && value.length % 4 === 0, "certificate isn't base64"); + return new Uint8Array(Buffer.from(value, "base64")); +}; +const parseCertificate = (der: Uint8Array) => { + try { + return new NodeCrypto.X509Certificate(der); + } catch { + return refuse("certificate doesn't parse"); + } +}; +const withinValidity = (certificate: NodeCrypto.X509Certificate, now: number) => + Date.parse(certificate.validFrom) <= now && now <= Date.parse(certificate.validTo); + +/** Each certificate is signed by the next one. */ +function verifyLinks(chain: ReadonlyArray, now: number) { + for (const [index, certificate] of chain.entries()) { + check(withinValidity(certificate, now), `certificate ${index} is outside its validity`); + const issuer = chain[index + 1]; + if (issuer === undefined) continue; + check( + certificate.checkIssued(issuer) && certificate.verify(issuer.publicKey), + `certificate ${index} isn't signed by the next one`, + ); + } +} + +const pointBytes = (jwk: { readonly x?: string; readonly y?: string }) => { + check(typeof jwk.x === "string" && typeof jwk.y === "string", "not an EC key"); + return new Uint8Array([ + 0x04, + ...Buffer.from(jwk.x!, "base64url"), + ...Buffer.from(jwk.y!, "base64url"), + ]); +}; +const jwkPoint = (jwk: KinApproverPublicJwk) => pointBytes(jwk); +const certificatePoint = (certificate: NodeCrypto.X509Certificate) => { + const jwk = certificate.publicKey.export({ format: "jwk" }); + check(jwk.kty === "EC" && jwk.crv === "P-256", "attested key isn't P-256"); + return pointBytes(jwk); +}; + +/** 1.3.6.1.4.1.11129.2.1.17 */ +const KEY_DESCRIPTION_OID = "2b06010401d679020111"; +const SECURITY_LEVEL = { trustedEnvironment: 1, strongBox: 2 } as const; +const TAG = { + purpose: 1, + algorithm: 2, + keySize: 3, + digest: 5, + ecCurve: 10, + noAuthRequired: 503, + userAuthType: 504, + authTimeout: 505, + origin: 702, + rootOfTrust: 704, + attestationApplicationId: 709, +} as const; +const PURPOSE_SIGN = 2; +const ALGORITHM_EC = 3; +const DIGEST_SHA_2_256 = 4; +const EC_CURVE_P_256 = 1; +const AUTH_FINGERPRINT = 2; +const ORIGIN_GENERATED = 0; +const BOOT_VERIFIED = 0; + +function authorizationList(tlv: Der.Tlv | undefined): ReadonlyMap { + const out = new Map(); + for (const entry of Der.sequence(tlv)) { + check(entry.cls === Der.CONTEXT && entry.constructed, "malformed authorization list"); + check(!out.has(entry.tag), "duplicate authorization tag"); + const inner = Der.children(entry); + check(inner.length === 1, "malformed authorization entry"); + out.set(entry.tag, inner[0]!); + } + return out; +} + +const integerSet = (tlv: Der.Tlv | undefined) => + Der.children(Der.expect(tlv, Der.T_SET)).map((element) => Der.integer(element)); +const exactly = (values: ReadonlyArray, expected: number) => + values.length === 1 && values[0] === expected; + +const normalizeSerial = (serial: string) => serial.toLowerCase().replace(/^0+(?=.)/, ""); + +export function verifyAndroidKeyAttestation(input: { + readonly certificateChain: ReadonlyArray; + readonly challenge: Uint8Array; + readonly publicJwk: KinApproverPublicJwk; + readonly trust: AttestationTrust; + /** Epoch milliseconds. */ + readonly now: number; +}): AttestationResult { + return run(() => { + const ders = input.certificateChain.map(decodeBase64); + check(ders.length >= 2, "attestation chain is too short"); + const chain = ders.map(parseCertificate); + verifyLinks(chain, input.now); + const root = chain[chain.length - 1]!; + const rootKey = spki(root); + check( + input.trust.googleRoots.some((pinned) => equalBytes(spki(pinned), rootKey)), + "chain doesn't end at a Google hardware attestation root", + ); + for (const certificate of chain) { + check( + !input.trust.androidRevokedSerials.has(normalizeSerial(certificate.serialNumber)), + "a certificate in the chain is revoked", + ); + } + check( + equalBytes(certificatePoint(chain[0]!), jwkPoint(input.publicJwk)), + "attested key isn't the registered key", + ); + const descriptions = ders.map((der) => Der.certificateExtensions(der).get(KEY_DESCRIPTION_OID)); + check(descriptions[0] !== undefined, "leaf has no key description"); + check( + descriptions.slice(1).every((extension) => extension === undefined), + "key description outside the leaf", + ); + + const fields = Der.sequence(Der.parse(descriptions[0]!.value)); + check(fields.length >= 8, "malformed key description"); + const attestationLevel = Der.enumerated(fields[1]); + const keyMintLevel = Der.enumerated(fields[3]); + const hardwareLevels: ReadonlyArray = [ + SECURITY_LEVEL.trustedEnvironment, + SECURITY_LEVEL.strongBox, + ]; + check( + hardwareLevels.includes(attestationLevel) && hardwareLevels.includes(keyMintLevel), + "attestation isn't from secure hardware", + ); + check(equalBytes(Der.octets(fields[4]), input.challenge), "attestation challenge mismatch"); + const software = authorizationList(fields[6]); + const hardware = authorizationList(fields[7]); + + check(exactly(integerSet(hardware.get(TAG.purpose)), PURPOSE_SIGN), "purpose isn't SIGN only"); + check(Der.integer(hardware.get(TAG.algorithm)) === ALGORITHM_EC, "algorithm isn't EC"); + check(Der.integer(hardware.get(TAG.ecCurve)) === EC_CURVE_P_256, "curve isn't P-256"); + const keySize = hardware.get(TAG.keySize); + check(keySize === undefined || Der.integer(keySize) === 256, "key size isn't 256"); + check(exactly(integerSet(hardware.get(TAG.digest)), DIGEST_SHA_2_256), "digest isn't SHA-256"); + check( + Der.integer(hardware.get(TAG.userAuthType)) === AUTH_FINGERPRINT, + "user auth isn't biometric only", + ); + for (const list of [software, hardware]) { + check(!list.has(TAG.authTimeout), "key has an auth timeout"); + check(!list.has(TAG.noAuthRequired), "key needs no auth"); + } + check( + Der.integer(hardware.get(TAG.origin)) === ORIGIN_GENERATED, + "key wasn't generated in hardware", + ); + const rootOfTrust = Der.sequence(hardware.get(TAG.rootOfTrust)); + check(rootOfTrust.length >= 3, "malformed root of trust"); + check(Der.boolean(rootOfTrust[1]), "bootloader is unlocked"); + check(Der.enumerated(rootOfTrust[2]) === BOOT_VERIFIED, "verified boot state isn't Verified"); + + // Keystore, not KeyMint, fills this in, so it is usually software-enforced. + const applicationId = + hardware.get(TAG.attestationApplicationId) ?? software.get(TAG.attestationApplicationId); + const [packages, digests] = Der.sequence(Der.parse(Der.octets(applicationId))); + const packageInfos = Der.children(Der.expect(packages, Der.T_SET)); + check(packageInfos.length === 1, "attestation names more than one package"); + const packageName = Buffer.from(Der.octets(Der.sequence(packageInfos[0])[0])).toString("utf8"); + const app = input.trust.androidApps.find((candidate) => candidate.packageName === packageName); + check(app !== undefined, "package isn't on the allowlist"); + const signers = Der.children(Der.expect(digests, Der.T_SET)).map((digest) => + Buffer.from(Der.octets(digest)).toString("hex"), + ); + check( + signers.length > 0 && signers.every((digest) => app!.signingCertSha256.includes(digest)), + "signing certificate isn't on the allowlist", + ); + + return { + attested: true, + hardware: attestationLevel === SECURITY_LEVEL.strongBox ? "strongbox" : "tee", + }; + }); +} + +/** 1.2.840.113635.100.8.2 */ +const APPLE_NONCE_OID = "2a864886f763640802"; +const AAGUID = { + production: new Uint8Array([...Buffer.from("appattest"), 0, 0, 0, 0, 0, 0, 0]), + development: new Uint8Array(Buffer.from("appattestdevelop")), +} as const; + +type Cbor = number | string | Uint8Array | ReadonlyArray | ReadonlyMap; + +/** Definite-length unsigned ints, byte and text strings, arrays and maps: all App Attest uses. */ +function decodeCbor(bytes: Uint8Array): Cbor { + let offset = 0; + const take = (count: number) => { + check(offset + count <= bytes.length, "malformed: truncated CBOR"); + const out = bytes.subarray(offset, offset + count); + offset += count; + return out; + }; + const argument = (info: number): number => { + if (info < 24) return info; + const width = + info === 24 ? 1 : info === 25 ? 2 : info === 26 ? 4 : refuse("malformed: CBOR length"); + let n = 0; + for (const byte of take(width)) n = n * 256 + byte; + return n; + }; + const item = (depth: number): Cbor => { + check(depth < 8, "malformed: CBOR too deep"); + const [initial] = take(1); + const major = initial! >> 5; + const value = argument(initial! & 0x1f); + switch (major) { + case 0: + return value; + case 2: + return take(value); + case 3: + return new TextDecoder("utf-8", { fatal: true }).decode(take(value)); + case 4: + return Array.from({ length: value }, () => item(depth + 1)); + case 5: { + const map = new Map(); + for (let i = 0; i < value; i++) { + const key = item(depth + 1); + check(typeof key === "string" && !map.has(key), "malformed: CBOR map key"); + map.set(key, item(depth + 1)); + } + return map; + } + default: + return refuse("malformed: unsupported CBOR"); + } + }; + const out = item(0); + check(offset === bytes.length, "malformed: trailing CBOR"); + return out; +} + +const field = (map: Cbor, key: string) => + map instanceof Map ? (map.get(key) as Cbor | undefined) : refuse("malformed: expected a map"); +const bytesOf = (value: Cbor | undefined) => + value instanceof Uint8Array ? value : refuse("malformed: expected bytes"); + +export function verifyAppleAppAttest(input: { + readonly keyId: string; + readonly attestationObject: string; + readonly challenge: Uint8Array; + readonly publicJwk: KinApproverPublicJwk; + readonly trust: AttestationTrust; + /** Epoch milliseconds. */ + readonly now: number; +}): AttestationResult { + return run(() => { + const keyId = decodeBase64(input.keyId); + check(keyId.length === 32, "keyId isn't a SHA-256"); + const object = decodeCbor(decodeBase64(input.attestationObject)); + check(field(object, "fmt") === "apple-appattest", "attestation format isn't apple-appattest"); + const statement = field(object, "attStmt"); + const x5c = field(statement ?? 0, "x5c"); + check(Array.isArray(x5c) && x5c.length >= 2, "attestation chain is too short"); + const chain = (x5c as ReadonlyArray).map((der) => parseCertificate(bytesOf(der))); + verifyLinks(chain, input.now); + const top = chain[chain.length - 1]!; + const root = input.trust.appleRoot; + check( + withinValidity(root, input.now) && top.checkIssued(root) && top.verify(root.publicKey), + "chain doesn't end at the Apple App Attest root", + ); + + const authData = bytesOf(field(object, "authData")); + check(authData.length >= 55, "authenticator data is too short"); + const clientDataHash = sha256(input.challenge, jwkPoint(input.publicJwk)); + const nonce = sha256(authData, clientDataHash); + const credCert = bytesOf((x5c as ReadonlyArray)[0]); + const extension = Der.certificateExtensions(credCert).get(APPLE_NONCE_OID); + check(extension !== undefined, "credential certificate has no nonce"); + const [wrapped] = Der.sequence(Der.parse(extension!.value)); + check(wrapped?.cls === Der.CONTEXT && wrapped.tag === 1, "malformed nonce extension"); + const [nonceElement] = Der.children(wrapped!); + check(equalBytes(Der.octets(nonceElement), nonce), "nonce doesn't bind this key and challenge"); + check(equalBytes(sha256(certificatePoint(chain[0]!)), keyId), "keyId isn't the attested key"); + + const rpIdHash = authData.subarray(0, 32); + check( + input.trust.appleAppIds.some((appId) => equalBytes(sha256(Buffer.from(appId)), rpIdHash)), + "app isn't on the allowlist", + ); + const counter = Buffer.from(authData.subarray(33, 37)).readUInt32BE(0); + check(counter === 0, "attestation counter isn't 0"); + const aaguid = authData.subarray(37, 53); + check( + input.trust.appleEnvironments.some((environment) => equalBytes(AAGUID[environment], aaguid)), + "App Attest environment isn't allowed", + ); + const credentialIdLength = Buffer.from(authData.subarray(53, 55)).readUInt16BE(0); + check( + equalBytes(authData.subarray(55, 55 + credentialIdLength), keyId), + "credential id isn't keyId", + ); + return { attested: true, hardware: "secure_enclave" }; + }); +} diff --git a/apps/server/src/kin/approvals/handlers/registerApproverKey.ts b/apps/server/src/kin/approvals/handlers/registerApproverKey.ts new file mode 100644 index 0000000000000..57113acdb860d --- /dev/null +++ b/apps/server/src/kin/approvals/handlers/registerApproverKey.ts @@ -0,0 +1,59 @@ +import { KinApprovalError, type KinGrant, type KinPendingAction } from "@t3tools/contracts"; +import * as Effect from "effect/Effect"; +import * as Option from "effect/Option"; + +import { ApproverKeys } from "../ApproverKeys.ts"; + +const refuse = (message: string) => + Effect.fail(new KinApprovalError({ reason: "invalid_state", message })); + +/** + * Activates a later approver key once an existing key's grant for it is verified and claimed. + * Shaped as spec section 6's `KinActionHandler`; APPR-9 registers it with the executor. + */ +export const makeRegisterApproverKeyHandler = Effect.gen(function* () { + const keys = yield* ApproverKeys; + + const pendingKey = Effect.fn("registerApproverKey.pendingKey")(function* ( + action: KinPendingAction, + ) { + if (action.kind !== "register_approver_key" || action.target._tag !== "device_key") + return yield* refuse("Not an approver key registration."); + const target = action.target; + const key = yield* keys.get({ orgId: action.orgId, thumbprint: target.thumbprint }); + if (Option.isNone(key)) return yield* refuse("The key to add no longer exists."); + return { target, key: key.value }; + }); + + const precheck = Effect.fn("registerApproverKey.precheck")(function* (action: KinPendingAction) { + const { target, key } = yield* pendingKey(action); + if (key.state !== "pending") return yield* refuse("The key isn't waiting to be added."); + // The card showed the target; the stored key must still be what it described. + if (!key.attested || key.hardware !== target.hardware) + return yield* refuse("The key doesn't match what was approved."); + }); + + const run = Effect.fn("registerApproverKey.run")(function* ( + action: KinPendingAction, + grant: KinGrant, + ) { + yield* precheck(action); + const { target } = yield* pendingKey(action); + if (grant.keyThumbprint === target.thumbprint) + return yield* refuse("A key can't approve itself."); + const activated = yield* keys.activateByGrant({ + orgId: action.orgId, + thumbprint: target.thumbprint, + }); + return activated ? ("succeeded" as const) : yield* refuse("The key couldn't be activated."); + }); + + const reconcile = Effect.fn("registerApproverKey.reconcile")(function* ( + action: KinPendingAction, + ) { + const { key } = yield* pendingKey(action); + return key.state === "active" ? ("done" as const) : ("not_done" as const); + }); + + return { kind: "register_approver_key" as const, precheck, run, reconcile }; +}); diff --git a/apps/server/src/kin/approvals/layer.ts b/apps/server/src/kin/approvals/layer.ts new file mode 100644 index 0000000000000..c60550d0c4559 --- /dev/null +++ b/apps/server/src/kin/approvals/layer.ts @@ -0,0 +1,13 @@ +import * as Layer from "effect/Layer"; +import * as FetchHttpClient from "effect/http/FetchHttpClient"; + +import * as KinPersistence from "../persistence/KinPersistence.ts"; +import * as ApproverKeys from "./ApproverKeys.ts"; +import * as AttestationTrust from "./attestation/AttestationTrust.ts"; +import * as PendingActions from "./PendingActions.ts"; + +export const layer = ApproverKeys.layer.pipe( + Layer.provide(PendingActions.layer), + Layer.provide(AttestationTrust.layer.pipe(Layer.provide(FetchHttpClient.layer))), + Layer.provide(KinPersistence.layer), +); diff --git a/apps/server/src/kin/approvals/rpcHandlers.ts b/apps/server/src/kin/approvals/rpcHandlers.ts index 0b07100bddb46..1934ceac679ed 100644 --- a/apps/server/src/kin/approvals/rpcHandlers.ts +++ b/apps/server/src/kin/approvals/rpcHandlers.ts @@ -1,30 +1,63 @@ import { KinApprovalError, KinApprovalRpcs } from "@t3tools/contracts"; +import * as Context from "effect/Context"; import * as Effect from "effect/Effect"; +import * as Option from "effect/Option"; import * as Stream from "effect/Stream"; +import * as HttpServerRequest from "effect/http/HttpServerRequest"; import * as RpcGroup from "effect/rpc/RpcGroup"; import type { AuthenticatedSession } from "../../auth/EnvironmentAuth.ts"; +import { KinIdentity } from "../chat/KinIdentity.ts"; +import { KinServer } from "../KinServer.ts"; +import { ApproverKeys, type KinKeyCaller } from "./ApproverKeys.ts"; const group = RpcGroup.make(...KinApprovalRpcs); -// Every method refuses until its task lands (APPR-3, -4, -5, -10); nothing here can approve. +// Every method refuses until its task lands (APPR-3, -4, -10); nothing here can approve. const unavailable = Effect.fail( new KinApprovalError({ reason: "unavailable", message: "Kin approvals are unavailable." }), ); -export const makeKinApprovalHandlers = (_session: AuthenticatedSession) => - Effect.sync(() => - group.of({ - "kin.approvals.list": () => Stream.fromEffect(unavailable), - "kin.approvals.get": () => unavailable, - "kin.approvals.challenge": () => unavailable, - "kin.approvals.submitGrant": () => unavailable, - "kin.approvals.reject": () => unavailable, - "kin.approvals.keyChallenge": () => unavailable, - "kin.approvals.registerKey": () => unavailable, - "kin.approvals.confirmKey": () => unavailable, - "kin.approvals.listKeys": () => unavailable, - "kin.approvals.revokeKey": () => unavailable, - "kin.audit.list": () => unavailable, - "kin.audit.verify": () => unavailable, +// The WS upgrade request, so `confirmKey` can tell a loopback socket from a proxied one. +const connectionOf = Effect.serviceOption(HttpServerRequest.HttpServerRequest).pipe( + Effect.map( + Option.flatMap((request) => { + const peer = Option.getOrUndefined(request.peerAddress); + const remote = Option.getOrUndefined(request.remoteAddress); + if (peer !== undefined && remote !== undefined && peer !== remote) return Option.none(); + return Option.some({ remoteAddress: peer ?? remote, headers: request.headers }); }), - ); + ), +); + +export const makeKinApprovalHandlers = Effect.fn("makeKinApprovalHandlers")(function* ( + session: AuthenticatedSession, +) { + const kin = yield* Effect.serviceOption(KinServer); + const connection = yield* connectionOf; + const keys = Effect.gen(function* () { + if (Option.isNone(kin) || Option.isNone(kin.value.services)) return yield* unavailable; + const services = kin.value.services.value; + const people = yield* Context.get(services, KinIdentity).resolve(session); + const caller: KinKeyCaller = { session, people, connection }; + return { keys: Context.get(services, ApproverKeys), caller }; + }); + return group.of({ + "kin.approvals.list": () => Stream.fromEffect(unavailable), + "kin.approvals.get": () => unavailable, + "kin.approvals.challenge": () => unavailable, + "kin.approvals.submitGrant": () => unavailable, + "kin.approvals.reject": () => unavailable, + "kin.approvals.keyChallenge": () => + keys.pipe(Effect.flatMap(({ keys, caller }) => keys.keyChallenge(caller))), + "kin.approvals.registerKey": (input) => + keys.pipe(Effect.flatMap(({ keys, caller }) => keys.registerKey(caller, input))), + "kin.approvals.confirmKey": (input) => + keys.pipe(Effect.flatMap(({ keys, caller }) => keys.confirmKey(caller, input))), + "kin.approvals.listKeys": (input) => + keys.pipe(Effect.flatMap(({ keys, caller }) => keys.listKeys(caller, input))), + "kin.approvals.revokeKey": (input) => + keys.pipe(Effect.flatMap(({ keys, caller }) => keys.revokeKey(caller, input))), + "kin.audit.list": () => unavailable, + "kin.audit.verify": () => unavailable, + }); +}); diff --git a/apps/server/src/kin/layer.ts b/apps/server/src/kin/layer.ts index ba72e1cf3a641..2253193403569 100644 --- a/apps/server/src/kin/layer.ts +++ b/apps/server/src/kin/layer.ts @@ -5,6 +5,7 @@ import * as Layer from "effect/Layer"; import * as HttpRouter from "effect/http/HttpRouter"; import * as Option from "effect/Option"; import * as KinChat from "./chat/layer.ts"; +import * as KinApprovals from "./approvals/layer.ts"; import { KinChatHub } from "./chat/KinChatHub.ts"; import { KinServer, type Services } from "./KinServer.ts"; @@ -25,7 +26,11 @@ const enabled = Layer.effect( subscribeForViewer: Option.some(hub.subscribeForViewer), }; }), -).pipe(Layer.provide(lead.pipe(Layer.provideMerge(KinChat.layer)))); +).pipe( + Layer.provide( + lead.pipe(Layer.provideMerge(KinChat.layer), Layer.provideMerge(KinApprovals.layer)), + ), +); const disabled = Layer.succeed(KinServer, { services: Option.none(), subscribeForViewer: Option.none(), diff --git a/packages/contracts/src/kinApprovals.ts b/packages/contracts/src/kinApprovals.ts index a3aa39dcb6985..d1e580e95853a 100644 --- a/packages/contracts/src/kinApprovals.ts +++ b/packages/contracts/src/kinApprovals.ts @@ -87,7 +87,12 @@ export const KinActionTarget = Schema.Union([ chatId: Schema.optional(KinChatId), level: KinLevel, }), - Schema.TaggedStruct("device_key", { thumbprint: KinKeyThumbprint }), + // The server never activates an unattested key, so only attested keys can be approved. + Schema.TaggedStruct("device_key", { + thumbprint: KinKeyThumbprint, + hardware: Schema.Literals(["secure_enclave", "strongbox", "tee"]), + attested: Schema.Literal(true), + }), ]); export type KinActionTarget = typeof KinActionTarget.Type; @@ -417,15 +422,29 @@ export const KinApprovalsKeyChallengeResult = Schema.Struct({ expiresAt: CanonicalUtcTimestamp, }); export type KinApprovalsKeyChallengeResult = typeof KinApprovalsKeyChallengeResult.Type; +const Base64Blob = Schema.String.check(Schema.isMaxLength(16_384)); +export const KinApproverKeyAttestation = Schema.Union([ + Schema.Struct({ + format: Schema.Literal("android-key"), + /** Base64 DER certificates, leaf first. */ + certificateChain: Schema.Array(Base64Blob).check(Schema.isMaxLength(10)), + }), + Schema.Struct({ + format: Schema.Literal("apple-app-attest"), + /** Base64 SHA-256 of the App Attest key's public key. */ + keyId: Base64Blob, + /** Base64 CBOR from `DCAppAttestService.attestKey` over `sha256(challenge ‖ 0x04 ‖ x ‖ y)`. */ + attestationObject: Base64Blob, + }), +]); +export type KinApproverKeyAttestation = typeof KinApproverKeyAttestation.Type; export const KinApprovalsRegisterKeyInput = Schema.Struct({ orgId: KinOrgId, publicJwk: KinApproverPublicJwk, platform: KinApproverKeyPlatform, challenge: Base64UrlString, - // Base64 DER certificates, leaf first. Required on Android; the server derives `hardware`. - attestation: Schema.optional( - Schema.Struct({ certificateChain: Schema.Array(Schema.String).check(Schema.isMaxLength(10)) }), - ), + // Without one the key is stored unattested and can never be activated. The server derives `hardware`. + attestation: Schema.optional(KinApproverKeyAttestation), deviceLabel: TrimmedNonEmptyString.check(Schema.isMaxLength(80)), }); export type KinApprovalsRegisterKeyInput = typeof KinApprovalsRegisterKeyInput.Type; @@ -479,6 +498,7 @@ export class KinApprovalError extends Schema.TaggedError()("Ki "bad_challenge", "bad_code", "not_local", + "unattested", ]), ]), message: Schema.String, diff --git a/packages/shared/src/kinGrant.test.ts b/packages/shared/src/kinGrant.test.ts index 274ba5ee48af1..d877106f684a8 100644 --- a/packages/shared/src/kinGrant.test.ts +++ b/packages/shared/src/kinGrant.test.ts @@ -218,8 +218,13 @@ describe("APPR-6 grant vectors", () => { "exp not after iat", "iat 301 s ahead of the device clock", ]); - // These predate LEAD-1: the level target is keyed by agentId, not leadId (approvals.md §2). - const STALE_LEVEL_TARGET = new Set(["set a level in one chat", "set a level everywhere"]); + // Device vectors behind the contract: the level target is keyed by agentId, not leadId (§2), + // and the device_key target gained `hardware` and `attested` in APPR-5 (§4). + const STALE_TARGET = new Set([ + "set a level in one chat", + "set a level everywhere", + "register an approver key", + ]); it("encodes every accepted grant to the exact bytes the device signs", () => { for (const vector of vectors.cases.filter((c) => !c.error)) { @@ -235,7 +240,7 @@ describe("APPR-6 grant vectors", () => { for (const vector of vectors.cases) { const input = vector.signingInput ?? `${b64(vector.header!)}.${b64(vector.payload!)}`; const decoded = decodeKinGrant(`${input}.${zeroSignature}`) !== null; - const expected = STALE_LEVEL_TARGET.has(vector.name) + const expected = STALE_TARGET.has(vector.name) ? false : DEVICE_ONLY.has(vector.name) || !vector.error; assert.strictEqual(decoded, expected, vector.name); From c4a810d907d59a8b0e967b01533d10d1492b2b91 Mon Sep 17 00:00:00 2001 From: Surajsm60720 <1ds22is166@dsce.edu.in> Date: Sun, 8 Nov 2026 07:32:06 +0530 Subject: [PATCH 03/16] fix(kin): match APPR-6's Android attestation rules and spec the key registry (APPR-5) keySize 256 is required, allApplications must be absent, and the signing-certificate set must equal the allowlist. Co-Authored-By: Claude Opus 5.5 --- .../src/kin/approvals/attestation/testFixtures.ts | 5 ++++- .../src/kin/approvals/attestation/verify.test.ts | 5 ++++- apps/server/src/kin/approvals/attestation/verify.ts | 12 ++++++++---- docs/kin/specs/approvals.md | 10 ++++++---- 4 files changed, 22 insertions(+), 10 deletions(-) diff --git a/apps/server/src/kin/approvals/attestation/testFixtures.ts b/apps/server/src/kin/approvals/attestation/testFixtures.ts index 47f6290896759..78efaa759d3e0 100644 --- a/apps/server/src/kin/approvals/attestation/testFixtures.ts +++ b/apps/server/src/kin/approvals/attestation/testFixtures.ts @@ -173,6 +173,8 @@ export type KeyDescriptionSpec = { readonly userAuthType?: number; readonly authTimeout?: number; readonly noAuthRequiredInSoftware?: boolean; + readonly allApplications?: boolean; + readonly omitKeySize?: boolean; readonly origin?: number; readonly deviceLocked?: boolean; readonly bootState?: number; @@ -200,11 +202,12 @@ function keyDescription(spec: KeyDescriptionSpec): Uint8Array { const hardware = der.seq( der.explicit(1, der.set(...(spec.purposes ?? [2]).map(der.int))), der.explicit(2, der.int(spec.algorithm ?? 3)), - der.explicit(3, der.int(256)), + ...(spec.omitKeySize ? [] : [der.explicit(3, der.int(256))]), der.explicit(5, der.set(...(spec.digests ?? [4]).map(der.int))), der.explicit(10, der.int(spec.ecCurve ?? 1)), der.explicit(504, der.int(spec.userAuthType ?? 2)), ...(spec.authTimeout === undefined ? [] : [der.explicit(505, der.int(spec.authTimeout))]), + ...(spec.allApplications ? [der.explicit(600, der.null())] : []), der.explicit(702, der.int(spec.origin ?? 0)), der.explicit( 704, diff --git a/apps/server/src/kin/approvals/attestation/verify.test.ts b/apps/server/src/kin/approvals/attestation/verify.test.ts index 5d6f80a671a82..1335c69f9a83f 100644 --- a/apps/server/src/kin/approvals/attestation/verify.test.ts +++ b/apps/server/src/kin/approvals/attestation/verify.test.ts @@ -47,6 +47,8 @@ describe("Android key attestation", () => { ["an encrypting key", { purposes: [0, 2] }, "SIGN only"], ["an RSA key", { algorithm: 1 }, "algorithm"], ["another curve", { ecCurve: 2 }, "P-256"], + ["no key size", { omitKeySize: true }, "missing element"], + ["a key for every app", { allApplications: true }, "every app"], ["a SHA-1 digest", { digests: [2] }, "SHA-256"], ["a PIN-gated key", { userAuthType: 1 }, "biometric only"], ["an auth timeout", { authTimeout: 30 }, "auth timeout"], @@ -56,7 +58,8 @@ describe("Android key attestation", () => { ["unverified boot", { bootState: 2 }, "Verified"], ["another app", { packages: ["com.evil.app"] }, "package"], ["two apps", { packages: ["com.gldroger.kin", "com.evil.app"] }, "more than one package"], - ["another signer", { signers: ["cd".repeat(32)] }, "signing certificate"], + ["another signer", { signers: ["cd".repeat(32)] }, "signing certificates"], + ["an extra signer", { signers: ["ab".repeat(32), "cd".repeat(32)] }, "signing certificates"], ["a key description above the leaf", { descriptionInIntermediate: true }, "outside the leaf"], ]; it.each(rejections)("refuses %s", (_name, spec, reason) => { diff --git a/apps/server/src/kin/approvals/attestation/verify.ts b/apps/server/src/kin/approvals/attestation/verify.ts index 27eb59c29dc41..d065114c181a4 100644 --- a/apps/server/src/kin/approvals/attestation/verify.ts +++ b/apps/server/src/kin/approvals/attestation/verify.ts @@ -107,6 +107,7 @@ const TAG = { noAuthRequired: 503, userAuthType: 504, authTimeout: 505, + allApplications: 600, origin: 702, rootOfTrust: 704, attestationApplicationId: 709, @@ -193,8 +194,7 @@ export function verifyAndroidKeyAttestation(input: { check(exactly(integerSet(hardware.get(TAG.purpose)), PURPOSE_SIGN), "purpose isn't SIGN only"); check(Der.integer(hardware.get(TAG.algorithm)) === ALGORITHM_EC, "algorithm isn't EC"); check(Der.integer(hardware.get(TAG.ecCurve)) === EC_CURVE_P_256, "curve isn't P-256"); - const keySize = hardware.get(TAG.keySize); - check(keySize === undefined || Der.integer(keySize) === 256, "key size isn't 256"); + check(Der.integer(hardware.get(TAG.keySize)) === 256, "key size isn't 256"); check(exactly(integerSet(hardware.get(TAG.digest)), DIGEST_SHA_2_256), "digest isn't SHA-256"); check( Der.integer(hardware.get(TAG.userAuthType)) === AUTH_FINGERPRINT, @@ -203,6 +203,7 @@ export function verifyAndroidKeyAttestation(input: { for (const list of [software, hardware]) { check(!list.has(TAG.authTimeout), "key has an auth timeout"); check(!list.has(TAG.noAuthRequired), "key needs no auth"); + check(!list.has(TAG.allApplications), "key is usable by every app"); } check( Der.integer(hardware.get(TAG.origin)) === ORIGIN_GENERATED, @@ -225,9 +226,12 @@ export function verifyAndroidKeyAttestation(input: { const signers = Der.children(Der.expect(digests, Der.T_SET)).map((digest) => Buffer.from(Der.octets(digest)).toString("hex"), ); + const allowed = new Set(app!.signingCertSha256); check( - signers.length > 0 && signers.every((digest) => app!.signingCertSha256.includes(digest)), - "signing certificate isn't on the allowlist", + allowed.size > 0 && + signers.length === allowed.size && + signers.every((digest) => allowed.has(digest)), + "signing certificates don't match the allowlist", ); return { diff --git a/docs/kin/specs/approvals.md b/docs/kin/specs/approvals.md index f5c58b2e940df..693a67c71dc5b 100644 --- a/docs/kin/specs/approvals.md +++ b/docs/kin/specs/approvals.md @@ -201,12 +201,14 @@ export const KinApproverKey = Schema.Struct({ Registration: -1. The phone calls `kin.approvals.keyChallenge()` (`access:write`), which returns a single-use 32-byte nonce bound to that session and valid for 5 minutes. It passes the nonce to `createKey`, then calls `kin.approvals.registerKey({publicJwk, platform, challenge, attestation?, deviceLabel})` over the same session. The server consumes the nonce, stores the key as `pending` and returns a 6-digit code derived from `sha256(thumbprint ‖ serverNonce)`. +1. The phone calls `kin.approvals.keyChallenge()` (`access:write`), which returns a single-use 32-byte nonce bound to that session and valid for 5 minutes. It passes the nonce to `createKey`, then calls `kin.approvals.registerKey({publicJwk, platform, challenge, attestation?, deviceLabel})` over the same session. The server consumes the nonce, stores the key as `pending` and returns a 6-digit code derived from `sha256(thumbprint ‖ serverNonce)`, where `serverNonce` is that challenge. Challenges and codes live in server memory: a code is good for 10 minutes and five tries, and after a restart the phone registers again. - **Android:** `attestation.certificateChain` is required. The server checks it offline: the chain verifies up to a Google hardware attestation root and no certificate is on Google's attestation revocation list; the leaf's public key equals `publicJwk`; the leaf's KeyDescription has `attestationChallenge` equal to the nonce, `attestationSecurityLevel` and `keyMintSecurityLevel` (`keymasterSecurityLevel` before KeyMint) of `TrustedEnvironment` or `StrongBox`, and in `hardwareEnforced`: purpose `SIGN`, algorithm EC on P-256, digest SHA-256, `userAuthType` biometric only (`FINGERPRINT`, the value Keystore uses for every strong biometric), no `authTimeout`, no `noAuthRequired`, `origin` `GENERATED`, and `rootOfTrust` with `verifiedBootState` `Verified` and `deviceLocked` true; `attestationApplicationId` names the release package with a signing-certificate SHA-256 on the server's allowlist. All pass: `attested: true`, and `hardware` is `strongbox` or `tee` from the attestation security level. Any check fails: `attested: false`, `hardware: "software"`. The client never supplies `hardware`. - **iOS:** no attestation in phase 1, so the key is stored with `attested: false` and `hardware: "secure_enclave"`, which is claimed by the platform, not proven. -2. **First key in an org:** confirmed on the Mac running the server, in the desktop app's local session (loopback only), where the owner checks the code shown on both screens. No remote path can confirm the first key. -3. **Later keys:** confirmed by a grant of kind `register_approver_key` signed by an existing active key. -4. Revoking (`kin.approvals.revokeKey`, from settings or the desktop) sets `revoked` and voids every `approved` action whose grant that key signed. Revoking a T3 device session (`revokeClient`) also revokes keys registered from it. +2. **First key in an org:** confirmed on the Mac running the server, in the desktop app's local session (loopback only), where the owner checks the code shown on both screens. No remote path can confirm the first key. "Local" means all of: the session's subject is `desktop-bootstrap` (only the desktop app holds that credential), the session was issued to a loopback address, and the call's own socket is loopback with no `Forwarded`, `X-Forwarded-*`, `X-Real-IP`, `CF-Connecting-IP` or `Tailscale-User-Login` header. A browser or tunnel process on the same Mac fails the first check; a desktop on WSL fails the second, so it can't confirm keys. `confirmKey` works only while the org has no active key. +3. **Later keys:** confirmed by a grant of kind `register_approver_key` signed by an existing active key. When an attested key registers in an org that already has an active key, `registerKey` opens that pending action itself (requester `kin-approver-keys`, provenance started by the registering person), and the handler activates the key only if it is still `pending`, attested and on the hardware the card showed. +4. Revoking (`kin.approvals.revokeKey`, from settings or the desktop) sets `revoked` and voids every `approved` action whose grant that key signed. Revoking a T3 device session (`revokeClient`) also revokes keys registered from it. Kin reads `auth_sessions.revoked_at` at startup and before it trusts, lists or activates a key, rather than hooking T3's auth code. Revoking also cancels a pending `register_approver_key` action for the key. Expiry is not revocation: a key outlives the session that registered it. A DPoP relay session that renews hourly gets a new session id, so revoking it later doesn't reach a key registered from an earlier one. + +The server's attestation allowlist comes from `KIN_ANDROID_PACKAGE`, `KIN_ANDROID_SIGNING_CERT_SHA256` (comma-separated hex), `KIN_IOS_APP_ID` (`.`) and `KIN_IOS_APP_ATTEST_DEVELOPMENT` (accept `appattestdevelop`; default false). With none set, every key registers unattested. Google's roots and Apple's App Attest root are pinned in `apps/server/src/kin/approvals/attestation/roots.ts`. Google's revocation list is fetched from `https://android.googleapis.com/attestation/status` and cached for an hour. If it can't be fetched, Android registration fails and the phone retries; it never stores a key whose chain went unchecked. 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 740744516571842b78d3bf41c497269420905183 Mon Sep 17 00:00:00 2001 From: Surajsm60720 <1ds22is166@dsce.edu.in> Date: Sun, 8 Nov 2026 07:39:43 +0530 Subject: [PATCH 04/16] fix(kin): register each approver key thumbprint once (APPR-5) Re-registering a pending key's public key without attestation could overwrite its attested record and session. Co-Authored-By: Claude Opus 5.5 --- .../src/kin/approvals/ApproverKeys.test.ts | 14 ++++++++++++++ apps/server/src/kin/approvals/ApproverKeys.ts | 18 ++++++------------ docs/kin/specs/approvals.md | 2 +- 3 files changed, 21 insertions(+), 13 deletions(-) diff --git a/apps/server/src/kin/approvals/ApproverKeys.test.ts b/apps/server/src/kin/approvals/ApproverKeys.test.ts index b6da7d3213faa..4e01802f39d6c 100644 --- a/apps/server/src/kin/approvals/ApproverKeys.test.ts +++ b/apps/server/src/kin/approvals/ApproverKeys.test.ts @@ -265,6 +265,20 @@ describe("ApproverKeys", () => { assert.strictEqual(ios.key.hardware, "software"); const failed = yield* registerAndroid(keys, phone, { deviceLocked: false }); assert.strictEqual(failed.key.attested, false); + // Re-registering an attested key's public key without attestation can't downgrade it. + const attested = yield* registerAndroid(keys); + const replay = yield* keys.keyChallenge(phone); + const downgrade = yield* Effect.exit( + keys.registerKey(phone, { + orgId, + publicJwk: attested.input.publicJwk, + platform: "ios", + challenge: replay.challenge, + deviceLabel: "iPhone", + }), + ); + assert.strictEqual(reasonOf(downgrade), "invalid_state"); + assert.isTrue(Option.getOrThrow(yield* keys.get(attested.key)).attested); for (const { key, code } of [ios, failed]) { const exit = yield* Effect.exit( keys.confirmKey(desktop, { orgId, thumbprint: key.thumbprint, code }), diff --git a/apps/server/src/kin/approvals/ApproverKeys.ts b/apps/server/src/kin/approvals/ApproverKeys.ts index 3a626255e2b62..03a63cbc934ad 100644 --- a/apps/server/src/kin/approvals/ApproverKeys.ts +++ b/apps/server/src/kin/approvals/ApproverKeys.ts @@ -322,12 +322,6 @@ const make = Effect.gen(function* () { reason: result.reason, }); } - const existing = yield* select(ref); - if ( - existing !== undefined && - (existing.state !== "pending" || existing.human_id !== person.personId) - ) - return yield* fail("invalid_state", "This key is already registered."); const row = { thumbprint, org_id: input.orgId, @@ -344,12 +338,12 @@ const make = Effect.gen(function* () { revoked_at: null, }; const key = yield* toKey(row); - yield* sql`INSERT INTO kin_approver_keys ${sql.insert(row)} - ON CONFLICT (org_id, thumbprint) DO UPDATE SET - public_jwk_json = excluded.public_jwk_json, device_label = excluded.device_label, - platform = excluded.platform, hardware = excluded.hardware, attested = excluded.attested, - session_id = excluded.session_id, created_at = excluded.created_at - WHERE kin_approver_keys.state = 'pending'`; + // An attestation is bound to the challenge given when the key was made, so a key never + // registers twice; refusing keeps anyone from rewriting a pending key's record. + const inserted = yield* sql`INSERT INTO kin_approver_keys ${sql.insert(row)} + ON CONFLICT (org_id, thumbprint) DO NOTHING RETURNING thumbprint`; + if (inserted.length === 0) + return yield* fail("invalid_state", "This key is already registered; make a new one."); const code = kinKeyConfirmationCode(thumbprint, challenge); if (!result.attested) return { key, code }; diff --git a/docs/kin/specs/approvals.md b/docs/kin/specs/approvals.md index 693a67c71dc5b..85934d67d24e3 100644 --- a/docs/kin/specs/approvals.md +++ b/docs/kin/specs/approvals.md @@ -201,7 +201,7 @@ export const KinApproverKey = Schema.Struct({ Registration: -1. The phone calls `kin.approvals.keyChallenge()` (`access:write`), which returns a single-use 32-byte nonce bound to that session and valid for 5 minutes. It passes the nonce to `createKey`, then calls `kin.approvals.registerKey({publicJwk, platform, challenge, attestation?, deviceLabel})` over the same session. The server consumes the nonce, stores the key as `pending` and returns a 6-digit code derived from `sha256(thumbprint ‖ serverNonce)`, where `serverNonce` is that challenge. Challenges and codes live in server memory: a code is good for 10 minutes and five tries, and after a restart the phone registers again. +1. The phone calls `kin.approvals.keyChallenge()` (`access:write`), which returns a single-use 32-byte nonce bound to that session and valid for 5 minutes. It passes the nonce to `createKey`, then calls `kin.approvals.registerKey({publicJwk, platform, challenge, attestation?, deviceLabel})` over the same session. The server consumes the nonce, stores the key as `pending` and returns a 6-digit code derived from `sha256(thumbprint ‖ serverNonce)`, where `serverNonce` is that challenge. Challenges and codes live in server memory: a code is good for 10 minutes and five tries, and after a restart the phone makes and registers a new key. A thumbprint registers only once. - **Android:** `attestation.certificateChain` is required. The server checks it offline: the chain verifies up to a Google hardware attestation root and no certificate is on Google's attestation revocation list; the leaf's public key equals `publicJwk`; the leaf's KeyDescription has `attestationChallenge` equal to the nonce, `attestationSecurityLevel` and `keyMintSecurityLevel` (`keymasterSecurityLevel` before KeyMint) of `TrustedEnvironment` or `StrongBox`, and in `hardwareEnforced`: purpose `SIGN`, algorithm EC on P-256, digest SHA-256, `userAuthType` biometric only (`FINGERPRINT`, the value Keystore uses for every strong biometric), no `authTimeout`, no `noAuthRequired`, `origin` `GENERATED`, and `rootOfTrust` with `verifiedBootState` `Verified` and `deviceLocked` true; `attestationApplicationId` names the release package with a signing-certificate SHA-256 on the server's allowlist. All pass: `attested: true`, and `hardware` is `strongbox` or `tee` from the attestation security level. Any check fails: `attested: false`, `hardware: "software"`. The client never supplies `hardware`. - **iOS:** no attestation in phase 1, so the key is stored with `attested: false` and `hardware: "secure_enclave"`, which is claimed by the platform, not proven. 2. **First key in an org:** confirmed on the Mac running the server, in the desktop app's local session (loopback only), where the owner checks the code shown on both screens. No remote path can confirm the first key. "Local" means all of: the session's subject is `desktop-bootstrap` (only the desktop app holds that credential), the session was issued to a loopback address, and the call's own socket is loopback with no `Forwarded`, `X-Forwarded-*`, `X-Real-IP`, `CF-Connecting-IP` or `Tailscale-User-Login` header. A browser or tunnel process on the same Mac fails the first check; a desktop on WSL fails the second, so it can't confirm keys. `confirmKey` works only while the org has no active key. From 8a59c87d12eee329776d7f0e087cb21d36f0c143 Mon Sep 17 00:00:00 2001 From: Surajsm60720 <1ds22is166@dsce.edu.in> Date: Sun, 8 Nov 2026 07:48:19 +0530 Subject: [PATCH 05/16] test(kin): generate minimal DER serials in attestation fixtures (APPR-5) Co-Authored-By: Claude Opus 5.5 --- apps/server/src/kin/approvals/attestation/testFixtures.ts | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/apps/server/src/kin/approvals/attestation/testFixtures.ts b/apps/server/src/kin/approvals/attestation/testFixtures.ts index 78efaa759d3e0..7c838595ab915 100644 --- a/apps/server/src/kin/approvals/attestation/testFixtures.ts +++ b/apps/server/src/kin/approvals/attestation/testFixtures.ts @@ -69,6 +69,12 @@ type KeyPair = { }; export const newKey = (): KeyPair => NodeCrypto.generateKeyPairSync("ec", { namedCurve: "P-256" }); +// A positive, minimally encoded INTEGER: no leading zero byte. +const randomSerial = () => { + const bytes = new Uint8Array(NodeCrypto.randomBytes(8)); + bytes[0] = (bytes[0]! & 0x7f) | 0x01; + return bytes; +}; const name = (cn: string) => der.seq(der.set(der.seq(der.oid("2.5.4.3"), der.utf8(cn)))); const ECDSA_SHA256 = der.seq(der.oid("1.2.840.10045.4.3.2")); @@ -95,7 +101,7 @@ function certificate(spec: CertificateSpec): Uint8Array { ]; const tbs = der.seq( der.explicit(0, der.int(2)), - der.serial(spec.serial ?? new Uint8Array(NodeCrypto.randomBytes(8))), + der.serial(spec.serial ?? randomSerial()), ECDSA_SHA256, name(spec.issuer), der.seq( From b17b7542d36cc1ae0726661a5a3ee5c7ea829cee Mon Sep 17 00:00:00 2001 From: Surajsm60720 <1ds22is166@dsce.edu.in> Date: Sun, 8 Nov 2026 08:19:20 +0530 Subject: [PATCH 06/16] fix(kin): anchor Android chains on the pinned root and refuse repeated signers (APPR-5) The chain's own root copy only names a pinned key now; the pinned certificate's validity and signature are checked in its place. A repeated signing digest no longer counts as two allowlisted signers. Co-Authored-By: Claude Opus 5.5 --- .../kin/approvals/attestation/testFixtures.ts | 2 +- .../kin/approvals/attestation/verify.test.ts | 53 +++++++++++++++++++ .../src/kin/approvals/attestation/verify.ts | 14 ++--- 3 files changed, 61 insertions(+), 8 deletions(-) diff --git a/apps/server/src/kin/approvals/attestation/testFixtures.ts b/apps/server/src/kin/approvals/attestation/testFixtures.ts index 7c838595ab915..0720494c3a853 100644 --- a/apps/server/src/kin/approvals/attestation/testFixtures.ts +++ b/apps/server/src/kin/approvals/attestation/testFixtures.ts @@ -90,7 +90,7 @@ export type CertificateSpec = { readonly serial?: Uint8Array; }; -function certificate(spec: CertificateSpec): Uint8Array { +export function certificate(spec: CertificateSpec): Uint8Array { const extensions = [ ...(spec.ca ? [der.seq(der.oid("2.5.29.19"), der.bool(true), der.octet(der.seq(der.bool(true))))] diff --git a/apps/server/src/kin/approvals/attestation/verify.test.ts b/apps/server/src/kin/approvals/attestation/verify.test.ts index 1335c69f9a83f..7376bc60ed3cf 100644 --- a/apps/server/src/kin/approvals/attestation/verify.test.ts +++ b/apps/server/src/kin/approvals/attestation/verify.test.ts @@ -6,6 +6,7 @@ import { assert, describe, it } from "@effect/vitest"; import { androidChain, appleAttestation, + certificate, makeTrustFixture, newKey, type AndroidChainSpec, @@ -80,6 +81,58 @@ describe("Android key attestation", () => { }); }); + it("refuses a repeated signing digest when the allowlist has two", () => { + const signers = ["ab".repeat(32), "cd".repeat(32)]; + const trust = { + ...fixture.trust, + androidApps: [{ packageName: "com.gldroger.kin", signingCertSha256: signers }], + }; + assert.isTrue(verify({ signers }, trust).attested); + const result = verify({ signers: [signers[0]!, signers[0]!] }, trust); + assert.deepStrictEqual(result, { + attested: false, + reason: "signing certificates don't match the allowlist", + }); + }); + + it("checks links and validity against the pinned root, not the copy the chain sends", () => { + // Google reissued its RSA root under the same key, so a device may send either copy. + const reissue = (notAfter: string) => + Buffer.from( + certificate({ + subject: "Test Google Root", + issuer: "Test Google Root", + subjectKey: fixture.googleRoot.publicKey, + issuerKey: fixture.googleRoot.privateKey, + ca: true, + notBefore: "200101000000Z", + notAfter, + }), + ).toString("base64"); + const chain = androidChain(fixture, { challenge }); + const base = { challenge, publicJwk: chain.publicJwk, now: NOW }; + const expiredPin = verifyAndroidKeyAttestation({ + ...base, + certificateChain: chain.certificateChain, + trust: { + ...fixture.trust, + googleRoots: [ + new NodeCrypto.X509Certificate(Buffer.from(reissue("260601000000Z"), "base64")), + ], + }, + }); + assert.deepStrictEqual(expiredPin, { + attested: false, + reason: "certificate 2 is outside its validity", + }); + const expiredCopy = verifyAndroidKeyAttestation({ + ...base, + certificateChain: [...chain.certificateChain.slice(0, -1), reissue("260601000000Z")], + trust: fixture.trust, + }); + assert.deepStrictEqual(expiredCopy, { attested: true, hardware: "strongbox" }); + }); + it("refuses a chain for another key and malformed input", () => { const chain = androidChain(fixture, { challenge }); const other = androidChain(fixture, { challenge }); diff --git a/apps/server/src/kin/approvals/attestation/verify.ts b/apps/server/src/kin/approvals/attestation/verify.ts index d065114c181a4..146725e05d705 100644 --- a/apps/server/src/kin/approvals/attestation/verify.ts +++ b/apps/server/src/kin/approvals/attestation/verify.ts @@ -151,13 +151,12 @@ export function verifyAndroidKeyAttestation(input: { const ders = input.certificateChain.map(decodeBase64); check(ders.length >= 2, "attestation chain is too short"); const chain = ders.map(parseCertificate); - verifyLinks(chain, input.now); - const root = chain[chain.length - 1]!; - const rootKey = spki(root); - check( - input.trust.googleRoots.some((pinned) => equalBytes(spki(pinned), rootKey)), - "chain doesn't end at a Google hardware attestation root", - ); + // The sent root only names a pinned key: Google reissued roots with the same key, so the + // pinned certificate, with its own validity, takes its place before the links are checked. + const rootKey = spki(chain[chain.length - 1]!); + const pinned = input.trust.googleRoots.find((root) => equalBytes(spki(root), rootKey)); + check(pinned !== undefined, "chain doesn't end at a Google hardware attestation root"); + verifyLinks([...chain.slice(0, -1), pinned!], input.now); for (const certificate of chain) { check( !input.trust.androidRevokedSerials.has(normalizeSerial(certificate.serialNumber)), @@ -229,6 +228,7 @@ export function verifyAndroidKeyAttestation(input: { const allowed = new Set(app!.signingCertSha256); check( allowed.size > 0 && + new Set(signers).size === signers.length && signers.length === allowed.size && signers.every((digest) => allowed.has(digest)), "signing certificates don't match the allowlist", From fdc04467133c851bb5e510ac46665dd40e0687d0 Mon Sep 17 00:00:00 2001 From: Surajsm60720 <1ds22is166@dsce.edu.in> Date: Sun, 8 Nov 2026 08:20:15 +0530 Subject: [PATCH 07/16] fix(kin): accept one spelling per approver key coordinate (APPR-5) A 43-character base64url coordinate has two padding bits, so one key could be spelled four ways and get four thumbprints. Co-Authored-By: Claude Opus 5.5 --- packages/contracts/src/kinApprovals.test.ts | 19 +++++++++++++++++++ packages/contracts/src/kinApprovals.ts | 9 +++++++-- 2 files changed, 26 insertions(+), 2 deletions(-) create mode 100644 packages/contracts/src/kinApprovals.test.ts diff --git a/packages/contracts/src/kinApprovals.test.ts b/packages/contracts/src/kinApprovals.test.ts new file mode 100644 index 0000000000000..4bcba222094c6 --- /dev/null +++ b/packages/contracts/src/kinApprovals.test.ts @@ -0,0 +1,19 @@ +import { describe, expect, it } from "@effect/vitest"; +import * as Schema from "effect/Schema"; + +import { KinApproverPublicJwk } from "./kinApprovals.ts"; + +describe("KinApproverPublicJwk", () => { + it("accepts only the canonical spelling of each coordinate", () => { + const is = Schema.is(KinApproverPublicJwk); + const jwk = { + kty: "EC", + crv: "P-256", + x: "f83OJ3D2xF1Bg8vub9tLe1gHMzV76e8Tus9uPHvRVEU", + y: "x_FEzRu9m36HLN_tue659LNpXW6pCyStikYjKIWI5a0", + }; + expect(is(jwk)).toBe(true); + // "U" and "V" differ only in a padding bit: the same 32 bytes under a second thumbprint. + expect(is({ ...jwk, x: `${jwk.x.slice(0, 42)}V` })).toBe(false); + }); +}); diff --git a/packages/contracts/src/kinApprovals.ts b/packages/contracts/src/kinApprovals.ts index 09f0411bfed59..1abe3923ea791 100644 --- a/packages/contracts/src/kinApprovals.ts +++ b/packages/contracts/src/kinApprovals.ts @@ -195,11 +195,16 @@ export const KinPendingAction = Schema.Struct({ }); export type KinPendingAction = typeof KinPendingAction.Type; +// 43 characters carry 258 bits; the last two must be zero, so a key has one spelling and one thumbprint. +const P256Coordinate = pattern( + /^[A-Za-z0-9_-]{42}[AEIMQUYcgkosw048]$/, + "a canonical base64url P-256 coordinate", +); export const KinApproverPublicJwk = Schema.Struct({ kty: Schema.Literal("EC"), crv: Schema.Literal("P-256"), - x: pattern(/^[A-Za-z0-9_-]{43}$/, "a base64url P-256 coordinate"), - y: pattern(/^[A-Za-z0-9_-]{43}$/, "a base64url P-256 coordinate"), + x: P256Coordinate, + y: P256Coordinate, }); export type KinApproverPublicJwk = typeof KinApproverPublicJwk.Type; From 41a4de9afb82236e2c6714176b85e0963fef71cf Mon Sep 17 00:00:00 2001 From: Surajsm60720 <1ds22is166@dsce.edu.in> Date: Sun, 8 Nov 2026 08:28:46 +0530 Subject: [PATCH 08/16] fix(kin): reserve the approver key requester id (APPR-5) KinPendingActions.create refuses kin-approver-keys as an agent or thread id except on the register_approver_key action registerKey opens, so an agent can't pose as the phone on a card. Co-Authored-By: Claude Opus 5.5 --- apps/server/src/kin/approvals/ApproverKeys.ts | 7 +++---- .../src/kin/approvals/PendingActions.test.ts | 14 ++++++++++++++ apps/server/src/kin/approvals/PendingActions.ts | 13 ++++++++++++- 3 files changed, 29 insertions(+), 5 deletions(-) diff --git a/apps/server/src/kin/approvals/ApproverKeys.ts b/apps/server/src/kin/approvals/ApproverKeys.ts index 03a63cbc934ad..172fd7d3dda1d 100644 --- a/apps/server/src/kin/approvals/ApproverKeys.ts +++ b/apps/server/src/kin/approvals/ApproverKeys.ts @@ -43,7 +43,7 @@ import { verifyAppleAppAttest, type AttestationResult, } from "./attestation/verify.ts"; -import { KinPendingActions } from "./PendingActions.ts"; +import { KIN_APPROVER_KEYS_REQUESTER, KinPendingActions } from "./PendingActions.ts"; const CHALLENGE_TTL_MS = 5 * 60 * 1000; const CONFIRM_TTL_MS = 10 * 60 * 1000; @@ -96,10 +96,9 @@ const decodeEventId = Schema.decodeEffect(KinEventId); const decodeTarget = Schema.decodeUnknownEffect(KinActionTarget); const isKinApprovalError = Schema.is(KinApprovalError); -// Not an agent: the phone asked for this action, and the approver signs it on an existing key. const SERVER_REQUESTER = { - agentId: Schema.decodeSync(KinAgentId)("kin-approver-keys"), - threadId: Schema.decodeSync(ThreadId)("kin-approver-keys"), + agentId: Schema.decodeSync(KinAgentId)(KIN_APPROVER_KEYS_REQUESTER), + threadId: Schema.decodeSync(ThreadId)(KIN_APPROVER_KEYS_REQUESTER), }; const fail = (reason: KinApprovalError["reason"], message: string) => diff --git a/apps/server/src/kin/approvals/PendingActions.test.ts b/apps/server/src/kin/approvals/PendingActions.test.ts index 21610dfbabcff..f4e7806827b8b 100644 --- a/apps/server/src/kin/approvals/PendingActions.test.ts +++ b/apps/server/src/kin/approvals/PendingActions.test.ts @@ -8,6 +8,7 @@ import { } from "@t3tools/contracts"; import * as Clock from "effect/Clock"; import * as Effect from "effect/Effect"; +import * as Exit from "effect/Exit"; import * as Layer from "effect/Layer"; import * as Option from "effect/Option"; import * as Schema from "effect/Schema"; @@ -107,6 +108,19 @@ describe("KinPendingActions", () => { } as unknown as KinPendingActionCreateInput); assert.isFalse(withExtra.created); assert.strictEqual(withExtra.action.id, first.action.id); + // Key registration's requester id is reserved, so an agent can't pose as the phone. + for (const requestedBy of [ + { agentId: "kin-approver-keys", threadId: "thread-lead" }, + { agentId: "kin-approver-keys", threadId: "kin-approver-keys" }, + ]) { + const posing = yield* Effect.exit( + actions.create({ + ...request("webhook-delivery-2"), + requestedBy, + } as unknown as KinPendingActionCreateInput), + ); + assert.isTrue(Exit.isFailure(posing)); + } const twice = yield* Effect.all( [ diff --git a/apps/server/src/kin/approvals/PendingActions.ts b/apps/server/src/kin/approvals/PendingActions.ts index 56832538d5688..09265adade588 100644 --- a/apps/server/src/kin/approvals/PendingActions.ts +++ b/apps/server/src/kin/approvals/PendingActions.ts @@ -39,6 +39,8 @@ const AWAITING_TTL_MS = 7 * 24 * 60 * 60 * 1000; // A grant lapses at min(exp, acceptedAt + 15 min) (approvals spec section 5). const GRANT_ACCEPTED_TTL_MS = 15 * 60 * 1000; +/** `registerKey`'s requester: the phone asked, not an agent, so no agent may use this id. */ +export const KIN_APPROVER_KEYS_REQUESTER = "kin-approver-keys"; const CreateInput = Schema.Struct({ orgId: KinOrgId, kind: KinActionKind, @@ -49,7 +51,16 @@ const CreateInput = Schema.Struct({ requestedBy: Schema.Struct({ agentId: KinAgentId, threadId: ThreadId }), provenance: KinProvenance, source: KinEventId, -}); +}).check( + Schema.makeFilter( + ({ kind, requestedBy: { agentId, threadId } }) => + (agentId !== KIN_APPROVER_KEYS_REQUESTER && threadId !== KIN_APPROVER_KEYS_REQUESTER) || + (kind === "register_approver_key" && + agentId === KIN_APPROVER_KEYS_REQUESTER && + threadId === KIN_APPROVER_KEYS_REQUESTER), + { expected: `a requester other than the reserved ${KIN_APPROVER_KEYS_REQUESTER}` }, + ), +); export type KinPendingActionCreateInput = typeof CreateInput.Type; const decodeCreateInput = Schema.decodeEffect(CreateInput); const StoredAction = Schema.Struct({ From de7d052283a8824637eb1d0bf02478354573cd14 Mon Sep 17 00:00:00 2001 From: Surajsm60720 <1ds22is166@dsce.edu.in> Date: Sun, 8 Nov 2026 08:29:03 +0530 Subject: [PATCH 09/16] fix(kin): keep the registering DPoP key on approver keys (APPR-5) Relay sessions renew hourly under a new id, so matching the session id alone stops revoking keys after the first hour. Keys now store the registering session's DPoP thumbprint; auth_sessions doesn't record it yet, so the spec hands the reconcile hook to lane A. Also: the pending key errors point at making a new key, the spec calls the loopback socket check defence in depth, and connectionOf has a test. Co-Authored-By: Claude Opus 5.5 --- apps/server/src/kin/approvals/ApproverKeys.ts | 11 ++++++-- .../src/kin/approvals/rpcHandlers.test.ts | 27 +++++++++++++++++++ apps/server/src/kin/approvals/rpcHandlers.ts | 2 +- .../persistence/migrations/K009_Approvals.ts | 1 + docs/kin/specs/approvals.md | 11 +++++--- 5 files changed, 45 insertions(+), 7 deletions(-) create mode 100644 apps/server/src/kin/approvals/rpcHandlers.test.ts diff --git a/apps/server/src/kin/approvals/ApproverKeys.ts b/apps/server/src/kin/approvals/ApproverKeys.ts index 172fd7d3dda1d..10c7925abc694 100644 --- a/apps/server/src/kin/approvals/ApproverKeys.ts +++ b/apps/server/src/kin/approvals/ApproverKeys.ts @@ -84,6 +84,7 @@ type KeyRow = { readonly hardware: string; readonly attested: number; readonly session_id: string | null; + readonly proof_key_thumbprint: string | null; readonly state: string; readonly created_at: number; readonly confirmed_at: number | null; @@ -331,6 +332,8 @@ const make = Effect.gen(function* () { hardware: result.attested ? result.hardware : "software", attested: result.attested ? 1 : 0, session_id: caller.session.sessionId, + // Relay sessions renew hourly under a new id; this DPoP key stays (spec section 4). + proof_key_thumbprint: caller.session.proofKeyThumbprint ?? null, state: "pending", created_at: now, confirmed_at: null, @@ -342,7 +345,10 @@ const make = Effect.gen(function* () { const inserted = yield* sql`INSERT INTO kin_approver_keys ${sql.insert(row)} ON CONFLICT (org_id, thumbprint) DO NOTHING RETURNING thumbprint`; if (inserted.length === 0) - return yield* fail("invalid_state", "This key is already registered; make a new one."); + return yield* fail( + "invalid_state", + "This key is already registered; make a new key on the phone.", + ); const code = kinKeyConfirmationCode(thumbprint, challenge); if (!result.attested) return { key, code }; @@ -365,6 +371,7 @@ const make = Effect.gen(function* () { requestedBy: SERVER_REQUESTER, provenance: { startedBy: { humanId: person.personId }, + // `KinIdentity.resolve` yields only the org owner until CHAT-11 adds roles (spec, Interfaces). startedByRole: "owner", chain: [{ kind: "approver_key", id: thumbprint, authorRole: "owner" }], }, @@ -415,7 +422,7 @@ const make = Effect.gen(function* () { const now = yield* Clock.currentTimeMillis; const pending = confirmations.get(slot(ref)); if (pending === undefined || pending.expiresAt <= now) - return yield* fail("bad_code", "The code expired; register the key again."); + return yield* fail("bad_code", "The code expired; make a new key on the phone."); if (!sameBytes(pending.code, input.code)) { pending.attempts += 1; if (pending.attempts >= MAX_CODE_ATTEMPTS) confirmations.delete(slot(ref)); diff --git a/apps/server/src/kin/approvals/rpcHandlers.test.ts b/apps/server/src/kin/approvals/rpcHandlers.test.ts new file mode 100644 index 0000000000000..26d663ad5d8dd --- /dev/null +++ b/apps/server/src/kin/approvals/rpcHandlers.test.ts @@ -0,0 +1,27 @@ +import { assert, it } from "@effect/vitest"; +import * as Effect from "effect/Effect"; +import * as Option from "effect/Option"; +import * as HttpServerRequest from "effect/http/HttpServerRequest"; + +import { connectionOf } from "./rpcHandlers.ts"; + +it.effect("reads the call's socket and headers from the upgrade request", () => + Effect.gen(function* () { + const upgrade = HttpServerRequest.fromWeb( + new Request("http://127.0.0.1/ws", { headers: { "X-Forwarded-For": "203.0.113.9" } }), + ).modify({ remoteAddress: Option.some("::ffff:127.0.0.1") }); + const read = (request: HttpServerRequest.HttpServerRequest) => + connectionOf.pipe(Effect.provideService(HttpServerRequest.HttpServerRequest, request)); + + const direct = Option.getOrThrow(yield* read(upgrade)); + assert.strictEqual(direct.remoteAddress, "::ffff:127.0.0.1"); + assert.strictEqual(direct.headers["x-forwarded-for"], "203.0.113.9"); + // A proxy-rewritten remote address hides the real socket, so there's no connection to trust. + const rewritten = upgrade.modify({ + remoteAddress: Option.some("127.0.0.1"), + peerAddress: Option.some("10.0.0.5"), + }); + assert.isTrue(Option.isNone(yield* read(rewritten))); + assert.isTrue(Option.isNone(yield* connectionOf)); + }), +); diff --git a/apps/server/src/kin/approvals/rpcHandlers.ts b/apps/server/src/kin/approvals/rpcHandlers.ts index 1934ceac679ed..9b92f5a2102c3 100644 --- a/apps/server/src/kin/approvals/rpcHandlers.ts +++ b/apps/server/src/kin/approvals/rpcHandlers.ts @@ -18,7 +18,7 @@ const unavailable = Effect.fail( ); // The WS upgrade request, so `confirmKey` can tell a loopback socket from a proxied one. -const connectionOf = Effect.serviceOption(HttpServerRequest.HttpServerRequest).pipe( +export const connectionOf = Effect.serviceOption(HttpServerRequest.HttpServerRequest).pipe( Effect.map( Option.flatMap((request) => { const peer = Option.getOrUndefined(request.peerAddress); diff --git a/apps/server/src/kin/persistence/migrations/K009_Approvals.ts b/apps/server/src/kin/persistence/migrations/K009_Approvals.ts index 678103b3b66b6..5f41d091d2ec0 100644 --- a/apps/server/src/kin/persistence/migrations/K009_Approvals.ts +++ b/apps/server/src/kin/persistence/migrations/K009_Approvals.ts @@ -79,6 +79,7 @@ export default Effect.gen(function* () { hardware TEXT NOT NULL CHECK (hardware IN ('secure_enclave', 'strongbox', 'tee', 'software')), attested INTEGER NOT NULL CHECK (attested IN (0, 1)), session_id TEXT, + proof_key_thumbprint TEXT, state TEXT NOT NULL CHECK (state IN ('pending', 'active', 'revoked')), created_at INTEGER NOT NULL, confirmed_at INTEGER, diff --git a/docs/kin/specs/approvals.md b/docs/kin/specs/approvals.md index ee3cecbaff9fe..b816e76edfe09 100644 --- a/docs/kin/specs/approvals.md +++ b/docs/kin/specs/approvals.md @@ -202,11 +202,11 @@ export const KinApproverKey = Schema.Struct({ Registration: 1. The phone calls `kin.approvals.keyChallenge()` (`access:write`), which returns a single-use 32-byte nonce bound to that session and valid for 5 minutes. It passes the nonce to `createKey`, then calls `kin.approvals.registerKey({publicJwk, platform, challenge, attestation?, deviceLabel})` over the same session. The server consumes the nonce, stores the key as `pending` and returns a 6-digit code derived from `sha256(thumbprint ‖ serverNonce)`, where `serverNonce` is that challenge. Challenges and codes live in server memory: a code is good for 10 minutes and five tries, and after a restart the phone makes and registers a new key. A thumbprint registers only once. - - **Android:** `attestation.certificateChain` is required. The server checks it offline: the chain verifies up to a Google hardware attestation root and no certificate is on Google's attestation revocation list; the leaf's public key equals `publicJwk`; the leaf's KeyDescription has `attestationChallenge` equal to the nonce, `attestationSecurityLevel` and `keyMintSecurityLevel` (`keymasterSecurityLevel` before KeyMint) of `TrustedEnvironment` or `StrongBox`, and in `hardwareEnforced`: purpose `SIGN`, algorithm EC on P-256, digest SHA-256, `userAuthType` biometric only (`FINGERPRINT`, the value Keystore uses for every strong biometric), no `authTimeout`, no `noAuthRequired`, `origin` `GENERATED`, and `rootOfTrust` with `verifiedBootState` `Verified` and `deviceLocked` true; `attestationApplicationId` names the release package with a signing-certificate SHA-256 on the server's allowlist. All pass: `attested: true`, and `hardware` is `strongbox` or `tee` from the attestation security level. Any check fails: `attested: false`, `hardware: "software"`. The client never supplies `hardware`. + - **Android:** `attestation.certificateChain` is required. The server checks it offline: the chain verifies up to a pinned Google hardware attestation root and no certificate is on Google's attestation revocation list; the leaf's public key equals `publicJwk`; the leaf's KeyDescription has `attestationChallenge` equal to the nonce, `attestationSecurityLevel` and `keyMintSecurityLevel` (`keymasterSecurityLevel` before KeyMint) of `TrustedEnvironment` or `StrongBox`, and in `hardwareEnforced`: purpose `SIGN`, algorithm EC on P-256, digest SHA-256, `userAuthType` biometric only (`FINGERPRINT`, the value Keystore uses for every strong biometric), no `authTimeout`, no `noAuthRequired`, `origin` `GENERATED`, and `rootOfTrust` with `verifiedBootState` `Verified` and `deviceLocked` true; `attestationApplicationId` names the release package with exactly the allowlisted signing-certificate SHA-256s, each once. The chain's last certificate only has to carry a pinned root's key, since Google reissued its RSA root under the same key; the pinned certificate takes its place, so its own validity and its signature on the next certificate are what count. All pass: `attested: true`, and `hardware` is `strongbox` or `tee` from the attestation security level. Any check fails: `attested: false`, `hardware: "software"`. The client never supplies `hardware`. - **iOS:** no attestation in phase 1, so the key is stored with `attested: false` and `hardware: "secure_enclave"`, which is claimed by the platform, not proven. -2. **First key in an org:** confirmed on the Mac running the server, in the desktop app's local session (loopback only), where the owner checks the code shown on both screens. No remote path can confirm the first key. "Local" means all of: the session's subject is `desktop-bootstrap` (only the desktop app holds that credential), the session was issued to a loopback address, and the call's own socket is loopback with no `Forwarded`, `X-Forwarded-*`, `X-Real-IP`, `CF-Connecting-IP` or `Tailscale-User-Login` header. A browser or tunnel process on the same Mac fails the first check; a desktop on WSL fails the second, so it can't confirm keys. `confirmKey` works only while the org has no active key. -3. **Later keys:** confirmed by a grant of kind `register_approver_key` signed by an existing active key. When an attested key registers in an org that already has an active key, `registerKey` opens that pending action itself (requester `kin-approver-keys`, provenance started by the registering person), and the handler activates the key only if it is still `pending`, attested and on the hardware the card showed. -4. Revoking (`kin.approvals.revokeKey`, from settings or the desktop) sets `revoked` and voids every `approved` action whose grant that key signed. Revoking a T3 device session (`revokeClient`) also revokes keys registered from it. Kin reads `auth_sessions.revoked_at` at startup and before it trusts, lists or activates a key, rather than hooking T3's auth code. Revoking also cancels a pending `register_approver_key` action for the key. Expiry is not revocation: a key outlives the session that registered it. A DPoP relay session that renews hourly gets a new session id, so revoking it later doesn't reach a key registered from an earlier one. +2. **First key in an org:** confirmed on the Mac running the server, in the desktop app's local session (loopback only), where the owner checks the code shown on both screens. No remote path can confirm the first key. "Local" means all of: the session's subject is `desktop-bootstrap` (only the desktop app holds that credential), the session was issued to a loopback address, and the call's own socket is loopback with no `Forwarded`, `X-Forwarded-*`, `X-Real-IP`, `CF-Connecting-IP` or `Tailscale-User-Login` header. A browser or tunnel process on the same Mac fails the first check; a desktop on WSL fails the second, so it can't confirm keys. The subject and the issuance address are the real guard. The socket check is defence in depth, since a proxy on the same Mac connects over loopback and can drop those headers. `confirmKey` works only while the org has no active key. +3. **Later keys:** confirmed by a grant of kind `register_approver_key` signed by an existing active key. When an attested key registers in an org that already has an active key, `registerKey` opens that pending action itself (requester `kin-approver-keys`, provenance started by the registering person). That requester id is reserved: `KinPendingActions.create` refuses it for any other kind, and as an agent or thread id, and the handler activates the key only if it is still `pending`, attested and on the hardware the card showed. +4. Revoking (`kin.approvals.revokeKey`, from settings or the desktop) sets `revoked` and voids every `approved` action whose grant that key signed. Revoking a T3 device session (`revokeClient`) also revokes keys registered from it. Kin reads `auth_sessions.revoked_at` at startup and before it trusts, lists or activates a key, rather than hooking T3's auth code. Revoking also cancels a pending `register_approver_key` action for the key. Expiry is not revocation: a key outlives the session that registered it. A DPoP relay session renews hourly under a new session id but the same DPoP key, so each key also stores that key's thumbprint (`proof_key_thumbprint`). Until `auth_sessions` records it too (see Interfaces, T3 auth), revoking a renewed session doesn't reach the key; revoke the key itself. The server's attestation allowlist comes from `KIN_ANDROID_PACKAGE`, `KIN_ANDROID_SIGNING_CERT_SHA256` (comma-separated hex), `KIN_IOS_APP_ID` (`.`) and `KIN_IOS_APP_ATTEST_DEVELOPMENT` (accept `appattestdevelop`; default false). With none set, every key registers unattested. Google's roots and Apple's App Attest root are pinned in `apps/server/src/kin/approvals/attestation/roots.ts`. Google's revocation list is fetched from `https://android.googleapis.com/attestation/status` and cached for an hour. If it can't be fetched, Android registration fails and the phone retries; it never stores a key whose chain went unchecked. @@ -480,6 +480,9 @@ RPCs and scopes: `kin.approvals.list` (stream) and `get` → `orchestration:read - **Lead:** registry of lead threads (for `request_action`), `KinEvent.id` (idempotency) and provenance, the stop switch (executor checks it), levels (`set_level` handler, `ceilingAllows`), `change_rules` handler. - **Triggers:** `pull_request` synchronize/closed webhooks → `refreshAction(actionId)`; `pull_request_review` → enables a card waiting on a GitHub review; `memory_purge` handler; Kin host setup (bot `gh` login, keychain items, hygiene check passing); upstream contract test for `GitHubRequestPolicy.credential` and `verifyDpopProof`. - **Mobile:** renders `ApprovalCard` inside the chat screens; this spec ships the card, the native module and the signing hook. +- **T3 auth (lane A), open hand-offs:** + - `SessionStore.issue` writes `claims.jkt` to a new nullable `auth_sessions.proof_key_thumbprint` column. `ApproverKeys.reconcileSessions` then also revokes a key when a revoked session matches `kin_approver_keys.proof_key_thumbprint`, which closes the hourly-renewal gap in section 4. Test: register over a DPoP session, renew, revoke the new session, and the key is `revoked`. + - `KinIdentity.resolve` returns each person's org role once members exist (CHAT-11). `registerKey` then refuses anyone but the owner and takes `startedByRole` from that role. Until then, `resolve` returns only the org owner, so the literal `"owner"` is accurate. ## Security tests (named, all in `apps/server/src/kin/approvals/*.test.ts` unless noted) From dca6609597fa5f2aca57fc39dca0ab861232a93c Mon Sep 17 00:00:00 2001 From: Surajsm60720 <1ds22is166@dsce.edu.in> Date: Sun, 8 Nov 2026 18:15:38 +0530 Subject: [PATCH 10/16] fix(kin): revoke approver keys through renewed relay sessions A relay phone's DPoP session renews hourly under a new id, so revoking it never matched the session an approver key was registered from. Reconcile now also revokes a key when any session of its proof key was individually revoked before it expired (kin_auth_session_keys, #54), and the direct session check follows the same rule, so "sign out other devices" keeps the caller's own key and revocations after expiry don't count. Registration refuses a proof key with such a revocation, since repairs don't restore approver keys. Co-Authored-By: Claude Opus 5.5 --- .../src/kin/approvals/ApproverKeys.test.ts | 90 +++++++++++++++++++ apps/server/src/kin/approvals/ApproverKeys.ts | 22 ++++- .../src/kin/auth/ProofKeySessions.test.ts | 12 +-- .../src/kin/auth/ProofKeySessions.testkit.ts | 50 +++++++++++ apps/server/src/kin/auth/ProofKeySessions.ts | 42 +++++++-- docs/kin/specs/approvals.md | 17 ++-- 6 files changed, 208 insertions(+), 25 deletions(-) create mode 100644 apps/server/src/kin/auth/ProofKeySessions.testkit.ts diff --git a/apps/server/src/kin/approvals/ApproverKeys.test.ts b/apps/server/src/kin/approvals/ApproverKeys.test.ts index 4e01802f39d6c..7e980c658d974 100644 --- a/apps/server/src/kin/approvals/ApproverKeys.test.ts +++ b/apps/server/src/kin/approvals/ApproverKeys.test.ts @@ -8,6 +8,7 @@ import { type KinApprovalsRegisterKeyInput, type KinPendingAction, } from "@t3tools/contracts"; +import * as Duration from "effect/Duration"; import * as Effect from "effect/Effect"; import * as Exit from "effect/Exit"; import * as Layer from "effect/Layer"; @@ -16,7 +17,9 @@ import * as Schema from "effect/Schema"; import * as SqlClient from "effect/sql/SqlClient"; import * as TestClock from "effect/testing/TestClock"; +import * as SessionStore from "../../auth/SessionStore.ts"; import * as Sqlite from "../../persistence/Sqlite.ts"; +import { layerKinAuthTest, repairProofKey } from "../auth/ProofKeySessions.testkit.ts"; import * as KinPersistence from "../persistence/KinPersistence.ts"; import { ApproverKeys, @@ -46,6 +49,14 @@ const layer = approverKeysLayer.pipe( Layer.provideMerge(database), ); +// Real T3 auth with Kin's proof key hooks, so revocations write what #54 writes. +const relayLayer = approverKeysLayer.pipe( + Layer.provideMerge(pendingActionsLayer), + Layer.provide(trustLayer), + Layer.provideMerge(KinPersistence.layer), + Layer.provideMerge(layerKinAuthTest("kin-approver-keys-")), +); + const orgId = Schema.decodeSync(KinOrgId)("org_01"); const owner = Schema.decodeSync(KinPersonId)("h_owner"); const sessionId = Schema.decodeSync(AuthSessionId); @@ -80,6 +91,32 @@ const seed = Effect.gen(function* () { return { keys: yield* ApproverKeys, actions: yield* KinPendingActions, sql }; }); +/** A relay phone: a DPoP session that renews hourly under a new id with the same proof key. */ +const relayPhone = (id: AuthSessionId, proofKeyThumbprint: string): KinKeyCaller => ({ + session: { + sessionId: id, + subject: "phone", + method: "dpop-access-token", + scopes: [], + proofKeyThumbprint, + }, + people: [{ _tag: "person", orgId, personId: owner }], + connection: Option.some({ remoteAddress: "100.64.0.9", headers: {} }), +}); + +const seedRelay = Effect.gen(function* () { + yield* TestClock.setTime(NOW); + const sql = yield* SqlClient.SqlClient; + yield* sql`INSERT INTO kin_orgs (org_id, name, created_at) + VALUES ('org_01', 'Kin', '2026-11-07T00:00:00.000Z')`; + const sessions = yield* SessionStore.SessionStore; + const relay = (proofKey: string) => + sessions + .issue({ proofKeyThumbprint: proofKey, ttl: Duration.hours(1) }) + .pipe(Effect.map((issued) => relayPhone(issued.sessionId, proofKey))); + return { keys: yield* ApproverKeys, sessions, relay }; +}); + const registerAndroid = ( keys: ApproverKeys["Service"], from: KinKeyCaller = phone, @@ -250,6 +287,59 @@ describe("ApproverKeys", () => { }).pipe(Effect.provide(layer)), ); + it.effect( + "revoking a renewed relay session revokes the key registered under an earlier one", + () => + Effect.gen(function* () { + const { keys, sessions, relay } = yield* seedRelay; + const { key } = yield* registerAndroid(keys, yield* relay("phone-a")); + yield* TestClock.adjust(Duration.minutes(61)); + const renewed = yield* relay("phone-a"); + yield* sessions.revoke(renewed.session.sessionId); + assert.strictEqual(Option.getOrThrow(yield* keys.get(key)).state, "revoked"); + }).pipe(Effect.provide(relayLayer)), + ); + + it.effect("signing out other devices from a phone keeps its own key and revokes the others", () => + Effect.gen(function* () { + const { keys, sessions, relay } = yield* seedRelay; + const own = yield* registerAndroid(keys, yield* relay("phone-a")); + const other = yield* registerAndroid(keys, yield* relay("phone-b")); + yield* TestClock.adjust(Duration.minutes(30)); + // Both renew early; the phone's first session is still live when it signs the others out. + const current = yield* relay("phone-a"); + yield* relay("phone-b"); + yield* sessions.revokeAllExcept(current.session.sessionId); + assert.strictEqual(Option.getOrThrow(yield* keys.get(own.key)).state, "pending"); + assert.strictEqual(Option.getOrThrow(yield* keys.get(other.key)).state, "revoked"); + }).pipe(Effect.provide(relayLayer)), + ); + + it.effect("revoking a session after it expired leaves its key alone", () => + Effect.gen(function* () { + const { keys, sessions, relay } = yield* seedRelay; + const phoneA = yield* relay("phone-a"); + const { key } = yield* registerAndroid(keys, phoneA); + yield* TestClock.adjust(Duration.minutes(61)); + yield* sessions.revoke(phoneA.session.sessionId); + assert.strictEqual(Option.getOrThrow(yield* keys.get(key)).state, "pending"); + }).pipe(Effect.provide(relayLayer)), + ); + + it.effect("a proof key revoked before can't register an approver key, even repaired", () => + Effect.gen(function* () { + const { keys, sessions, relay } = yield* seedRelay; + yield* sessions.revoke((yield* relay("phone-a")).session.sessionId); + const repaired = yield* repairProofKey("phone-a"); + const exit = yield* Effect.exit( + registerAndroid(keys, relayPhone(repaired.sessionId, "phone-a")), + ); + assert.strictEqual(reasonOf(exit), "invalid_state"); + const fresh = yield* registerAndroid(keys, yield* relay("phone-a-fresh")); + assert.strictEqual(fresh.key.state, "pending"); + }).pipe(Effect.provide(relayLayer)), + ); + it.effect("the server never activates an unattested key", () => Effect.gen(function* () { const { keys } = yield* seed; diff --git a/apps/server/src/kin/approvals/ApproverKeys.ts b/apps/server/src/kin/approvals/ApproverKeys.ts index 10c7925abc694..65ee886e8e59f 100644 --- a/apps/server/src/kin/approvals/ApproverKeys.ts +++ b/apps/server/src/kin/approvals/ApproverKeys.ts @@ -36,6 +36,7 @@ import * as Base64Url from "effect/encoding/Base64Url"; import * as SqlClient from "effect/sql/SqlClient"; import type { AuthenticatedSession } from "../../auth/EnvironmentAuth.ts"; +import { proofKeyRevoked, revokedBySession } from "../auth/ProofKeySessions.ts"; import type { PersonIdentity } from "../chat/KinIdentity.ts"; import { KinAttestationTrust } from "./attestation/AttestationTrust.ts"; import { @@ -245,12 +246,17 @@ const make = Effect.gen(function* () { // T3 revokes sessions in SessionStore (revokeClient, revokeOtherClients, managed policy). // Reading its table here keeps auth free of Kin hooks, and runs before every key is trusted. + // Relay sessions renew under new ids, so the DPoP key's own revocations count too (spec section 4). const reconcileSessions = Effect.fn("ApproverKeys.reconcileSessions")( function* () { const rows = yield* sql<{ org_id: KinOrgId; thumbprint: KinKeyThumbprint }>` SELECT k.org_id, k.thumbprint FROM kin_approver_keys k - JOIN auth_sessions s ON s.session_id = k.session_id - WHERE k.state != 'revoked' AND s.revoked_at IS NOT NULL`; + WHERE k.state != 'revoked' AND ${revokedBySession( + sql, + { sessionId: sql`k.session_id`, proofKey: sql`k.proof_key_thumbprint` }, + // A repair re-trusts a proof key, never an approver key (spec section 4). + { honorRepairs: false }, + )}`; for (const row of rows) { yield* revokeRow({ orgId: row.org_id, thumbprint: row.thumbprint }, "session_revoked"); } @@ -312,6 +318,18 @@ const make = Effect.gen(function* () { return yield* fail("bad_challenge", "Ask for a new key challenge on this connection."); const challenge = new Uint8Array(Buffer.from(input.challenge, "base64url")); yield* reconcileSessions(); + // Reconcile ignores repairs, so a key from a re-paired proof key would be revoked at once. + const proofKey = caller.session.proofKeyThumbprint; + if (proofKey !== undefined) { + const [seen] = yield* sql<{ revoked: number }>`SELECT ${proofKeyRevoked(sql, proofKey, { + honorRepairs: false, + })} AS revoked`; + if (seen?.revoked === 1) + return yield* fail( + "invalid_state", + "This phone's connection key was revoked before. Pair the phone again so it makes a new key, then add the approver key.", + ); + } const thumbprint = computeDpopJwkThumbprint(input.publicJwk) as KinKeyThumbprint; const ref = { orgId: input.orgId, thumbprint }; diff --git a/apps/server/src/kin/auth/ProofKeySessions.test.ts b/apps/server/src/kin/auth/ProofKeySessions.test.ts index 26a092953cbb0..eb61630fe9e96 100644 --- a/apps/server/src/kin/auth/ProofKeySessions.test.ts +++ b/apps/server/src/kin/auth/ProofKeySessions.test.ts @@ -341,8 +341,6 @@ it.layer(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))("Kin proof key se Effect.gen(function* () { const sessions = yield* SessionStore.SessionStore; const sql = yield* SqlClient.SqlClient; - yield* sql`CREATE TABLE kin_approver_keys (org_id TEXT, thumbprint TEXT, proof_key_thumbprint TEXT, state TEXT)`; - yield* sql`INSERT INTO kin_approver_keys VALUES ('org', 'signing-key', 'device', 'active'), ('org', 'other-signing-key', 'other', 'active')`; const original = yield* sessions.issue({ proofKeyThumbprint: "device", ttl: Duration.hours(1), @@ -356,12 +354,10 @@ it.layer(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))("Kin proof key se const renewed = yield* sessions.issue({ proofKeyThumbprint: "device" }); yield* TestClock.adjust(Duration.minutes(2)); yield* sessions.revoke(renewed.sessionId); - expect( - yield* sql`SELECT DISTINCT k.org_id, k.thumbprint FROM kin_approver_keys k - JOIN kin_auth_session_keys m ON m.proof_key_thumbprint = k.proof_key_thumbprint - JOIN auth_sessions s ON s.session_id = m.session_id - WHERE k.state != 'revoked' AND s.revoked_at IS NOT NULL`, - ).toEqual([{ org_id: "org", thumbprint: "signing-key" }]); + const revoked = (proofKey: string) => + sql`SELECT ${ProofKeySessions.proofKeyRevoked(sql, proofKey, { honorRepairs: false })} AS revoked`; + expect(yield* revoked("device")).toEqual([{ revoked: 1 }]); + expect(yield* revoked("other")).toEqual([{ revoked: 0 }]); expect( yield* sql`SELECT * FROM kin_auth_session_keys WHERE session_id = ${unbound.sessionId}`, ).toEqual([]); diff --git a/apps/server/src/kin/auth/ProofKeySessions.testkit.ts b/apps/server/src/kin/auth/ProofKeySessions.testkit.ts new file mode 100644 index 0000000000000..dbc6e5add5d7f --- /dev/null +++ b/apps/server/src/kin/auth/ProofKeySessions.testkit.ts @@ -0,0 +1,50 @@ +import * as NodeCrypto from "@effect/platform-node/NodeCrypto"; +import * as NodeServices from "@effect/platform-node/NodeServices"; +import * as ConfigProvider from "effect/ConfigProvider"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; +import * as SqlClient from "effect/sql/SqlClient"; + +import * as EnvironmentAuth from "../../auth/EnvironmentAuth.ts"; +import * as SessionStore from "../../auth/SessionStore.ts"; +import * as ServerConfig from "../../config.ts"; +import * as Sqlite from "../../persistence/Sqlite.ts"; +import * as ManagedPolicy from "../../policy/ManagedPolicy.ts"; +import { layerAuth } from "../../server.ts"; + +/** T3 auth with Kin on, so session issue and revoke write the proof key marks #54 defines. */ +export const layerKinAuthTest = (prefix: string) => + layerAuth.pipe( + Layer.provide(ManagedPolicy.layerTest()), + Layer.provide( + Layer.succeed( + ConfigProvider.ConfigProvider, + ConfigProvider.fromEnv({ env: { KIN_ENABLED: "true" } }), + ), + ), + Layer.provideMerge(Sqlite.layerConfig), + Layer.provide(ServerConfig.layerTest(process.cwd(), { prefix })), + Layer.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer)), + ); + +/** The owner's `--repair-proof-key` pairing, exchanged by the phone holding that key. */ +export const repairProofKey = Effect.fn("ProofKeySessions.testkit.repairProofKey")(function* ( + thumbprint: string, +) { + const auth = yield* EnvironmentAuth.EnvironmentAuth; + const sessions = yield* SessionStore.SessionStore; + const sql = yield* SqlClient.SqlClient; + const link = yield* auth.createPairingLink({ + subject: "one-time-token", + proofKeyThumbprint: thumbprint, + }); + yield* sql`INSERT INTO kin_auth_key_repairs (thumbprint, pairing_link_id, created_at) + VALUES (${thumbprint}, ${link.id}, 0)`; + const exchanged = yield* auth.exchangeBootstrapCredentialForAccessToken( + link.credential, + undefined, + { deviceType: "mobile" }, + { proofKeyThumbprint: thumbprint }, + ); + return yield* sessions.verify(exchanged.access_token); +}); diff --git a/apps/server/src/kin/auth/ProofKeySessions.ts b/apps/server/src/kin/auth/ProofKeySessions.ts index 618af604a4741..8407d58f54bdf 100644 --- a/apps/server/src/kin/auth/ProofKeySessions.ts +++ b/apps/server/src/kin/auth/ProofKeySessions.ts @@ -3,6 +3,7 @@ import * as Effect from "effect/Effect"; import * as Layer from "effect/Layer"; import type * as Context from "effect/Context"; import * as SqlClient from "effect/sql/SqlClient"; +import type * as Statement from "effect/sql/Statement"; import type { AuthSessionId } from "@t3tools/contracts"; import * as SessionStore from "../../auth/SessionStore.ts"; import * as Ref from "effect/Ref"; @@ -11,17 +12,48 @@ import * as KinEnabled from "../KinEnabled.ts"; import * as KinPersistence from "../persistence/KinPersistence.ts"; import { SessionHooks } from "./sessionHooks.ts"; +type Column = Statement.Fragment | string; +type RevocationOptions = { readonly honorRepairs: boolean }; + +/** + * A revocation reaches a proof key when it was individual (bulk sign-out never marks the caller's + * own key) and landed before that session expired. Approver keys ignore repairs (spec section 4). + */ +export const proofKeyRevoked = ( + sql: SqlClient.SqlClient, + proofKey: Column, + options: RevocationOptions, +) => + sql`EXISTS (SELECT 1 FROM kin_auth_session_keys m JOIN auth_sessions s ON s.session_id = m.session_id + WHERE m.proof_key_thumbprint = ${proofKey} AND m.individually_revoked = 1 + ${options.honorRepairs ? sql`AND m.repaired_at IS NULL` : sql``} + AND s.revoked_at IS NOT NULL AND s.revoked_at <= s.expires_at)`; + +/** + * Whether a revocation reached something registered from `sessionId` under `proofKey`: that + * session's own (an unmapped one counts unless after expiry), or any of its proof key's. + */ +export const revokedBySession = ( + sql: SqlClient.SqlClient, + row: { readonly sessionId: Column; readonly proofKey: Column }, + options: RevocationOptions, +) => + sql`(EXISTS (SELECT 1 FROM auth_sessions s LEFT JOIN kin_auth_session_keys m ON m.session_id = s.session_id + WHERE s.session_id = ${row.sessionId} AND s.revoked_at IS NOT NULL AND s.revoked_at <= s.expires_at + AND (m.session_id IS NULL OR (m.individually_revoked = 1 + ${options.honorRepairs ? sql`AND m.repaired_at IS NULL` : sql``}))) + OR ${proofKeyRevoked(sql, row.proofKey, options)})`; + const enabled = Layer.effect( SessionHooks, Effect.gen(function* () { const sql = yield* SqlClient.SqlClient; const blocked = Effect.fn("ProofKeySessions.blocked")( 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`; - return rows.length > 0; + const [row] = yield* sql<{ blocked: number }>`SELECT ${proofKeyRevoked(sql, thumbprint, { + honorRepairs: true, + })} AS blocked`; + return row?.blocked === 1; }, Effect.mapError(toPersistenceSqlError("ProofKeySessions.blocked")), ); diff --git a/docs/kin/specs/approvals.md b/docs/kin/specs/approvals.md index eb5963c8580c7..4fcd7344ae243 100644 --- a/docs/kin/specs/approvals.md +++ b/docs/kin/specs/approvals.md @@ -206,20 +206,18 @@ Registration: - **iOS:** no attestation in phase 1, so the key is stored with `attested: false` and `hardware: "secure_enclave"`, which is claimed by the platform, not proven. 2. **First key in an org:** confirmed on the Mac running the server, in the desktop app's local session (loopback only), where the owner checks the code shown on both screens. No remote path can confirm the first key. "Local" means all of: the session's subject is `desktop-bootstrap` (only the desktop app holds that credential), the session was issued to a loopback address, and the call's own socket is loopback with no `Forwarded`, `X-Forwarded-*`, `X-Real-IP`, `CF-Connecting-IP` or `Tailscale-User-Login` header. A browser or tunnel process on the same Mac fails the first check; a desktop on WSL fails the second, so it can't confirm keys. The subject and the issuance address are the real guard. The socket check is defence in depth, since a proxy on the same Mac connects over loopback and can drop those headers. `confirmKey` works only while the org has no active key. 3. **Later keys:** confirmed by a grant of kind `register_approver_key` signed by an existing active key. When an attested key registers in an org that already has an active key, `registerKey` opens that pending action itself (requester `kin-approver-keys`, provenance started by the registering person). That requester id is reserved: `KinPendingActions.create` refuses it for any other kind, and as an agent or thread id, and the handler activates the key only if it is still `pending`, attested and on the hardware the card showed. -4. Revoking (`kin.approvals.revokeKey`, from settings or the desktop) sets `revoked` and voids every `approved` action whose grant that key signed. Revoking a T3 device session (`revokeClient`) also revokes keys registered from it. Kin reads `auth_sessions.revoked_at` at startup and before it trusts, lists or activates a key, rather than hooking T3's auth code. Revoking also cancels a pending `register_approver_key` action for the key. Expiry is not revocation: a key outlives the session that registered it. A DPoP relay session renews hourly under a new session id but the same DPoP key, so each key also stores that key's thumbprint (`proof_key_thumbprint`). Until `auth_sessions` records it too (see Interfaces, T3 auth), revoking a renewed session doesn't reach the key; revoke the key itself. +4. Revoking (`kin.approvals.revokeKey`, from settings or the desktop) sets `revoked` and voids every `approved` action whose grant that key signed. Revoking a T3 device session (`revokeClient`) also revokes keys registered from it. Kin reads `auth_sessions.revoked_at` at startup and before it trusts, lists or activates a key, rather than hooking T3's auth code. Revoking also cancels a pending `register_approver_key` action for the key. Expiry is not revocation: a key outlives the session that registered it. A DPoP relay session renews hourly under a new session id but the same DPoP key, so each key also stores that key's thumbprint (`proof_key_thumbprint`), and revoking any session of that DPoP key revokes the key (below). The server's attestation allowlist comes from `KIN_ANDROID_PACKAGE`, `KIN_ANDROID_SIGNING_CERT_SHA256` (comma-separated hex), `KIN_IOS_APP_ID` (`.`) and `KIN_IOS_APP_ATTEST_DEVELOPMENT` (accept `appattestdevelop`; default false). With none set, every key registers unattested. Google's roots and Apple's App Attest root are pinned in `apps/server/src/kin/approvals/attestation/roots.ts`. Google's revocation list is fetched from `https://android.googleapis.com/attestation/status` and cached for an hour. If it can't be fetched, Android registration fails and the phone retries; it never stores a key whose chain went unchecked. #### Device session revocation (lane B integration) -PR #54 must land before or with #42. Keep the registering `session_id` reconcile alongside this exact-thumbprint fallback: +`ApproverKeys.reconcileSessions` revokes a key when either of these holds (`revokedBySession` in `apps/server/src/kin/auth/ProofKeySessions.ts`; the exchange block below uses the same proof key rule, except that it honours repairs): -```sql -SELECT DISTINCT k.org_id, k.thumbprint FROM kin_approver_keys k -JOIN kin_auth_session_keys m ON m.proof_key_thumbprint = k.proof_key_thumbprint -JOIN auth_sessions s ON s.session_id = m.session_id -WHERE k.state != 'revoked' AND s.revoked_at IS NOT NULL -``` +- Its registering session was revoked before it expired, and that session either has no `kin_auth_session_keys` row or is marked `individually_revoked`. +- Any session mapped to the key's `proof_key_thumbprint` is marked `individually_revoked` and was revoked before it expired. This is how a renewed relay session's revocation reaches a key registered under an earlier id. + +"Sign out other devices" revokes every other session, but marks only other keys' live sessions as individual, so the caller's own key and its earlier renewals keep their approver keys. A phone whose sessions had all expired isn't reached by it, or by revoking one of those expired sessions; revoke that phone's key itself. Repairs don't count here: the join still sees a repaired revocation, so a repair never restores an approver key. For the same reason `registerKey` refuses (`invalid_state`) a session whose proof key has such a revocation; the phone pairs again with a fresh DPoP key and registers from that. 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. @@ -227,7 +225,7 @@ With Kin enabled, an individually revoked mapped session blocks fresh exchanges 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. -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. +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. @@ -500,7 +498,6 @@ RPCs and scopes: `kin.approvals.list` (stream) and `get` → `orchestration:read - **Triggers:** `pull_request` synchronize/closed webhooks → `refreshAction(actionId)`; `pull_request_review` → enables a card waiting on a GitHub review; `memory_purge` handler; Kin host setup (bot `gh` login, keychain items, hygiene check passing); upstream contract test for `GitHubRequestPolicy.credential` and `verifyDpopProof`. - **Mobile:** renders `ApprovalCard` inside the chat screens; this spec ships the card, the native module and the signing hook. - **T3 auth (lane A), open hand-offs:** - - `SessionStore.issue` writes `claims.jkt` to a new nullable `auth_sessions.proof_key_thumbprint` column. `ApproverKeys.reconcileSessions` then also revokes a key when a revoked session matches `kin_approver_keys.proof_key_thumbprint`, which closes the hourly-renewal gap in section 4. Test: register over a DPoP session, renew, revoke the new session, and the key is `revoked`. - `KinIdentity.resolve` returns each person's org role once members exist (CHAT-11). `registerKey` then refuses anyone but the owner and takes `startedByRole` from that role. Until then, `resolve` returns only the org owner, so the literal `"owner"` is accurate. ## Security tests (named, all in `apps/server/src/kin/approvals/*.test.ts` unless noted) From a8e57515d490f70df19c02481657532931ae0459 Mon Sep 17 00:00:00 2001 From: Surajsm60720 <1ds22is166@dsce.edu.in> Date: Sun, 8 Nov 2026 18:38:32 +0530 Subject: [PATCH 11/16] fix(kin): let repaired phones register approver keys Mobile keeps one DPoP key per install, so refusing any proof key with a past revocation locked a mistakenly revoked and then repaired phone out of approver keys for good. Registration now refuses only an unrepaired revocation. Reconcile counts a revocation against a key when it is unrepaired or landed at or after the key's created_at (revoked_at's ISO text converted to milliseconds), so a revocation after registration still revokes the key permanently and the phone registers a new one. Co-Authored-By: Claude Opus 5.5 --- .../src/kin/approvals/ApproverKeys.test.ts | 37 +++++++++++++++---- apps/server/src/kin/approvals/ApproverKeys.ts | 13 +++---- .../src/kin/auth/ProofKeySessions.test.ts | 2 +- apps/server/src/kin/auth/ProofKeySessions.ts | 35 ++++++++++++------ docs/kin/specs/approvals.md | 4 +- 5 files changed, 62 insertions(+), 29 deletions(-) diff --git a/apps/server/src/kin/approvals/ApproverKeys.test.ts b/apps/server/src/kin/approvals/ApproverKeys.test.ts index 7e980c658d974..0ee3823900624 100644 --- a/apps/server/src/kin/approvals/ApproverKeys.test.ts +++ b/apps/server/src/kin/approvals/ApproverKeys.test.ts @@ -326,17 +326,38 @@ describe("ApproverKeys", () => { }).pipe(Effect.provide(relayLayer)), ); - it.effect("a proof key revoked before can't register an approver key, even repaired", () => + it.effect("a proof key registers an approver key once every revocation of it is repaired", () => Effect.gen(function* () { const { keys, sessions, relay } = yield* seedRelay; - yield* sessions.revoke((yield* relay("phone-a")).session.sessionId); - const repaired = yield* repairProofKey("phone-a"); - const exit = yield* Effect.exit( - registerAndroid(keys, relayPhone(repaired.sessionId, "phone-a")), + const signedOut = yield* relay("phone-a"); + yield* sessions.revoke(signedOut.session.sessionId); + // A call that authenticated just before the revocation landed. + assert.strictEqual( + reasonOf(yield* Effect.exit(registerAndroid(keys, signedOut))), + "invalid_state", ); - assert.strictEqual(reasonOf(exit), "invalid_state"); - const fresh = yield* registerAndroid(keys, yield* relay("phone-a-fresh")); - assert.strictEqual(fresh.key.state, "pending"); + const repaired = yield* repairProofKey("phone-a"); + yield* TestClock.adjust(Duration.minutes(1)); + const { key } = yield* registerAndroid(keys, relayPhone(repaired.sessionId, "phone-a")); + // Reconcile doesn't count the repaired revocation from before the key existed. + assert.strictEqual(Option.getOrThrow(yield* keys.get(key)).state, "pending"); + }).pipe(Effect.provide(relayLayer)), + ); + + it.effect("a revocation after a key registered revokes it for good, even once repaired", () => + Effect.gen(function* () { + const { keys, sessions, relay } = yield* seedRelay; + const phoneA = yield* relay("phone-a"); + const first = yield* registerAndroid(keys, phoneA); + yield* TestClock.adjust(Duration.minutes(1)); + // No key read between the revocation and the repair, so only `created_at` can catch it. + yield* sessions.revoke(phoneA.session.sessionId); + const repaired = yield* repairProofKey("phone-a"); + yield* TestClock.adjust(Duration.minutes(1)); + assert.strictEqual(Option.getOrThrow(yield* keys.get(first.key)).state, "revoked"); + const second = yield* registerAndroid(keys, relayPhone(repaired.sessionId, "phone-a")); + assert.strictEqual(Option.getOrThrow(yield* keys.get(second.key)).state, "pending"); + assert.strictEqual(Option.getOrThrow(yield* keys.get(first.key)).state, "revoked"); }).pipe(Effect.provide(relayLayer)), ); diff --git a/apps/server/src/kin/approvals/ApproverKeys.ts b/apps/server/src/kin/approvals/ApproverKeys.ts index 65ee886e8e59f..be78a87418bb9 100644 --- a/apps/server/src/kin/approvals/ApproverKeys.ts +++ b/apps/server/src/kin/approvals/ApproverKeys.ts @@ -254,8 +254,7 @@ const make = Effect.gen(function* () { WHERE k.state != 'revoked' AND ${revokedBySession( sql, { sessionId: sql`k.session_id`, proofKey: sql`k.proof_key_thumbprint` }, - // A repair re-trusts a proof key, never an approver key (spec section 4). - { honorRepairs: false }, + { since: sql`k.created_at` }, )}`; for (const row of rows) { yield* revokeRow({ orgId: row.org_id, thumbprint: row.thumbprint }, "session_revoked"); @@ -318,16 +317,16 @@ const make = Effect.gen(function* () { return yield* fail("bad_challenge", "Ask for a new key challenge on this connection."); const challenge = new Uint8Array(Buffer.from(input.challenge, "base64url")); yield* reconcileSessions(); - // Reconcile ignores repairs, so a key from a re-paired proof key would be revoked at once. + // Mobile keeps one DPoP key per install, so a repaired revocation must not lock it out. const proofKey = caller.session.proofKeyThumbprint; if (proofKey !== undefined) { - const [seen] = yield* sql<{ revoked: number }>`SELECT ${proofKeyRevoked(sql, proofKey, { - honorRepairs: false, - })} AS revoked`; + const [seen] = yield* sql<{ + revoked: number; + }>`SELECT ${proofKeyRevoked(sql, proofKey)} AS revoked`; if (seen?.revoked === 1) return yield* fail( "invalid_state", - "This phone's connection key was revoked before. Pair the phone again so it makes a new key, then add the approver key.", + "This phone was signed out. Ask the owner to restore it, then try again.", ); } diff --git a/apps/server/src/kin/auth/ProofKeySessions.test.ts b/apps/server/src/kin/auth/ProofKeySessions.test.ts index eb61630fe9e96..f32ff94a01771 100644 --- a/apps/server/src/kin/auth/ProofKeySessions.test.ts +++ b/apps/server/src/kin/auth/ProofKeySessions.test.ts @@ -355,7 +355,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))("Kin proof key se yield* TestClock.adjust(Duration.minutes(2)); yield* sessions.revoke(renewed.sessionId); const revoked = (proofKey: string) => - sql`SELECT ${ProofKeySessions.proofKeyRevoked(sql, proofKey, { honorRepairs: false })} AS revoked`; + sql`SELECT ${ProofKeySessions.proofKeyRevoked(sql, proofKey)} AS revoked`; expect(yield* revoked("device")).toEqual([{ revoked: 1 }]); expect(yield* revoked("other")).toEqual([{ revoked: 0 }]); expect( diff --git a/apps/server/src/kin/auth/ProofKeySessions.ts b/apps/server/src/kin/auth/ProofKeySessions.ts index 8407d58f54bdf..c274314954c96 100644 --- a/apps/server/src/kin/auth/ProofKeySessions.ts +++ b/apps/server/src/kin/auth/ProofKeySessions.ts @@ -12,21 +12,35 @@ import * as KinEnabled from "../KinEnabled.ts"; import * as KinPersistence from "../persistence/KinPersistence.ts"; import { SessionHooks } from "./sessionHooks.ts"; -type Column = Statement.Fragment | string; -type RevocationOptions = { readonly honorRepairs: boolean }; +type Column = Statement.Fragment | string | number; +/** + * Repaired revocations don't count, except ones at or after `since` (epoch ms): a repair re-trusts + * a proof key, never an approver key registered before the revocation (approvals spec section 4). + */ +type RevocationOptions = { readonly since?: Column }; + +// `auth_sessions` stores ISO-8601 UTC text; Kin stores integer milliseconds. +const epochMillis = (sql: SqlClient.SqlClient, iso: Statement.Fragment) => + sql`CAST(ROUND((julianday(${iso}) - 2440587.5) * 86400000) AS INTEGER)`; + +const unrepaired = (sql: SqlClient.SqlClient, options: RevocationOptions) => + options.since === undefined + ? sql`m.repaired_at IS NULL` + : sql`(m.repaired_at IS NULL OR ${epochMillis(sql, sql`s.revoked_at`)} >= ${options.since})`; /** * A revocation reaches a proof key when it was individual (bulk sign-out never marks the caller's - * own key) and landed before that session expired. Approver keys ignore repairs (spec section 4). + * own key), landed before that session expired, and isn't repaired (see `RevocationOptions`). */ export const proofKeyRevoked = ( sql: SqlClient.SqlClient, proofKey: Column, - options: RevocationOptions, + options: RevocationOptions = {}, ) => + // The literal `individually_revoked = 1` lets SQLite use the partial index from K016. sql`EXISTS (SELECT 1 FROM kin_auth_session_keys m JOIN auth_sessions s ON s.session_id = m.session_id WHERE m.proof_key_thumbprint = ${proofKey} AND m.individually_revoked = 1 - ${options.honorRepairs ? sql`AND m.repaired_at IS NULL` : sql``} + AND ${unrepaired(sql, options)} AND s.revoked_at IS NOT NULL AND s.revoked_at <= s.expires_at)`; /** @@ -36,12 +50,11 @@ export const proofKeyRevoked = ( export const revokedBySession = ( sql: SqlClient.SqlClient, row: { readonly sessionId: Column; readonly proofKey: Column }, - options: RevocationOptions, + options: RevocationOptions = {}, ) => sql`(EXISTS (SELECT 1 FROM auth_sessions s LEFT JOIN kin_auth_session_keys m ON m.session_id = s.session_id WHERE s.session_id = ${row.sessionId} AND s.revoked_at IS NOT NULL AND s.revoked_at <= s.expires_at - AND (m.session_id IS NULL OR (m.individually_revoked = 1 - ${options.honorRepairs ? sql`AND m.repaired_at IS NULL` : sql``}))) + AND (m.session_id IS NULL OR (m.individually_revoked = 1 AND ${unrepaired(sql, options)}))) OR ${proofKeyRevoked(sql, row.proofKey, options)})`; const enabled = Layer.effect( @@ -50,9 +63,9 @@ const enabled = Layer.effect( const sql = yield* SqlClient.SqlClient; const blocked = Effect.fn("ProofKeySessions.blocked")( function* (thumbprint: string) { - const [row] = yield* sql<{ blocked: number }>`SELECT ${proofKeyRevoked(sql, thumbprint, { - honorRepairs: true, - })} AS blocked`; + const [row] = yield* sql<{ + blocked: number; + }>`SELECT ${proofKeyRevoked(sql, thumbprint)} AS blocked`; return row?.blocked === 1; }, Effect.mapError(toPersistenceSqlError("ProofKeySessions.blocked")), diff --git a/docs/kin/specs/approvals.md b/docs/kin/specs/approvals.md index 4fcd7344ae243..b30ce248330d1 100644 --- a/docs/kin/specs/approvals.md +++ b/docs/kin/specs/approvals.md @@ -212,12 +212,12 @@ The server's attestation allowlist comes from `KIN_ANDROID_PACKAGE`, `KIN_ANDROI #### Device session revocation (lane B integration) -`ApproverKeys.reconcileSessions` revokes a key when either of these holds (`revokedBySession` in `apps/server/src/kin/auth/ProofKeySessions.ts`; the exchange block below uses the same proof key rule, except that it honours repairs): +`ApproverKeys.reconcileSessions` revokes a key when either of these holds (`revokedBySession` in `apps/server/src/kin/auth/ProofKeySessions.ts`, which grant check 10 also uses): - Its registering session was revoked before it expired, and that session either has no `kin_auth_session_keys` row or is marked `individually_revoked`. - Any session mapped to the key's `proof_key_thumbprint` is marked `individually_revoked` and was revoked before it expired. This is how a renewed relay session's revocation reaches a key registered under an earlier id. -"Sign out other devices" revokes every other session, but marks only other keys' live sessions as individual, so the caller's own key and its earlier renewals keep their approver keys. A phone whose sessions had all expired isn't reached by it, or by revoking one of those expired sessions; revoke that phone's key itself. Repairs don't count here: the join still sees a repaired revocation, so a repair never restores an approver key. For the same reason `registerKey` refuses (`invalid_state`) a session whose proof key has such a revocation; the phone pairs again with a fresh DPoP key and registers from that. +"Sign out other devices" revokes every other session, but marks only other keys' live sessions as individual, so the caller's own key and its earlier renewals keep their approver keys. A phone whose sessions had all expired isn't reached by it, or by revoking one of those expired sessions; revoke that phone's key itself. Either revocation counts against a key unless it was repaired and landed before the key's `created_at` (integer milliseconds; `auth_sessions.revoked_at` is ISO-8601 text, converted to milliseconds before comparing). So a revocation after a key registered revokes it for good, even once repaired, and a repair never restores an approver key; the phone registers a new one. `registerKey` refuses (`invalid_state`) a proof key with any unrepaired revocation and allows one whose revocations are all repaired, because mobile keeps one DPoP key per install and can't pair with a fresh one. The exchange block below uses the same proof key rule, where every repaired revocation stops counting. 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. From b32199282033142f131fa36f4d54d628be02c0f4 Mon Sep 17 00:00:00 2001 From: Surajsm60720 <1ds22is166@dsce.edu.in> Date: Sun, 8 Nov 2026 20:31:44 +0530 Subject: [PATCH 12/16] fix(kin): keep approval handlers off the judge's import graph approvals/rpcHandlers.ts imported KinServer, whose service union pulls in KinChatService and through it floor/JudgeShadow.ts. The kin aggregator now resolves the Kin services and passes them in, so approvals/ no longer imports KinServer. Co-Authored-By: Claude Opus 5.5 --- apps/server/src/kin/approvals/rpcHandlers.ts | 8 ++++---- apps/server/src/kin/rpcHandlers.ts | 8 +++++++- 2 files changed, 11 insertions(+), 5 deletions(-) diff --git a/apps/server/src/kin/approvals/rpcHandlers.ts b/apps/server/src/kin/approvals/rpcHandlers.ts index 9b92f5a2102c3..da1e1774b1508 100644 --- a/apps/server/src/kin/approvals/rpcHandlers.ts +++ b/apps/server/src/kin/approvals/rpcHandlers.ts @@ -8,7 +8,6 @@ import * as RpcGroup from "effect/rpc/RpcGroup"; import type { AuthenticatedSession } from "../../auth/EnvironmentAuth.ts"; import { KinIdentity } from "../chat/KinIdentity.ts"; -import { KinServer } from "../KinServer.ts"; import { ApproverKeys, type KinKeyCaller } from "./ApproverKeys.ts"; const group = RpcGroup.make(...KinApprovalRpcs); @@ -31,12 +30,13 @@ export const connectionOf = Effect.serviceOption(HttpServerRequest.HttpServerReq export const makeKinApprovalHandlers = Effect.fn("makeKinApprovalHandlers")(function* ( session: AuthenticatedSession, + // Passed in rather than read from `KinServer`, whose service union reaches the judge. + kin: Option.Option>, ) { - const kin = yield* Effect.serviceOption(KinServer); const connection = yield* connectionOf; const keys = Effect.gen(function* () { - if (Option.isNone(kin) || Option.isNone(kin.value.services)) return yield* unavailable; - const services = kin.value.services.value; + if (Option.isNone(kin)) return yield* unavailable; + const services = kin.value; const people = yield* Context.get(services, KinIdentity).resolve(session); const caller: KinKeyCaller = { session, people, connection }; return { keys: Context.get(services, ApproverKeys), caller }; diff --git a/apps/server/src/kin/rpcHandlers.ts b/apps/server/src/kin/rpcHandlers.ts index 9aca38a00947f..3b4a8126c880f 100644 --- a/apps/server/src/kin/rpcHandlers.ts +++ b/apps/server/src/kin/rpcHandlers.ts @@ -1,17 +1,23 @@ import { KinRpcs } from "@t3tools/contracts"; import * as Effect from "effect/Effect"; +import * as Option from "effect/Option"; import * as RpcGroup from "effect/rpc/RpcGroup"; import type { AuthenticatedSession } from "../auth/EnvironmentAuth.ts"; import { makeKinApprovalHandlers } from "./approvals/rpcHandlers.ts"; import { makeKinChatHandlers } from "./chat/rpcHandlers.ts"; +import { KinServer } from "./KinServer.ts"; const group = RpcGroup.make(...KinRpcs); export const makeKinHandlers = Effect.fn("makeKinHandlers")(function* ( session: AuthenticatedSession, ) { + const kin = yield* Effect.serviceOption(KinServer); return group.of({ ...(yield* makeKinChatHandlers(session)), - ...(yield* makeKinApprovalHandlers(session)), + ...(yield* makeKinApprovalHandlers( + session, + Option.flatMap(kin, (kin) => kin.services), + )), }); }); From 018df80a79c5f1d1bd41c861038e45aaea058403 Mon Sep 17 00:00:00 2001 From: Surajsm60720 <1ds22is166@dsce.edu.in> Date: Sun, 8 Nov 2026 21:43:24 +0530 Subject: [PATCH 13/16] fix(server): report approver key RPCs as disabled when Kin is off Co-Authored-By: Claude Opus 5.5 --- .../src/kin/approvals/ApproverKeys.test.ts | 6 +++++ .../src/kin/approvals/rpcHandlers.test.ts | 24 ++++++++++++++++++- apps/server/src/kin/approvals/rpcHandlers.ts | 7 +++++- 3 files changed, 35 insertions(+), 2 deletions(-) diff --git a/apps/server/src/kin/approvals/ApproverKeys.test.ts b/apps/server/src/kin/approvals/ApproverKeys.test.ts index 2e5961b07b667..cc880962bb29f 100644 --- a/apps/server/src/kin/approvals/ApproverKeys.test.ts +++ b/apps/server/src/kin/approvals/ApproverKeys.test.ts @@ -494,6 +494,12 @@ describe("ApproverKeys", () => { WHERE kind = 'register_approver_key' AND json_extract(target_json, '$.thumbprint') = ${third.key.thumbprint}`; assert.strictEqual(cancelled?.state, "cancelled"); + + yield* sql`ALTER TABLE kin_approver_keys RENAME TO kin_approver_keys_gone`; + assert.strictEqual( + reasonOf(yield* Effect.exit(keys.listKeys(phone, { orgId }))), + "unavailable", + ); }).pipe(Effect.provide(layer)), ); }); diff --git a/apps/server/src/kin/approvals/rpcHandlers.test.ts b/apps/server/src/kin/approvals/rpcHandlers.test.ts index 26d663ad5d8dd..2e741f12b5205 100644 --- a/apps/server/src/kin/approvals/rpcHandlers.test.ts +++ b/apps/server/src/kin/approvals/rpcHandlers.test.ts @@ -1,9 +1,10 @@ import { assert, it } from "@effect/vitest"; +import { AuthSessionId, AuthStandardClientScopes, KinOrgId } from "@t3tools/contracts"; import * as Effect from "effect/Effect"; import * as Option from "effect/Option"; import * as HttpServerRequest from "effect/http/HttpServerRequest"; -import { connectionOf } from "./rpcHandlers.ts"; +import { connectionOf, makeKinApprovalHandlers } from "./rpcHandlers.ts"; it.effect("reads the call's socket and headers from the upgrade request", () => Effect.gen(function* () { @@ -25,3 +26,24 @@ it.effect("reads the call's socket and headers from the upgrade request", () => assert.isTrue(Option.isNone(yield* connectionOf)); }), ); + +it.effect("key methods refuse as disabled when Kin is off", () => + Effect.gen(function* () { + const handlers = yield* makeKinApprovalHandlers( + { + sessionId: AuthSessionId.make("session"), + subject: "browser", + method: "browser-session-cookie", + scopes: AuthStandardClientScopes, + }, + Option.none(), + ); + const orgId = KinOrgId.make("org_01"); + assert.include(yield* handlers["kin.approvals.listKeys"]({ orgId }).pipe(Effect.flip), { + reason: "disabled", + }); + assert.include(yield* handlers["kin.approvals.keyChallenge"]({}).pipe(Effect.flip), { + reason: "disabled", + }); + }), +); diff --git a/apps/server/src/kin/approvals/rpcHandlers.ts b/apps/server/src/kin/approvals/rpcHandlers.ts index da1e1774b1508..8b51841217f04 100644 --- a/apps/server/src/kin/approvals/rpcHandlers.ts +++ b/apps/server/src/kin/approvals/rpcHandlers.ts @@ -16,6 +16,11 @@ const unavailable = Effect.fail( new KinApprovalError({ reason: "unavailable", message: "Kin approvals are unavailable." }), ); +const disabled = new KinApprovalError({ + reason: "disabled", + message: "Kin is not running on this host.", +}); + // The WS upgrade request, so `confirmKey` can tell a loopback socket from a proxied one. export const connectionOf = Effect.serviceOption(HttpServerRequest.HttpServerRequest).pipe( Effect.map( @@ -35,7 +40,7 @@ export const makeKinApprovalHandlers = Effect.fn("makeKinApprovalHandlers")(func ) { const connection = yield* connectionOf; const keys = Effect.gen(function* () { - if (Option.isNone(kin)) return yield* unavailable; + if (Option.isNone(kin)) return yield* disabled; const services = kin.value; const people = yield* Context.get(services, KinIdentity).resolve(session); const caller: KinKeyCaller = { session, people, connection }; From 2c0692ce652469ba2336b1462c3498e4216b8a0a Mon Sep 17 00:00:00 2001 From: Surajsm60720 <1ds22is166@dsce.edu.in> Date: Sun, 8 Nov 2026 22:13:40 +0530 Subject: [PATCH 14/16] test(server): call keyChallenge without input Co-Authored-By: Claude Opus 5.5 --- apps/server/src/kin/approvals/rpcHandlers.test.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/apps/server/src/kin/approvals/rpcHandlers.test.ts b/apps/server/src/kin/approvals/rpcHandlers.test.ts index 2e741f12b5205..7ada43a6b6533 100644 --- a/apps/server/src/kin/approvals/rpcHandlers.test.ts +++ b/apps/server/src/kin/approvals/rpcHandlers.test.ts @@ -42,7 +42,7 @@ it.effect("key methods refuse as disabled when Kin is off", () => assert.include(yield* handlers["kin.approvals.listKeys"]({ orgId }).pipe(Effect.flip), { reason: "disabled", }); - assert.include(yield* handlers["kin.approvals.keyChallenge"]({}).pipe(Effect.flip), { + assert.include(yield* handlers["kin.approvals.keyChallenge"]().pipe(Effect.flip), { reason: "disabled", }); }), From a34d53fd910e90c09f4df5f51295c7b37a2b894d Mon Sep 17 00:00:00 2001 From: GLDRoger <130458023+GLDRoger@users.noreply.github.com> Date: Mon, 9 Nov 2026 00:30:13 +0530 Subject: [PATCH 15/16] fix(kin): approver-key reconcile is per org, SQL causes are logged, hardware match tested reconcileSessions takes the org (every caller has one; startup sweeps all, as sessions are environment-local) and orders its rows. Persistence failures log through toPersistenceSqlError before the unavailable refusal. The later-key test refuses a run whose stored hardware no longer matches the card. Co-Authored-By: Claude Opus 5.5 --- .../src/kin/approvals/ApproverKeys.test.ts | 4 ++ apps/server/src/kin/approvals/ApproverKeys.ts | 58 ++++++++++++------- 2 files changed, 40 insertions(+), 22 deletions(-) diff --git a/apps/server/src/kin/approvals/ApproverKeys.test.ts b/apps/server/src/kin/approvals/ApproverKeys.test.ts index cc880962bb29f..747aac0a61013 100644 --- a/apps/server/src/kin/approvals/ApproverKeys.test.ts +++ b/apps/server/src/kin/approvals/ApproverKeys.test.ts @@ -482,6 +482,10 @@ describe("ApproverKeys", () => { if (approved._tag !== "approved") return; const handler = yield* makeRegisterApproverKeyHandler; assert.strictEqual(yield* handler.reconcile(action), "not_done"); + // The stored key must still be what the card described. + yield* sql`UPDATE kin_approver_keys SET hardware = 'strongbox' WHERE thumbprint = ${second.key.thumbprint}`; + assert.isTrue(Exit.isFailure(yield* Effect.exit(handler.run(action, approved.grant)))); + yield* sql`UPDATE kin_approver_keys SET hardware = 'tee' WHERE thumbprint = ${second.key.thumbprint}`; assert.strictEqual(yield* handler.run(action, approved.grant), "succeeded"); assert.strictEqual(yield* handler.reconcile(action), "done"); assert.strictEqual((yield* keys.requireActive(second.key)).state, "active"); diff --git a/apps/server/src/kin/approvals/ApproverKeys.ts b/apps/server/src/kin/approvals/ApproverKeys.ts index be78a87418bb9..354229125ac31 100644 --- a/apps/server/src/kin/approvals/ApproverKeys.ts +++ b/apps/server/src/kin/approvals/ApproverKeys.ts @@ -35,6 +35,8 @@ import * as SecureRandom from "effect/crypto/SecureRandom"; import * as Base64Url from "effect/encoding/Base64Url"; import * as SqlClient from "effect/sql/SqlClient"; +import { toPersistenceSqlError } from "../../persistence/Errors.ts"; + import type { AuthenticatedSession } from "../../auth/EnvironmentAuth.ts"; import { proofKeyRevoked, revokedBySession } from "../auth/ProofKeySessions.ts"; import type { PersonIdentity } from "../chat/KinIdentity.ts"; @@ -175,7 +177,10 @@ export class ApproverKeys extends Context.Service< /** The `register_approver_key` handler's step, only after a verified grant. */ readonly activateByGrant: (ref: KeyRef) => Effect.Effect; /** Revokes keys whose T3 session was revoked. Returns how many. */ - readonly reconcileSessions: () => Effect.Effect; + /** One org, or every org at startup: sessions are environment-local (the `kin_auth_*` exception). */ + readonly reconcileSessions: ( + orgId: KinOrgId | undefined, + ) => Effect.Effect; } >()("t3/kin/approvals/ApproverKeys") {} @@ -194,10 +199,17 @@ const make = Effect.gen(function* () { >(); const slot = (ref: KeyRef) => `${ref.orgId}\u0000${ref.thumbprint}`; + // Callers see a plain refusal; the cause is logged through the persistence error shape. const internal = (operation: string) => (cause: unknown) => isKinApprovalError(cause) - ? cause - : new KinApprovalError({ reason: "unavailable", message: `${operation} failed.` }); + ? Effect.fail(cause) + : Effect.logWarning(`${operation} failed`, toPersistenceSqlError(operation)(cause)).pipe( + Effect.andThen( + Effect.fail( + new KinApprovalError({ reason: "unavailable", message: `${operation} failed.` }), + ), + ), + ); const personIn = (caller: KinKeyCaller, orgId: KinOrgId) => { const person = caller.people.find((candidate) => candidate.orgId === orgId); @@ -248,20 +260,22 @@ const make = Effect.gen(function* () { // Reading its table here keeps auth free of Kin hooks, and runs before every key is trusted. // Relay sessions renew under new ids, so the DPoP key's own revocations count too (spec section 4). const reconcileSessions = Effect.fn("ApproverKeys.reconcileSessions")( - function* () { + function* (orgId: KinOrgId | undefined) { const rows = yield* sql<{ org_id: KinOrgId; thumbprint: KinKeyThumbprint }>` SELECT k.org_id, k.thumbprint FROM kin_approver_keys k - WHERE k.state != 'revoked' AND ${revokedBySession( - sql, - { sessionId: sql`k.session_id`, proofKey: sql`k.proof_key_thumbprint` }, - { since: sql`k.created_at` }, - )}`; + WHERE k.state != 'revoked' AND ${orgId === undefined ? sql`1 = 1` : sql`k.org_id = ${orgId}`} + AND ${revokedBySession( + sql, + { sessionId: sql`k.session_id`, proofKey: sql`k.proof_key_thumbprint` }, + { since: sql`k.created_at` }, + )} + ORDER BY k.org_id, k.thumbprint`; for (const row of rows) { yield* revokeRow({ orgId: row.org_id, thumbprint: row.thumbprint }, "session_revoked"); } return rows.length; }, - Effect.mapError(internal("ApproverKeys.reconcileSessions")), + Effect.catch(internal("ApproverKeys.reconcileSessions")), ); const keyChallenge = Effect.fn("ApproverKeys.keyChallenge")(function* (caller: KinKeyCaller) { @@ -316,7 +330,7 @@ const make = Effect.gen(function* () { ) return yield* fail("bad_challenge", "Ask for a new key challenge on this connection."); const challenge = new Uint8Array(Buffer.from(input.challenge, "base64url")); - yield* reconcileSessions(); + yield* reconcileSessions(input.orgId); // Mobile keeps one DPoP key per install, so a repaired revocation must not lock it out. const proofKey = caller.session.proofKeyThumbprint; if (proofKey !== undefined) { @@ -397,7 +411,7 @@ const make = Effect.gen(function* () { } return { key, code }; }, - Effect.mapError(internal("ApproverKeys.registerKey")), + Effect.catch(internal("ApproverKeys.registerKey")), ); const isLocalDesktop = Effect.fn("ApproverKeys.isLocalDesktop")(function* (caller: KinKeyCaller) { @@ -421,7 +435,7 @@ const make = Effect.gen(function* () { "not_local", "Confirm the first approver key in the desktop app on the Kin host.", ); - yield* reconcileSessions(); + yield* reconcileSessions(input.orgId); const ref = { orgId: input.orgId, thumbprint: input.thumbprint }; const row = yield* select(ref); if (row === undefined) return yield* fail("not_found", "No such approver key."); @@ -457,18 +471,18 @@ const make = Effect.gen(function* () { confirmations.delete(slot(ref)); return yield* toKey(active); }, - Effect.mapError(internal("ApproverKeys.confirmKey")), + Effect.catch(internal("ApproverKeys.confirmKey")), ); const listKeys = Effect.fn("ApproverKeys.listKeys")( function* (caller: KinKeyCaller, input: KinApprovalsOrgInput) { yield* personIn(caller, input.orgId); - yield* reconcileSessions(); + yield* reconcileSessions(input.orgId); const rows = yield* sql`SELECT * FROM kin_approver_keys WHERE org_id = ${input.orgId} ORDER BY created_at, thumbprint`; return { keys: yield* Effect.forEach(rows, toKey) }; }, - Effect.mapError(internal("ApproverKeys.listKeys")), + Effect.catch(internal("ApproverKeys.listKeys")), ); const revokeKey = Effect.fn("ApproverKeys.revokeKey")( @@ -481,16 +495,16 @@ const make = Effect.gen(function* () { const revoked = yield* revokeRow(input, "key_revoked"); return yield* toKey(revoked ?? row); }, - Effect.mapError(internal("ApproverKeys.revokeKey")), + Effect.catch(internal("ApproverKeys.revokeKey")), ); const get = Effect.fn("ApproverKeys.get")( function* (ref: KeyRef) { - yield* reconcileSessions(); + yield* reconcileSessions(ref.orgId); const row = yield* select(ref); return row === undefined ? Option.none() : Option.some(yield* toKey(row)); }, - Effect.mapError(internal("ApproverKeys.get")), + Effect.catch(internal("ApproverKeys.get")), ); const requireActive = Effect.fn("ApproverKeys.requireActive")(function* (ref: KeyRef) { @@ -504,7 +518,7 @@ const make = Effect.gen(function* () { const activateByGrant = Effect.fn("ApproverKeys.activateByGrant")( function* (ref: KeyRef) { - yield* reconcileSessions(); + yield* reconcileSessions(ref.orgId); const now = yield* Clock.currentTimeMillis; const rows = yield* sql`UPDATE kin_approver_keys SET state = 'active', confirmed_at = ${now} @@ -514,10 +528,10 @@ const make = Effect.gen(function* () { if (rows.length > 0) confirmations.delete(slot(ref)); return rows.length > 0; }, - Effect.mapError(internal("ApproverKeys.activateByGrant")), + Effect.catch(internal("ApproverKeys.activateByGrant")), ); - yield* reconcileSessions().pipe( + yield* reconcileSessions(undefined).pipe( Effect.catch((error) => Effect.logError("Kin approver key reconciliation failed.", error)), ); From f2d32d518e472a2e9b2f8005c378f735b29b3636 Mon Sep 17 00:00:00 2001 From: GLDRoger <130458023+GLDRoger@users.noreply.github.com> Date: Mon, 9 Nov 2026 04:59:36 +0530 Subject: [PATCH 16/16] docs(kin): state what attested means for iOS approver keys Co-Authored-By: Claude Opus 5.5 --- docs/kin/specs/approvals.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/kin/specs/approvals.md b/docs/kin/specs/approvals.md index 52fd39695dd3e..147c8ead65239 100644 --- a/docs/kin/specs/approvals.md +++ b/docs/kin/specs/approvals.md @@ -203,7 +203,7 @@ Registration: 1. The phone calls `kin.approvals.keyChallenge()` (`access:write`), which returns a single-use 32-byte nonce bound to that session and valid for 5 minutes. It passes the nonce to `createKey`, then calls `kin.approvals.registerKey({publicJwk, platform, challenge, attestation?, deviceLabel})` over the same session. The server consumes the nonce, stores the key as `pending` and returns a 6-digit code derived from `sha256(thumbprint ‖ serverNonce)`, where `serverNonce` is that challenge. Challenges and codes live in server memory: a code is good for 10 minutes and five tries, and after a restart the phone makes and registers a new key. A thumbprint registers only once. - **Android:** `attestation.certificateChain` is required. The server checks it offline: the chain verifies up to a pinned Google hardware attestation root and no certificate is on Google's attestation revocation list; the leaf's public key equals `publicJwk`; the leaf's KeyDescription has `attestationChallenge` equal to the nonce, `attestationSecurityLevel` and `keyMintSecurityLevel` (`keymasterSecurityLevel` before KeyMint) of `TrustedEnvironment` or `StrongBox`, and in `hardwareEnforced`: purpose `SIGN`, algorithm EC on P-256, digest SHA-256, `userAuthType` biometric only (`FINGERPRINT`, the value Keystore uses for every strong biometric), no `authTimeout`, no `noAuthRequired`, `origin` `GENERATED`, and `rootOfTrust` with `verifiedBootState` `Verified` and `deviceLocked` true; `attestationApplicationId` names the release package with exactly the allowlisted signing-certificate SHA-256s, each once. The chain's last certificate only has to carry a pinned root's key, since Google reissued its RSA root under the same key; the pinned certificate takes its place, so its own validity and its signature on the next certificate are what count. All pass: `attested: true`, and `hardware` is `strongbox` or `tee` from the attestation security level. Any check fails: `attested: false`, `hardware: "software"`. The client never supplies `hardware`. - - **iOS:** no attestation in phase 1, so the key is stored with `attested: false` and `hardware: "secure_enclave"`, which is claimed by the platform, not proven. + - **iOS:** App Attest, as `attestation/verify.ts` checks it. On iOS `attested: true` means a genuine Kin app instance asked for this public key, bound through `clientDataHash = sha256(challenge ‖ 0x04 ‖ x ‖ y)`. It does not prove the approver key is in the Secure Enclave or gated by biometrics, and it does not detect a jailbroken phone; Android's attestation does prove hardware storage and a verified, locked boot. The owner accepted this weaker meaning for phase 1 (2026-11-09), since without it no iPhone could approve. `hardware: "secure_enclave"` is claimed by the platform, not proven. 2. **First key in an org:** confirmed on the Mac running the server, in the desktop app's local session (loopback only), where the owner checks the code shown on both screens. No remote path can confirm the first key. "Local" means all of: the session's subject is `desktop-bootstrap` (only the desktop app holds that credential), the session was issued to a loopback address, and the call's own socket is loopback with no `Forwarded`, `X-Forwarded-*`, `X-Real-IP`, `CF-Connecting-IP` or `Tailscale-User-Login` header. A browser or tunnel process on the same Mac fails the first check; a desktop on WSL fails the second, so it can't confirm keys. The subject and the issuance address are the real guard. The socket check is defence in depth, since a proxy on the same Mac connects over loopback and can drop those headers. `confirmKey` works only while the org has no active key. 3. **Later keys:** confirmed by a grant of kind `register_approver_key` signed by an existing active key. When an attested key registers in an org that already has an active key, `registerKey` opens that pending action itself (requester `kin-approver-keys`, provenance started by the registering person). That requester id is reserved: `KinPendingActions.create` refuses it for any other kind, and as an agent or thread id, and the handler activates the key only if it is still `pending`, attested and on the hardware the card showed. 4. Revoking (`kin.approvals.revokeKey`, from settings or the desktop) sets `revoked` and voids every `approved` action whose grant that key signed. Revoking a T3 device session (`revokeClient`) also revokes keys registered from it. Kin reads `auth_sessions.revoked_at` at startup and before it trusts, lists or activates a key, rather than hooking T3's auth code. Revoking also cancels a pending `register_approver_key` action for the key. Expiry is not revocation: a key outlives the session that registered it. A DPoP relay session renews hourly under a new session id but the same DPoP key, so each key also stores that key's thumbprint (`proof_key_thumbprint`), and revoking any session of that DPoP key revokes the key (below).