diff --git a/apps/server/src/kin/KinServer.ts b/apps/server/src/kin/KinServer.ts index b8fdc2b0822c0..fba20b359ec5c 100644 --- a/apps/server/src/kin/KinServer.ts +++ b/apps/server/src/kin/KinServer.ts @@ -8,6 +8,7 @@ import { KinChatHub } from "./chat/KinChatHub.ts"; import { KinBudget } from "./lead/KinBudget.ts"; import { KinEventQueue } from "./lead/KinEventQueue.ts"; import { ApproverKeys } from "./approvals/ApproverKeys.ts"; +import { GrantVerifier } from "./approvals/GrantVerifier.ts"; import { KinStop } from "./lead/KinStop.ts"; import type { KinGithubWebhookLock } from "./triggers/githubWebhooks.ts"; @@ -19,7 +20,8 @@ export type Services = | KinChatHub | KinStop | KinGithubWebhookLock - | ApproverKeys; + | ApproverKeys + | GrantVerifier; export class KinServer extends Context.Service< KinServer, diff --git a/apps/server/src/kin/approvals/ApproverKeys.ts b/apps/server/src/kin/approvals/ApproverKeys.ts index 4c19b4abb87c8..a38a27a7cff07 100644 --- a/apps/server/src/kin/approvals/ApproverKeys.ts +++ b/apps/server/src/kin/approvals/ApproverKeys.ts @@ -9,8 +9,6 @@ import { KinEventId, ThreadId, type AuthSessionId, - type Hex64, - type KinActionKind, type KinApprovalsConfirmKeyInput, type KinApprovalsKeyChallengeResult, type KinApprovalsKeyInput, @@ -46,7 +44,11 @@ import { verifyAppleAppAttest, type AttestationResult, } from "./attestation/verify.ts"; -import { KIN_APPROVER_KEYS_REQUESTER, KinPendingActions } from "./PendingActions.ts"; +import { + KIN_APPROVER_KEYS_REQUESTER, + KinPendingActions, + kinTargetDigest, +} from "./PendingActions.ts"; const CHALLENGE_TTL_MS = 5 * 60 * 1000; const CONFIRM_TTL_MS = 10 * 60 * 1000; @@ -120,10 +122,6 @@ export const kinKeyConfirmationCode = (thumbprint: string, challenge: Uint8Array 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, @@ -397,7 +395,7 @@ const make = Effect.gen(function* () { kind: "register_approver_key", target, resolved: { _tag: "none" }, - targetDigest: kinTargetDigest("register_approver_key", target), + targetDigest: kinTargetDigest("register_approver_key", target, { _tag: "none" }), reason: `Add approver key for "${input.deviceLabel}".`, requestedBy: SERVER_REQUESTER, provenance: { diff --git a/apps/server/src/kin/approvals/Audit.test.ts b/apps/server/src/kin/approvals/Audit.test.ts index 0747d63ae5002..01f9209915ac6 100644 --- a/apps/server/src/kin/approvals/Audit.test.ts +++ b/apps/server/src/kin/approvals/Audit.test.ts @@ -103,6 +103,10 @@ const seed = Effect.gen(function* () { yield* sql`INSERT INTO kin_orgs (org_id, name, created_at) VALUES ('org_01', 'Kin', '2026-11-07T00:00:00.000Z'), ('org_02', 'Other', '2026-11-07T00:00:00.000Z')`; + // Check 10 approves only while the signing key is active. + yield* sql`INSERT INTO kin_approver_keys (thumbprint, org_id, public_jwk_json, human_id, + device_label, platform, hardware, attested, state, created_at) + VALUES (${kid}, 'org_01', '{}', ${owner}, 'Pixel 9', 'android', 'tee', 1, 'active', 0)`; return yield* KinAudit; }); diff --git a/apps/server/src/kin/approvals/GrantPorts.ts b/apps/server/src/kin/approvals/GrantPorts.ts new file mode 100644 index 0000000000000..0bb277c8be67d --- /dev/null +++ b/apps/server/src/kin/approvals/GrantPorts.ts @@ -0,0 +1,108 @@ +import { + KinApprovalError, + KinPersonId, + type KinActionKind, + type KinActionTarget, + type KinOrgId, + type KinResolvedTarget, +} from "@t3tools/contracts"; +import * as Context from "effect/Context"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; +import * as Schema from "effect/Schema"; +import * as SqlClient from "effect/sql/SqlClient"; + +import { toPersistenceSqlError } from "../../persistence/Errors.ts"; +import { KinAudit, type KinAuditAppendInput } from "./Audit.ts"; + +/** The verifier's rejection trace: the refusal is already decided, so a lost entry is only logged. */ +export class KinGrantAudit extends Context.Service< + KinGrantAudit, + { readonly append: (input: KinAuditAppendInput) => Effect.Effect } +>()("t3/kin/approvals/GrantPorts/KinGrantAudit") {} + +export const auditLayer = Layer.effect( + KinGrantAudit, + Effect.gen(function* () { + const audit = yield* KinAudit; + return KinGrantAudit.of({ + append: Effect.fn("KinGrantAudit.append")(function* (entry) { + yield* audit + .append(entry) + .pipe( + Effect.catch((error) => + Effect.logWarning(`Kin audit: ${entry.event} not written`, error), + ), + ); + }), + }); + }), +); + +/** Grant check 4's role lookup: never from the grant or the client, only stored identity. */ +export class KinOrgRoles extends Context.Service< + KinOrgRoles, + { + readonly isOwner: (ref: { + readonly orgId: KinOrgId; + readonly personId: KinPersonId; + }) => Effect.Effect; + } +>()("t3/kin/approvals/GrantPorts/KinOrgRoles") {} + +// Phase 1 (chat spec, Identity): the org owner is the reserved person bootstrap creates. +// Phase 2 replaces this with org membership. +export const BOOTSTRAP_OWNER = Schema.decodeSync(KinPersonId)("kin-default-owner"); + +export const orgRolesLayer = Layer.effect( + KinOrgRoles, + Effect.gen(function* () { + const sql = yield* SqlClient.SqlClient; + return KinOrgRoles.of({ + isOwner: Effect.fn("KinOrgRoles.isOwner")( + function* (ref) { + if (ref.personId !== BOOTSTRAP_OWNER) return false; + const rows = yield* sql`SELECT 1 FROM kin_people + WHERE org_id = ${ref.orgId} AND person_id = ${ref.personId}`; + return rows.length > 0; + }, + Effect.catch((cause) => + Effect.logWarning( + "KinOrgRoles.isOwner failed", + toPersistenceSqlError("KinOrgRoles.isOwner")(cause), + ).pipe( + Effect.andThen( + Effect.fail( + new KinApprovalError({ reason: "unavailable", message: "Org roles unavailable." }), + ), + ), + ), + ), + ), + }); + }), +); + +/** Grant check 9: the server's own read of the PR or branch, with the bot's credential. */ +export class KinLiveTargets extends Context.Service< + KinLiveTargets, + { + readonly resolve: (input: { + readonly kind: KinActionKind; + readonly target: KinActionTarget; + }) => Effect.Effect; + } +>()("t3/kin/approvals/GrantPorts/KinLiveTargets") {} + +// Fails closed until APPR-8's installation tokens back it: no live read, no approval. +export const liveTargetsUnconfiguredLayer = Layer.succeed( + KinLiveTargets, + KinLiveTargets.of({ + resolve: Effect.fn("KinLiveTargets.resolve")(function* () { + return yield* new KinApprovalError({ + reason: "unavailable", + message: "Kin can't read GitHub yet, so it can't approve this.", + }); + }), + }), +); diff --git a/apps/server/src/kin/approvals/GrantVerifier.test.ts b/apps/server/src/kin/approvals/GrantVerifier.test.ts new file mode 100644 index 0000000000000..ee58377cfabed --- /dev/null +++ b/apps/server/src/kin/approvals/GrantVerifier.test.ts @@ -0,0 +1,1205 @@ +// @effect-diagnostics nodeBuiltinImport:off -- node:crypto signs like the phone; node:fs reads the import graph. +import * as NodeCrypto from "node:crypto"; +import * as NodeFS from "node:fs"; +import * as NodePath from "node:path"; + +import { assert, describe, it } from "@effect/vitest"; +import { + AuthSessionId, + KinEventId, + KinOrgId, + KinPersonId, + type KinActionTarget, + KinApprovalError, + type KinGrantHeader, + type KinGrantPayload, + type KinPendingAction, + type KinResolvedTarget, +} from "@t3tools/contracts"; +import { computeDpopJwkThumbprint } from "@t3tools/shared/dpop"; +import { encodeGrantSigningInput } from "@t3tools/shared/kinGrant"; +import { stableStringify } from "@t3tools/shared/relaySigning"; +import * as Duration from "effect/Duration"; +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 SessionStore from "../../auth/SessionStore.ts"; +import * as Sqlite from "../../persistence/Sqlite.ts"; +import { layerKinAuthTest } from "../auth/ProofKeySessions.testkit.ts"; +import * as KinPersistence from "../persistence/KinPersistence.ts"; +import { ApproverKeys, layer as approverKeysLayer, type KinKeyCaller } from "./ApproverKeys.ts"; +import { KinAudit, make as makeAudit, type KinAuditAppendInput } from "./Audit.ts"; +import { KinAttestationTrust } from "./attestation/AttestationTrust.ts"; +import { androidChain, makeTrustFixture, newKey } from "./attestation/testFixtures.ts"; +import { + BOOTSTRAP_OWNER, + auditLayer as grantAuditLayer, + KinLiveTargets, + KinOrgRoles, + orgRolesLayer, +} from "./GrantPorts.ts"; +import { GrantVerifier, layer as grantVerifierLayer } from "./GrantVerifier.ts"; +import { + KinPendingActions, + kinTargetDigest, + layer as pendingActionsLayer, + type KinPendingActionCreateInput, +} from "./PendingActions.ts"; + +const NOW = Date.parse("2026-11-08T00:00:00Z"); +const NOW_S = NOW / 1000; +const P256_N = BigInt("0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551"); +const fixture = makeTrustFixture(); +const orgId = Schema.decodeSync(KinOrgId)("org_01"); +const owner = Schema.decodeSync(KinPersonId)("h_owner"); +const member = Schema.decodeSync(KinPersonId)("h_member"); +const sessionId = Schema.decodeSync(AuthSessionId); +const decodeEventId = Schema.decodeSync(KinEventId); +const decodeOrgId = Schema.decodeSync(KinOrgId); +const decodePersonId = Schema.decodeSync(KinPersonId); + +const callerFor = (id: string, personId: KinPersonId, subject = "phone"): KinKeyCaller => ({ + session: { sessionId: sessionId(id), subject, method: "bearer-access-token", scopes: [] }, + people: [{ _tag: "person", orgId, personId }], + connection: Option.some({ + remoteAddress: subject === "desktop-bootstrap" ? "127.0.0.1" : "192.168.1.20", + headers: {}, + }), +}); +const ownerPhone = callerFor("sess-phone", owner); +const ownerLaptop = callerFor("sess-laptop", owner); +const desktop = callerFor("sess-desktop", owner, "desktop-bootstrap"); +const memberPhone = callerFor("sess-member", member); +const nobody: KinKeyCaller = { ...callerFor("sess-nobody", owner), people: [] }; + +const sha = (char: string) => char.repeat(40); +const pr = (number: number, mergeMethod: "squash" | "merge" = "squash"): KinActionTarget => ({ + _tag: "pull_request", + host: "github.com", + repo: "GLDRoger/t3code", + number, + mergeMethod, + deleteBranchAfter: false, +}); +const prFacts = (headSha: string, base = "main"): KinResolvedTarget => ({ + _tag: "pull_request", + headSha, + base, + head: "kin/fix", + title: "Fix", + additions: 3, + deletions: 1, + files: 1, + checks: [{ name: "ci", required: true, status: "passed" }], +}); + +const DECISION_EVENTS = new Set(["grant_accepted", "grant_rejected", "action_rejected"]); + +/** One test's world: an in-memory database, a recorded audit and a scriptable GitHub. */ +function harness() { + const audit: Array = []; + const github = new Map(); + // Runs inside check 9's read, between check 6 and check 10: a concurrent writer's slot. + const race: { during?: Effect.Effect } = {}; + const roles = Layer.succeed(KinOrgRoles, { + isOwner: (ref) => Effect.succeed(ref.orgId === orgId && ref.personId === owner), + }); + const live = Layer.succeed(KinLiveTargets, { + resolve: ({ target }) => + Effect.suspend(() => race.during ?? Effect.void).pipe( + Effect.andThen(() => { + const facts = target._tag === "pull_request" ? github.get(target.number) : undefined; + return facts === undefined || facts === "down" + ? Effect.fail( + new KinApprovalError({ reason: "unavailable", message: "GitHub is down." }), + ) + : Effect.succeed(facts); + }), + ), + }); + // The real chain, recording the grant decisions whichever writer appended them. + const recordingAudit = Layer.effect( + KinAudit, + Effect.gen(function* () { + const real = yield* makeAudit; + return KinAudit.of({ + ...real, + append: (entry) => + real + .append(entry) + .pipe( + Effect.tap(() => + DECISION_EVENTS.has(entry.event) + ? Effect.sync(() => void audit.push(entry)) + : Effect.void, + ), + ), + }); + }), + ); + const trust = Layer.succeed(KinAttestationTrust, { load: () => Effect.succeed(fixture.trust) }); + const on = (database: Layer.Layer) => + grantVerifierLayer.pipe( + Layer.provideMerge(approverKeysLayer), + Layer.provideMerge(pendingActionsLayer), + Layer.provide(Layer.mergeAll(trust, roles, live, grantAuditLayer)), + Layer.provideMerge(recordingAudit), + Layer.provideMerge(Layer.provideMerge(KinPersistence.layer, database)), + ); + const layer = on(Sqlite.layerMemory); + // Real T3 auth with Kin's proof key hooks, so revocations write what #54 writes. + const relayLayer = on(layerKinAuthTest("kin-grants-")); + return { audit, github, race, layer, relayLayer }; +} + +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-laptop", "phone", "192.168.1.21"], + ["sess-member", "phone", "192.168.1.30"], + ["sess-desktop", "desktop-bootstrap", "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 { + sql, + keys: yield* ApproverKeys, + actions: yield* KinPendingActions, + grants: yield* GrantVerifier, + }; +}); + +/** Through the real path: key challenge, attested Android registration. */ +const register = (keys: ApproverKeys["Service"], from: KinKeyCaller) => + Effect.gen(function* () { + const { challenge } = yield* keys.keyChallenge(from); + const chain = androidChain(fixture, { + challenge: new Uint8Array(Buffer.from(challenge, "base64url")), + }); + const registered = yield* keys.registerKey(from, { + orgId, + publicJwk: chain.publicJwk, + platform: "android", + challenge, + attestation: { format: "android-key", certificateChain: chain.certificateChain }, + deviceLabel: "Pixel 9", + }); + return { ...registered, privateKey: chain.approvalKey.privateKey }; + }); + +/** The owner's first key, confirmed on the desktop; the member's activated as a later key. */ +const enrol = Effect.gen(function* () { + const world = yield* seed; + const ownerKey = yield* register(world.keys, ownerPhone); + yield* world.keys.confirmKey(desktop, { + orgId, + thumbprint: ownerKey.key.thumbprint, + code: ownerKey.code, + }); + const memberKey = yield* register(world.keys, memberPhone); + assert.isTrue(yield* world.keys.activateByGrant(memberKey.key)); + yield* world.sql`DELETE FROM kin_pending_actions WHERE kind = 'register_approver_key'`; + return { ...world, ownerKey, memberKey }; +}); + +const requestMerge = ( + actions: KinPendingActions["Service"], + number: number, + github: Map, +) => + Effect.gen(function* () { + const target = pr(number); + const resolved = prFacts(sha(number === 212 ? "a" : "b")); + github.set(number, resolved); + const input = { + orgId, + kind: "merge_pull_request", + target, + resolved, + targetDigest: kinTargetDigest("merge_pull_request", target, resolved), + reason: "CI is green.", + requestedBy: { agentId: "lead", threadId: "thread-lead" }, + provenance: { + startedBy: "github", + startedByRole: "none", + chain: [], + ceilingBelowOwner: true, + }, + source: decodeEventId(`evt-${number}`), + } as unknown as KinPendingActionCreateInput; + return (yield* actions.create(input)).action; + }); + +const lowS = (raw: Buffer) => { + const s = BigInt(`0x${raw.subarray(32).toString("hex")}`); + const low = s > P256_N / 2n ? P256_N - s : s; + return { r: raw.subarray(0, 32), s: low }; +}; +const sigBytes = (r: Buffer, s: bigint) => + Buffer.concat([r, Buffer.from(s.toString(16).padStart(64, "0"), "hex")]).toString("base64url"); + +/** Signs exactly like the phone module: canonical parts, ES256, low-S, r‖s. */ +function signGrant( + privateKey: NodeCrypto.KeyObject, + header: object, + payload: object, + options: { readonly highS?: boolean } = {}, +) { + const input = encodeGrantSigningInput(header as KinGrantHeader, payload as KinGrantPayload); + const raw = NodeCrypto.sign("sha256", Buffer.from(input), { + key: privateKey, + dsaEncoding: "ieee-p1363", + }); + const { r, s } = lowS(raw); + return `${input}.${sigBytes(r, options.highS ? P256_N - s : s)}`; +} + +let jtiCounter = 0; +const freshJti = () => Buffer.from(`device-jti-${++jtiCounter}-0000`).toString("base64url"); + +type Signer = { readonly privateKey: NodeCrypto.KeyObject; readonly kid: string }; + +/** The phone's flow: ask for the card's payload, add jti/iat/exp, sign. */ +const signFor = ( + grants: GrantVerifier["Service"], + from: KinKeyCaller, + action: KinPendingAction, + signer: Signer, + edit: (payload: Record) => Record = (payload) => payload, +) => + Effect.gen(function* () { + const { payload } = yield* grants.challenge(from, { actionId: action.id }); + const full = edit({ + ...payload, + approver: { ...payload.approver, kid: signer.kid }, + jti: freshJti(), + iat: NOW_S, + exp: NOW_S + 600, + }); + return signGrant( + signer.privateKey, + { typ: "kin-grant+jws", alg: "ES256", kid: signer.kid }, + full, + ); + }); + +const reasonOf = (exit: Exit.Exit) => + Exit.isFailure(exit) && exit.cause.reasons[0]?._tag === "Fail" + ? (exit.cause.reasons[0].error as KinApprovalError).reason + : "success"; + +const stateOf = (actions: KinPendingActions["Service"], action: KinPendingAction) => + actions.get({ orgId, actionId: action.id }).pipe(Effect.map((found) => Option.getOrThrow(found))); + +/** The owner's relay phone: a DPoP session that renews under a new id with the same proof key. */ +const relayPhone = (ttl: Duration.Duration) => + Effect.gen(function* () { + const issued = yield* (yield* SessionStore.SessionStore).issue({ + proofKeyThumbprint: "relay-phone", + ttl, + }); + const phone = callerFor(issued.sessionId, owner); + return { + ...phone, + session: { ...phone.session, method: "dpop-access-token", proofKeyThumbprint: "relay-phone" }, + } satisfies KinKeyCaller; + }); + +const signerOf = (key: { key: { thumbprint: string }; privateKey: NodeCrypto.KeyObject }) => ({ + privateKey: key.privateKey, + kid: key.key.thumbprint, +}); + +describe("GrantVerifier", () => { + it.effect("an owner grant approves the action once, bound to what the card showed", () => { + const h = harness(); + return Effect.gen(function* () { + const { grants, actions, ownerKey } = yield* enrol; + const action = yield* requestMerge(actions, 212, h.github); + const { payload, resolved } = yield* grants.challenge(ownerPhone, { actionId: action.id }); + assert.deepStrictEqual(payload, { + v: 1, + orgId, + actionId: action.id, + revision: 0, + nonce: action.nonce, + kind: "merge_pull_request", + targetDigest: action.targetDigest, + target: action.target, + headSha: sha("a"), + base: "main", + mergeMethod: "squash", + approver: { humanId: owner, kid: ownerKey.key.thumbprint }, + decision: "approve", + }); + assert.deepStrictEqual(resolved, action.resolved); + + const compact = yield* signFor(grants, ownerPhone, action, signerOf(ownerKey)); + // Another session of the same person may send it (check 5). + const result = yield* grants.submitGrant(ownerLaptop, { compact }); + assert.deepStrictEqual(result, { actionId: action.id, state: "approved" }); + assert.strictEqual((yield* stateOf(actions, action)).state, "approved"); + assert.deepStrictEqual( + h.audit.map((entry) => [entry.event, entry.result]), + [["grant_accepted", undefined]], + ); + assert.strictEqual(h.audit[0]?.sessionId, "sess-laptop"); + }).pipe(Effect.provide(h.layer)); + }); + + it.effect("a member's client sends a forged approval and the server rejects it", () => { + const h = harness(); + return Effect.gen(function* () { + const { grants, actions, memberKey } = yield* enrol; + const action = yield* requestMerge(actions, 212, h.github); + // A member gets no challenge, so the forger copies the owner's card facts. + assert.strictEqual( + reasonOf(yield* Effect.exit(grants.challenge(memberPhone, { actionId: action.id }))), + "not_owner", + ); + const { payload } = yield* grants.challenge(ownerPhone, { actionId: action.id }); + const compact = signGrant( + memberKey.privateKey, + { typ: "kin-grant+jws", alg: "ES256", kid: memberKey.key.thumbprint }, + { + ...payload, + approver: { humanId: member, kid: memberKey.key.thumbprint }, + jti: freshJti(), + iat: NOW_S, + exp: NOW_S + 600, + }, + ); + const exit = yield* Effect.exit(grants.submitGrant(memberPhone, { compact })); + assert.strictEqual(reasonOf(exit), "not_owner"); + assert.strictEqual((yield* stateOf(actions, action)).state, "awaiting_approval"); + assert.deepStrictEqual(h.audit.at(-1), { + orgId, + event: "grant_rejected", + actionId: action.id, + kind: "merge_pull_request", + grantJti: Buffer.from(`device-jti-${jtiCounter}-0000`).toString("base64url"), + keyThumbprint: memberKey.key.thumbprint, + headSha: sha("a"), + sessionId: sessionId("sess-member"), + result: "not_owner", + }); + }).pipe(Effect.provide(h.layer)); + }); + + it.effect("a grant signed by an unregistered key is rejected", () => { + const h = harness(); + return Effect.gen(function* () { + const { grants, actions } = yield* enrol; + const action = yield* requestMerge(actions, 212, h.github); + const stranger = newKey(); + const jwk = stranger.publicKey.export({ format: "jwk" }); + const kid = computeDpopJwkThumbprint({ kty: "EC", crv: "P-256", x: jwk.x!, y: jwk.y! }); + const compact = yield* signFor(grants, ownerPhone, action, { + privateKey: stranger.privateKey, + kid, + }); + assert.strictEqual( + reasonOf(yield* Effect.exit(grants.submitGrant(ownerPhone, { compact }))), + "unknown_key", + ); + assert.strictEqual((yield* stateOf(actions, action)).state, "awaiting_approval"); + }).pipe(Effect.provide(h.layer)); + }); + + it.effect("a grant whose header carries a jwk is rejected", () => { + const h = harness(); + return Effect.gen(function* () { + const { grants, actions, ownerKey } = yield* enrol; + const action = yield* requestMerge(actions, 212, h.github); + const { payload } = yield* grants.challenge(ownerPhone, { actionId: action.id }); + const header = { + typ: "kin-grant+jws", + alg: "ES256", + kid: ownerKey.key.thumbprint, + jwk: ownerKey.key.publicJwk, + }; + const full = { ...payload, jti: freshJti(), iat: NOW_S, exp: NOW_S + 600 }; + const b64 = (value: unknown) => Buffer.from(stableStringify(value)).toString("base64url"); + const input = `${b64(header)}.${b64(full)}`; + const { r, s } = lowS( + NodeCrypto.sign("sha256", Buffer.from(input), { + key: ownerKey.privateKey, + dsaEncoding: "ieee-p1363", + }), + ); + const exit = yield* Effect.exit( + grants.submitGrant(ownerPhone, { compact: `${input}.${sigBytes(r, s)}` }), + ); + assert.strictEqual(reasonOf(exit), "malformed"); + assert.strictEqual(h.audit.at(-1)?.result, "malformed"); + }).pipe(Effect.provide(h.layer)); + }); + + it.effect( + "a grant signed by a revoked key is rejected, and revoking voids approved actions it signed", + () => { + const h = harness(); + return Effect.gen(function* () { + const { grants, actions, keys, ownerKey } = yield* enrol; + const signed = yield* requestMerge(actions, 212, h.github); + const waiting = yield* requestMerge(actions, 213, h.github); + const first = yield* signFor(grants, ownerPhone, signed, signerOf(ownerKey)); + const second = yield* signFor(grants, ownerPhone, waiting, signerOf(ownerKey)); + yield* grants.submitGrant(ownerPhone, { compact: first }); + + yield* keys.revokeKey(ownerPhone, ownerKey.key); + assert.strictEqual((yield* stateOf(actions, signed)).state, "voided"); + const exit = yield* Effect.exit(grants.submitGrant(ownerPhone, { compact: second })); + assert.strictEqual(reasonOf(exit), "revoked_key"); + assert.strictEqual((yield* stateOf(actions, waiting)).state, "awaiting_approval"); + }).pipe(Effect.provide(h.layer)); + }, + ); + + it.effect("an owner grant replayed a second time is rejected", () => { + const h = harness(); + return Effect.gen(function* () { + const { grants, actions, ownerKey, sql } = yield* enrol; + const action = yield* requestMerge(actions, 212, h.github); + const compact = yield* signFor(grants, ownerPhone, action, signerOf(ownerKey)); + yield* grants.submitGrant(ownerPhone, { compact }); + const exit = yield* Effect.exit(grants.submitGrant(ownerPhone, { compact })); + assert.strictEqual(reasonOf(exit), "replayed"); + const rows = yield* sql`SELECT 1 FROM kin_grants`; + assert.strictEqual(rows.length, 1); + assert.strictEqual(h.audit.at(-1)?.result, "replayed"); + }).pipe(Effect.provide(h.layer)); + }); + + it.effect("an owner grant for PR 212 can't approve PR 213", () => { + const h = harness(); + return Effect.gen(function* () { + const { grants, actions, ownerKey } = yield* enrol; + const for212 = yield* requestMerge(actions, 212, h.github); + const for213 = yield* requestMerge(actions, 213, h.github); + // Pointed at 213 with 213's nonce, but still describing 212. + const retargeted = yield* signFor(grants, ownerPhone, for212, signerOf(ownerKey), (p) => ({ + ...p, + actionId: for213.id, + nonce: for213.nonce, + })); + assert.strictEqual( + reasonOf(yield* Effect.exit(grants.submitGrant(ownerPhone, { compact: retargeted }))), + "target_mismatch", + ); + // Pointed at 213 with 212's nonce. + const wrongNonce = yield* signFor(grants, ownerPhone, for212, signerOf(ownerKey), (p) => ({ + ...p, + actionId: for213.id, + })); + assert.strictEqual( + reasonOf(yield* Effect.exit(grants.submitGrant(ownerPhone, { compact: wrongNonce }))), + "stale", + ); + assert.strictEqual((yield* stateOf(actions, for213)).state, "awaiting_approval"); + assert.strictEqual((yield* stateOf(actions, for212)).state, "awaiting_approval"); + }).pipe(Effect.provide(h.layer)); + }); + + it.effect("a grant for the old nonce fails after a new commit", () => { + const h = harness(); + return Effect.gen(function* () { + const { grants, actions, ownerKey } = yield* enrol; + const action = yield* requestMerge(actions, 212, h.github); + const old = yield* signFor(grants, ownerPhone, action, signerOf(ownerKey)); + // Checks alone moving isn't what check 9 compares, so the card shows them without a rotation. + const failing = { + ...prFacts(sha("a")), + checks: [{ name: "ci", required: true, status: "failed" as const }], + }; + h.github.set(212, failing); + const reopened = yield* grants.challenge(ownerPhone, { actionId: action.id }); + assert.deepStrictEqual( + [reopened.payload.revision, reopened.payload.nonce, reopened.resolved], + [0, action.nonce, failing], + ); + h.github.set(212, prFacts(sha("c"))); + // Opening the card again re-reads GitHub, bumps the revision and rotates the nonce. + const { payload } = yield* grants.challenge(ownerPhone, { actionId: action.id }); + assert.strictEqual(payload.revision, 1); + assert.strictEqual(payload.headSha, sha("c")); + assert.notStrictEqual(payload.nonce, action.nonce); + const exit = yield* Effect.exit(grants.submitGrant(ownerPhone, { compact: old })); + assert.strictEqual(reasonOf(exit), "stale"); + const fresh = yield* signFor(grants, ownerPhone, action, signerOf(ownerKey)); + assert.strictEqual( + (yield* grants.submitGrant(ownerPhone, { compact: fresh })).state, + "approved", + ); + }).pipe(Effect.provide(h.layer)); + }); + + it.effect("a grant older than 15 minutes is voided before execution", () => { + const h = harness(); + return Effect.gen(function* () { + const { grants, actions, ownerKey, sql } = yield* enrol; + const action = yield* requestMerge(actions, 212, h.github); + const compact = yield* signFor(grants, ownerPhone, action, signerOf(ownerKey), (p) => ({ + ...p, + exp: NOW_S + 900, + })); + yield* grants.submitGrant(ownerPhone, { compact }); + const [grant] = yield* sql<{ grant_id: string }>`SELECT grant_id FROM kin_grants`; + yield* TestClock.adjust("14 minutes"); + assert.deepStrictEqual((yield* actions.sweep()).voided, []); + yield* TestClock.adjust("1 minute"); + assert.deepStrictEqual((yield* actions.sweep()).voided, [{ orgId, actionId: action.id }]); + assert.strictEqual((yield* stateOf(actions, action)).state, "voided"); + const claimed = yield* actions.claim({ + orgId, + actionId: action.id, + revision: 0, + grantId: grant!.grant_id as never, + }); + assert.isFalse(claimed); + }).pipe(Effect.provide(h.layer)); + }); + + it.effect("a grant with exp more than 900 s after iat is rejected", () => { + const h = harness(); + return Effect.gen(function* () { + const { grants, actions, ownerKey } = yield* enrol; + const action = yield* requestMerge(actions, 212, h.github); + const compact = yield* signFor(grants, ownerPhone, action, signerOf(ownerKey), (p) => ({ + ...p, + exp: NOW_S + 901, + })); + assert.strictEqual( + reasonOf(yield* Effect.exit(grants.submitGrant(ownerPhone, { compact }))), + "time_window", + ); + }).pipe(Effect.provide(h.layer)); + }); + + it.effect("each check rejects with its own reason and leaves the action waiting", () => { + const h = harness(); + return Effect.gen(function* () { + const world = yield* enrol; + const { grants, actions, keys, ownerKey, memberKey } = world; + const owner_ = signerOf(ownerKey); + const pending = yield* register(keys, ownerPhone); + + type Case = { + readonly name: string; + readonly reason: string; + readonly build: (action: KinPendingAction) => Effect.Effect; + readonly from?: KinKeyCaller; + readonly before?: (action: KinPendingAction) => void; + }; + const edit = + (change: (p: Record) => Record, signer = owner_) => + (action: KinPendingAction) => + signFor(grants, ownerPhone, action, signer, change); + const cases: ReadonlyArray = [ + { + name: "1: whitespace in a part", + reason: "malformed", + build: (action) => + edit((p) => p)(action).pipe( + Effect.map((compact) => { + const [header, payload, sig] = compact.split("."); + const text = Buffer.from(payload!, "base64url").toString().replace(":", ": "); + return `${header}.${Buffer.from(text).toString("base64url")}.${sig}`; + }), + ), + }, + { + name: "1: wrong typ", + reason: "malformed", + build: (action) => + grants + .challenge(ownerPhone, { actionId: action.id }) + .pipe( + Effect.map(({ payload }) => + signGrant( + ownerKey.privateKey, + { typ: "JWT", alg: "ES256", kid: owner_.kid }, + { ...payload, jti: freshJti(), iat: NOW_S, exp: NOW_S + 600 }, + ), + ), + ), + }, + { + name: "1: a jti shorter than 16 bytes", + reason: "malformed", + build: edit((p) => ({ ...p, jti: Buffer.alloc(15, 1).toString("base64url") })), + }, + { + name: "2: a pending key", + reason: "unknown_key", + build: edit((p) => p, signerOf(pending)), + }, + { + name: "2: approver.kid differs from the header kid", + reason: "unknown_key", + build: edit((p) => ({ + ...p, + approver: { humanId: owner, kid: memberKey.key.thumbprint }, + })), + }, + { + name: "3: a flipped signature", + reason: "bad_signature", + build: (action) => + edit((p) => p)(action).pipe( + Effect.map((compact) => { + const sig = Buffer.from(compact.split(".")[2]!, "base64url"); + sig[10]! ^= 1; + return `${compact.split(".").slice(0, 2).join(".")}.${sig.toString("base64url")}`; + }), + ), + }, + { + name: "3: the high-S twin", + reason: "bad_signature", + build: (action) => + grants + .challenge(ownerPhone, { actionId: action.id }) + .pipe( + Effect.map(({ payload }) => + signGrant( + ownerKey.privateKey, + { typ: "kin-grant+jws", alg: "ES256", kid: owner_.kid }, + { ...payload, jti: freshJti(), iat: NOW_S, exp: NOW_S + 600 }, + { highS: true }, + ), + ), + ), + }, + { + name: "4: approver.humanId isn't the key's person", + reason: "not_owner", + build: edit((p) => ({ ...p, approver: { humanId: member, kid: owner_.kid } })), + }, + { + name: "4 before 8: a member's expired grant", + reason: "not_owner", + from: memberPhone, + build: edit( + (p) => ({ + ...p, + approver: { humanId: member, kid: memberKey.key.thumbprint }, + iat: NOW_S - 1000, + exp: NOW_S - 500, + }), + signerOf(memberKey), + ), + }, + { + name: "5: the owner's grant from the member's session", + reason: "session_mismatch", + from: memberPhone, + build: edit((p) => p), + }, + { + name: "5: a session that is nobody", + reason: "session_mismatch", + from: nobody, + build: edit((p) => p), + }, + { name: "6: wrong revision", reason: "stale", build: edit((p) => ({ ...p, revision: 7 })) }, + { + name: "6: wrong nonce", + reason: "stale", + build: edit((p) => ({ ...p, nonce: Buffer.alloc(32, 7).toString("base64url") })), + }, + { + name: "7: another targetDigest", + reason: "target_mismatch", + build: edit((p) => ({ ...p, targetDigest: "f".repeat(64) })), + }, + { + name: "7: another merge method", + reason: "target_mismatch", + build: edit((p) => ({ ...p, target: pr(212, "merge"), mergeMethod: "merge" })), + }, + { + name: "7: another headSha", + reason: "target_mismatch", + build: edit((p) => ({ ...p, headSha: sha("d") })), + }, + { + name: "7: another base", + reason: "target_mismatch", + build: edit((p) => ({ ...p, base: "release" })), + }, + { + name: "8: iat more than 300 s ago", + reason: "time_window", + build: edit((p) => ({ ...p, iat: NOW_S - 301, exp: NOW_S + 100 })), + }, + { + name: "8: already expired", + reason: "time_window", + build: edit((p) => ({ ...p, iat: NOW_S - 10, exp: NOW_S })), + }, + { + name: "8: exp not after iat", + reason: "time_window", + build: edit((p) => ({ ...p, iat: NOW_S, exp: NOW_S })), + }, + { + name: "9: GitHub shows a new head", + reason: "head_moved", + build: edit((p) => p), + before: (action) => { + const target = action.target as Extract; + h.github.set(target.number, prFacts(sha("e"))); + }, + }, + { + name: "9: GitHub shows a new base", + reason: "head_moved", + build: edit((p) => p), + before: (action) => { + const target = action.target as Extract; + h.github.set(target.number, prFacts(sha("b"), "release")); + }, + }, + { + name: "9: GitHub can't be read", + reason: "unavailable", + build: edit((p) => p), + before: (action) => { + const target = action.target as Extract; + h.github.set(target.number, "down"); + }, + }, + ]; + + let number = 300; + for (const testCase of cases) { + const action = yield* requestMerge(actions, ++number, h.github); + const compact = yield* testCase.build(action); + testCase.before?.(action); + const exit = yield* Effect.exit( + grants.submitGrant(testCase.from ?? ownerPhone, { compact }), + ); + assert.strictEqual(reasonOf(exit), testCase.reason, testCase.name); + const after = yield* stateOf(actions, action); + assert.strictEqual(after.state, "awaiting_approval", testCase.name); + // A moved head rotates the nonce; nothing else touches the action. + assert.strictEqual(after.revision, testCase.reason === "head_moved" ? 1 : 0, testCase.name); + if (testCase.from !== nobody) + assert.deepStrictEqual( + [h.audit.at(-1)?.event, h.audit.at(-1)?.result], + ["grant_rejected", testCase.reason], + testCase.name, + ); + } + }).pipe(Effect.provide(h.layer)); + }); + + it.effect("a grant that loses the race at check 10 is replayed, stale or revoked", () => { + const h = harness(); + return Effect.gen(function* () { + const { grants, actions, keys, ownerKey, sql } = yield* enrol; + const raced = yield* requestMerge(actions, 212, h.github); + const compact = yield* signFor(grants, ownerPhone, raced, signerOf(ownerKey)); + // Another grant from the same approver lands after this one passed check 6. + h.race.during = actions + .approve({ + orgId, + actionId: raced.id, + revision: raced.revision, + nonce: raced.nonce, + jti: "concurrent-jti", + approverHumanId: owner, + keyThumbprint: ownerKey.key.thumbprint, + compact: "concurrent", + iat: NOW_S, + exp: NOW_S + 600, + }) + .pipe(Effect.orDie); + assert.strictEqual( + reasonOf(yield* Effect.exit(grants.submitGrant(ownerPhone, { compact }))), + "replayed", + ); + + const rejected = yield* requestMerge(actions, 213, h.github); + const late = yield* signFor(grants, ownerPhone, rejected, signerOf(ownerKey)); + h.race.during = actions + .transition({ + orgId, + actionId: rejected.id, + revision: 0, + to: "rejected", + }) + .pipe(Effect.orDie); + assert.strictEqual( + reasonOf(yield* Effect.exit(grants.submitGrant(ownerPhone, { compact: late }))), + "stale", + ); + assert.strictEqual((yield* stateOf(actions, rejected)).state, "rejected"); + + // The signing key's session is revoked, or the key itself, after check 2 passed. + const laptopKey = yield* register(keys, ownerLaptop); + assert.isTrue(yield* keys.activateByGrant(laptopKey.key)); + const revocations = [ + { + number: 214, + signer: signerOf(laptopKey), + from: ownerLaptop, + revoke: Effect.orDie(sql`UPDATE auth_sessions SET revoked_at = '2026-11-08T00:00:00.000Z' + WHERE session_id = 'sess-laptop'`), + }, + { + number: 215, + signer: signerOf(ownerKey), + from: ownerPhone, + revoke: Effect.orDie(keys.revokeKey(ownerPhone, ownerKey.key)), + }, + ]; + for (const { number, signer, from, revoke } of revocations) { + const action = yield* requestMerge(actions, number, h.github); + const signed = yield* signFor(grants, from, action, signer); + h.race.during = revoke; + assert.strictEqual( + reasonOf(yield* Effect.exit(grants.submitGrant(from, { compact: signed }))), + "revoked_key", + `${number}`, + ); + assert.strictEqual((yield* stateOf(actions, action)).state, "awaiting_approval"); + } + delete h.race.during; + const held = yield* sql`SELECT 1 FROM kin_grants WHERE action_id IN ( + SELECT action_id FROM kin_pending_actions WHERE state = 'awaiting_approval')`; + assert.strictEqual(held.length, 0); + // `approve` records its own refusals; the verifier doesn't write them a second time. The + // race's own writer re-runs on later reads and has no session, so it is left out. + assert.deepStrictEqual( + h.audit + .filter((entry) => entry.event === "grant_rejected" && entry.sessionId !== undefined) + .map((entry) => entry.result), + ["replayed", "stale", "revoked_key", "revoked_key"], + ); + }).pipe(Effect.provide(h.layer)); + }); + + it.effect( + "revoking a relay phone's renewed session rejects its key's grants, even mid-check", + () => { + const h = harness(); + return Effect.gen(function* () { + const { grants, actions, keys } = yield* enrol; + const sessions = yield* SessionStore.SessionStore; + const first = yield* relayPhone(Duration.minutes(1)); + const relayKey = yield* register(keys, first); + assert.isTrue(yield* keys.activateByGrant(relayKey.key)); + yield* TestClock.adjust(Duration.minutes(2)); + const renewed = yield* relayPhone(Duration.hours(1)); + + // Settings revokes the session it lists, while check 9 reads GitHub. + const raced = yield* requestMerge(actions, 212, h.github); + const compact = yield* signFor(grants, renewed, raced, signerOf(relayKey)); + h.race.during = Effect.orDie(sessions.revoke(renewed.session.sessionId)); + assert.strictEqual( + reasonOf(yield* Effect.exit(grants.submitGrant(renewed, { compact }))), + "revoked_key", + ); + assert.strictEqual((yield* stateOf(actions, raced)).state, "awaiting_approval"); + delete h.race.during; + + const later = yield* requestMerge(actions, 213, h.github); + const next = yield* signFor(grants, renewed, later, signerOf(relayKey)); + assert.strictEqual( + reasonOf(yield* Effect.exit(grants.submitGrant(renewed, { compact: next }))), + "revoked_key", + ); + }).pipe(Effect.provide(h.relayLayer)); + }, + ); + + it.effect( + "an approved grant can't be claimed once a renewed relay session of its key is revoked", + () => { + const h = harness(); + return Effect.gen(function* () { + const { grants, actions, keys, sql } = yield* enrol; + const sessions = yield* SessionStore.SessionStore; + const relayKey = yield* register(keys, yield* relayPhone(Duration.minutes(1))); + assert.isTrue(yield* keys.activateByGrant(relayKey.key)); + yield* TestClock.adjust(Duration.minutes(2)); + const renewed = yield* relayPhone(Duration.hours(1)); + const action = yield* requestMerge(actions, 212, h.github); + const compact = yield* signFor(grants, renewed, action, signerOf(relayKey)); + yield* grants.submitGrant(renewed, { compact }); + assert.strictEqual((yield* stateOf(actions, action)).state, "approved"); + + // No key read runs between the revoke and the claim, so nothing has voided the action yet. + yield* sessions.revoke(renewed.session.sessionId); + const [grant] = yield* sql<{ grant_id: string }>`SELECT grant_id FROM kin_grants + WHERE action_id = ${action.id}`; + assert.isFalse( + yield* actions.claim({ + orgId, + actionId: action.id, + revision: action.revision, + grantId: grant!.grant_id as never, + }), + ); + }).pipe(Effect.provide(h.relayLayer)); + }, + ); + + it.effect("a phone that signs out other devices still approves with its own key", () => { + const h = harness(); + return Effect.gen(function* () { + const { grants, actions, keys } = yield* enrol; + const sessions = yield* SessionStore.SessionStore; + const first = yield* relayPhone(Duration.hours(1)); + const relayKey = yield* register(keys, first); + assert.isTrue(yield* keys.activateByGrant(relayKey.key)); + const renewed = yield* relayPhone(Duration.hours(1)); + yield* sessions.revokeAllExcept(renewed.session.sessionId); + + const action = yield* requestMerge(actions, 212, h.github); + const compact = yield* signFor(grants, renewed, action, signerOf(relayKey)); + yield* grants.submitGrant(renewed, { compact }); + assert.strictEqual((yield* stateOf(actions, action)).state, "approved"); + }).pipe(Effect.provide(h.relayLayer)); + }); + + it.effect("an active key the server never attested can't sign", () => { + const h = harness(); + return Effect.gen(function* () { + const { grants, actions, ownerKey, sql } = yield* enrol; + const action = yield* requestMerge(actions, 212, h.github); + const compact = yield* signFor(grants, ownerPhone, action, signerOf(ownerKey)); + // No path stores this row; it stands for a database edited behind the server's back. + yield* sql`UPDATE kin_approver_keys SET attested = 0 WHERE thumbprint = ${ownerKey.key.thumbprint}`; + assert.strictEqual( + reasonOf(yield* Effect.exit(grants.submitGrant(ownerPhone, { compact }))), + "unknown_key", + ); + }).pipe(Effect.provide(h.layer)); + }); + + it.effect("rejections are bounded per session per minute, with junk on its own budget", () => { + const h = harness(); + return Effect.gen(function* () { + const { grants, actions, ownerKey, memberKey, sql } = yield* enrol; + for (let attempt = 0; attempt < 25; attempt++) { + yield* Effect.exit(grants.submitGrant(memberPhone, { compact: "not.a.grant" })); + } + assert.strictEqual(h.audit.length, 20); + // Past the junk budget, a forgery against the owner's real key is still recorded. + const action = yield* requestMerge(actions, 212, h.github); + const forger = { privateKey: memberKey.privateKey, kid: ownerKey.key.thumbprint }; + const forged = yield* signFor(grants, ownerPhone, action, forger); + assert.strictEqual( + reasonOf(yield* Effect.exit(grants.submitGrant(memberPhone, { compact: forged }))), + "bad_signature", + ); + assert.deepStrictEqual( + [h.audit.length, h.audit.at(-1)?.keyThumbprint, h.audit.at(-1)?.sessionId], + [21, ownerKey.key.thumbprint, "sess-member"], + ); + // Forgeries against a real key have a budget of their own, so they can't flood the chain either. + for (let attempt = 0; attempt < 24; attempt++) { + yield* Effect.exit(grants.submitGrant(memberPhone, { compact: forged })); + } + assert.strictEqual(h.audit.length, 40); + // Another session has its own budget. + yield* Effect.exit(grants.submitGrant(ownerPhone, { compact: "not.a.grant" })); + assert.strictEqual(h.audit.length, 41); + // The skipped counts are written when the windows end, not on a later rejection. + yield* TestClock.adjust("1 minute"); + assert.deepStrictEqual( + h.audit.slice(41).map((entry) => [entry.event, entry.sessionId, entry.result]), + [ + ["grant_rejected", "sess-member", "5 more not recorded"], + ["grant_rejected", "sess-member", "5 more not recorded"], + ], + ); + + // Before its signature verifies, a grant naming another org's key is audited in the + // caller's org: an unproven claim can't write into a chain it doesn't belong to. + yield* sql`INSERT INTO kin_orgs (org_id, name, created_at) + VALUES ('org_02', 'Other', '2026-11-07T00:00:00.000Z')`; + yield* sql`INSERT INTO kin_approver_keys SELECT thumbprint, 'org_02', public_jwk_json, + human_id, device_label, platform, hardware, attested, NULL, NULL, state, created_at, + confirmed_at, revoked_at + FROM kin_approver_keys WHERE thumbprint = ${ownerKey.key.thumbprint}`; + const elsewhere = yield* signFor(grants, ownerPhone, action, forger, (p) => ({ + ...p, + orgId: "org_02", + })); + assert.strictEqual( + reasonOf(yield* Effect.exit(grants.submitGrant(memberPhone, { compact: elsewhere }))), + "bad_signature", + ); + assert.strictEqual(h.audit.length, 44); + assert.isTrue(h.audit.every((entry) => entry.orgId === orgId)); + }).pipe(Effect.provide(h.layer)); + }); + + it.effect("only the owner can reject, against the card's revision, and it is audited", () => { + const h = harness(); + return Effect.gen(function* () { + const { grants, actions, ownerKey } = yield* enrol; + const action = yield* requestMerge(actions, 212, h.github); + const compact = yield* signFor(grants, ownerPhone, action, signerOf(ownerKey)); + const input = { actionId: action.id, revision: 0 }; + assert.strictEqual( + reasonOf(yield* Effect.exit(grants.reject(memberPhone, input))), + "not_owner", + ); + assert.strictEqual(reasonOf(yield* Effect.exit(grants.reject(nobody, input))), "not_owner"); + assert.strictEqual( + reasonOf(yield* Effect.exit(grants.reject(ownerPhone, { ...input, revision: 1 }))), + "stale", + ); + assert.deepStrictEqual(yield* grants.reject(ownerPhone, input), { + actionId: action.id, + state: "rejected", + }); + assert.deepStrictEqual( + [h.audit.at(-1)?.event, h.audit.at(-1)?.sessionId], + ["action_rejected", "sess-phone"], + ); + assert.strictEqual( + reasonOf(yield* Effect.exit(grants.submitGrant(ownerPhone, { compact }))), + "stale", + ); + assert.strictEqual( + reasonOf(yield* Effect.exit(grants.challenge(ownerPhone, { actionId: action.id }))), + "invalid_state", + ); + + // Past `expiresAt` it is expired, not rejected, even before the sweep runs. + const lapsed = yield* requestMerge(actions, 213, h.github); + yield* TestClock.adjust("7 days"); + assert.strictEqual( + reasonOf( + yield* Effect.exit(grants.reject(ownerPhone, { actionId: lapsed.id, revision: 0 })), + ), + "invalid_state", + ); + assert.strictEqual((yield* stateOf(actions, lapsed)).state, "expired"); + }).pipe(Effect.provide(h.layer)); + }); + + it.effect("challenge finds actions only in the caller's own org", () => { + const h = harness(); + return Effect.gen(function* () { + const { grants, actions, sql } = yield* enrol; + yield* sql`INSERT INTO kin_orgs (org_id, name, created_at) + VALUES ('org_02', 'Other', '2026-11-07T00:00:00.000Z')`; + const action = yield* requestMerge(actions, 212, h.github); + yield* sql`UPDATE kin_pending_actions SET org_id = 'org_02' WHERE action_id = ${action.id}`; + assert.strictEqual( + reasonOf(yield* Effect.exit(grants.challenge(ownerPhone, { actionId: action.id }))), + "not_found", + ); + }).pipe(Effect.provide(h.layer)); + }); + + it.effect("phase 1's org owner is the person bootstrap reserved", () => + Effect.gen(function* () { + const sql = yield* SqlClient.SqlClient; + yield* sql`INSERT INTO kin_orgs (org_id, name, created_at) + VALUES ('kin-default', 'Kin', '2026-11-07T00:00:00.000Z')`; + yield* sql`INSERT INTO kin_people (person_id, org_id, handle, display_name, created_at) + VALUES (${BOOTSTRAP_OWNER}, 'kin-default', 'owner', 'Owner', '2026-11-07T00:00:00.000Z'), + ('h_member', 'kin-default', 'priya', 'Priya', '2026-11-07T00:00:00.000Z')`; + const roles = yield* KinOrgRoles; + const ask = (org: string, person: string) => + roles.isOwner({ + orgId: decodeOrgId(org), + personId: decodePersonId(person), + }); + assert.isTrue(yield* ask("kin-default", BOOTSTRAP_OWNER)); + assert.isFalse(yield* ask("kin-default", "h_member")); + assert.isFalse(yield* ask("org_01", BOOTSTRAP_OWNER)); + }).pipe( + Effect.provide( + orgRolesLayer.pipe( + Layer.provideMerge(Layer.provideMerge(KinPersistence.layer, Sqlite.layerMemory)), + ), + ), + ), + ); + + it("no agent, MCP tool or model-reachable path can reach grant decisions", () => { + const root = NodePath.resolve(import.meta.dirname, "../.."); + const files = (NodeFS.readdirSync(root, { recursive: true }) as Array) + .filter((file) => file.endsWith(".ts") && !file.endsWith(".test.ts")) + .map((file) => file.split(NodePath.sep).join("/")) + .toSorted(); + const source = (file: string) => NodeFS.readFileSync(NodePath.join(root, file), "utf8"); + // Every relative specifier, static or dynamic, resolved from the importing file. + const imports = (file: string) => + [...source(file).matchAll(/(?:from|import\s*\()\s*["'](\.{1,2}\/[^"']+)["']/g)].map((match) => + NodePath.posix.normalize(NodePath.posix.join(NodePath.posix.dirname(file), match[1]!)), + ); + const importers = (target: string) => files.filter((file) => imports(file).includes(target)); + const modelFacing = (file: string) => + file.startsWith("mcp/") || file.startsWith("kin/mcp/") || file.startsWith("kin/lead/"); + const forbidden = (file: string) => modelFacing(file) || file === "kin/approvals/mcp.ts"; + + // Only check 10 moves an action to `approved`, and only the verifier runs it. + assert.deepStrictEqual( + files.filter( + (file) => /KinPendingActions/.test(source(file)) && /\.approve\(/.test(source(file)), + ), + ["kin/approvals/GrantVerifier.ts"], + ); + // The verifier is built in the approvals layer, exposed on KinServer and called by WS only. + const verifierImporters = importers("kin/approvals/GrantVerifier.ts"); + assert.deepStrictEqual(verifierImporters, [ + "kin/KinServer.ts", + "kin/approvals/layer.ts", + "kin/approvals/rpcHandlers.ts", + ]); + // Those handlers are served only on the authenticated `/ws` session, never over MCP. + const handlerImporters = importers("kin/approvals/rpcHandlers.ts"); + assert.deepStrictEqual(handlerImporters, ["kin/rpcHandlers.ts"]); + assert.deepStrictEqual(importers("kin/rpcHandlers.ts"), ["ws.ts"]); + // request_action's tool is the one approvals module the model reaches, and it only requests. + const approvalsImports = (file: string) => + imports(file).filter((target) => target.startsWith("kin/approvals/")); + assert.deepStrictEqual( + [...new Set(files.filter(modelFacing).flatMap(approvalsImports))], + ["kin/approvals/mcp.ts"], + ); + const fromTool = new Set(); + const pending = ["kin/approvals/mcp.ts"]; + for (let file = pending.pop(); file !== undefined; file = pending.pop()) { + for (const target of approvalsImports(file)) { + if (!fromTool.has(target)) pending.push(target); + fromTool.add(target); + } + } + assert.deepStrictEqual( + [...fromTool].filter( + (file) => + [ + "kin/approvals/GrantVerifier.ts", + "kin/approvals/rpcHandlers.ts", + "kin/approvals/ApproverKeys.ts", + "kin/approvals/layer.ts", + ].includes(file) || file.startsWith("kin/approvals/handlers/"), + ), + [], + ); + assert.deepStrictEqual([...verifierImporters, ...handlerImporters].filter(forbidden), []); + }); +}); diff --git a/apps/server/src/kin/approvals/GrantVerifier.ts b/apps/server/src/kin/approvals/GrantVerifier.ts new file mode 100644 index 0000000000000..eaef1b10efed3 --- /dev/null +++ b/apps/server/src/kin/approvals/GrantVerifier.ts @@ -0,0 +1,461 @@ +import { + KinApprovalError, + KinGrantUnsignedPayload, + type AuthSessionId, + type KinActionKind, + type KinApprovalsActionInput, + type KinApprovalsChallengeResult, + type KinApprovalsDecisionResult, + type KinApprovalsRejectInput, + type KinApprovalsSubmitGrantInput, + type KinGrantPayload, + type KinGrantRejectionReason, + type KinOrgId, + type KinPendingAction, +} from "@t3tools/contracts"; +import { decodeKinGrant, verifyKinGrant } from "@t3tools/shared/kinGrant"; +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 Duration from "effect/Duration"; +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 type { PersonIdentity } from "../chat/KinIdentity.ts"; +import { ApproverKeys, type KinKeyCaller } from "./ApproverKeys.ts"; +import { toPersistenceSqlError } from "../../persistence/Errors.ts"; +import type { KinAuditAppendInput } from "./Audit.ts"; +import { KinGrantAudit, KinLiveTargets, KinOrgRoles } from "./GrantPorts.ts"; +import { KinPendingActions, kinTargetDigest } from "./PendingActions.ts"; + +// Each kind of rejection gets its own budget per session and org a minute, so junk can't use up +// the budget that records forgeries against a real key. Past the budget, rejections are counted. +const AUDITS_PER_WINDOW = 20; +const JUNK_WINDOW = Duration.minutes(1); +const auditBucket = (reason: KinApprovalError["reason"], signatureVerified: boolean) => + signatureVerified + ? "signed" + : reason === "malformed" || reason === "unknown_key" + ? "junk" + : "names_key"; + +// A jti is 16+ random bytes (spec section 5): 22 unpadded base64url characters. Kept out of the +// shared decoder so it stays byte-for-byte with the device's parser. +const MIN_JTI_CHARS = 22; + +const isKinApprovalError = Schema.is(KinApprovalError); +const decodeUnsigned = Schema.decodeUnknownEffect(KinGrantUnsignedPayload); + +const fail = (reason: KinApprovalError["reason"], message: string) => + Effect.fail(new KinApprovalError({ reason, message })); + +const REJECTION_MESSAGES = { + malformed: "The grant isn't a well-formed Kin grant.", + unknown_key: "No active approver key with this id.", + revoked_key: "This approver key was revoked.", + bad_signature: "The grant's signature doesn't verify.", + not_owner: "Only the owner can approve this.", + session_mismatch: "This grant was sent from another person's session.", + stale: "The card changed; refresh it and approve again.", + target_mismatch: "The grant doesn't match this action.", + time_window: "The grant's time window is invalid or over.", + head_moved: "The pull request changed; refresh the card.", + replayed: "This grant was already used.", +} as const satisfies Record; + +const reject = (reason: KinGrantRejectionReason) => fail(reason, REJECTION_MESSAGES[reason]); + +const pinsHead = (kind: KinActionKind) => kind === "merge_pull_request" || kind === "delete_branch"; + +/** The facts a grant must copy from the server's record (check 7), absent ones dropped. */ +const recordFacts = (action: KinPendingAction) => ({ + kind: action.kind, + target: action.target, + targetDigest: action.targetDigest, + headSha: + pinsHead(action.kind) && action.resolved._tag !== "none" ? action.resolved.headSha : undefined, + base: + action.kind === "merge_pull_request" && action.resolved._tag === "pull_request" + ? action.resolved.base + : undefined, + mergeMethod: action.target._tag === "pull_request" ? action.target.mergeMethod : undefined, +}); + +const grantFacts = (payload: KinGrantPayload) => ({ + kind: payload.kind, + target: payload.target, + targetDigest: payload.targetDigest, + headSha: payload.headSha, + base: payload.base, + mergeMethod: payload.mergeMethod, +}); + +const headOf = (action: KinPendingAction) => { + const resolved = action.resolved; + return stableStringify({ + tag: resolved._tag, + headSha: resolved._tag === "none" ? undefined : resolved.headSha, + base: resolved._tag === "pull_request" ? resolved.base : undefined, + }); +}; + +/** What the rejection audit knows. `orgId` is the key's, set only once its signature verified. */ +type Seen = { + orgId?: KinOrgId; + claimedOrgId?: KinOrgId; + claim?: Pick; + /** The refusal is already on the audit chain. */ + audited?: boolean; +}; + +export class GrantVerifier extends Context.Service< + GrantVerifier, + { + /** The unsigned payload the phone renders and signs; re-reads GitHub and rotates if it moved. */ + readonly challenge: ( + caller: KinKeyCaller, + input: KinApprovalsActionInput, + ) => Effect.Effect; + /** Approvals spec section 5 checks 1-10, in order; every rejection is audited. */ + readonly submitGrant: ( + caller: KinKeyCaller, + input: KinApprovalsSubmitGrantInput, + ) => Effect.Effect; + /** No signature: rejecting is always safe. Still only the approver can, and it's audited. */ + readonly reject: ( + caller: KinKeyCaller, + input: KinApprovalsRejectInput, + ) => Effect.Effect; + } +>()("t3/kin/approvals/GrantVerifier") {} + +const make = Effect.gen(function* () { + const keys = yield* ApproverKeys; + const actions = yield* KinPendingActions; + const roles = yield* KinOrgRoles; + const live = yield* KinLiveTargets; + const audit = yield* KinGrantAudit; + const scope = yield* Effect.scope; + const junkWindows = new Map(); + + // Callers see a plain refusal; the cause is logged through the persistence error shape. + const internal = (operation: string) => (cause: unknown) => + isKinApprovalError(cause) + ? Effect.fail(cause) + : Effect.logWarning(`${operation} failed`, toPersistenceSqlError(operation)(cause)).pipe( + Effect.andThen( + Effect.fail( + new KinApprovalError({ reason: "unavailable", message: "Kin approvals failed." }), + ), + ), + ); + + /** The action by id in one of the caller's own orgs: the client never names the org. */ + const actionFor = Effect.fn("GrantVerifier.actionFor")(function* ( + caller: KinKeyCaller, + actionId: KinPendingAction["id"], + ) { + if (caller.people.length === 0) + return yield* fail("not_owner", "Only the owner can decide this."); + for (const person of caller.people) { + const action = yield* actions.get({ orgId: person.orgId, actionId }); + if (Option.isSome(action)) { + // Phase 1 requirements are all the owner role; phase 3 and 5 add kinds here (spec §3). + if (!(yield* roles.isOwner(person))) + return yield* fail("not_owner", "Only the owner can decide this."); + return { action: action.value, person }; + } + } + return yield* fail("not_found", "No such action."); + }); + + /** Check 9's read; a moved head or base rotates the nonce so the card refreshes. */ + const readLive = Effect.fn("GrantVerifier.readLive")(function* (action: KinPendingAction) { + const resolved = yield* live.resolve({ kind: action.kind, target: action.target }); + if (resolved._tag !== action.resolved._tag) + return yield* fail("unavailable", "GitHub returned a different kind of target."); + return resolved; + }); + + const refreshWith = (action: KinPendingAction, resolved: KinPendingAction["resolved"]) => + actions.refresh({ + orgId: action.orgId, + actionId: action.id, + revision: action.revision, + resolved, + targetDigest: kinTargetDigest(action.kind, action.target, resolved), + }); + + const check = Effect.fn("GrantVerifier.check")(function* ( + caller: KinKeyCaller, + compact: string, + seen: Seen, + ) { + // 1. Shape and canonical bytes. + const decoded = decodeKinGrant(compact); + if (decoded === null) return yield* reject("malformed"); + const { header, payload } = decoded; + seen.claimedOrgId = payload.orgId; + seen.claim = { + actionId: payload.actionId, + kind: payload.kind, + grantJti: payload.jti, + keyThumbprint: header.kid, + ...(payload.headSha === undefined ? {} : { headSha: payload.headSha }), + }; + if (payload.jti.length < MIN_JTI_CHARS) return yield* reject("malformed"); + + // 2. An active key in the grant's org, after session revocations. + const key = yield* keys.requireActive({ orgId: payload.orgId, thumbprint: header.kid }); + if (!key.attested) return yield* reject("unknown_key"); + + // 2's kid binding, 3 and 8 are the shared pure check; its time_window waits for step 8. + const now = yield* Clock.currentTimeMillis; + const verified = verifyKinGrant({ + compact, + publicJwk: key.publicJwk, + nowEpochSeconds: now / 1000, + }); + if (!verified.ok && verified.reason !== "time_window") return yield* reject(verified.reason); + // The key's holder signed this, so its rejections may go in the key's org. + seen.orgId = key.orgId; + + // 4. The signer is the key's person, who holds the owner role now. + if ( + payload.approver.humanId !== key.humanId || + !(yield* roles.isOwner({ orgId: key.orgId, personId: key.humanId })) + ) + return yield* reject("not_owner"); + + // 5. Sent by the key's session or another session of the same person. + const fromKeySession = + key.sessionId !== undefined && key.sessionId === caller.session.sessionId; + const samePerson = caller.people.some( + (person) => person.orgId === key.orgId && person.personId === key.humanId, + ); + if (!fromKeySession && !samePerson) return yield* reject("session_mismatch"); + + // 6. The action is waiting at this revision and nonce. + const found = yield* actions.get({ orgId: key.orgId, actionId: payload.actionId }); + if ( + Option.isNone(found) || + found.value.state !== "awaiting_approval" || + found.value.revision !== payload.revision || + found.value.nonce !== payload.nonce || + DateTime.toEpochMillis(found.value.expiresAt) <= now + ) { + const held = yield* actions.heldGrant({ + orgId: key.orgId, + actionId: payload.actionId, + jti: payload.jti, + approverHumanId: key.humanId, + }); + return yield* reject(held ? "replayed" : "stale"); + } + const action = found.value; + + // 7. What was signed is what the server recorded. + if (stableStringify(grantFacts(payload)) !== stableStringify(recordFacts(action))) + return yield* reject("target_mismatch"); + + // 8. + if (!verified.ok) return yield* reject("time_window"); + + // 9. GitHub still shows the head and base that were signed. + if (pinsHead(action.kind)) { + const resolved = yield* readLive(action); + if (headOf({ ...action, resolved }) !== headOf(action)) { + yield* refreshWith(action, resolved); + return yield* reject("head_moved"); + } + } + + // 10. Grant row and CAS in one transaction, against the row's own org and nonce. + const result = yield* actions.approve({ + orgId: action.orgId, + actionId: action.id, + revision: action.revision, + nonce: action.nonce, + jti: payload.jti, + approverHumanId: key.humanId, + keyThumbprint: key.thumbprint, + compact, + iat: payload.iat, + exp: payload.exp, + sessionId: caller.session.sessionId, + }); + if (result._tag !== "approved") { + // `approve` already wrote this refusal's `grant_rejected` on the action's own chain. + seen.audited = true; + return yield* reject(result._tag); + } + return { action, grant: result.grant }; + }); + + /** The window's skipped count is written when it ends, or when the server stops. */ + const openJunkWindow = (slot: string, orgId: KinOrgId, sessionId: AuthSessionId) => { + const window = { used: 0, skipped: 0 }; + junkWindows.set(slot, window); + const close = Effect.suspend(() => { + junkWindows.delete(slot); + return window.skipped === 0 + ? Effect.void + : audit.append({ + orgId, + event: "grant_rejected", + sessionId, + result: `${window.skipped} more not recorded`, + }); + }); + return Effect.sleep(JUNK_WINDOW).pipe( + Effect.ensuring(close), + Effect.forkIn(scope), + Effect.as(window), + ); + }; + + const recordRejection = Effect.fn("GrantVerifier.recordRejection")(function* ( + caller: KinKeyCaller, + seen: Seen, + error: KinApprovalError, + ) { + const sessionId = caller.session.sessionId; + // Before a signature verifies, the org named in the grant is only a claim: use the caller's. + const orgId = + seen.orgId ?? + (caller.people.find((person) => person.orgId === seen.claimedOrgId) ?? caller.people[0]) + ?.orgId; + if (orgId === undefined) { + // No org to chain it in: a session that is no person in Kin. Logged, never silent. + return yield* Effect.logWarning("Kin grant rejected from a session with no Kin person.", { + sessionId, + reason: error.reason, + }); + } + const entry = { + orgId, + event: "grant_rejected" as const, + ...seen.claim, + sessionId, + result: error.reason, + }; + const slot = `${orgId} ${sessionId} ${auditBucket(error.reason, seen.orgId !== undefined)}`; + const window = junkWindows.get(slot) ?? (yield* openJunkWindow(slot, orgId, sessionId)); + if (window.used >= AUDITS_PER_WINDOW) { + window.skipped += 1; + return; + } + window.used += 1; + yield* audit.append(entry); + }); + + const submitGrant = Effect.fn("GrantVerifier.submitGrant")(function* ( + caller: KinKeyCaller, + input: KinApprovalsSubmitGrantInput, + ) { + const seen: Seen = {}; + // `grant_accepted` is written by `approve`, in the transaction that approves. + const { action } = yield* check(caller, input.compact, seen).pipe( + Effect.catch(internal("GrantVerifier.submitGrant")), + Effect.tapError((error) => + seen.audited ? Effect.void : recordRejection(caller, seen, error), + ), + ); + return { actionId: action.id, state: "approved" as const }; + }); + + /** The key this person signs with: this session's, else their most recently confirmed one. */ + const signingKey = Effect.fn("GrantVerifier.signingKey")(function* ( + caller: KinKeyCaller, + person: PersonIdentity, + ) { + const { keys: listed } = yield* keys.listKeys(caller, { orgId: person.orgId }); + const usable = listed + .filter((key) => key.state === "active" && key.attested && key.humanId === person.personId) + .toSorted( + (a, b) => + (b.confirmedAt === undefined ? 0 : DateTime.toEpochMillis(b.confirmedAt)) - + (a.confirmedAt === undefined ? 0 : DateTime.toEpochMillis(a.confirmedAt)), + ); + const key = + usable.find((candidate) => candidate.sessionId === caller.session.sessionId) ?? usable[0]; + if (key === undefined) + return yield* fail("unknown_key", "Add an approver key on this phone first."); + return key; + }); + + const challenge = Effect.fn("GrantVerifier.challenge")( + function* (caller: KinKeyCaller, input: KinApprovalsActionInput) { + const { action: found, person } = yield* actionFor(caller, input.actionId); + const now = yield* Clock.currentTimeMillis; + if (found.state !== "awaiting_approval" || DateTime.toEpochMillis(found.expiresAt) <= now) + return yield* fail("invalid_state", "This action isn't waiting for approval."); + let action = found; + let resolved = found.resolved; + if (pinsHead(found.kind)) { + resolved = yield* readLive(found); + // Rotate only on what check 9 compares; checks or size moving would only void a good grant. + if (headOf({ ...found, resolved }) !== headOf(found)) { + const refreshed = yield* refreshWith(found, resolved); + if (Option.isNone(refreshed)) return yield* fail("stale", REJECTION_MESSAGES.stale); + action = refreshed.value; + } + } + const key = yield* signingKey(caller, person); + const facts = recordFacts(action); + const payload = yield* decodeUnsigned({ + v: 1, + orgId: action.orgId, + actionId: action.id, + revision: action.revision, + nonce: action.nonce, + ...facts, + approver: { humanId: key.humanId, kid: key.thumbprint }, + decision: "approve", + }); + return { payload, resolved }; + }, + Effect.catch(internal("GrantVerifier.challenge")), + ); + + const rejectAction = Effect.fn("GrantVerifier.reject")( + function* (caller: KinKeyCaller, input: KinApprovalsRejectInput) { + const { action } = yield* actionFor(caller, input.actionId); + if ( + action.state === "awaiting_approval" && + DateTime.toEpochMillis(action.expiresAt) <= (yield* Clock.currentTimeMillis) + ) { + const expired = yield* actions.transition({ + orgId: action.orgId, + actionId: action.id, + revision: action.revision, + to: "expired", + reason: "expired", + sessionId: caller.session.sessionId, + }); + // An approve that landed first wins; say so rather than claim it expired. + if (!expired) return yield* fail("stale", "This action already changed; refresh the card."); + return yield* fail("invalid_state", "This action expired."); + } + const won = yield* actions.transition({ + orgId: action.orgId, + actionId: action.id, + revision: input.revision, + to: "rejected", + reason: "owner_rejected", + sessionId: caller.session.sessionId, + }); + // `transition` writes `action_rejected` in the same transaction. + if (!won) return yield* fail("stale", "This action already changed; refresh the card."); + return { actionId: action.id, state: "rejected" as const }; + }, + Effect.catch(internal("GrantVerifier.reject")), + ); + + return GrantVerifier.of({ challenge, submitGrant, reject: rejectAction }); +}); + +export const layer = Layer.effect(GrantVerifier, make); diff --git a/apps/server/src/kin/approvals/PendingActions.test.ts b/apps/server/src/kin/approvals/PendingActions.test.ts index c9429ae559a85..a3224dac62c33 100644 --- a/apps/server/src/kin/approvals/PendingActions.test.ts +++ b/apps/server/src/kin/approvals/PendingActions.test.ts @@ -72,6 +72,10 @@ const seed = Effect.gen(function* () { 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')`; + // Check 10 approves only while the signing key is active. + yield* sql`INSERT INTO kin_approver_keys (thumbprint, org_id, public_jwk_json, human_id, + device_label, platform, hardware, attested, state, created_at) + VALUES (${kid}, 'org_01', '{}', ${owner}, 'Pixel 9', 'android', 'tee', 1, 'active', 0)`; return yield* KinPendingActions; }); diff --git a/apps/server/src/kin/approvals/PendingActions.ts b/apps/server/src/kin/approvals/PendingActions.ts index dd9711c3bee51..43e455d86f461 100644 --- a/apps/server/src/kin/approvals/PendingActions.ts +++ b/apps/server/src/kin/approvals/PendingActions.ts @@ -29,12 +29,14 @@ 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 * as Statement from "effect/sql/Statement"; import { PersistenceDecodeError, type PersistenceSqlError, toPersistenceSqlError, } from "../../persistence/Errors.ts"; +import { revokedBySession } from "../auth/ProofKeySessions.ts"; import { KinAudit } from "./Audit.ts"; const AWAITING_TTL_MS = 7 * 24 * 60 * 60 * 1000; @@ -82,11 +84,13 @@ const decodeActionId = Schema.decodeEffect(KinActionId); type ActionRef = { readonly orgId: KinOrgId; readonly actionId: KinActionId }; type RevisionRef = ActionRef & { readonly revision: number }; +type GrantRef = ActionRef & { readonly jti: string; readonly approverHumanId: KinPersonId }; export type KinApproveResult = | { readonly _tag: "approved"; readonly grant: KinGrant } | { readonly _tag: "replayed" } - | { readonly _tag: "stale" }; + | { readonly _tag: "stale" } + | { readonly _tag: "revoked_key" }; type Errors = PersistenceSqlError | PersistenceDecodeError; @@ -108,6 +112,23 @@ export const kinIdempotencyKey = (input: { ) .digest("hex"); +/** `sha256(stableStringify({kind, target, headSha, base}))`, approvals spec section 3. */ +export const kinTargetDigest = ( + kind: KinActionKind, + target: KinActionTarget, + resolved: KinResolvedTarget, +): Hex64 => + NodeCrypto.createHash("sha256") + .update( + stableStringify({ + kind, + target, + headSha: resolved._tag === "none" ? undefined : resolved.headSha, + base: resolved._tag === "pull_request" ? resolved.base : undefined, + }), + ) + .digest("hex"); + const newNonce = () => Base64Url.encode(SecureRandom.randomBytesUnsafe(32)); const iso = (ms: number) => DateTime.formatIso(DateTime.makeUnsafe(ms)); @@ -174,6 +195,7 @@ const auditFacts = (row: FactsRow) => ); class Rollback extends Schema.TaggedError()("Rollback", {}) {} +class KeyUnusable extends Schema.TaggedError()("KeyUnusable", {}) {} export class KinPendingActions extends Context.Service< KinPendingActions, @@ -212,6 +234,8 @@ export class KinPendingActions extends Context.Service< readonly deviceLabel?: string; }, ) => Effect.Effect; + /** Whether the org already holds this `jti`, or this approver's grant for the action. */ + readonly heldGrant: (ref: GrantRef) => Effect.Effect; /** The executor's single claim: the `kin_executions` insert plus `approved → executing`. */ readonly claim: ( input: RevisionRef & { readonly grantId: KinGrant["id"] }, @@ -355,6 +379,7 @@ const make = Effect.gen(function* () { WHERE org_id = ${input.orgId} AND action_id = ${input.actionId} AND state = ${from} AND revision = ${input.revision} AND (${input.to} != 'expired' OR expires_at <= ${now}) + AND (${input.to} NOT IN ('rejected', 'cancelled') OR expires_at > ${now}) RETURNING action_id, kind, resolved_json`; if (row === undefined) return false; yield* audit.append({ @@ -371,6 +396,33 @@ const make = Effect.gen(function* () { Effect.mapError(toError("KinPendingActions.transition")), ); + const selectHeld = (ref: GrantRef) => + sql`SELECT 1 FROM kin_grants + WHERE org_id = ${ref.orgId} AND (jti = ${ref.jti} OR (action_id = ${ref.actionId} + AND approver_human_id = ${ref.approverHumanId}))`.pipe( + Effect.map((rows) => rows.length > 0), + ); + + // A revoke can land while check 9 reads GitHub, so check 10 re-reads the key in its own write, + // and so does `claim`, since a revoke between them only voids the action on the next key read. + const signingKeyUsable = (input: { + readonly orgId: KinOrgId | Statement.Fragment; + readonly keyThumbprint: KinKeyThumbprint | Statement.Fragment; + readonly approverHumanId: KinPersonId | Statement.Fragment; + }) => sql`EXISTS (SELECT 1 FROM kin_approver_keys k + WHERE k.org_id = ${input.orgId} AND k.thumbprint = ${input.keyThumbprint} + AND k.human_id = ${input.approverHumanId} AND k.state = 'active' AND k.attested = 1 + AND NOT ${revokedBySession( + sql, + { sessionId: sql`k.session_id`, proofKey: sql`k.proof_key_thumbprint` }, + { since: sql`k.created_at` }, + )})`; + + const heldGrant = Effect.fn("KinPendingActions.heldGrant")( + selectHeld, + Effect.mapError(toError("KinPendingActions.heldGrant")), + ); + const approve = Effect.fn("KinPendingActions.approve")( function* ( input: RevisionRef & { @@ -406,20 +458,21 @@ const make = Effect.gen(function* () { ON CONFLICT DO NOTHING RETURNING grant_id`; if (inserted === undefined) { - const [seen] = yield* sql`SELECT 1 FROM kin_grants - WHERE org_id = ${input.orgId} AND (jti = ${input.jti} OR (action_id = ${input.actionId} - AND approver_human_id = ${input.approverHumanId}))`; - return seen === undefined - ? { _tag: "stale" as const } - : { _tag: "replayed" as const }; + return (yield* selectHeld(input)) + ? { _tag: "replayed" as const } + : { _tag: "stale" as const }; } const [won] = yield* sql`UPDATE kin_pending_actions SET state = 'approved', updated_at = ${now} WHERE org_id = ${input.orgId} AND action_id = ${input.actionId} AND state = 'awaiting_approval' AND revision = ${input.revision} AND nonce = ${input.nonce} AND expires_at > ${now} AND ${input.exp} * 1000 > ${now} + AND ${signingKeyUsable(input)} RETURNING action_id, kind, resolved_json`; - if (won === undefined) return yield* new Rollback(); + if (won === undefined) { + const [usable] = yield* sql`SELECT 1 WHERE ${signingKeyUsable(input)}`; + return yield* usable === undefined ? new KeyUnusable() : new Rollback(); + } yield* audit.append({ orgId: input.orgId, event: "grant_accepted", @@ -443,7 +496,12 @@ const make = Effect.gen(function* () { return { _tag: "approved" as const, grant }; }), ) - .pipe(Effect.catchTags({ Rollback: () => Effect.succeed({ _tag: "stale" as const }) })); + .pipe( + Effect.catchTags({ + Rollback: () => Effect.succeed({ _tag: "stale" as const }), + KeyUnusable: () => Effect.succeed({ _tag: "revoked_key" as const }), + }), + ); // A refused grant still leaves a trace (spec section 11), but only on the chain of the org // that owns the action: an unknown org or action stays `stale` and writes nothing. if (result._tag !== "approved") { @@ -487,6 +545,11 @@ const make = Effect.gen(function* () { AND action_id = ${input.actionId} AND revision = ${input.revision} AND consumed_at IS NULL AND MIN(exp_s * 1000, accepted_at + ${GRANT_ACCEPTED_TTL_MS}) > ${now} + AND ${signingKeyUsable({ + orgId: sql`kin_grants.org_id`, + keyThumbprint: sql`kin_grants.key_thumbprint`, + approverHumanId: sql`kin_grants.approver_human_id`, + })} ON CONFLICT DO NOTHING RETURNING action_id`; if (claimed.length === 0) return false; @@ -600,7 +663,17 @@ const make = Effect.gen(function* () { Effect.mapError(toError("KinPendingActions.sweep")), ); - return KinPendingActions.of({ create, get, refresh, transition, approve, claim, finish, sweep }); + return KinPendingActions.of({ + create, + get, + refresh, + transition, + approve, + heldGrant, + claim, + finish, + sweep, + }); }); const isDecodeError = Schema.is(PersistenceDecodeError); diff --git a/apps/server/src/kin/approvals/layer.ts b/apps/server/src/kin/approvals/layer.ts index bda5a056badf5..4418b6466bb7d 100644 --- a/apps/server/src/kin/approvals/layer.ts +++ b/apps/server/src/kin/approvals/layer.ts @@ -5,10 +5,21 @@ import * as KinPersistence from "../persistence/KinPersistence.ts"; import * as ApproverKeys from "./ApproverKeys.ts"; import * as Audit from "./Audit.ts"; import * as AttestationTrust from "./attestation/AttestationTrust.ts"; +import * as GrantPorts from "./GrantPorts.ts"; +import * as GrantVerifier from "./GrantVerifier.ts"; import * as PendingActions from "./PendingActions.ts"; -export const layer = ApproverKeys.layer.pipe( - Layer.provide(PendingActions.layer.pipe(Layer.provide(Audit.layer))), - Layer.provide(AttestationTrust.layer.pipe(Layer.provide(FetchHttpClient.layer))), +export const layer = GrantVerifier.layer.pipe( + Layer.provideMerge(ApproverKeys.layer), + Layer.provide( + Layer.mergeAll( + PendingActions.layer, + AttestationTrust.layer.pipe(Layer.provide(FetchHttpClient.layer)), + GrantPorts.orgRolesLayer, + GrantPorts.liveTargetsUnconfiguredLayer, + GrantPorts.auditLayer, + ), + ), + Layer.provide(Audit.layer), Layer.provide(KinPersistence.layer), ); diff --git a/apps/server/src/kin/approvals/rpcHandlers.test.ts b/apps/server/src/kin/approvals/rpcHandlers.test.ts index c2cdc2333cf3a..e302b05142f48 100644 --- a/apps/server/src/kin/approvals/rpcHandlers.test.ts +++ b/apps/server/src/kin/approvals/rpcHandlers.test.ts @@ -1,9 +1,16 @@ import { assert, it } from "@effect/vitest"; -import { AuthSessionId, AuthStandardClientScopes, KinOrgId } from "@t3tools/contracts"; +import { + AuthOrchestrationOperateScope, + AuthSessionId, + AuthStandardClientScopes, + KinActionId, + KinOrgId, +} from "@t3tools/contracts"; import * as Effect from "effect/Effect"; import * as Option from "effect/Option"; import * as HttpServerRequest from "effect/http/HttpServerRequest"; +import { requiredScopeForRpcMethod } from "../../auth/RpcAuthorization.ts"; import * as Sqlite from "../../persistence/Sqlite.ts"; import { connectionOf, makeKinApprovalHandlers } from "./rpcHandlers.ts"; @@ -28,7 +35,7 @@ it.effect("reads the call's socket and headers from the upgrade request", () => }), ); -it.effect("key methods refuse as disabled when Kin is off", () => +it.effect("key and grant methods refuse as disabled when Kin is off", () => Effect.gen(function* () { const handlers = yield* makeKinApprovalHandlers( { @@ -46,5 +53,16 @@ it.effect("key methods refuse as disabled when Kin is off", () => assert.include(yield* handlers["kin.approvals.keyChallenge"]().pipe(Effect.flip), { reason: "disabled", }); + const actionId = KinActionId.make("act_01"); + assert.include(yield* handlers["kin.approvals.challenge"]({ actionId }).pipe(Effect.flip), { + reason: "disabled", + }); }).pipe(Effect.provide(Sqlite.layerMemory)), ); + +it.each(["kin.approvals.challenge", "kin.approvals.submitGrant", "kin.approvals.reject"])( + "%s needs orchestration:operate", + (method) => { + assert.strictEqual(requiredScopeForRpcMethod(method), AuthOrchestrationOperateScope); + }, +); diff --git a/apps/server/src/kin/approvals/rpcHandlers.ts b/apps/server/src/kin/approvals/rpcHandlers.ts index 70dd5fb3470b5..eb62477f205c1 100644 --- a/apps/server/src/kin/approvals/rpcHandlers.ts +++ b/apps/server/src/kin/approvals/rpcHandlers.ts @@ -10,9 +10,10 @@ import type { AuthenticatedSession } from "../../auth/EnvironmentAuth.ts"; import { KinIdentity } from "../chat/KinIdentity.ts"; import { ApproverKeys, type KinKeyCaller } from "./ApproverKeys.ts"; import * as Audit from "./Audit.ts"; +import { GrantVerifier } from "./GrantVerifier.ts"; const group = RpcGroup.make(...KinApprovalRpcs); -// Every method refuses until its task lands (APPR-3, -4); nothing here can approve. +// Methods refuse until their task lands (APPR-3). Approving only goes through GrantVerifier. const unavailable = Effect.fail( new KinApprovalError({ reason: "unavailable", message: "Kin approvals are unavailable." }), ); @@ -38,7 +39,7 @@ 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>, + kin: Option.Option>, ) { const connection = yield* connectionOf; const audit = yield* Audit.make; @@ -47,7 +48,11 @@ export const makeKinApprovalHandlers = Effect.fn("makeKinApprovalHandlers")(func 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 }; + return { + keys: Context.get(services, ApproverKeys), + grants: Context.get(services, GrantVerifier), + caller, + }; }); // Owner-only (spec section 11): membership in the org is not enough. const asOwner = Effect.fn("KinApprovals.asOwner")(function* (orgId: KinOrgId) { @@ -66,9 +71,12 @@ export const makeKinApprovalHandlers = Effect.fn("makeKinApprovalHandlers")(func 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.challenge": (input) => + keys.pipe(Effect.flatMap(({ grants, caller }) => grants.challenge(caller, input))), + "kin.approvals.submitGrant": (input) => + keys.pipe(Effect.flatMap(({ grants, caller }) => grants.submitGrant(caller, input))), + "kin.approvals.reject": (input) => + keys.pipe(Effect.flatMap(({ grants, caller }) => grants.reject(caller, input))), "kin.approvals.keyChallenge": () => keys.pipe(Effect.flatMap(({ keys, caller }) => keys.keyChallenge(caller))), "kin.approvals.registerKey": (input) => diff --git a/docs/kin/specs/approvals.md b/docs/kin/specs/approvals.md index e77c6aec23839..263ed43d21762 100644 --- a/docs/kin/specs/approvals.md +++ b/docs/kin/specs/approvals.md @@ -145,16 +145,16 @@ export const KinPendingAction = Schema.Struct({ Transitions (every one is a compare-and-set `UPDATE … WHERE id = ? AND state = ? AND revision = ?`; zero rows changed means someone else won and the caller stops): -| From | To | When | -| ------------------- | ------------------------------------------- | ------------------------------------------------------------------------------------ | -| — | `awaiting_approval` | `request_action` inserts; card posted | -| `awaiting_approval` | `awaiting_approval` (revision+1, new nonce) | PR head, base or checks change (webhook from triggers spec, or re-read at card open) | -| `awaiting_approval` | `approved` | A grant passes every check in section 5; grant row inserted in the same transaction | -| `awaiting_approval` | `rejected` / `cancelled` / `expired` | Owner taps Reject; lead withdraws; `expiresAt` passes | -| `approved` | `executing` | Executor claims it (single claim, section 6) | -| `approved` | `voided` | Grant expires before claim, head moved, signing key revoked, stop switch on | -| `executing` | `succeeded` / `failed` | GitHub answers | -| `executing` | `succeeded` / `interrupted` | Restart finds it mid-flight; reconciliation decides (section 6) | +| From | To | When | +| ------------------- | ------------------------------------------- | ----------------------------------------------------------------------------------- | +| — | `awaiting_approval` | `request_action` inserts; card posted | +| `awaiting_approval` | `awaiting_approval` (revision+1, new nonce) | PR head or base changes (webhook from triggers spec, or re-read at card open) | +| `awaiting_approval` | `approved` | A grant passes every check in section 5; grant row inserted in the same transaction | +| `awaiting_approval` | `rejected` / `cancelled` / `expired` | Owner taps Reject; lead withdraws; `expiresAt` passes | +| `approved` | `executing` | Executor claims it (single claim, section 6) | +| `approved` | `voided` | Grant expires before claim, head moved, signing key revoked, stop switch on | +| `executing` | `succeeded` / `failed` | GitHub answers | +| `executing` | `succeeded` / `interrupted` | Restart finds it mid-flight; reconciliation decides (section 6) | Storage (new, SQLite, Kin's own migration track in `apps/server/src/kin/persistence/` (`KinMigrations.ts`, one `migrations/K00N_*.ts` file per change) with its own `Migrator` table `kin_sql_migrations`; owned with the chat spec so all Kin tables share one runner): @@ -267,26 +267,28 @@ export const KinGrantPayload = Schema.Struct({ }); ``` -**The card is drawn from the payload it signs.** `kin.approvals.challenge(actionId)` returns the unsigned payload (minus `jti`, `iat`, `exp`, which the device adds). The app parses it and renders repo, PR, SHA, base, method, diff size and checks from those fields and `resolved`, then signs the same bytes. There is no second copy of the facts that could drift from what is signed. +**The card is drawn from the payload it signs.** `kin.approvals.challenge(actionId)` returns the unsigned payload (minus `jti`, `iat`, `exp`, which the device adds). The app parses it and renders repo, PR, SHA, base, method, diff size and checks from those fields and `resolved`, then signs the same bytes. There is no second copy of the facts that could drift from what is signed. `challenge` takes no org: the server looks the action up in the caller's own orgs and refuses anyone who isn't an approver (`not_owner`). For `merge_pull_request` and `delete_branch` it re-reads GitHub first and, if the head or base changed (what check 9 compares), rotates the nonce before answering. Other live facts, such as checks and diff size, are returned fresh without a rotation, so a check finishing never voids a grant check 9 would accept. `approver.kid` is the person's active key registered from this session, else their most recently confirmed one. **The device checks what it signs.** The approval key module parses the signing input natively before it asks for a biometric, and refuses it unless: both parts are canonical `stableStringify` JSON (no whitespace, sorted keys, so no duplicate keys); the header has exactly `alg: "ES256"`, `typ: "kin-grant+jws"` and a `kid`; the payload has only the fields above, with `v: 1`, `decision: "approve"`, a `kind` the module has a prompt for, the matching `target` tag, `approver.kid` equal to the header `kid` byte for byte, `exp − iat ≤ 900` and `|deviceNow − iat| ≤ 300`. The prompt text comes from fixed per-kind templates in the module, such as `Merge GLDRoger/t3code #212 (a1b2c3d4e5f60718293a4b5c6d7e8f9012345678) into "main" by squashing`, with every hash in full (the agent writes commits and content, so it could grind a value that matches a shortened hash), wrapped rather than cut. Shown values are refused, never cleaned, unless they are ASCII from a per-field allowlist (branches and paths: letters, digits, `. _ - / +`; lead and chat ids: letters, digits, `. _ -`), and a prompt over 200 characters is refused rather than cut. A kind with no template can't be signed until the module adds one. The server's checks below still apply in full. `kin.approvals.submitGrant({compact})` checks, in this order, and stops at the first failure with a typed reason: -1. Decode header and payload; `alg`, `typ`, no `jwk`; each part's bytes equal `stableStringify(JSON.parse(bytes))` → `malformed`. -2. `kid` is an `active` key in `payload.orgId`, and `payload.approver.kid` equals it → `unknown_key` / `revoked_key`. +1. Decode header and payload; `alg`, `typ`, no `jwk`; each part's bytes equal `stableStringify(JSON.parse(bytes))`; `jti` is at least 16 bytes (22 base64url characters) → `malformed`. +2. `kid` is an `active` and attested key in `payload.orgId`, and `payload.approver.kid` equals it → `unknown_key` / `revoked_key`. An unattested key never activates, so one found active means the database was edited; it fails `unknown_key`. 3. Signature verifies with `p256.verify(sig, sha256(signingInput), key, {prehash: false, format: "compact", lowS: true})` → `bad_signature`. Unlike `verifyDpopProof`, `lowS: true` is required: the device always sends low-S, and ECDSA's `(r, n − s)` twin of a signature would otherwise also verify. Never identify or deduplicate a grant by its compact string; `jti` is its identity, and `compact` is kept for audit only. 4. `approver.humanId` equals the key's `humanId`, and that person currently meets a `requiredApprovers` entry (phase 1: holds the owner role in the org) → `not_owner`. 5. The RPC caller's session is the session the key was registered from, or another session of the same person → `session_mismatch`. (Defence in depth; the signature is the real check.) -6. Pending action exists in the org, is `awaiting_approval`, and `revision` and `nonce` match → `stale` (the card refreshes). +6. Pending action exists in the org, is `awaiting_approval`, and `revision` and `nonce` match → `stale` (the card refreshes), or `replayed` when the org already holds this `jti` or this approver's grant for the action. An accepted grant sent again fails here, before check 10, because its action is no longer `awaiting_approval`. 7. `kind`, `target`, `targetDigest`, `headSha`, `base`, `mergeMethod` equal the server's record → `target_mismatch`. 8. `now` is a finite number, `|now − iat| ≤ 300`, `iat < exp`, `exp − iat ≤ 900` and `now < exp` → `time_window`. -9. Re-read the PR from GitHub with the bot token; head and base still match → `head_moved` (rotate nonce, refresh card). -10. In one transaction: insert `kin_grants` (`jti` UNIQUE, `(action_id, approver)` UNIQUE) and CAS the action to `approved` while both the action and the grant are unexpired → `replayed` when that org already holds the `jti` or this approver's grant for the action, `stale` otherwise. +9. Re-read the PR from GitHub with the bot token; head and base still match → `head_moved` (rotate nonce, refresh card). Only `merge_pull_request` and `delete_branch` (head only) have GitHub state to re-read. If GitHub can't be read, the grant fails `unavailable`. +10. In one transaction: insert `kin_grants` (`jti` UNIQUE, `(action_id, approver)` UNIQUE) and CAS the action to `approved` while both the action and the grant are unexpired and the signing key is still `active`, attested and from an unrevoked session → `replayed` when that org already holds the `jti` or this approver's grant for the action, `revoked_key` when the key was revoked after check 2 (say, during check 9's read), `stale` otherwise. -The grant's life ends at `min(exp, acceptedAt + 15 min)`. It is consumed when the executor claims the action, and can't be used for anything else: the binding is to `actionId`, `nonce` and `targetDigest`, all server-chosen. +The grant's life ends at `min(exp, acceptedAt + 15 min)`. It is consumed when the executor claims the action, which needs the signing key to pass check 10's key test again, since a session revocation voids the action only on the next key read. It can't be used for anything else: the binding is to `actionId`, `nonce` and `targetDigest`, all server-chosen. -A rejection doesn't need a signature (rejecting is always safe) but is still recorded with the session that sent it. +A rejection doesn't need a signature (rejecting is always safe) but is still recorded with the session that sent it. `reject({actionId, revision})` is limited to the action's approvers and is a compare-and-set on the revision. An action past `expiresAt` moves to `expired` instead, and the reject fails `invalid_state`. + +Every refused grant writes `grant_rejected` with its reason, the sending session, and the grant's claimed `actionId`, `kind`, `jti`, `kid` and `headSha`. The entry goes in the key's org once check 3 has verified the signature, and before that in the caller's org, so an unproven grant can't write into another org's chain. A session with no Kin person is only logged. Each kind of rejection has its own cap of 20 entries per session and org a minute: junk (`malformed`, `unknown_key`), grants that name a real key but haven't verified (such as `bad_signature` or `revoked_key`), and verified grants refused later (such as `replayed` or `stale`). Junk can't use up the budget that records forgeries against a real key; when a minute ends, one entry per kind records how many were skipped (`5 more not recorded`), so a flood can't grow the audit chain without bound or hide a real attempt. ### 6. The action executor @@ -500,7 +502,7 @@ export const KinAuditEntry = Schema.Struct({ Append-only: `BEFORE UPDATE` and `BEFORE DELETE` triggers on `kin_audit` abort every edit, and the repository code has no such statements. The hash chain makes edits that bypass the triggers visible; `kin.audit.verify` recomputes it. Rejected grants are audited with their failure reason and the sending session, so a forged approval leaves a trace. `kin.audit.list` and `kin.audit.verify` are owner-only: the session must resolve to the org's owner, not just a person in the org. `list` returns a row that no longer decodes as `{ seq, corrupt: true }` instead of failing the page. The audit stores the grant's `jti` and the key thumbprint, never tokens or keychain contents. -`apps/server/src/kin/approvals/Audit.ts` (`KinAudit`) is the only writer. `append` joins the caller's transaction, so `PendingActions.ts` writes each transition's entry atomically with the transition: `action_requested` on insert (not on an idempotent replay), `action_refreshed`, `grant_accepted`, the four terminal `action_*` moves (the sweep included), `execution_started` with the claim, and `execution_finished`, or `execution_reconciled` when startup reconciliation decides the outcome. `approve` also writes `grant_rejected` for `stale` and `replayed`, after its transaction ends: when no grant row was inserted the transaction commits empty, and only a lost compare-and-set on the action rolls the inserted grant back. The entry goes on the chain of the org that owns the action; a grant naming an unknown org or action stays `stale` and writes nothing. Rejections decided before `approve` (checks 1–9), key events and `credential_check_failed` are written by APPR-4, APPR-5 and APPR-8 through `KinAudit.append`. No RPC or MCP tool writes or deletes entries. +`apps/server/src/kin/approvals/Audit.ts` (`KinAudit`) is the only writer. `append` joins the caller's transaction, so `PendingActions.ts` writes each transition's entry atomically with the transition: `action_requested` on insert (not on an idempotent replay), `action_refreshed`, `grant_accepted`, the four terminal `action_*` moves (the sweep included), `execution_started` with the claim, and `execution_finished`, or `execution_reconciled` when startup reconciliation decides the outcome. `approve` also writes `grant_rejected` for `stale`, `replayed` and `revoked_key`, after its transaction ends: when no grant row was inserted the transaction commits empty, and only a lost compare-and-set on the action rolls the inserted grant back. The entry goes on the chain of the org that owns the action; a grant naming an unknown org or action stays `stale` and writes nothing. Rejections decided before `approve` (checks 1–9), key events and `credential_check_failed` are written by APPR-4, APPR-5 and APPR-8 through `KinAudit.append`. No RPC or MCP tool writes or deletes entries. Each org has its own chain. The first entry's `prevHash` is 64 zeros, and `seq` counts from 1 with no gaps. Appends are serialized by SQLite's single `BEGIN IMMEDIATE` writer, with `UNIQUE(org_id, seq)` as a backstop. `entry_json` holds `stableStringify` of the whole entry. `verify` walks the chain in `seq` order and reports the first entry whose bytes, columns, position, `prevHash` or `hash` don't hold, which catches an edited, deleted, reordered or inserted row. The chain has no secret and no outside anchor, so it can't show a truncated tail or a chain recomputed from the edit onward by someone with write access to the database. It catches tampering, not a compromised server.