From 352c26e6288d46f7f7dce25d3241d471ebeef162 Mon Sep 17 00:00:00 2001 From: Surajsm60720 <1ds22is166@dsce.edu.in> Date: Sun, 8 Nov 2026 08:00:46 +0530 Subject: [PATCH 01/12] docs(kin): a resubmitted accepted grant fails check 6 as replayed (APPR-4) Check 6 runs before check 10, so under the old text a grant sent a second time after acceptance reported stale, contradicting security test 5. Co-Authored-By: Claude Opus 5.5 --- docs/kin/specs/approvals.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/kin/specs/approvals.md b/docs/kin/specs/approvals.md index ee3cecbaff9fe..3a48f9cb64982 100644 --- a/docs/kin/specs/approvals.md +++ b/docs/kin/specs/approvals.md @@ -253,7 +253,7 @@ export const KinGrantPayload = Schema.Struct({ 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). From bd49173dae0a02c3631299a427b5f7f03a9e696e Mon Sep 17 00:00:00 2001 From: Surajsm60720 <1ds22is166@dsce.edu.in> Date: Sun, 8 Nov 2026 08:20:54 +0530 Subject: [PATCH 02/12] feat(kin): verify approval grants and serve challenge, submitGrant and reject (APPR-4) GrantVerifier runs approvals spec section 5 checks 1-10 in order, reusing decodeKinGrant/verifyKinGrant and ApproverKeys.requireActive. The org, person and key come only from server state and the session. Every refused grant is audited, at most 20 entries per session per minute. Audit, org roles and the live GitHub read are narrow ports until APPR-10 and APPR-8 land; the GitHub read fails closed. Co-Authored-By: Claude Opus 5.5 --- apps/server/src/kin/KinServer.ts | 3 +- apps/server/src/kin/approvals/ApproverKeys.ts | 10 +- apps/server/src/kin/approvals/GrantPorts.ts | 91 ++ .../src/kin/approvals/GrantVerifier.test.ts | 925 ++++++++++++++++++ .../server/src/kin/approvals/GrantVerifier.ts | 426 ++++++++ .../src/kin/approvals/PendingActions.ts | 53 +- apps/server/src/kin/approvals/layer.ts | 16 +- apps/server/src/kin/approvals/rpcHandlers.ts | 18 +- docs/kin/specs/approvals.md | 8 +- 9 files changed, 1523 insertions(+), 27 deletions(-) create mode 100644 apps/server/src/kin/approvals/GrantPorts.ts create mode 100644 apps/server/src/kin/approvals/GrantVerifier.test.ts create mode 100644 apps/server/src/kin/approvals/GrantVerifier.ts diff --git a/apps/server/src/kin/KinServer.ts b/apps/server/src/kin/KinServer.ts index 288d392666633..f107a8d04867a 100644 --- a/apps/server/src/kin/KinServer.ts +++ b/apps/server/src/kin/KinServer.ts @@ -4,8 +4,9 @@ import { KinIdentity } from "./chat/KinIdentity.ts"; import { KinChatService } from "./chat/KinChatService.ts"; import { KinChatHub } from "./chat/KinChatHub.ts"; import { ApproverKeys } from "./approvals/ApproverKeys.ts"; +import { GrantVerifier } from "./approvals/GrantVerifier.ts"; -export type Services = KinIdentity | KinChatService | ApproverKeys; +export type Services = KinIdentity | KinChatService | 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 03a63cbc934ad..2825d0ddaef5d 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, @@ -43,7 +41,7 @@ import { verifyAppleAppAttest, type AttestationResult, } from "./attestation/verify.ts"; -import { KinPendingActions } from "./PendingActions.ts"; +import { KinPendingActions, kinTargetDigest } from "./PendingActions.ts"; const CHALLENGE_TTL_MS = 5 * 60 * 1000; const CONFIRM_TTL_MS = 10 * 60 * 1000; @@ -117,10 +115,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, @@ -361,7 +355,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/GrantPorts.ts b/apps/server/src/kin/approvals/GrantPorts.ts new file mode 100644 index 0000000000000..f6c4a9bb9e12a --- /dev/null +++ b/apps/server/src/kin/approvals/GrantPorts.ts @@ -0,0 +1,91 @@ +import { + KinApprovalError, + KinPersonId, + type KinActionKind, + type KinActionTarget, + type KinAuditEntry, + 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"; + +/** The same input as APPR-10's `KinAudit.append`, which this port forwards to once #41 lands. */ +export type KinAuditAppendInput = Omit; + +export class KinGrantAudit extends Context.Service< + KinGrantAudit, + { readonly append: (input: KinAuditAppendInput) => Effect.Effect } +>()("t3/kin/approvals/GrantPorts/KinGrantAudit") {} + +// Until APPR-10 (#41) provides the hash-chained table, entries go to the server log. +export const auditLogLayer = Layer.succeed( + KinGrantAudit, + KinGrantAudit.of({ + append: Effect.fn("KinGrantAudit.append")(function* (entry) { + yield* Effect.logWarning("Kin approvals audit", entry); + }), + }), +); + +/** 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. +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.mapError( + () => 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..f70661a0fa283 --- /dev/null +++ b/apps/server/src/kin/approvals/GrantVerifier.test.ts @@ -0,0 +1,925 @@ +// @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 Effect from "effect/Effect"; +import * as Exit from "effect/Exit"; +import * as Layer from "effect/Layer"; +import * as Option from "effect/Option"; +import * as Schema from "effect/Schema"; +import * as SqlClient from "effect/sql/SqlClient"; +import * as TestClock from "effect/testing/TestClock"; + +import * as Sqlite from "../../persistence/Sqlite.ts"; +import * as KinPersistence from "../persistence/KinPersistence.ts"; +import { ApproverKeys, layer as approverKeysLayer, type KinKeyCaller } from "./ApproverKeys.ts"; +import { KinAttestationTrust } from "./attestation/AttestationTrust.ts"; +import { androidChain, makeTrustFixture, newKey } from "./attestation/testFixtures.ts"; +import { + KinGrantAudit, + KinLiveTargets, + KinOrgRoles, + orgRolesLayer, + type KinAuditAppendInput, +} 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" }], +}); + +/** 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); + }), + ), + }); + const auditLayer = Layer.succeed(KinGrantAudit, { + append: (entry) => Effect.sync(() => void audit.push(entry)), + }); + const trust = Layer.succeed(KinAttestationTrust, { load: () => Effect.succeed(fixture.trust) }); + const database = Layer.provideMerge(KinPersistence.layer, Sqlite.layerMemory); + const layer = grantVerifierLayer.pipe( + Layer.provideMerge(approverKeysLayer), + Layer.provideMerge(pendingActionsLayer), + Layer.provide(Layer.mergeAll(trust, roles, live, auditLayer)), + Layer.provideMerge(database), + ); + return { audit, github, race, layer }; +} + +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: [] }, + 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))); + +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)); + 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: "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 or stale", () => { + const h = harness(); + return Effect.gen(function* () { + const { grants, actions, ownerKey } = 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"); + }).pipe(Effect.provide(h.layer)); + }); + + 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("rejection audits are bounded per session per minute", () => { + const h = harness(); + return Effect.gen(function* () { + const { grants } = 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); + // Another session has its own budget. + yield* Effect.exit(grants.submitGrant(ownerPhone, { compact: "not.a.grant" })); + assert.strictEqual(h.audit.length, 21); + yield* TestClock.adjust("1 minute"); + yield* Effect.exit(grants.submitGrant(memberPhone, { compact: "not.a.grant" })); + assert.strictEqual(h.audit.at(-1)?.result, "malformed; 5 more not recorded"); + 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", + ); + }).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 ('kin-default-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", "kin-default-owner")); + assert.isFalse(yield* ask("kin-default", "h_member")); + assert.isFalse(yield* ask("org_01", "kin-default-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 importers = (pattern: RegExp) => + files.filter((file) => pattern.test(NodeFS.readFileSync(NodePath.join(root, file), "utf8"))); + // The verifier is built in the approvals layer, exposed on KinServer and called by WS only. + assert.deepStrictEqual(importers(/from "[./]*(approvals\/)?GrantVerifier\.ts"/), [ + "kin/KinServer.ts", + "kin/approvals/layer.ts", + "kin/approvals/rpcHandlers.ts", + ]); + // Those handlers are served only on the authenticated `/ws` session, never over MCP. + assert.deepStrictEqual(importers(/approvals\/rpcHandlers\.ts"/), ["ws.ts"]); + assert.deepStrictEqual( + importers(/kin\/approvals\/|from "\.\.\/approvals\//).filter( + (file) => + file.startsWith("mcp/") || file.startsWith("kin/mcp/") || file.startsWith("kin/lead/"), + ), + [], + ); + }); +}); diff --git a/apps/server/src/kin/approvals/GrantVerifier.ts b/apps/server/src/kin/approvals/GrantVerifier.ts new file mode 100644 index 0000000000000..9d59b1f7fe195 --- /dev/null +++ b/apps/server/src/kin/approvals/GrantVerifier.ts @@ -0,0 +1,426 @@ +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 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 { + KinGrantAudit, + KinLiveTargets, + KinOrgRoles, + type KinAuditAppendInput, +} from "./GrantPorts.ts"; +import { KinPendingActions, kinTargetDigest } from "./PendingActions.ts"; + +// Enough to see an attack in the audit; more only fills the chain. The rest are counted. +const REJECTION_AUDITS_PER_WINDOW = 20; +const REJECTION_WINDOW_MS = 60_000; +const MAX_TRACKED_SESSIONS = 1024; + +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; the org is server state (the key's), else the caller's. */ +type Seen = { + orgId?: KinOrgId; + claim?: Pick; +}; + +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 budgets = new Map< + AuthSessionId, + { windowStart: number; used: number; suppressed: number } + >(); + + const internal = (cause: unknown) => + isKinApprovalError(cause) + ? cause + : 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.claim = { + actionId: payload.actionId, + kind: payload.kind, + grantJti: payload.jti, + keyThumbprint: header.kid, + ...(payload.headSha === undefined ? {} : { headSha: payload.headSha }), + }; + + // 2. An active key in the grant's org, after session revocations. + const key = yield* keys.requireActive({ orgId: payload.orgId, thumbprint: header.kid }); + seen.orgId = key.orgId; + 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); + + // 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, + }); + if (result._tag !== "approved") return yield* reject(result._tag); + return { action, grant: result.grant }; + }); + + /** At most REJECTION_AUDITS_PER_WINDOW per session per minute; returns how many were held back. */ + const admitRejection = (sessionId: AuthSessionId, now: number) => { + let budget = budgets.get(sessionId); + let carried = 0; + if (budget === undefined || now - budget.windowStart >= REJECTION_WINDOW_MS) { + carried = budget?.suppressed ?? 0; + if (budget === undefined && budgets.size >= MAX_TRACKED_SESSIONS) { + for (const [id, entry] of budgets) { + if (now - entry.windowStart >= REJECTION_WINDOW_MS) budgets.delete(id); + } + } + budget = { windowStart: now, used: 0, suppressed: 0 }; + budgets.set(sessionId, budget); + } + if (budget.used >= REJECTION_AUDITS_PER_WINDOW) { + budget.suppressed += 1; + return { admitted: false, carried }; + } + budget.used += 1; + return { admitted: true, carried }; + }; + + const recordRejection = Effect.fn("GrantVerifier.recordRejection")(function* ( + caller: KinKeyCaller, + seen: Seen, + error: KinApprovalError, + ) { + const sessionId = caller.session.sessionId; + const orgId = seen.orgId ?? 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 { admitted, carried } = admitRejection(sessionId, yield* Clock.currentTimeMillis); + if (!admitted) return; + yield* audit.append({ + orgId, + event: "grant_rejected", + ...seen.claim, + sessionId, + result: carried > 0 ? `${error.reason}; ${carried} more not recorded` : error.reason, + }); + }); + + const submitGrant = Effect.fn("GrantVerifier.submitGrant")(function* ( + caller: KinKeyCaller, + input: KinApprovalsSubmitGrantInput, + ) { + const seen: Seen = {}; + const { action, grant } = yield* check(caller, input.compact, seen).pipe( + Effect.mapError(internal), + Effect.tapError((error) => recordRejection(caller, seen, error)), + ); + const { headSha } = recordFacts(action); + yield* audit.append({ + orgId: action.orgId, + event: "grant_accepted", + actionId: action.id, + kind: action.kind, + target: action.target, + ...(headSha === undefined ? {} : { headSha }), + grantJti: grant.jti, + keyThumbprint: grant.keyThumbprint, + sessionId: caller.session.sessionId, + provenance: action.provenance, + }); + 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; + if (pinsHead(found.kind)) { + const resolved = yield* readLive(found); + if (stableStringify(resolved) !== stableStringify(found.resolved)) { + 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: action.resolved }; + }, Effect.mapError(internal)); + + const rejectAction = Effect.fn("GrantVerifier.reject")(function* ( + caller: KinKeyCaller, + input: KinApprovalsRejectInput, + ) { + const { action } = yield* actionFor(caller, input.actionId); + const won = yield* actions.transition({ + orgId: action.orgId, + actionId: action.id, + revision: input.revision, + to: "rejected", + reason: "owner_rejected", + }); + if (!won) return yield* fail("stale", "This action already changed; refresh the card."); + yield* audit.append({ + orgId: action.orgId, + event: "action_rejected", + actionId: action.id, + kind: action.kind, + target: action.target, + sessionId: caller.session.sessionId, + provenance: action.provenance, + }); + return { actionId: action.id, state: "rejected" as const }; + }, Effect.mapError(internal)); + + return GrantVerifier.of({ challenge, submitGrant, reject: rejectAction }); +}); + +export const layer = Layer.effect(GrantVerifier, make); diff --git a/apps/server/src/kin/approvals/PendingActions.ts b/apps/server/src/kin/approvals/PendingActions.ts index 56832538d5688..27f7243b3874b 100644 --- a/apps/server/src/kin/approvals/PendingActions.ts +++ b/apps/server/src/kin/approvals/PendingActions.ts @@ -69,6 +69,7 @@ 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 } @@ -95,6 +96,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)); @@ -178,6 +196,8 @@ export class KinPendingActions extends Context.Service< readonly exp: number; }, ) => 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"] }, @@ -297,6 +317,18 @@ 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), + ); + + const heldGrant = Effect.fn("KinPendingActions.heldGrant")( + selectHeld, + Effect.mapError(toError("KinPendingActions.heldGrant")), + ); + const approve = Effect.fn("KinPendingActions.approve")( function* ( input: RevisionRef & { @@ -324,12 +356,9 @@ 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} @@ -452,7 +481,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 c60550d0c4559..65bafbef2a5a4 100644 --- a/apps/server/src/kin/approvals/layer.ts +++ b/apps/server/src/kin/approvals/layer.ts @@ -4,10 +4,20 @@ import * as FetchHttpClient from "effect/http/FetchHttpClient"; import * as KinPersistence from "../persistence/KinPersistence.ts"; import * as ApproverKeys from "./ApproverKeys.ts"; import * as AttestationTrust from "./attestation/AttestationTrust.ts"; +import * as 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), - 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.auditLogLayer, + ), + ), Layer.provide(KinPersistence.layer), ); diff --git a/apps/server/src/kin/approvals/rpcHandlers.ts b/apps/server/src/kin/approvals/rpcHandlers.ts index 1934ceac679ed..b4dcf11ed2798 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 { KinServer } from "../KinServer.ts"; import { ApproverKeys, type KinKeyCaller } from "./ApproverKeys.ts"; +import { GrantVerifier } from "./GrantVerifier.ts"; const group = RpcGroup.make(...KinApprovalRpcs); -// Every method refuses until its task lands (APPR-3, -4, -10); nothing here can approve. +// Methods refuse until their task lands (APPR-3, -10). Approving only goes through GrantVerifier. const unavailable = Effect.fail( new KinApprovalError({ reason: "unavailable", message: "Kin approvals are unavailable." }), ); @@ -39,14 +40,21 @@ export const makeKinApprovalHandlers = Effect.fn("makeKinApprovalHandlers")(func const services = kin.value.services.value; const people = yield* Context.get(services, KinIdentity).resolve(session); const caller: KinKeyCaller = { session, people, connection }; - return { keys: Context.get(services, ApproverKeys), caller }; + return { + keys: Context.get(services, ApproverKeys), + grants: Context.get(services, GrantVerifier), + caller, + }; }); return group.of({ "kin.approvals.list": () => Stream.fromEffect(unavailable), "kin.approvals.get": () => unavailable, - "kin.approvals.challenge": () => unavailable, - "kin.approvals.submitGrant": () => unavailable, - "kin.approvals.reject": () => unavailable, + "kin.approvals.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 3a48f9cb64982..5cff44660ec5b 100644 --- a/docs/kin/specs/approvals.md +++ b/docs/kin/specs/approvals.md @@ -244,7 +244,7 @@ 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 anything in `resolved` changed, rotates the nonce before answering. `approver.kid` is the person's active key registered from this session, else their most recently confirmed one. `kin.approvals.submitGrant({compact})` checks, in this order, and stops at the first failure with a typed reason: @@ -256,12 +256,14 @@ export const KinGrantPayload = Schema.Struct({ 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). +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 → `replayed` when that org already holds the `jti` or this approver's grant for the action, `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. -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. + +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 2 has found the key, and before that in the caller's org. A session with no Kin person is only logged. Each session gets at most 20 rejection entries a minute. The first entry after the limit counts the ones it skipped (`malformed; 5 more not recorded`), so a flood can't grow the audit chain without bound. ### 6. The action executor From ccf0dc3717afaeec384ccfb1800d82a9a9c7322a Mon Sep 17 00:00:00 2001 From: Surajsm60720 <1ds22is166@dsce.edu.in> Date: Sun, 8 Nov 2026 08:58:05 +0530 Subject: [PATCH 03/12] fix(kin): close the grant verifier's security review findings (APPR-4) - Check 10's compare-and-set also requires the signing key to be active, attested and from an unrevoked session, so a revoke during check 9's GitHub read can't leave the action approved (revoked_key). - Rejections that name a real key are always audited; only malformed and unknown_key share the 20-a-minute budget, and the skipped count is written when the window ends. - Rejections go in the key's org only after its signature verifies; before that, in the caller's org. - challenge rotates the nonce only when head or base move, matching check 9; other live facts are returned fresh. - reject expires an action past expiresAt instead of rejecting it, and transition refuses rejected/cancelled past expiry. - check 1 refuses a jti under 16 bytes. - The static guard resolves imports at any depth, asserts only GrantVerifier calls approve, and names kin/approvals/mcp.ts. - Spec: check 2 says active and attested; iOS keys use App Attest. Co-Authored-By: Claude Opus 5.5 --- apps/server/src/kin/approvals/GrantPorts.ts | 2 +- .../src/kin/approvals/GrantVerifier.test.ts | 146 ++++++++++++++++-- .../server/src/kin/approvals/GrantVerifier.ts | 115 +++++++++----- .../src/kin/approvals/PendingActions.test.ts | 4 + .../src/kin/approvals/PendingActions.ts | 29 +++- docs/kin/specs/approvals.md | 36 ++--- 6 files changed, 254 insertions(+), 78 deletions(-) diff --git a/apps/server/src/kin/approvals/GrantPorts.ts b/apps/server/src/kin/approvals/GrantPorts.ts index f6c4a9bb9e12a..f881f0af0774a 100644 --- a/apps/server/src/kin/approvals/GrantPorts.ts +++ b/apps/server/src/kin/approvals/GrantPorts.ts @@ -44,7 +44,7 @@ export class KinOrgRoles extends Context.Service< // Phase 1 (chat spec, Identity): the org owner is the reserved person bootstrap creates. // Phase 2 replaces this with org membership. -const BOOTSTRAP_OWNER = Schema.decodeSync(KinPersonId)("kin-default-owner"); +export const BOOTSTRAP_OWNER = Schema.decodeSync(KinPersonId)("kin-default-owner"); export const orgRolesLayer = Layer.effect( KinOrgRoles, diff --git a/apps/server/src/kin/approvals/GrantVerifier.test.ts b/apps/server/src/kin/approvals/GrantVerifier.test.ts index f70661a0fa283..02ad61cf487a0 100644 --- a/apps/server/src/kin/approvals/GrantVerifier.test.ts +++ b/apps/server/src/kin/approvals/GrantVerifier.test.ts @@ -33,6 +33,7 @@ import { ApproverKeys, layer as approverKeysLayer, type KinKeyCaller } from "./A import { KinAttestationTrust } from "./attestation/AttestationTrust.ts"; import { androidChain, makeTrustFixture, newKey } from "./attestation/testFixtures.ts"; import { + BOOTSTRAP_OWNER, KinGrantAudit, KinLiveTargets, KinOrgRoles, @@ -473,6 +474,17 @@ describe("GrantVerifier", () => { 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 }); @@ -579,6 +591,11 @@ describe("GrantVerifier", () => { ), ), }, + { + 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", @@ -745,10 +762,10 @@ describe("GrantVerifier", () => { }).pipe(Effect.provide(h.layer)); }); - it.effect("a grant that loses the race at check 10 is replayed or stale", () => { + 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, ownerKey } = yield* enrol; + 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. @@ -786,6 +803,40 @@ describe("GrantVerifier", () => { "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); }).pipe(Effect.provide(h.layer)); }); @@ -804,20 +855,53 @@ describe("GrantVerifier", () => { }).pipe(Effect.provide(h.layer)); }); - it.effect("rejection audits are bounded per session per minute", () => { + it.effect("junk rejections are bounded per session per minute; ones naming a key never", () => { const h = harness(); return Effect.gen(function* () { - const { grants } = yield* enrol; + 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"], + ); // Another session has its own budget. yield* Effect.exit(grants.submitGrant(ownerPhone, { compact: "not.a.grant" })); - assert.strictEqual(h.audit.length, 21); + assert.strictEqual(h.audit.length, 22); + // The skipped count is written when the window ends, not on a later rejection. yield* TestClock.adjust("1 minute"); - yield* Effect.exit(grants.submitGrant(memberPhone, { compact: "not.a.grant" })); - assert.strictEqual(h.audit.at(-1)?.result, "malformed; 5 more not recorded"); + assert.deepStrictEqual( + h.audit.slice(22).map((entry) => [entry.event, entry.sessionId, entry.result]), + [["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, 24); assert.isTrue(h.audit.every((entry) => entry.orgId === orgId)); }).pipe(Effect.provide(h.layer)); }); @@ -854,6 +938,17 @@ describe("GrantVerifier", () => { 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)); }); @@ -878,7 +973,7 @@ describe("GrantVerifier", () => { 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 ('kin-default-owner', 'kin-default', 'owner', 'Owner', '2026-11-07T00:00:00.000Z'), + 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) => @@ -886,9 +981,9 @@ describe("GrantVerifier", () => { orgId: decodeOrgId(org), personId: decodePersonId(person), }); - assert.isTrue(yield* ask("kin-default", "kin-default-owner")); + assert.isTrue(yield* ask("kin-default", BOOTSTRAP_OWNER)); assert.isFalse(yield* ask("kin-default", "h_member")); - assert.isFalse(yield* ask("org_01", "kin-default-owner")); + assert.isFalse(yield* ask("org_01", BOOTSTRAP_OWNER)); }).pipe( Effect.provide( orgRolesLayer.pipe( @@ -904,22 +999,41 @@ describe("GrantVerifier", () => { .filter((file) => file.endsWith(".ts") && !file.endsWith(".test.ts")) .map((file) => file.split(NodePath.sep).join("/")) .toSorted(); - const importers = (pattern: RegExp) => - files.filter((file) => pattern.test(NodeFS.readFileSync(NodePath.join(root, file), "utf8"))); + 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. - assert.deepStrictEqual(importers(/from "[./]*(approvals\/)?GrantVerifier\.ts"/), [ + 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. - assert.deepStrictEqual(importers(/approvals\/rpcHandlers\.ts"/), ["ws.ts"]); + const handlerImporters = importers("kin/approvals/rpcHandlers.ts"); + assert.deepStrictEqual(handlerImporters, ["ws.ts"]); assert.deepStrictEqual( - importers(/kin\/approvals\/|from "\.\.\/approvals\//).filter( + files.filter( (file) => - file.startsWith("mcp/") || file.startsWith("kin/mcp/") || file.startsWith("kin/lead/"), + modelFacing(file) && imports(file).some((target) => target.startsWith("kin/approvals/")), ), [], ); + assert.deepStrictEqual([...verifierImporters, ...handlerImporters].filter(forbidden), []); }); }); diff --git a/apps/server/src/kin/approvals/GrantVerifier.ts b/apps/server/src/kin/approvals/GrantVerifier.ts index 9d59b1f7fe195..c9fc6b49101fa 100644 --- a/apps/server/src/kin/approvals/GrantVerifier.ts +++ b/apps/server/src/kin/approvals/GrantVerifier.ts @@ -18,6 +18,7 @@ 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"; @@ -33,10 +34,16 @@ import { } from "./GrantPorts.ts"; import { KinPendingActions, kinTargetDigest } from "./PendingActions.ts"; -// Enough to see an attack in the audit; more only fills the chain. The rest are counted. -const REJECTION_AUDITS_PER_WINDOW = 20; -const REJECTION_WINDOW_MS = 60_000; -const MAX_TRACKED_SESSIONS = 1024; +// Junk that names no key: enough to see a flood, the rest only counted. Anything that +// names a real key is always recorded. +const JUNK_AUDITS_PER_WINDOW = 20; +const JUNK_WINDOW = Duration.minutes(1); +const isJunk = (reason: KinApprovalError["reason"]) => + reason === "malformed" || reason === "unknown_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); @@ -94,9 +101,10 @@ const headOf = (action: KinPendingAction) => { }); }; -/** What the rejection audit knows; the org is server state (the key's), else the caller's. */ +/** What the rejection audit knows. `orgId` is the key's, set only once its signature verified. */ type Seen = { orgId?: KinOrgId; + claimedOrgId?: KinOrgId; claim?: Pick; }; @@ -127,10 +135,8 @@ const make = Effect.gen(function* () { const roles = yield* KinOrgRoles; const live = yield* KinLiveTargets; const audit = yield* KinGrantAudit; - const budgets = new Map< - AuthSessionId, - { windowStart: number; used: number; suppressed: number } - >(); + const scope = yield* Effect.scope; + const junkWindows = new Map(); const internal = (cause: unknown) => isKinApprovalError(cause) @@ -182,6 +188,7 @@ const make = Effect.gen(function* () { 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, @@ -189,10 +196,10 @@ const make = Effect.gen(function* () { 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 }); - seen.orgId = key.orgId; 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. @@ -203,6 +210,8 @@ const make = Effect.gen(function* () { 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 ( @@ -271,26 +280,26 @@ const make = Effect.gen(function* () { return { action, grant: result.grant }; }); - /** At most REJECTION_AUDITS_PER_WINDOW per session per minute; returns how many were held back. */ - const admitRejection = (sessionId: AuthSessionId, now: number) => { - let budget = budgets.get(sessionId); - let carried = 0; - if (budget === undefined || now - budget.windowStart >= REJECTION_WINDOW_MS) { - carried = budget?.suppressed ?? 0; - if (budget === undefined && budgets.size >= MAX_TRACKED_SESSIONS) { - for (const [id, entry] of budgets) { - if (now - entry.windowStart >= REJECTION_WINDOW_MS) budgets.delete(id); - } - } - budget = { windowStart: now, used: 0, suppressed: 0 }; - budgets.set(sessionId, budget); - } - if (budget.used >= REJECTION_AUDITS_PER_WINDOW) { - budget.suppressed += 1; - return { admitted: false, carried }; - } - budget.used += 1; - return { admitted: true, carried }; + /** 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* ( @@ -299,7 +308,11 @@ const make = Effect.gen(function* () { error: KinApprovalError, ) { const sessionId = caller.session.sessionId; - const orgId = seen.orgId ?? caller.people[0]?.orgId; + // 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.", { @@ -307,15 +320,22 @@ const make = Effect.gen(function* () { reason: error.reason, }); } - const { admitted, carried } = admitRejection(sessionId, yield* Clock.currentTimeMillis); - if (!admitted) return; - yield* audit.append({ + const entry = { orgId, - event: "grant_rejected", + event: "grant_rejected" as const, ...seen.claim, sessionId, - result: carried > 0 ? `${error.reason}; ${carried} more not recorded` : error.reason, - }); + result: error.reason, + }; + if (!isJunk(error.reason)) return yield* audit.append(entry); + const slot = `${orgId} ${sessionId}`; + const window = junkWindows.get(slot) ?? (yield* openJunkWindow(slot, orgId, sessionId)); + if (window.used >= JUNK_AUDITS_PER_WINDOW) { + window.skipped += 1; + return; + } + window.used += 1; + yield* audit.append(entry); }); const submitGrant = Effect.fn("GrantVerifier.submitGrant")(function* ( @@ -372,9 +392,11 @@ const make = Effect.gen(function* () { 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)) { - const resolved = yield* readLive(found); - if (stableStringify(resolved) !== stableStringify(found.resolved)) { + 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; @@ -392,7 +414,7 @@ const make = Effect.gen(function* () { approver: { humanId: key.humanId, kid: key.thumbprint }, decision: "approve", }); - return { payload, resolved: action.resolved }; + return { payload, resolved }; }, Effect.mapError(internal)); const rejectAction = Effect.fn("GrantVerifier.reject")(function* ( @@ -400,6 +422,19 @@ const make = Effect.gen(function* () { input: KinApprovalsRejectInput, ) { const { action } = yield* actionFor(caller, input.actionId); + if ( + action.state === "awaiting_approval" && + DateTime.toEpochMillis(action.expiresAt) <= (yield* Clock.currentTimeMillis) + ) { + yield* actions.transition({ + orgId: action.orgId, + actionId: action.id, + revision: action.revision, + to: "expired", + reason: "expired", + }); + return yield* fail("invalid_state", "This action expired."); + } const won = yield* actions.transition({ orgId: action.orgId, actionId: action.id, diff --git a/apps/server/src/kin/approvals/PendingActions.test.ts b/apps/server/src/kin/approvals/PendingActions.test.ts index f4e7806827b8b..c7ef8e1593da5 100644 --- a/apps/server/src/kin/approvals/PendingActions.test.ts +++ b/apps/server/src/kin/approvals/PendingActions.test.ts @@ -68,6 +68,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 8e06c5d5e3edb..188e0aef209f7 100644 --- a/apps/server/src/kin/approvals/PendingActions.ts +++ b/apps/server/src/kin/approvals/PendingActions.ts @@ -85,7 +85,8 @@ type GrantRef = ActionRef & { readonly jti: string; readonly approverHumanId: Ki 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; @@ -172,6 +173,7 @@ const toAction = (row: ActionRow) => }); class Rollback extends Schema.TaggedError()("Rollback", {}) {} +class KeyUnusable extends Schema.TaggedError()("KeyUnusable", {}) {} export class KinPendingActions extends Context.Service< KinPendingActions, @@ -322,6 +324,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`; return rows.length > 0; }, @@ -335,6 +338,17 @@ const make = Effect.gen(function* () { 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. + const signingKeyUsable = (input: { + readonly orgId: KinOrgId; + readonly keyThumbprint: KinKeyThumbprint; + readonly approverHumanId: KinPersonId; + }) => 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 EXISTS (SELECT 1 FROM auth_sessions s + WHERE s.session_id = k.session_id AND s.revoked_at IS NOT NULL))`; + const heldGrant = Effect.fn("KinPendingActions.heldGrant")( selectHeld, Effect.mapError(toError("KinPendingActions.heldGrant")), @@ -376,8 +390,12 @@ const make = Effect.gen(function* () { 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`; - if (won.length === 0) return yield* new Rollback(); + if (won.length === 0) { + const [usable] = yield* sql`SELECT 1 WHERE ${signingKeyUsable(input)}`; + return yield* usable === undefined ? new KeyUnusable() : new Rollback(); + } const grant = yield* decodeGrant({ id: grantId, orgId: input.orgId, @@ -395,7 +413,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 }), + }), + ); }, Effect.mapError(toError("KinPendingActions.approve")), ); diff --git a/docs/kin/specs/approvals.md b/docs/kin/specs/approvals.md index 64f98e9bdd9be..e63966af9f2c5 100644 --- a/docs/kin/specs/approvals.md +++ b/docs/kin/specs/approvals.md @@ -142,16 +142,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): @@ -172,7 +172,7 @@ Storage (new, SQLite, Kin's own migration track in `apps/server/src/kin/persiste | Key | P-256 in the Secure Enclave: `SecKeyCreateRandomKey` with `kSecAttrTokenIDSecureEnclave`, not exportable | EC `secp256r1` in `AndroidKeyStore`, `PURPOSE_SIGN`, `DIGEST_SHA256`, `setIsStrongBoxBacked(true)` with fallback to TEE | | Gate | `SecAccessControlCreateWithFlags(… kSecAttrAccessibleWhenPasscodeSetThisDeviceOnly, [.privateKeyUsage, .biometryCurrentSet])`: every signature needs Face ID or Touch ID; the key dies if biometrics are re-enrolled | `setUserAuthenticationRequired(true)`, `setUserAuthenticationParameters(0, AUTH_BIOMETRIC_STRONG)` (per-use), `setInvalidatedByBiometricEnrollment(true)`; sign inside `BiometricPrompt` with a `CryptoObject(Signature)` | | Signature | `SecKeyCreateSignature(.ecdsaSignatureMessageX962SHA256)` → DER; convert to 64-byte `r‖s` | `SHA256withECDSA` → DER; convert the same way | -| Attestation | Not in phase 1 (App Attest is a later option) | Record the `setAttestationChallenge` certificate chain; verify the root is Google's hardware root; store `attested: true/false` | +| Attestation | App Attest (`DCAppAttestService`) with the approval key's public key in its client data; store `attested: true/false` | Record the `setAttestationChallenge` certificate chain; verify the root is Google's hardware root; store `attested: true/false` | **Modules.** None of this exists in the repo's dependencies. @@ -203,7 +203,7 @@ Registration: 1. The phone calls `kin.approvals.keyChallenge()` (`access:write`), which returns a single-use 32-byte nonce bound to that session and valid for 5 minutes. It passes the nonce to `createKey`, then calls `kin.approvals.registerKey({publicJwk, platform, challenge, attestation?, deviceLabel})` over the same session. The server consumes the nonce, stores the key as `pending` and returns a 6-digit code derived from `sha256(thumbprint ‖ serverNonce)`, where `serverNonce` is that challenge. Challenges and codes live in server memory: a code is good for 10 minutes and five tries, and after a restart the phone makes and registers a new key. A thumbprint registers only once. - **Android:** `attestation.certificateChain` is required. The server checks it offline: the chain verifies up to a pinned Google hardware attestation root and no certificate is on Google's attestation revocation list; the leaf's public key equals `publicJwk`; the leaf's KeyDescription has `attestationChallenge` equal to the nonce, `attestationSecurityLevel` and `keyMintSecurityLevel` (`keymasterSecurityLevel` before KeyMint) of `TrustedEnvironment` or `StrongBox`, and in `hardwareEnforced`: purpose `SIGN`, algorithm EC on P-256, digest SHA-256, `userAuthType` biometric only (`FINGERPRINT`, the value Keystore uses for every strong biometric), no `authTimeout`, no `noAuthRequired`, `origin` `GENERATED`, and `rootOfTrust` with `verifiedBootState` `Verified` and `deviceLocked` true; `attestationApplicationId` names the release package with exactly the allowlisted signing-certificate SHA-256s, each once. The chain's last certificate only has to carry a pinned root's key, since Google reissued its RSA root under the same key; the pinned certificate takes its place, so its own validity and its signature on the next certificate are what count. All pass: `attested: true`, and `hardware` is `strongbox` or `tee` from the attestation security level. Any check fails: `attested: false`, `hardware: "software"`. The client never supplies `hardware`. - - **iOS:** no attestation in phase 1, so the key is stored with `attested: false` and `hardware: "secure_enclave"`, which is claimed by the platform, not proven. + - **iOS:** `attestation.keyId` and `attestation.attestationObject` from App Attest are required, with client data `sha256(challenge ‖ publicJwk point)`. The server checks the chain up to the pinned Apple App Attest root, that the credential certificate's nonce binds that client data, that `keyId` is the attested key, the App ID allowlist, a zero counter and an allowed environment. All pass: `attested: true`, `hardware: "secure_enclave"`. App Attest proves a genuine copy of the app vouched for this public key; that the approval key itself is a Secure Enclave key behind `.biometryCurrentSet` is the app's claim, not proven. Any check fails: `attested: false`, `hardware: "software"`. 2. **First key in an org:** confirmed on the Mac running the server, in the desktop app's local session (loopback only), where the owner checks the code shown on both screens. No remote path can confirm the first key. "Local" means all of: the session's subject is `desktop-bootstrap` (only the desktop app holds that credential), the session was issued to a loopback address, and the call's own socket is loopback with no `Forwarded`, `X-Forwarded-*`, `X-Real-IP`, `CF-Connecting-IP` or `Tailscale-User-Login` header. A browser or tunnel process on the same Mac fails the first check; a desktop on WSL fails the second, so it can't confirm keys. The subject and the issuance address are the real guard. The socket check is defence in depth, since a proxy on the same Mac connects over loopback and can drop those headers. `confirmKey` works only while the org has no active key. 3. **Later keys:** confirmed by a grant of kind `register_approver_key` signed by an existing active key. When an attested key registers in an org that already has an active key, `registerKey` opens that pending action itself (requester `kin-approver-keys`, provenance started by the registering person). That requester id is reserved: `KinPendingActions.create` refuses it for any other kind, and as an agent or thread id, and the handler activates the key only if it is still `pending`, attested and on the hardware the card showed. 4. Revoking (`kin.approvals.revokeKey`, from settings or the desktop) sets `revoked` and voids every `approved` action whose grant that key signed. Revoking a T3 device session (`revokeClient`) also revokes keys registered from it. Kin reads `auth_sessions.revoked_at` at startup and before it trusts, lists or activates a key, rather than hooking T3's auth code. Revoking also cancels a pending `register_approver_key` action for the key. Expiry is not revocation: a key outlives the session that registered it. A DPoP relay session renews hourly under a new session id but the same DPoP key, so each key also stores that key's thumbprint (`proof_key_thumbprint`). Until `auth_sessions` records it too (see Interfaces, T3 auth), revoking a renewed session doesn't reach the key; revoke the key itself. @@ -244,12 +244,12 @@ 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. `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 anything in `resolved` changed, rotates the nonce before answering. `approver.kid` is the person's active key registered from this session, else their most recently confirmed one. +**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. `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.) @@ -257,13 +257,13 @@ export const KinGrantPayload = Schema.Struct({ 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). 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 → `replayed` when that org already holds the `jti` or this approver's grant for the action, `stale` otherwise. +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. -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. +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 2 has found the key, and before that in the caller's org. A session with no Kin person is only logged. Each session gets at most 20 rejection entries a minute. The first entry after the limit counts the ones it skipped (`malformed; 5 more not recorded`), so a flood can't grow the audit chain without bound. +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. Rejections that name a real key (anything but `malformed` and `unknown_key`) are always recorded. Junk is capped at 20 entries per session and org a minute; when that minute ends, one entry 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 From b725c9f3db71538f2859eabf7df9b1b40941481e Mon Sep 17 00:00:00 2001 From: Surajsm60720 <1ds22is166@dsce.edu.in> Date: Sun, 8 Nov 2026 09:22:47 +0530 Subject: [PATCH 04/12] fix(kin): cap every kind of grant rejection in the audit; reject reports a lost race (APPR-4) Co-Authored-By: Claude Opus 5.5 --- .../src/kin/approvals/GrantVerifier.test.ts | 20 +++++++++++----- .../server/src/kin/approvals/GrantVerifier.ts | 23 +++++++++++-------- docs/kin/specs/approvals.md | 2 +- 3 files changed, 29 insertions(+), 16 deletions(-) diff --git a/apps/server/src/kin/approvals/GrantVerifier.test.ts b/apps/server/src/kin/approvals/GrantVerifier.test.ts index 02ad61cf487a0..8776691f00063 100644 --- a/apps/server/src/kin/approvals/GrantVerifier.test.ts +++ b/apps/server/src/kin/approvals/GrantVerifier.test.ts @@ -855,7 +855,7 @@ describe("GrantVerifier", () => { }).pipe(Effect.provide(h.layer)); }); - it.effect("junk rejections are bounded per session per minute; ones naming a key never", () => { + 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; @@ -875,14 +875,22 @@ describe("GrantVerifier", () => { [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, 22); - // The skipped count is written when the window ends, not on a later rejection. + 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(22).map((entry) => [entry.event, entry.sessionId, entry.result]), - [["grant_rejected", "sess-member", "5 more not recorded"]], + 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 @@ -901,7 +909,7 @@ describe("GrantVerifier", () => { reasonOf(yield* Effect.exit(grants.submitGrant(memberPhone, { compact: elsewhere }))), "bad_signature", ); - assert.strictEqual(h.audit.length, 24); + assert.strictEqual(h.audit.length, 44); assert.isTrue(h.audit.every((entry) => entry.orgId === orgId)); }).pipe(Effect.provide(h.layer)); }); diff --git a/apps/server/src/kin/approvals/GrantVerifier.ts b/apps/server/src/kin/approvals/GrantVerifier.ts index c9fc6b49101fa..9d5f76d5a51cc 100644 --- a/apps/server/src/kin/approvals/GrantVerifier.ts +++ b/apps/server/src/kin/approvals/GrantVerifier.ts @@ -34,12 +34,16 @@ import { } from "./GrantPorts.ts"; import { KinPendingActions, kinTargetDigest } from "./PendingActions.ts"; -// Junk that names no key: enough to see a flood, the rest only counted. Anything that -// names a real key is always recorded. -const JUNK_AUDITS_PER_WINDOW = 20; +// 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 isJunk = (reason: KinApprovalError["reason"]) => - reason === "malformed" || reason === "unknown_key"; +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. @@ -327,10 +331,9 @@ const make = Effect.gen(function* () { sessionId, result: error.reason, }; - if (!isJunk(error.reason)) return yield* audit.append(entry); - const slot = `${orgId} ${sessionId}`; + const slot = `${orgId} ${sessionId} ${auditBucket(error.reason, seen.orgId !== undefined)}`; const window = junkWindows.get(slot) ?? (yield* openJunkWindow(slot, orgId, sessionId)); - if (window.used >= JUNK_AUDITS_PER_WINDOW) { + if (window.used >= AUDITS_PER_WINDOW) { window.skipped += 1; return; } @@ -426,13 +429,15 @@ const make = Effect.gen(function* () { action.state === "awaiting_approval" && DateTime.toEpochMillis(action.expiresAt) <= (yield* Clock.currentTimeMillis) ) { - yield* actions.transition({ + const expired = yield* actions.transition({ orgId: action.orgId, actionId: action.id, revision: action.revision, to: "expired", reason: "expired", }); + // 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({ diff --git a/docs/kin/specs/approvals.md b/docs/kin/specs/approvals.md index e63966af9f2c5..ff9b60c197022 100644 --- a/docs/kin/specs/approvals.md +++ b/docs/kin/specs/approvals.md @@ -263,7 +263,7 @@ The grant's life ends at `min(exp, acceptedAt + 15 min)`. It is consumed when th 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. Rejections that name a real key (anything but `malformed` and `unknown_key`) are always recorded. Junk is capped at 20 entries per session and org a minute; when that minute ends, one entry 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. +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 From 1ce521e3a76cdac02bf4a2879d15695e2feb4a89 Mon Sep 17 00:00:00 2001 From: Surajsm60720 <1ds22is166@dsce.edu.in> Date: Sun, 8 Nov 2026 10:07:25 +0530 Subject: [PATCH 05/12] fix(kin): follow approval handlers through the makeKinHandlers aggregator in the WS-only guard Co-Authored-By: Claude Opus 5.5 --- apps/server/src/kin/approvals/GrantVerifier.test.ts | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/apps/server/src/kin/approvals/GrantVerifier.test.ts b/apps/server/src/kin/approvals/GrantVerifier.test.ts index 8776691f00063..916953a325e59 100644 --- a/apps/server/src/kin/approvals/GrantVerifier.test.ts +++ b/apps/server/src/kin/approvals/GrantVerifier.test.ts @@ -1034,7 +1034,8 @@ describe("GrantVerifier", () => { ]); // Those handlers are served only on the authenticated `/ws` session, never over MCP. const handlerImporters = importers("kin/approvals/rpcHandlers.ts"); - assert.deepStrictEqual(handlerImporters, ["ws.ts"]); + assert.deepStrictEqual(handlerImporters, ["kin/rpcHandlers.ts"]); + assert.deepStrictEqual(importers("kin/rpcHandlers.ts"), ["ws.ts"]); assert.deepStrictEqual( files.filter( (file) => From c95f2508941dc10ea7cb47ee06fca3dba94334aa Mon Sep 17 00:00:00 2001 From: Surajsm60720 <1ds22is166@dsce.edu.in> Date: Sun, 8 Nov 2026 18:18:32 +0530 Subject: [PATCH 06/12] fix(kin): check 10 re-reads key revocation through relay sessions Check 10 re-read only the key's registering session, so revoking a relay phone's renewed session while check 9 read GitHub still approved the grant, and a phone that signed out other devices lost its own grants. It now uses the same revocation rule as ApproverKeys reconcile. Co-Authored-By: Claude Opus 5.5 --- .../src/kin/approvals/GrantVerifier.test.ts | 88 +++++++++++++++++-- .../src/kin/approvals/PendingActions.ts | 8 +- 2 files changed, 86 insertions(+), 10 deletions(-) diff --git a/apps/server/src/kin/approvals/GrantVerifier.test.ts b/apps/server/src/kin/approvals/GrantVerifier.test.ts index 916953a325e59..4cf9a90669b9f 100644 --- a/apps/server/src/kin/approvals/GrantVerifier.test.ts +++ b/apps/server/src/kin/approvals/GrantVerifier.test.ts @@ -19,6 +19,7 @@ import { 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"; @@ -27,7 +28,9 @@ import * as Schema from "effect/Schema"; import * as SqlClient from "effect/sql/SqlClient"; import * as TestClock from "effect/testing/TestClock"; +import * as SessionStore from "../../auth/SessionStore.ts"; import * as Sqlite from "../../persistence/Sqlite.ts"; +import { layerKinAuthTest } from "../auth/ProofKeySessions.testkit.ts"; import * as KinPersistence from "../persistence/KinPersistence.ts"; import { ApproverKeys, layer as approverKeysLayer, type KinKeyCaller } from "./ApproverKeys.ts"; import { KinAttestationTrust } from "./attestation/AttestationTrust.ts"; @@ -121,14 +124,17 @@ function harness() { append: (entry) => Effect.sync(() => void audit.push(entry)), }); const trust = Layer.succeed(KinAttestationTrust, { load: () => Effect.succeed(fixture.trust) }); - const database = Layer.provideMerge(KinPersistence.layer, Sqlite.layerMemory); - const layer = grantVerifierLayer.pipe( - Layer.provideMerge(approverKeysLayer), - Layer.provideMerge(pendingActionsLayer), - Layer.provide(Layer.mergeAll(trust, roles, live, auditLayer)), - Layer.provideMerge(database), - ); - return { audit, github, race, layer }; + const on = (database: Layer.Layer) => + grantVerifierLayer.pipe( + Layer.provideMerge(approverKeysLayer), + Layer.provideMerge(pendingActionsLayer), + Layer.provide(Layer.mergeAll(trust, roles, live, auditLayer)), + 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* () { @@ -272,6 +278,20 @@ const reasonOf = (exit: Exit.Exit) => 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, @@ -840,6 +860,58 @@ describe("GrantVerifier", () => { }).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("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* () { diff --git a/apps/server/src/kin/approvals/PendingActions.ts b/apps/server/src/kin/approvals/PendingActions.ts index 188e0aef209f7..5e83dc7c507f4 100644 --- a/apps/server/src/kin/approvals/PendingActions.ts +++ b/apps/server/src/kin/approvals/PendingActions.ts @@ -34,6 +34,7 @@ import { type PersistenceSqlError, toPersistenceSqlError, } from "../../persistence/Errors.ts"; +import { revokedBySession } from "../auth/ProofKeySessions.ts"; const AWAITING_TTL_MS = 7 * 24 * 60 * 60 * 1000; // A grant lapses at min(exp, acceptedAt + 15 min) (approvals spec section 5). @@ -346,8 +347,11 @@ const make = Effect.gen(function* () { }) => 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 EXISTS (SELECT 1 FROM auth_sessions s - WHERE s.session_id = k.session_id AND s.revoked_at IS NOT NULL))`; + AND NOT ${revokedBySession( + sql, + { sessionId: sql`k.session_id`, proofKey: sql`k.proof_key_thumbprint` }, + { honorRepairs: false }, + )})`; const heldGrant = Effect.fn("KinPendingActions.heldGrant")( selectHeld, From 67da33d3c34976793e157c8458a784372f8688d0 Mon Sep 17 00:00:00 2001 From: Surajsm60720 <1ds22is166@dsce.edu.in> Date: Sun, 8 Nov 2026 18:43:49 +0530 Subject: [PATCH 07/12] fix(kin): recheck the signing key when claiming a grant Revoking a key's session voids its approved actions only on the next key read, so an approved action could still be claimed for up to 15 minutes after its key's relay session was revoked. The claim insert now requires the same usable signing key as check 10, and both use the repair-aware rule: a revocation counts unless repaired and older than the key. Co-Authored-By: Claude Opus 5.5 --- .../src/kin/approvals/GrantVerifier.test.ts | 32 +++++++++++++++++++ .../src/kin/approvals/PendingActions.ts | 17 +++++++--- 2 files changed, 44 insertions(+), 5 deletions(-) diff --git a/apps/server/src/kin/approvals/GrantVerifier.test.ts b/apps/server/src/kin/approvals/GrantVerifier.test.ts index 4cf9a90669b9f..130f143dfb3ae 100644 --- a/apps/server/src/kin/approvals/GrantVerifier.test.ts +++ b/apps/server/src/kin/approvals/GrantVerifier.test.ts @@ -894,6 +894,38 @@ describe("GrantVerifier", () => { }, ); + 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* () { diff --git a/apps/server/src/kin/approvals/PendingActions.ts b/apps/server/src/kin/approvals/PendingActions.ts index 5e83dc7c507f4..ebd3271226bae 100644 --- a/apps/server/src/kin/approvals/PendingActions.ts +++ b/apps/server/src/kin/approvals/PendingActions.ts @@ -28,6 +28,7 @@ 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, @@ -339,18 +340,19 @@ const make = Effect.gen(function* () { 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. + // 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; - readonly keyThumbprint: KinKeyThumbprint; - readonly approverHumanId: KinPersonId; + 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` }, - { honorRepairs: false }, + { since: sql`k.created_at` }, )})`; const heldGrant = Effect.fn("KinPendingActions.heldGrant")( @@ -440,6 +442,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; From 1e79706f9c09ce52976120cee5efc88753fcfc8f Mon Sep 17 00:00:00 2001 From: Surajsm60720 <1ds22is166@dsce.edu.in> Date: Sun, 8 Nov 2026 18:44:54 +0530 Subject: [PATCH 08/12] docs(kin): note that claim rechecks the signing key Co-Authored-By: Claude Opus 5.5 --- docs/kin/specs/approvals.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/kin/specs/approvals.md b/docs/kin/specs/approvals.md index 014ecf7f92e0c..69a7036d715ee 100644 --- a/docs/kin/specs/approvals.md +++ b/docs/kin/specs/approvals.md @@ -276,7 +276,7 @@ export const KinGrantPayload = Schema.Struct({ 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. `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`. From 17924466be911c27f20b04ce712823f25c63b79d Mon Sep 17 00:00:00 2001 From: Surajsm60720 <1ds22is166@dsce.edu.in> Date: Sun, 8 Nov 2026 20:38:06 +0530 Subject: [PATCH 09/12] fix(kin): pass GrantVerifier into approval handlers with the other Kin services Co-Authored-By: Claude Opus 5.5 --- apps/server/src/kin/approvals/rpcHandlers.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/apps/server/src/kin/approvals/rpcHandlers.ts b/apps/server/src/kin/approvals/rpcHandlers.ts index f36a70f248624..e4468c597c1d3 100644 --- a/apps/server/src/kin/approvals/rpcHandlers.ts +++ b/apps/server/src/kin/approvals/rpcHandlers.ts @@ -32,7 +32,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 keys = Effect.gen(function* () { From 7003bfdedd84b2a9fdd6d8190b676958dda0261e Mon Sep 17 00:00:00 2001 From: Surajsm60720 <1ds22is166@dsce.edu.in> Date: Sun, 8 Nov 2026 21:43:48 +0530 Subject: [PATCH 10/12] test(server): cover grant RPCs refusing as disabled when Kin is off Co-Authored-By: Claude Opus 5.5 --- apps/server/src/kin/approvals/rpcHandlers.test.ts | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/apps/server/src/kin/approvals/rpcHandlers.test.ts b/apps/server/src/kin/approvals/rpcHandlers.test.ts index 2e741f12b5205..d5044d47b3f38 100644 --- a/apps/server/src/kin/approvals/rpcHandlers.test.ts +++ b/apps/server/src/kin/approvals/rpcHandlers.test.ts @@ -1,5 +1,5 @@ import { assert, it } from "@effect/vitest"; -import { AuthSessionId, AuthStandardClientScopes, KinOrgId } from "@t3tools/contracts"; +import { 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"; @@ -27,7 +27,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( { @@ -45,5 +45,9 @@ 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", + }); }), ); From 96f4eeb1a8ac0f1d5291a1e7def8b7d94b93992c Mon Sep 17 00:00:00 2001 From: Surajsm60720 <1ds22is166@dsce.edu.in> Date: Sun, 8 Nov 2026 22:54:11 +0530 Subject: [PATCH 11/12] test(kin): mirror APPR-6's full-hash grant vectors MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Keeps grant-vectors.json byte-identical with #34 (sha256 107090b4…). Co-Authored-By: Claude Opus 5.5 --- .../fixtures/grant-vectors.json | 34 +++++++++---------- 1 file changed, 17 insertions(+), 17 deletions(-) diff --git a/apps/mobile/modules/kin-approval-key/fixtures/grant-vectors.json b/apps/mobile/modules/kin-approval-key/fixtures/grant-vectors.json index 4a4d3291f22de..6ed02791d7ab4 100644 --- a/apps/mobile/modules/kin-approval-key/fixtures/grant-vectors.json +++ b/apps/mobile/modules/kin-approval-key/fixtures/grant-vectors.json @@ -5,19 +5,19 @@ "name": "merge by squashing", "header": "{\"alg\":\"ES256\",\"kid\":\"Y0ZkXVc6eNfxv3xVNHZJp1x7m3kQqb2O8s5vB1aWc9E\",\"typ\":\"kin-grant+jws\"}", "payload": "{\"actionId\":\"act_01JD7Z0000000000000000000\",\"approver\":{\"humanId\":\"h_owner\",\"kid\":\"Y0ZkXVc6eNfxv3xVNHZJp1x7m3kQqb2O8s5vB1aWc9E\"},\"base\":\"main\",\"decision\":\"approve\",\"exp\":1798762190,\"headSha\":\"a1b2c3d4e5f60718293a4b5c6d7e8f9012345678\",\"iat\":1798761590,\"jti\":\"ZGV2aWNlLWp0aS0xNi1i\",\"kind\":\"merge_pull_request\",\"mergeMethod\":\"squash\",\"nonce\":\"c2VydmVyLW5vbmNlLTMyLWJ5dGVzLWJhc2U2NHVybA\",\"orgId\":\"org_01\",\"revision\":2,\"target\":{\"_tag\":\"pull_request\",\"deleteBranchAfter\":false,\"host\":\"github.com\",\"mergeMethod\":\"squash\",\"number\":212,\"repo\":\"GLDRoger/t3code\"},\"targetDigest\":\"9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08\",\"v\":1}", - "prompt": "Merge GLDRoger/t3code #212 (a1b2c3d4e5f60718) into \"main\" by squashing" + "prompt": "Merge GLDRoger/t3code #212 (a1b2c3d4e5f60718293a4b5c6d7e8f9012345678) into \"main\" by squashing" }, { "name": "merge commit, then delete the branch", "header": "{\"alg\":\"ES256\",\"kid\":\"Y0ZkXVc6eNfxv3xVNHZJp1x7m3kQqb2O8s5vB1aWc9E\",\"typ\":\"kin-grant+jws\"}", "payload": "{\"actionId\":\"act_01JD7Z0000000000000000000\",\"approver\":{\"humanId\":\"h_owner\",\"kid\":\"Y0ZkXVc6eNfxv3xVNHZJp1x7m3kQqb2O8s5vB1aWc9E\"},\"base\":\"main\",\"decision\":\"approve\",\"exp\":1798762190,\"headSha\":\"a1b2c3d4e5f60718293a4b5c6d7e8f9012345678\",\"iat\":1798761590,\"jti\":\"ZGV2aWNlLWp0aS0xNi1i\",\"kind\":\"merge_pull_request\",\"mergeMethod\":\"merge\",\"nonce\":\"c2VydmVyLW5vbmNlLTMyLWJ5dGVzLWJhc2U2NHVybA\",\"orgId\":\"org_01\",\"revision\":2,\"target\":{\"_tag\":\"pull_request\",\"deleteBranchAfter\":true,\"host\":\"github.com\",\"mergeMethod\":\"merge\",\"number\":212,\"repo\":\"GLDRoger/t3code\"},\"targetDigest\":\"9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08\",\"v\":1}", - "prompt": "Merge GLDRoger/t3code #212 (a1b2c3d4e5f60718) into \"main\" with a merge commit, then delete its branch" + "prompt": "Merge GLDRoger/t3code #212 (a1b2c3d4e5f60718293a4b5c6d7e8f9012345678) into \"main\" with a merge commit, then delete its branch" }, { "name": "rebase onto a base with . / + and _", "header": "{\"alg\":\"ES256\",\"kid\":\"Y0ZkXVc6eNfxv3xVNHZJp1x7m3kQqb2O8s5vB1aWc9E\",\"typ\":\"kin-grant+jws\"}", "payload": "{\"actionId\":\"act_01JD7Z0000000000000000000\",\"approver\":{\"humanId\":\"h_owner\",\"kid\":\"Y0ZkXVc6eNfxv3xVNHZJp1x7m3kQqb2O8s5vB1aWc9E\"},\"base\":\"release/v2.1+hotfix_x\",\"decision\":\"approve\",\"exp\":1798762190,\"headSha\":\"a1b2c3d4e5f60718293a4b5c6d7e8f9012345678\",\"iat\":1798761590,\"jti\":\"ZGV2aWNlLWp0aS0xNi1i\",\"kind\":\"merge_pull_request\",\"mergeMethod\":\"rebase\",\"nonce\":\"c2VydmVyLW5vbmNlLTMyLWJ5dGVzLWJhc2U2NHVybA\",\"orgId\":\"org_01\",\"revision\":2,\"target\":{\"_tag\":\"pull_request\",\"deleteBranchAfter\":false,\"host\":\"github.com\",\"mergeMethod\":\"rebase\",\"number\":212,\"repo\":\"GLDRoger/t3code\"},\"targetDigest\":\"9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08\",\"v\":1}", - "prompt": "Merge GLDRoger/t3code #212 (a1b2c3d4e5f60718) into \"release/v2.1+hotfix_x\" by rebasing" + "prompt": "Merge GLDRoger/t3code #212 (a1b2c3d4e5f60718293a4b5c6d7e8f9012345678) into \"release/v2.1+hotfix_x\" by rebasing" }, { "name": "a non-ASCII base is refused", @@ -155,7 +155,7 @@ "name": "a 100-character branch is shown in full", "header": "{\"alg\":\"ES256\",\"kid\":\"Y0ZkXVc6eNfxv3xVNHZJp1x7m3kQqb2O8s5vB1aWc9E\",\"typ\":\"kin-grant+jws\"}", "payload": "{\"actionId\":\"act_01JD7Z0000000000000000000\",\"approver\":{\"humanId\":\"h_owner\",\"kid\":\"Y0ZkXVc6eNfxv3xVNHZJp1x7m3kQqb2O8s5vB1aWc9E\"},\"base\":\"bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\",\"decision\":\"approve\",\"exp\":1798762190,\"headSha\":\"a1b2c3d4e5f60718293a4b5c6d7e8f9012345678\",\"iat\":1798761590,\"jti\":\"ZGV2aWNlLWp0aS0xNi1i\",\"kind\":\"merge_pull_request\",\"mergeMethod\":\"squash\",\"nonce\":\"c2VydmVyLW5vbmNlLTMyLWJ5dGVzLWJhc2U2NHVybA\",\"orgId\":\"org_01\",\"revision\":2,\"target\":{\"_tag\":\"pull_request\",\"deleteBranchAfter\":false,\"host\":\"github.com\",\"mergeMethod\":\"squash\",\"number\":212,\"repo\":\"GLDRoger/t3code\"},\"targetDigest\":\"9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08\",\"v\":1}", - "prompt": "Merge GLDRoger/t3code #212 (a1b2c3d4e5f60718) into \"bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\" by squashing" + "prompt": "Merge GLDRoger/t3code #212 (a1b2c3d4e5f60718293a4b5c6d7e8f9012345678) into \"bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\" by squashing" }, { "name": "a long repo and branch over 200 characters are refused", @@ -166,20 +166,20 @@ { "name": "a prompt of exactly 200 characters keeps its fixed words", "header": "{\"alg\":\"ES256\",\"kid\":\"Y0ZkXVc6eNfxv3xVNHZJp1x7m3kQqb2O8s5vB1aWc9E\",\"typ\":\"kin-grant+jws\"}", - "payload": "{\"actionId\":\"act_01JD7Z0000000000000000000\",\"approver\":{\"humanId\":\"h_owner\",\"kid\":\"Y0ZkXVc6eNfxv3xVNHZJp1x7m3kQqb2O8s5vB1aWc9E\"},\"base\":\"xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\",\"decision\":\"approve\",\"exp\":1798762190,\"headSha\":\"a1b2c3d4e5f60718293a4b5c6d7e8f9012345678\",\"iat\":1798761590,\"jti\":\"ZGV2aWNlLWp0aS0xNi1i\",\"kind\":\"merge_pull_request\",\"mergeMethod\":\"merge\",\"nonce\":\"c2VydmVyLW5vbmNlLTMyLWJ5dGVzLWJhc2U2NHVybA\",\"orgId\":\"org_01\",\"revision\":2,\"target\":{\"_tag\":\"pull_request\",\"deleteBranchAfter\":true,\"host\":\"github.com\",\"mergeMethod\":\"merge\",\"number\":212,\"repo\":\"GLDRoger/t3code\"},\"targetDigest\":\"9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08\",\"v\":1}", - "prompt": "Merge GLDRoger/t3code #212 (a1b2c3d4e5f60718) into \"xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\" with a merge commit, then delete its branch" + "payload": "{\"actionId\":\"act_01JD7Z0000000000000000000\",\"approver\":{\"humanId\":\"h_owner\",\"kid\":\"Y0ZkXVc6eNfxv3xVNHZJp1x7m3kQqb2O8s5vB1aWc9E\"},\"base\":\"xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\",\"decision\":\"approve\",\"exp\":1798762190,\"headSha\":\"a1b2c3d4e5f60718293a4b5c6d7e8f9012345678\",\"iat\":1798761590,\"jti\":\"ZGV2aWNlLWp0aS0xNi1i\",\"kind\":\"merge_pull_request\",\"mergeMethod\":\"merge\",\"nonce\":\"c2VydmVyLW5vbmNlLTMyLWJ5dGVzLWJhc2U2NHVybA\",\"orgId\":\"org_01\",\"revision\":2,\"target\":{\"_tag\":\"pull_request\",\"deleteBranchAfter\":true,\"host\":\"github.com\",\"mergeMethod\":\"merge\",\"number\":212,\"repo\":\"GLDRoger/t3code\"},\"targetDigest\":\"9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08\",\"v\":1}", + "prompt": "Merge GLDRoger/t3code #212 (a1b2c3d4e5f60718293a4b5c6d7e8f9012345678) into \"xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\" with a merge commit, then delete its branch" }, { "name": "a prompt of 201 characters is refused, not cut", "header": "{\"alg\":\"ES256\",\"kid\":\"Y0ZkXVc6eNfxv3xVNHZJp1x7m3kQqb2O8s5vB1aWc9E\",\"typ\":\"kin-grant+jws\"}", - "payload": "{\"actionId\":\"act_01JD7Z0000000000000000000\",\"approver\":{\"humanId\":\"h_owner\",\"kid\":\"Y0ZkXVc6eNfxv3xVNHZJp1x7m3kQqb2O8s5vB1aWc9E\"},\"base\":\"xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\",\"decision\":\"approve\",\"exp\":1798762190,\"headSha\":\"a1b2c3d4e5f60718293a4b5c6d7e8f9012345678\",\"iat\":1798761590,\"jti\":\"ZGV2aWNlLWp0aS0xNi1i\",\"kind\":\"merge_pull_request\",\"mergeMethod\":\"merge\",\"nonce\":\"c2VydmVyLW5vbmNlLTMyLWJ5dGVzLWJhc2U2NHVybA\",\"orgId\":\"org_01\",\"revision\":2,\"target\":{\"_tag\":\"pull_request\",\"deleteBranchAfter\":true,\"host\":\"github.com\",\"mergeMethod\":\"merge\",\"number\":212,\"repo\":\"GLDRoger/t3code\"},\"targetDigest\":\"9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08\",\"v\":1}", + "payload": "{\"actionId\":\"act_01JD7Z0000000000000000000\",\"approver\":{\"humanId\":\"h_owner\",\"kid\":\"Y0ZkXVc6eNfxv3xVNHZJp1x7m3kQqb2O8s5vB1aWc9E\"},\"base\":\"xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\",\"decision\":\"approve\",\"exp\":1798762190,\"headSha\":\"a1b2c3d4e5f60718293a4b5c6d7e8f9012345678\",\"iat\":1798761590,\"jti\":\"ZGV2aWNlLWp0aS0xNi1i\",\"kind\":\"merge_pull_request\",\"mergeMethod\":\"merge\",\"nonce\":\"c2VydmVyLW5vbmNlLTMyLWJ5dGVzLWJhc2U2NHVybA\",\"orgId\":\"org_01\",\"revision\":2,\"target\":{\"_tag\":\"pull_request\",\"deleteBranchAfter\":true,\"host\":\"github.com\",\"mergeMethod\":\"merge\",\"number\":212,\"repo\":\"GLDRoger/t3code\"},\"targetDigest\":\"9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08\",\"v\":1}", "error": "E_NOT_A_GRANT" }, { "name": "delete a branch", "header": "{\"alg\":\"ES256\",\"kid\":\"Y0ZkXVc6eNfxv3xVNHZJp1x7m3kQqb2O8s5vB1aWc9E\",\"typ\":\"kin-grant+jws\"}", "payload": "{\"actionId\":\"act_01JD7Z0000000000000000000\",\"approver\":{\"humanId\":\"h_owner\",\"kid\":\"Y0ZkXVc6eNfxv3xVNHZJp1x7m3kQqb2O8s5vB1aWc9E\"},\"decision\":\"approve\",\"exp\":1798762190,\"headSha\":\"a1b2c3d4e5f60718293a4b5c6d7e8f9012345678\",\"iat\":1798761590,\"jti\":\"ZGV2aWNlLWp0aS0xNi1i\",\"kind\":\"delete_branch\",\"nonce\":\"c2VydmVyLW5vbmNlLTMyLWJ5dGVzLWJhc2U2NHVybA\",\"orgId\":\"org_01\",\"revision\":2,\"target\":{\"_tag\":\"branch\",\"host\":\"github.com\",\"ref\":\"kin/fix-212\",\"repo\":\"GLDRoger/t3code\"},\"targetDigest\":\"9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08\",\"v\":1}", - "prompt": "Delete branch \"kin/fix-212\" (a1b2c3d4e5f60718) in GLDRoger/t3code" + "prompt": "Delete branch \"kin/fix-212\" (a1b2c3d4e5f60718293a4b5c6d7e8f9012345678) in GLDRoger/t3code" }, { "name": "set a level in one chat", @@ -197,31 +197,31 @@ "name": "change rules", "header": "{\"alg\":\"ES256\",\"kid\":\"Y0ZkXVc6eNfxv3xVNHZJp1x7m3kQqb2O8s5vB1aWc9E\",\"typ\":\"kin-grant+jws\"}", "payload": "{\"actionId\":\"act_01JD7Z0000000000000000000\",\"approver\":{\"humanId\":\"h_owner\",\"kid\":\"Y0ZkXVc6eNfxv3xVNHZJp1x7m3kQqb2O8s5vB1aWc9E\"},\"decision\":\"approve\",\"exp\":1798762190,\"iat\":1798761590,\"jti\":\"ZGV2aWNlLWp0aS0xNi1i\",\"kind\":\"change_rules\",\"nonce\":\"c2VydmVyLW5vbmNlLTMyLWJ5dGVzLWJhc2U2NHVybA\",\"orgId\":\"org_01\",\"revision\":2,\"target\":{\"_tag\":\"content\",\"path\":\"rules.md\",\"sha256\":\"9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08\"},\"targetDigest\":\"9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08\",\"v\":1}", - "prompt": "Change rules to \"rules.md\" (sha256 9f86d081884c7d65)" + "prompt": "Change rules to \"rules.md\" (sha256 9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08)" }, { "name": "purge memory", "header": "{\"alg\":\"ES256\",\"kid\":\"Y0ZkXVc6eNfxv3xVNHZJp1x7m3kQqb2O8s5vB1aWc9E\",\"typ\":\"kin-grant+jws\"}", "payload": "{\"actionId\":\"act_01JD7Z0000000000000000000\",\"approver\":{\"humanId\":\"h_owner\",\"kid\":\"Y0ZkXVc6eNfxv3xVNHZJp1x7m3kQqb2O8s5vB1aWc9E\"},\"decision\":\"approve\",\"exp\":1798762190,\"iat\":1798761590,\"jti\":\"ZGV2aWNlLWp0aS0xNi1i\",\"kind\":\"memory_purge\",\"nonce\":\"c2VydmVyLW5vbmNlLTMyLWJ5dGVzLWJhc2U2NHVybA\",\"orgId\":\"org_01\",\"revision\":2,\"target\":{\"_tag\":\"content\",\"path\":\"purge/item-4.json\",\"sha256\":\"9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08\"},\"targetDigest\":\"9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08\",\"v\":1}", - "prompt": "Purge memory using \"purge/item-4.json\" (sha256 9f86d081884c7d65)" + "prompt": "Purge memory using \"purge/item-4.json\" (sha256 9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08)" }, { "name": "register an approver key", "header": "{\"alg\":\"ES256\",\"kid\":\"Y0ZkXVc6eNfxv3xVNHZJp1x7m3kQqb2O8s5vB1aWc9E\",\"typ\":\"kin-grant+jws\"}", "payload": "{\"actionId\":\"act_01JD7Z0000000000000000000\",\"approver\":{\"humanId\":\"h_owner\",\"kid\":\"Y0ZkXVc6eNfxv3xVNHZJp1x7m3kQqb2O8s5vB1aWc9E\"},\"decision\":\"approve\",\"exp\":1798762190,\"iat\":1798761590,\"jti\":\"ZGV2aWNlLWp0aS0xNi1i\",\"kind\":\"register_approver_key\",\"nonce\":\"c2VydmVyLW5vbmNlLTMyLWJ5dGVzLWJhc2U2NHVybA\",\"orgId\":\"org_01\",\"revision\":2,\"target\":{\"_tag\":\"device_key\",\"attested\":true,\"hardware\":\"secure_enclave\",\"thumbprint\":\"NzbLsXh8uDCcd-6MNwXF4W_7noWXFZAfHkxZsRGC9Xs\"},\"targetDigest\":\"9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08\",\"v\":1}", - "prompt": "Add approver key NzbLsXh8uDCcd-6M (Secure Enclave, attested)" + "prompt": "Add approver key NzbLsXh8uDCcd-6MNwXF4W_7noWXFZAfHkxZsRGC9Xs (Secure Enclave, attested)" }, { "name": "register a StrongBox approver key", "header": "{\"alg\":\"ES256\",\"kid\":\"Y0ZkXVc6eNfxv3xVNHZJp1x7m3kQqb2O8s5vB1aWc9E\",\"typ\":\"kin-grant+jws\"}", "payload": "{\"actionId\":\"act_01JD7Z0000000000000000000\",\"approver\":{\"humanId\":\"h_owner\",\"kid\":\"Y0ZkXVc6eNfxv3xVNHZJp1x7m3kQqb2O8s5vB1aWc9E\"},\"decision\":\"approve\",\"exp\":1798762190,\"iat\":1798761590,\"jti\":\"ZGV2aWNlLWp0aS0xNi1i\",\"kind\":\"register_approver_key\",\"nonce\":\"c2VydmVyLW5vbmNlLTMyLWJ5dGVzLWJhc2U2NHVybA\",\"orgId\":\"org_01\",\"revision\":2,\"target\":{\"_tag\":\"device_key\",\"attested\":true,\"hardware\":\"strongbox\",\"thumbprint\":\"NzbLsXh8uDCcd-6MNwXF4W_7noWXFZAfHkxZsRGC9Xs\"},\"targetDigest\":\"9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08\",\"v\":1}", - "prompt": "Add approver key NzbLsXh8uDCcd-6M (StrongBox, attested)" + "prompt": "Add approver key NzbLsXh8uDCcd-6MNwXF4W_7noWXFZAfHkxZsRGC9Xs (StrongBox, attested)" }, { "name": "register a TEE approver key", "header": "{\"alg\":\"ES256\",\"kid\":\"Y0ZkXVc6eNfxv3xVNHZJp1x7m3kQqb2O8s5vB1aWc9E\",\"typ\":\"kin-grant+jws\"}", "payload": "{\"actionId\":\"act_01JD7Z0000000000000000000\",\"approver\":{\"humanId\":\"h_owner\",\"kid\":\"Y0ZkXVc6eNfxv3xVNHZJp1x7m3kQqb2O8s5vB1aWc9E\"},\"decision\":\"approve\",\"exp\":1798762190,\"iat\":1798761590,\"jti\":\"ZGV2aWNlLWp0aS0xNi1i\",\"kind\":\"register_approver_key\",\"nonce\":\"c2VydmVyLW5vbmNlLTMyLWJ5dGVzLWJhc2U2NHVybA\",\"orgId\":\"org_01\",\"revision\":2,\"target\":{\"_tag\":\"device_key\",\"attested\":true,\"hardware\":\"tee\",\"thumbprint\":\"NzbLsXh8uDCcd-6MNwXF4W_7noWXFZAfHkxZsRGC9Xs\"},\"targetDigest\":\"9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08\",\"v\":1}", - "prompt": "Add approver key NzbLsXh8uDCcd-6M (TEE, attested)" + "prompt": "Add approver key NzbLsXh8uDCcd-6MNwXF4W_7noWXFZAfHkxZsRGC9Xs (TEE, attested)" }, { "name": "an unattested approver key is refused", @@ -263,13 +263,13 @@ "name": "escapes decode in a field that isn't shown", "header": "{\"alg\":\"ES256\",\"kid\":\"Y0ZkXVc6eNfxv3xVNHZJp1x7m3kQqb2O8s5vB1aWc9E\",\"typ\":\"kin-grant+jws\"}", "payload": "{\"actionId\":\"act_\\\"q\\\\\\u0001\",\"approver\":{\"humanId\":\"h_owner\",\"kid\":\"Y0ZkXVc6eNfxv3xVNHZJp1x7m3kQqb2O8s5vB1aWc9E\"},\"base\":\"main\",\"decision\":\"approve\",\"exp\":1798762190,\"headSha\":\"a1b2c3d4e5f60718293a4b5c6d7e8f9012345678\",\"iat\":1798761590,\"jti\":\"ZGV2aWNlLWp0aS0xNi1i\",\"kind\":\"merge_pull_request\",\"mergeMethod\":\"squash\",\"nonce\":\"c2VydmVyLW5vbmNlLTMyLWJ5dGVzLWJhc2U2NHVybA\",\"orgId\":\"org_01\",\"revision\":2,\"target\":{\"_tag\":\"pull_request\",\"deleteBranchAfter\":false,\"host\":\"github.com\",\"mergeMethod\":\"squash\",\"number\":212,\"repo\":\"GLDRoger/t3code\"},\"targetDigest\":\"9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08\",\"v\":1}", - "prompt": "Merge GLDRoger/t3code #212 (a1b2c3d4e5f60718) into \"main\" by squashing" + "prompt": "Merge GLDRoger/t3code #212 (a1b2c3d4e5f60718293a4b5c6d7e8f9012345678) into \"main\" by squashing" }, { "name": "iat 300 s behind the device clock", "header": "{\"alg\":\"ES256\",\"kid\":\"Y0ZkXVc6eNfxv3xVNHZJp1x7m3kQqb2O8s5vB1aWc9E\",\"typ\":\"kin-grant+jws\"}", "payload": "{\"actionId\":\"act_01JD7Z0000000000000000000\",\"approver\":{\"humanId\":\"h_owner\",\"kid\":\"Y0ZkXVc6eNfxv3xVNHZJp1x7m3kQqb2O8s5vB1aWc9E\"},\"base\":\"main\",\"decision\":\"approve\",\"exp\":1798761600,\"headSha\":\"a1b2c3d4e5f60718293a4b5c6d7e8f9012345678\",\"iat\":1798761300,\"jti\":\"ZGV2aWNlLWp0aS0xNi1i\",\"kind\":\"merge_pull_request\",\"mergeMethod\":\"squash\",\"nonce\":\"c2VydmVyLW5vbmNlLTMyLWJ5dGVzLWJhc2U2NHVybA\",\"orgId\":\"org_01\",\"revision\":2,\"target\":{\"_tag\":\"pull_request\",\"deleteBranchAfter\":false,\"host\":\"github.com\",\"mergeMethod\":\"squash\",\"number\":212,\"repo\":\"GLDRoger/t3code\"},\"targetDigest\":\"9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08\",\"v\":1}", - "prompt": "Merge GLDRoger/t3code #212 (a1b2c3d4e5f60718) into \"main\" by squashing" + "prompt": "Merge GLDRoger/t3code #212 (a1b2c3d4e5f60718293a4b5c6d7e8f9012345678) into \"main\" by squashing" }, { "name": "empty", @@ -300,7 +300,7 @@ "name": "control for the trailing-bits case", "header": "{\"alg\":\"ES256\",\"kid\":\"Y0ZkXVc6eNfxv3xVNHZJp1x7m3kQqb2O8s5vB1aWc9E\",\"typ\":\"kin-grant+jws\"}", "payload": "{\"actionId\":\"act_01JD7Z0000000000000000000\",\"approver\":{\"humanId\":\"h_owner\",\"kid\":\"Y0ZkXVc6eNfxv3xVNHZJp1x7m3kQqb2O8s5vB1aWc9E\"},\"base\":\"maina\",\"decision\":\"approve\",\"exp\":1798762190,\"headSha\":\"a1b2c3d4e5f60718293a4b5c6d7e8f9012345678\",\"iat\":1798761590,\"jti\":\"ZGV2aWNlLWp0aS0xNi1i\",\"kind\":\"merge_pull_request\",\"mergeMethod\":\"squash\",\"nonce\":\"c2VydmVyLW5vbmNlLTMyLWJ5dGVzLWJhc2U2NHVybA\",\"orgId\":\"org_01\",\"revision\":2,\"target\":{\"_tag\":\"pull_request\",\"deleteBranchAfter\":false,\"host\":\"github.com\",\"mergeMethod\":\"squash\",\"number\":212,\"repo\":\"GLDRoger/t3code\"},\"targetDigest\":\"9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08\",\"v\":1}", - "prompt": "Merge GLDRoger/t3code #212 (a1b2c3d4e5f60718) into \"maina\" by squashing" + "prompt": "Merge GLDRoger/t3code #212 (a1b2c3d4e5f60718293a4b5c6d7e8f9012345678) into \"maina\" by squashing" }, { "name": "non-zero trailing bits", @@ -592,7 +592,7 @@ "name": "a kid with K, the same bytes in header and approver", "header": "{\"alg\":\"ES256\",\"kid\":\"K0ZkXVc6eNfxv3xVNHZJp1x7m3kQqb2O8s5vB1aWc9E\",\"typ\":\"kin-grant+jws\"}", "payload": "{\"actionId\":\"act_01JD7Z0000000000000000000\",\"approver\":{\"humanId\":\"h_owner\",\"kid\":\"K0ZkXVc6eNfxv3xVNHZJp1x7m3kQqb2O8s5vB1aWc9E\"},\"base\":\"main\",\"decision\":\"approve\",\"exp\":1798762190,\"headSha\":\"a1b2c3d4e5f60718293a4b5c6d7e8f9012345678\",\"iat\":1798761590,\"jti\":\"ZGV2aWNlLWp0aS0xNi1i\",\"kind\":\"merge_pull_request\",\"mergeMethod\":\"squash\",\"nonce\":\"c2VydmVyLW5vbmNlLTMyLWJ5dGVzLWJhc2U2NHVybA\",\"orgId\":\"org_01\",\"revision\":2,\"target\":{\"_tag\":\"pull_request\",\"deleteBranchAfter\":false,\"host\":\"github.com\",\"mergeMethod\":\"squash\",\"number\":212,\"repo\":\"GLDRoger/t3code\"},\"targetDigest\":\"9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08\",\"v\":1}", - "prompt": "Merge GLDRoger/t3code #212 (a1b2c3d4e5f60718) into \"main\" by squashing" + "prompt": "Merge GLDRoger/t3code #212 (a1b2c3d4e5f60718293a4b5c6d7e8f9012345678) into \"main\" by squashing" }, { "name": "approver.kid differs from the header kid", From eb69a903ecac5996fb2ff0302689d568fba24ccc Mon Sep 17 00:00:00 2001 From: GLDRoger <130458023+GLDRoger@users.noreply.github.com> Date: Mon, 9 Nov 2026 06:09:04 +0530 Subject: [PATCH 12/12] test(kin): the MCP reachability guard also forbids approver keys, the approvals layer and handlers Co-Authored-By: Claude Opus 5.5 --- apps/server/src/kin/approvals/GrantVerifier.test.ts | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/apps/server/src/kin/approvals/GrantVerifier.test.ts b/apps/server/src/kin/approvals/GrantVerifier.test.ts index af1623f21a5b9..ee58377cfabed 100644 --- a/apps/server/src/kin/approvals/GrantVerifier.test.ts +++ b/apps/server/src/kin/approvals/GrantVerifier.test.ts @@ -1191,7 +1191,12 @@ describe("GrantVerifier", () => { assert.deepStrictEqual( [...fromTool].filter( (file) => - file === "kin/approvals/GrantVerifier.ts" || file === "kin/approvals/rpcHandlers.ts", + [ + "kin/approvals/GrantVerifier.ts", + "kin/approvals/rpcHandlers.ts", + "kin/approvals/ApproverKeys.ts", + "kin/approvals/layer.ts", + ].includes(file) || file.startsWith("kin/approvals/handlers/"), ), [], );