From bae00837ad7722143f1a16bce0bb6257241cff7a Mon Sep 17 00:00:00 2001 From: GLDRoger <130458023+GLDRoger@users.noreply.github.com> Date: Tue, 10 Nov 2026 11:38:51 +0530 Subject: [PATCH 1/8] fix(kin): approval cards reach the owner, and kin.approvals.get answers Nothing posted an approval card or a Waiting on you item for a pending action, and kin.approvals.get always refused, so no client could show what waits on the owner. - PendingActions publishes every action it creates, refreshes, decides or sweeps, after commit. - chat/approvalCards.ts keeps one server-drawn card per merge or level raise in the lead's direct chat, waiting on the owner until the action settles. - GrantVerifier.view answers kin.approvals.get: the full action (with the lead's and the earlier speaker's names) for the owner, the redacted card naming who it waits on for anyone else. Co-Authored-By: Claude Opus 5.5 --- .../src/kin/approvals/GrantVerifier.test.ts | 102 +++++++++ .../server/src/kin/approvals/GrantVerifier.ts | 81 ++++++- .../src/kin/approvals/PendingActions.ts | 10 + apps/server/src/kin/approvals/rpcHandlers.ts | 5 +- apps/server/src/kin/chat/approvalCards.ts | 216 ++++++++++++++++++ apps/server/src/kin/layer.ts | 10 +- apps/server/src/kin/levels/Promotion.test.ts | 37 ++- packages/contracts/src/kinApprovals.ts | 14 ++ 8 files changed, 467 insertions(+), 8 deletions(-) create mode 100644 apps/server/src/kin/chat/approvalCards.ts diff --git a/apps/server/src/kin/approvals/GrantVerifier.test.ts b/apps/server/src/kin/approvals/GrantVerifier.test.ts index 3cc7537f4c01c..bb005fdc78b2b 100644 --- a/apps/server/src/kin/approvals/GrantVerifier.test.ts +++ b/apps/server/src/kin/approvals/GrantVerifier.test.ts @@ -221,6 +221,7 @@ const requestMerge = ( actions: KinPendingActions["Service"], number: number, github: Map, + afterNonOwnerMessage?: { readonly humanId: string; readonly messageId: string }, ) => Effect.gen(function* () { const target = pr(number); @@ -239,6 +240,7 @@ const requestMerge = ( startedByRole: "none", chain: [], ceilingBelowOwner: true, + ...(afterNonOwnerMessage === undefined ? {} : { afterNonOwnerMessage }), }, source: decodeEventId(`evt-${number}`), } as unknown as KinPendingActionCreateInput; @@ -421,6 +423,106 @@ describe("GrantVerifier", () => { }).pipe(Effect.provide(h.layer)); }); + it.effect("non-owners get the redacted card and no challenge", () => { + const h = harness(); + return Effect.gen(function* () { + const { grants, actions, sql } = yield* enrol; + yield* sql`INSERT INTO kin_people (person_id, org_id, handle, display_name, created_at) + VALUES (${owner}, 'org_01', 'nishchay', 'Nishchay', '2026-11-07T00:00:00.000Z'), + (${member}, 'org_01', 'priya', 'Priya', '2026-11-07T00:00:00.000Z')`; + yield* sql`INSERT INTO kin_agents (agent_id, org_id, display_name, role, owner_person_id, + created_at) + VALUES ('lead', 'org_01', 'Tech lead', 'lead', ${owner}, '2026-11-07T00:00:00.000Z')`; + const action = yield* requestMerge(actions, 212, h.github, { + humanId: member, + messageId: "msg-priya", + }); + assert.deepStrictEqual(yield* grants.view(ownerPhone, { actionId: action.id }), { + _tag: "full", + action, + canApprove: true, + leadName: "Tech lead", + afterNonOwnerName: "Priya", + }); + assert.deepStrictEqual(yield* grants.view(memberPhone, { actionId: action.id }), { + _tag: "redacted", + actionId: action.id, + orgId, + kind: "merge_pull_request", + repo: "GLDRoger/t3code", + number: 212, + title: "Fix", + state: "awaiting_approval", + waitingOn: "Nishchay", + canApprove: false, + }); + assert.strictEqual( + reasonOf(yield* Effect.exit(grants.challenge(memberPhone, { actionId: action.id }))), + "not_owner", + ); + assert.strictEqual( + reasonOf(yield* Effect.exit(grants.view(nobody, { actionId: action.id }))), + "not_found", + ); + }).pipe(Effect.provide(h.layer)); + }); + + it.effect("a phone with no active approver key gets no challenge and can't approve", () => { + const h = harness(); + return Effect.gen(function* () { + const { keys, actions, grants } = yield* seed; + const action = yield* requestMerge(actions, 212, h.github); + assert.strictEqual( + reasonOf(yield* Effect.exit(grants.challenge(ownerPhone, { actionId: action.id }))), + "unknown_key", + ); + // An iPhone simulator has no App Attest: its key registers unattested and stays pending. + const simulator = newKey(); + const jwk = simulator.publicKey.export({ format: "jwk" }); + const publicJwk = { kty: "EC" as const, crv: "P-256" as const, x: jwk.x!, y: jwk.y! }; + const { challenge } = yield* keys.keyChallenge(ownerPhone); + const { key } = yield* keys.registerKey(ownerPhone, { + orgId, + publicJwk, + platform: "ios", + challenge, + deviceLabel: "iPhone simulator", + }); + assert.deepInclude(key, { state: "pending", attested: false, hardware: "software" }); + assert.strictEqual( + reasonOf(yield* Effect.exit(grants.challenge(ownerPhone, { actionId: action.id }))), + "unknown_key", + ); + const compact = signGrant( + simulator.privateKey, + { typ: "kin-grant+jws", alg: "ES256", kid: key.thumbprint }, + { + v: 1, + orgId, + actionId: action.id, + revision: action.revision, + nonce: action.nonce, + kind: action.kind, + targetDigest: action.targetDigest, + target: action.target, + headSha: sha("a"), + base: "main", + mergeMethod: "squash", + approver: { humanId: owner, kid: key.thumbprint }, + decision: "approve", + jti: freshJti(), + iat: NOW_S, + exp: NOW_S + 600, + }, + ); + 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* () { diff --git a/apps/server/src/kin/approvals/GrantVerifier.ts b/apps/server/src/kin/approvals/GrantVerifier.ts index 6dee99bc90a15..4feb1087d108c 100644 --- a/apps/server/src/kin/approvals/GrantVerifier.ts +++ b/apps/server/src/kin/approvals/GrantVerifier.ts @@ -7,6 +7,7 @@ import { type KinApprovalsDecisionResult, type KinApprovalsRejectInput, type KinApprovalsSubmitGrantInput, + type KinApprovalView, type KinGrantRejectionReason, type KinOrgId, type KinPendingAction, @@ -22,6 +23,7 @@ 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 type { PersonIdentity } from "../chat/KinIdentity.ts"; import { ApproverKeys, type KinKeyCaller } from "./ApproverKeys.ts"; @@ -68,6 +70,10 @@ const REJECTION_MESSAGES = { const reject = (reason: KinGrantRejectionReason) => fail(reason, REJECTION_MESSAGES[reason]); +/** The lead an action concerns: a raise names its lead, anything else its requester. */ +const leadOf = (action: KinPendingAction) => + action.target._tag === "level" ? action.target.agentId : action.requestedBy.agentId; + const headOf = (action: KinPendingAction) => { const resolved = action.resolved; return stableStringify({ @@ -89,6 +95,11 @@ type Seen = { export class GrantVerifier extends Context.Service< GrantVerifier, { + /** `get`: the full card for an approver, the redacted one for anyone else in the action's org. */ + readonly view: ( + caller: KinKeyCaller, + input: KinApprovalsActionInput, + ) => Effect.Effect; /** The unsigned payload the phone renders and signs; re-reads GitHub and rotates if it moved. */ readonly challenge: ( caller: KinKeyCaller, @@ -113,6 +124,7 @@ const make = Effect.gen(function* () { const roles = yield* KinOrgRoles; const live = yield* KinLiveTargets; const audit = yield* KinGrantAudit; + const sql = yield* SqlClient.SqlClient; const scope = yield* Effect.scope; const junkWindows = new Map(); @@ -422,6 +434,73 @@ const make = Effect.gen(function* () { Effect.catch(internal("GrantVerifier.challenge")), ); + const displayName = Effect.fn("GrantVerifier.displayName")(function* ( + table: "kin_people" | "kin_agents", + orgId: KinOrgId, + id: string, + ) { + const [row] = + table === "kin_people" + ? yield* sql<{ name: string }>`SELECT display_name AS name FROM kin_people + WHERE org_id = ${orgId} AND person_id = ${id}` + : yield* sql<{ name: string }>`SELECT display_name AS name FROM kin_agents + WHERE org_id = ${orgId} AND agent_id = ${id}`; + return row?.name.trim() || undefined; + }); + + /** The person the card waits on: the owner of the lead it concerns (phase 1's only approver). */ + const ownerName = Effect.fn("GrantVerifier.ownerName")(function* (action: KinPendingAction) { + const lead = leadOf(action); + const [row] = yield* sql<{ name: string }>`SELECT p.display_name AS name FROM kin_agents a + JOIN kin_people p ON p.org_id = a.org_id AND p.person_id = a.owner_person_id + WHERE a.org_id = ${action.orgId} AND a.agent_id = ${lead}`; + return row?.name.trim() || undefined; + }); + + const view = Effect.fn("GrantVerifier.view")( + function* (caller: KinKeyCaller, input: KinApprovalsActionInput) { + for (const person of caller.people) { + const found = yield* actions.get({ orgId: person.orgId, actionId: input.actionId }); + if (Option.isNone(found)) continue; + const action = found.value; + if (yield* roles.isOwner(person)) { + const leadName = yield* displayName("kin_agents", action.orgId, leadOf(action)); + const after = action.provenance.afterNonOwnerMessage; + const afterNonOwnerName = + after === undefined + ? undefined + : yield* displayName("kin_people", action.orgId, after.humanId); + return { + _tag: "full" as const, + action, + canApprove: true as const, + ...(leadName === undefined ? {} : { leadName }), + ...(afterNonOwnerName === undefined ? {} : { afterNonOwnerName }), + }; + } + // Anyone else sees what waits and on whom, never the facts a challenge would sign. + const pr = action.target._tag === "pull_request" ? action.target : undefined; + return { + _tag: "redacted" as const, + actionId: action.id, + orgId: action.orgId, + kind: action.kind, + repo: + action.target._tag === "pull_request" || action.target._tag === "branch" + ? action.target.repo + : null, + number: pr?.number ?? null, + title: action.resolved._tag === "pull_request" ? action.resolved.title : null, + state: action.state, + waitingOn: (yield* ownerName(action)) ?? "the owner", + canApprove: false as const, + }; + } + return yield* fail("not_found", "No such action."); + }, + Effect.catch(internal("GrantVerifier.view")), + ); + const rejectAction = Effect.fn("GrantVerifier.reject")( function* (caller: KinKeyCaller, input: KinApprovalsRejectInput) { const { action } = yield* actionFor(caller, input.actionId); @@ -456,7 +535,7 @@ const make = Effect.gen(function* () { Effect.catch(internal("GrantVerifier.reject")), ); - return GrantVerifier.of({ challenge, submitGrant, reject: rejectAction }); + return GrantVerifier.of({ view, 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 50bba74344135..d30f592d53310 100644 --- a/apps/server/src/kin/approvals/PendingActions.ts +++ b/apps/server/src/kin/approvals/PendingActions.ts @@ -268,6 +268,8 @@ export class KinPendingActions extends Context.Service< >; /** Every action `approve` moves to `approved`, published after its transaction commits. */ readonly approvals: Effect.Effect, never, Scope.Scope>; + /** Every action this instance creates, refreshes, decides or sweeps, after its commit. */ + readonly changes: Effect.Effect, never, Scope.Scope>; /** Expires unapproved actions past `expiresAt` and voids approvals whose grant lapsed. */ readonly sweep: () => Effect.Effect< { readonly expired: ReadonlyArray; readonly voided: ReadonlyArray }, @@ -316,6 +318,8 @@ const make = Effect.gen(function* () { const sql = yield* SqlClient.SqlClient; const audit = yield* KinAudit; const approvedHub = yield* PubSub.unbounded(); + const changedHub = yield* PubSub.unbounded(); + const changed = (ref: ActionRef) => sql.afterCommit(PubSub.publish(changedHub, ref)); const select = (ref: ActionRef) => sql`SELECT * FROM kin_pending_actions @@ -365,6 +369,7 @@ const make = Effect.gen(function* () { ON CONFLICT (org_id, idempotency_key) DO NOTHING RETURNING action_id`; if (inserted.length === 0) return false; + yield* changed({ orgId: action.orgId, actionId: action.id }); yield* audit.append({ orgId: action.orgId, event: "action_requested", @@ -405,6 +410,7 @@ const make = Effect.gen(function* () { AND expires_at > ${now} RETURNING *`; if (row === undefined) return Option.none(); + yield* changed(input); yield* audit.append({ orgId: input.orgId, event: "action_refreshed", @@ -437,6 +443,7 @@ const make = Effect.gen(function* () { AND (${input.to} NOT IN ('rejected', 'cancelled') OR expires_at > ${now}) RETURNING action_id, kind, resolved_json`; if (row === undefined) return false; + yield* changed(input); yield* audit.append({ orgId: input.orgId, event: `action_${input.to}`, @@ -563,6 +570,7 @@ const make = Effect.gen(function* () { // that owns the action: an unknown org or action stays `stale` and writes nothing. if (result._tag === "approved") { yield* PubSub.publish(approvedHub, { orgId: input.orgId, actionId: input.actionId }); + yield* PubSub.publish(changedHub, { orgId: input.orgId, actionId: input.actionId }); } else if (input.auditRefusal !== false) { yield* sql .withTransaction( @@ -833,6 +841,7 @@ const make = Effect.gen(function* () { yield* record("action_voided", "grant_expired"); const refs = (rows: ReadonlyArray) => rows.map((row) => ({ orgId: row.org_id, actionId: row.action_id })); + yield* Effect.forEach(refs(expired), changed, { discard: true }); return { expired: refs(expired), voided: refs(voided) }; }), ); @@ -851,6 +860,7 @@ const make = Effect.gen(function* () { approvedWithGrant, executingWithGrant, approvals: PubSub.subscribe(approvedHub), + changes: PubSub.subscribe(changedHub), sweep, }), ledger: KinExecutionLedger.of({ diff --git a/apps/server/src/kin/approvals/rpcHandlers.ts b/apps/server/src/kin/approvals/rpcHandlers.ts index 726777c1ccab1..66fbc01119020 100644 --- a/apps/server/src/kin/approvals/rpcHandlers.ts +++ b/apps/server/src/kin/approvals/rpcHandlers.ts @@ -13,7 +13,7 @@ import * as Audit from "./Audit.ts"; import { GrantVerifier } from "./GrantVerifier.ts"; const group = RpcGroup.make(...KinApprovalRpcs); -// Methods refuse until their task lands (APPR-3). Approving only goes through GrantVerifier. +// `list` refuses until its task lands. Approving only goes through GrantVerifier. const unavailable = Effect.fail( new KinApprovalError({ reason: "unavailable", message: "Kin approvals are unavailable." }), ); @@ -69,7 +69,8 @@ export const makeKinApprovalHandlers = Effect.fn("makeKinApprovalHandlers")(func }); return group.of({ "kin.approvals.list": () => Stream.fromEffect(unavailable), - "kin.approvals.get": () => unavailable, + "kin.approvals.get": (input) => + keys.pipe(Effect.flatMap(({ grants, caller }) => grants.view(caller, input))), "kin.approvals.challenge": (input) => keys.pipe(Effect.flatMap(({ grants, caller }) => grants.challenge(caller, input))), "kin.approvals.submitGrant": (input) => diff --git a/apps/server/src/kin/chat/approvalCards.ts b/apps/server/src/kin/chat/approvalCards.ts new file mode 100644 index 0000000000000..50f1fa84cdb99 --- /dev/null +++ b/apps/server/src/kin/chat/approvalCards.ts @@ -0,0 +1,216 @@ +import { + KinActionId, + KinChatId, + KinMessageId, + KinOrgId, + KinPersonId, + KinWaitingId, + KinWidgetId, + kinApprovalWidgetId, + type KinActionKind, + type KinPendingAction, + type KinWidget, +} from "@t3tools/contracts"; +import * as Cause from "effect/Cause"; +import * as Clock from "effect/Clock"; +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 PubSub from "effect/PubSub"; +import * as Schema from "effect/Schema"; +import * as SecureRandom from "effect/crypto/SecureRandom"; +import * as SqlClient from "effect/sql/SqlClient"; + +import type { ActionRef } from "../approvals/PendingActions.ts"; +import { KinPendingActions } from "../approvals/PendingActions.ts"; +import { KinChatHub } from "./KinChatHub.ts"; +import { KinChatRepository } from "./KinChatRepository.ts"; +import { KinChatService } from "./KinChatService.ts"; + +/** Kinds the phone can approve today; other kinds have no card yet and stay off the owner's list. */ +const CARD_KINDS: ReadonlySet = new Set(["merge_pull_request", "set_level"]); + +const decodeWaitingId = Schema.decodeEffect(KinWaitingId); +const iso = (ms: number) => DateTime.formatIso(DateTime.makeUnsafe(ms)); + +/** The lead whose direct chat carries the card: a raise names its lead, a merge its requester. */ +const leadOf = (action: KinPendingAction) => + action.target._tag === "level" ? action.target.agentId : action.requestedBy.agentId; + +const noticeBody = (action: KinPendingAction) => { + switch (action.target._tag) { + case "pull_request": + return `Approval needed: merge ${action.target.repo} #${action.target.number}.`; + case "level": + return `Approval needed: raise to ${action.target.level}.`; + default: + return "Approval needed."; + } +}; + +/** + * Keeps one server-drawn approval card per action in the lead's direct chat, waiting on the + * owner while the action does. The card carries only the action's id and where it stands; apps + * read the facts from `kin.approvals.get`, so nothing an agent wrote reaches it. + */ +export const layer = Layer.effectDiscard( + Effect.gen(function* () { + const pending = yield* KinPendingActions; + const repo = yield* KinChatRepository; + const chat = yield* KinChatService; + const hub = yield* KinChatHub; + const sql = yield* SqlClient.SqlClient; + const changes = yield* pending.changes; + + const ownerChat = Effect.fn("KinApprovalCards.ownerChat")(function* (action: KinPendingAction) { + const [row] = yield* sql<{ chatId: string; owner: string }>` + SELECT l.owner_chat_id AS "chatId", a.owner_person_id AS owner FROM kin_leads l + JOIN kin_agents a ON a.org_id = l.org_id AND a.agent_id = l.agent_id + JOIN kin_chats c ON c.org_id = l.org_id AND c.chat_id = l.owner_chat_id AND c.kind = 'direct' + WHERE l.org_id = ${action.orgId} AND l.agent_id = ${leadOf(action)} AND a.role = 'lead' + ORDER BY l.agent_id`; + return row; + }); + + const open = Effect.fn("KinApprovalCards.open")(function* ( + action: KinPendingAction, + widgetId: KinWidgetId, + ) { + const owner = yield* ownerChat(action); + if (owner === undefined) { + yield* Effect.logInfo("Kin approval card has no chat", { actionId: action.id }); + return; + } + const updatedAt = iso(yield* Clock.currentTimeMillis); + const personId = KinPersonId.make(owner.owner); + const { message } = yield* chat.notice({ + orgId: action.orgId, + chatId: KinChatId.make(owner.chatId), + messageId: KinMessageId.make(widgetId), + body: noticeBody(action), + }); + const widget: KinWidget = { + orgId: action.orgId, + chatId: message.chatId, + widgetId, + messageId: message.messageId, + widgetClass: "native", + type: "approval", + revision: 1, + state: { actionId: action.id, revision: action.revision, state: action.state }, + source: null, + feed: null, + awaiting: [personId], + pinnedAt: null, + closedAt: null, + updatedAt, + }; + yield* repo.insertWidget(widget); + const item = { + waitingId: yield* decodeWaitingId(SecureRandom.uuidV4Unsafe()), + orgId: action.orgId, + personId, + chatId: message.chatId, + messageId: message.messageId, + widgetId, + reason: "approval" as const, + createdAt: updatedAt, + resolvedAt: null, + resolution: null, + }; + yield* repo.addApprovalWaiting(item); + yield* hub.publish({ type: "widget.updated", orgId: action.orgId, widget }); + yield* hub.publish({ type: "waiting.updated", orgId: action.orgId, item }); + }); + + const update = Effect.fn("KinApprovalCards.update")(function* ( + action: KinPendingAction, + current: KinWidget, + ) { + const settled = action.state !== "awaiting_approval"; + const state = { actionId: action.id, revision: action.revision, state: action.state }; + const sameState = + typeof current.state === "object" && + current.state !== null && + "revision" in current.state && + "state" in current.state && + current.state.revision === state.revision && + current.state.state === state.state; + if (sameState && (current.closedAt !== null) === settled) return; + const now = iso(yield* Clock.currentTimeMillis); + const widget = yield* repo.updateWidget({ + ...current, + state, + awaiting: settled ? [] : current.awaiting, + closedAt: settled ? (current.closedAt ?? now) : null, + expectedRevision: current.revision, + updatedAt: now, + }); + if (settled) + for (const item of yield* repo.waitingForWidget(widget)) { + if (!(yield* repo.resolveWaiting({ ...item, resolution: action.state, resolvedAt: now }))) + continue; + const resolved = yield* repo.getWaiting(item); + if (Option.isSome(resolved)) + yield* hub.publish({ + type: "waiting.updated", + orgId: item.orgId, + item: resolved.value, + }); + } + yield* hub.publish({ type: "widget.updated", orgId: action.orgId, widget }); + }); + + const sync = Effect.fn("KinApprovalCards.sync")( + function* (ref: ActionRef) { + const found = yield* pending.get(ref); + if (Option.isNone(found) || !CARD_KINDS.has(found.value.kind)) return; + const action = found.value; + const widgetId = KinWidgetId.make(kinApprovalWidgetId(action.id)); + yield* sql.withTransaction( + Effect.gen(function* () { + const existing = yield* repo.getWidget({ orgId: action.orgId, widgetId }); + if (Option.isSome(existing)) { + if (existing.value.type === "approval") yield* update(action, existing.value); + return; + } + if (action.state === "awaiting_approval") yield* open(action, widgetId); + }), + ); + }, + Effect.catchCause((cause) => + Effect.logWarning("Kin approval card not updated", Cause.pretty(cause).slice(0, 500)), + ), + ); + + // Anything that changed while the server was down: open actions, and cards still open. + const startup = Effect.gen(function* () { + const rows = yield* sql<{ orgId: string; actionId: string }>` + SELECT org_id AS "orgId", action_id AS "actionId" FROM kin_pending_actions + WHERE state = 'awaiting_approval' AND kind IN ('merge_pull_request', 'set_level') + UNION + SELECT p.org_id, p.action_id FROM kin_widgets w + JOIN kin_pending_actions p ON p.org_id = w.org_id + AND w.widget_id = 'kin-approval:' || p.action_id + WHERE w.type = 'approval' AND w.closed_at IS NULL + ORDER BY 1, 2`; + yield* Effect.forEach( + rows, + (row) => + sync({ orgId: KinOrgId.make(row.orgId), actionId: KinActionId.make(row.actionId) }), + { discard: true }, + ); + }).pipe( + Effect.catchCause((cause) => + Effect.logWarning( + "Kin approval cards startup pass failed", + Cause.pretty(cause).slice(0, 500), + ), + ), + ); + + yield* PubSub.take(changes).pipe(Effect.flatMap(sync), Effect.forever, Effect.forkScoped); + yield* startup.pipe(Effect.forkScoped); + }), +); diff --git a/apps/server/src/kin/layer.ts b/apps/server/src/kin/layer.ts index 0c55bb5600dd9..30bd8cbbdedd9 100644 --- a/apps/server/src/kin/layer.ts +++ b/apps/server/src/kin/layer.ts @@ -11,6 +11,7 @@ import * as Option from "effect/Option"; import * as KinChat from "./chat/layer.ts"; import * as KinApprovals from "./approvals/layer.ts"; import * as KeySeal from "./approvals/KeySeal.ts"; +import * as ApprovalCards from "./chat/approvalCards.ts"; import * as ExecutionNotices from "./chat/executionNotices.ts"; import * as KinPush from "./push/layer.ts"; import * as Promotion from "./levels/Promotion.ts"; @@ -49,9 +50,12 @@ const enabled = (seal: Layer.Layer) => KinApprovals.executorLayer.pipe( Layer.provide(ExecutionNotices.layer), Layer.provideMerge( - Layer.mergeAll(KinPush.layer, Promotion.layer, MemoryChanges.layer).pipe( - Layer.provideMerge(KinApprovals.layer), - ), + Layer.mergeAll( + KinPush.layer, + Promotion.layer, + MemoryChanges.layer, + ApprovalCards.layer, + ).pipe(Layer.provideMerge(KinApprovals.layer)), ), ), GithubWebhooks.lockLayer, diff --git a/apps/server/src/kin/levels/Promotion.test.ts b/apps/server/src/kin/levels/Promotion.test.ts index 2089a87e6c677..8b2779de4c5e6 100644 --- a/apps/server/src/kin/levels/Promotion.test.ts +++ b/apps/server/src/kin/levels/Promotion.test.ts @@ -14,6 +14,7 @@ import { KinPromotionCard, KinShadowReviewCard, KinWidgetId, + kinApprovalWidgetId, RpcScopeAuthorization, WsRpcGroup, WS_METHODS, @@ -24,6 +25,8 @@ import * as Context from "effect/Context"; import * as Effect from "effect/Effect"; import * as Layer from "effect/Layer"; import * as Option from "effect/Option"; +import * as Result from "effect/Result"; +import * as Stream from "effect/Stream"; import * as RpcGroup from "effect/rpc/RpcGroup"; import * as RpcTest from "effect/rpc/RpcTest"; import * as Schema from "effect/Schema"; @@ -36,6 +39,7 @@ import * as Audit from "../approvals/Audit.ts"; import { makeSetLevelHandler } from "../approvals/handlers/setLevel.ts"; import * as PendingActions from "../approvals/PendingActions.ts"; import * as Chat from "../chat/layer.ts"; +import { KinChatHub } from "../chat/KinChatHub.ts"; import { KinChatService } from "../chat/KinChatService.ts"; import * as Repository from "../chat/KinChatRepository.ts"; import { KinIdentity } from "../chat/KinIdentity.ts"; @@ -699,11 +703,40 @@ it.effect("a raise applies only through the claimed set_level action its own own it.effect("the executor applies an approved raise on a host without GitHub configured", () => Effect.gen(function* () { const ctx = yield* seed; - const { lead, client, widget, level, pending, sign } = ctx; + const { lead, client, widget, level, pending, sign, services, direct, owner, sql } = ctx; yield* eligible(ctx); + const events = yield* Context.get(services, KinChatHub).subscribeAll; const { actionId } = yield* client["kin.levels.raise"]({ ...lead, level: "L1" }); + // The raise waits on the owner as an approval card in the lead's direct chat. + const approvalCard = (closed: boolean) => + events.pipe( + Stream.filterMap((event) => + event.type === "widget.updated" && + event.widget.widgetId === kinApprovalWidgetId(actionId) && + (event.widget.closedAt !== null) === closed + ? Result.succeed(event.widget) + : Result.failVoid, + ), + Stream.runHead, + Effect.map(Option.getOrThrow), + ); + const waiting = sql<{ person: string; resolution: string | null }>` + SELECT person_id AS person, resolution FROM kin_waiting + WHERE widget_id = ${kinApprovalWidgetId(actionId)} AND reason = 'approval'`; + assert.deepInclude(yield* approvalCard(false), { + chatId: direct.chatId, + type: "approval", + awaiting: [owner.personId], + state: { actionId, revision: 0, state: "awaiting_approval" }, + }); + assert.deepStrictEqual(yield* waiting, [{ person: owner.personId, resolution: null }]); // Approved only: the production worker claims and runs it, with no credential check. yield* sign(actionId, { claim: false }); + assert.deepInclude(yield* approvalCard(true), { + awaiting: [], + state: { actionId, revision: 0, state: "approved" }, + }); + assert.deepStrictEqual(yield* waiting, [{ person: owner.personId, resolution: "approved" }]); yield* TestClock.adjust("1 second"); assert.deepInclude(Option.getOrThrow(yield* pending.get({ orgId: lead.orgId, actionId })), { state: "succeeded", @@ -711,7 +744,7 @@ it.effect("the executor applies an approved raise on a host without GitHub confi assert.strictEqual(yield* level, "L1"); const card = yield* widget(`promotion:${agentId}:L1`); assert.deepInclude(card && decodePromotion(card.state), { status: "raised" }); - }).pipe(Effect.provide(root)), + }).pipe(Effect.scoped, Effect.provide(root)), ); it.effect("lowering withdraws the raises it overtook and shows what stays open", () => diff --git a/packages/contracts/src/kinApprovals.ts b/packages/contracts/src/kinApprovals.ts index a69cc427730f0..da50a58e59edb 100644 --- a/packages/contracts/src/kinApprovals.ts +++ b/packages/contracts/src/kinApprovals.ts @@ -408,6 +408,9 @@ export const KinApprovalView = Schema.Union([ Schema.TaggedStruct("full", { action: KinPendingAction, canApprove: Schema.Literal(true), + /** Display names the server looked up: the lead it concerns, and `afterNonOwnerMessage`'s author. */ + leadName: Schema.optional(KinText), + afterNonOwnerName: Schema.optional(KinText), }), Schema.TaggedStruct("redacted", { actionId: KinActionId, @@ -423,6 +426,17 @@ export const KinApprovalView = Schema.Union([ ]); export type KinApprovalView = typeof KinApprovalView.Type; +// One approval card per action, so a client reads the action from a waiting item's widget id. +const KIN_APPROVAL_WIDGET_PREFIX = "kin-approval:"; +export const kinApprovalWidgetId = (actionId: KinActionId): string => + `${KIN_APPROVAL_WIDGET_PREFIX}${actionId}`; +const isKinActionId = Schema.is(KinActionId); +export const kinApprovalActionIdOf = (widgetId: string): KinActionId | null => { + if (!widgetId.startsWith(KIN_APPROVAL_WIDGET_PREFIX)) return null; + const actionId = widgetId.slice(KIN_APPROVAL_WIDGET_PREFIX.length); + return isKinActionId(actionId) ? actionId : null; +}; + export const KinApprovalListEvent = Schema.Union([ Schema.TaggedStruct("snapshot", { actions: Schema.Array(KinApprovalView) }), Schema.TaggedStruct("action", { action: KinApprovalView }), From 86bacb86bcf11407b0bcb46b66a45d2377006ede Mon Sep 17 00:00:00 2001 From: GLDRoger <130458023+GLDRoger@users.noreply.github.com> Date: Tue, 10 Nov 2026 11:39:24 +0530 Subject: [PATCH 2/8] feat(client-runtime): the approval card's presentation kinApprovalCardView draws a pending action as the owner's card (title, full head SHA, branches, method, changes, required checks, who asked, the lead's quoted reason, and one status line per state) or as the redacted card that names whom it waits on. A decision this device just made shows at once and leaves no button. kinApprovalFailure turns host refusals and the key module's error codes into one plain sentence and the next step. Co-Authored-By: Claude Opus 5.5 --- packages/client-runtime/package.json | 4 + .../src/kin/kinApprovalPresentation.test.ts | 262 ++++++++++ .../src/kin/kinApprovalPresentation.ts | 473 ++++++++++++++++++ .../src/kin/kinCardPresentation.ts | 6 + 4 files changed, 745 insertions(+) create mode 100644 packages/client-runtime/src/kin/kinApprovalPresentation.test.ts create mode 100644 packages/client-runtime/src/kin/kinApprovalPresentation.ts diff --git a/packages/client-runtime/package.json b/packages/client-runtime/package.json index f750fcd49a99e..c93300ebc2449 100644 --- a/packages/client-runtime/package.json +++ b/packages/client-runtime/package.json @@ -611,6 +611,10 @@ "types": "./src/kin/kinMemoryChangesPresentation.ts", "default": "./src/kin/kinMemoryChangesPresentation.ts" }, + "./kin/kinApprovalPresentation": { + "types": "./src/kin/kinApprovalPresentation.ts", + "default": "./src/kin/kinApprovalPresentation.ts" + }, "./kin/kinLevelsPresentation": { "types": "./src/kin/kinLevelsPresentation.ts", "default": "./src/kin/kinLevelsPresentation.ts" diff --git a/packages/client-runtime/src/kin/kinApprovalPresentation.test.ts b/packages/client-runtime/src/kin/kinApprovalPresentation.test.ts new file mode 100644 index 0000000000000..36e4d1978aba1 --- /dev/null +++ b/packages/client-runtime/src/kin/kinApprovalPresentation.test.ts @@ -0,0 +1,262 @@ +import { + KinApprovalError, + type EnvironmentId, + type KinApprovalView, + type KinPendingAction, + type KinWidget, +} from "@t3tools/contracts"; +import { describe, expect, it } from "vite-plus/test"; + +import { kinApprovalCardView, kinApprovalFailure } from "./kinApprovalPresentation.ts"; +import { kinCardView } from "./kinCardPresentation.ts"; + +const SHA = "a1b2c3d4e5f60718293a4b5c6d7e8f9012345678"; + +const merge = (overrides: Partial = {}) => + ({ + id: "act_1", + orgId: "kin-default", + idempotencyKey: "0".repeat(64), + kind: "merge_pull_request", + target: { + _tag: "pull_request", + host: "github.com", + repo: "GLDRoger/t3code", + number: 212, + mergeMethod: "squash", + deleteBranchAfter: true, + }, + resolved: { + _tag: "pull_request", + headSha: SHA, + base: "main", + head: "kin/fix-212", + title: "Fix the payments test", + additions: 120, + deletions: 30, + files: 4, + checks: [ + { name: "ci", required: true, status: "passed" }, + { name: "lint", required: false, status: "pending" }, + ], + }, + targetDigest: "f".repeat(64), + nonce: "n".repeat(43), + revision: 0, + reason: "CI is green and Priya asked for it.", + requestedBy: { agentId: "lead", threadId: "thread-lead" }, + provenance: { + startedBy: { humanId: "priya" }, + startedByRole: "member", + chain: [], + ceilingBelowOwner: true, + afterNonOwnerMessage: { humanId: "priya", messageId: "msg-1" }, + }, + requiredApprovers: [{ role: "owner" }], + state: "awaiting_approval", + createdAt: "2026-11-10T09:00:00.000Z", + updatedAt: "2026-11-10T09:00:00.000Z", + expiresAt: "2026-11-17T09:00:00.000Z", + ...overrides, + }) as unknown as KinPendingAction; + +const full = ( + action: KinPendingAction, + names: { leadName?: string; afterNonOwnerName?: string } = { + leadName: "Tech lead", + afterNonOwnerName: "Priya", + }, +) => ({ _tag: "full", action, canApprove: true, ...names }) as KinApprovalView; + +const prFacts = merge().resolved as Extract; + +describe("kinApprovalCardView", () => { + it("draws a merge from the host's facts, full SHA and who asked", () => { + const card = kinApprovalCardView(full(merge())); + expect(card).toMatchObject({ + eyebrow: "Approval needed", + title: "Merge #212 into main", + subtitle: "Fix the payments test", + asked: { text: "Asked for after Priya's message.", warning: true }, + reason: { label: "Tech lead says", text: "CI is green and Priya asked for it." }, + status: null, + settled: false, + decidable: true, + approveBlocked: null, + }); + expect(card.facts.map((fact) => [fact.label, fact.value])).toEqual([ + ["Repository", "GLDRoger/t3code"], + ["Commit", SHA], + ["Branches", "main ← kin/fix-212"], + ["Method", "Squash, then delete the branch"], + ["Changes", "4 files, +120 −30"], + ["Checks", "1 passed, 1 pending"], + ]); + // Only required checks are listed; an optional one pending doesn't hold Approve. + expect(card.checks.map((check) => [check.name, check.label])).toEqual([["ci", "Passed"]]); + }); + + it("names who asked from the provenance the host recorded", () => { + const asked = ( + provenance: Partial, + names: { leadName?: string; afterNonOwnerName?: string } = { leadName: "Tech lead" }, + ) => + kinApprovalCardView( + full( + merge({ + provenance: { + startedBy: { humanId: "kin-default-owner" }, + startedByRole: "owner", + chain: [], + ceilingBelowOwner: false, + ...provenance, + } as KinPendingAction["provenance"], + }), + names, + ), + ).asked; + expect(asked({})).toEqual({ text: "Asked by Tech lead.", warning: false }); + expect(asked({ ceilingBelowOwner: true, startedBy: "github" })).toEqual({ + text: "Asked for after activity on GitHub.", + warning: true, + }); + expect( + asked({ + ceilingBelowOwner: true, + afterNonOwnerMessage: { humanId: "priya", messageId: "m" }, + } as Partial), + ).toEqual({ text: "Asked for after someone else's message.", warning: true }); + }); + + it("holds Approve while a required check is pending or failed, never Decline", () => { + const withCheck = (status: "pending" | "failed") => + kinApprovalCardView( + full(merge({ resolved: { ...prFacts, checks: [{ name: "ci", required: true, status }] } })), + ); + expect(withCheck("pending")).toMatchObject({ + decidable: true, + approveBlocked: "Waiting for checks.", + }); + expect(withCheck("failed")).toMatchObject({ + decidable: true, + approveBlocked: "A required check failed.", + }); + }); + + it("a settled card offers nothing, including one this phone just decided", () => { + const waiting = full(merge()); + expect(kinApprovalCardView(waiting, { busy: "approving" })).toMatchObject({ + decidable: false, + status: "Waiting for Face ID…", + }); + // The submit's answer shows at once, before the host redraws. + expect(kinApprovalCardView(waiting, { decided: "approved" })).toMatchObject({ + settled: true, + decidable: false, + status: "Approved. Merging soon.", + }); + // Once the host moves on, its state wins over the local one. + expect( + kinApprovalCardView(full(merge({ state: "succeeded" })), { decided: "approved" }).status, + ).toBe("Merged."); + expect( + kinApprovalCardView(full(merge({ state: "failed", stateReason: "head_moved: HTTP 409" }))) + .status, + ).toBe( + "A new commit landed after you approved, so it didn't merge. Approve the new request instead.", + ); + expect(kinApprovalCardView(waiting, { decided: "rejected" })).toMatchObject({ + decidable: false, + status: "Declined.", + }); + }); + + it("a level raise names the lead and says the owner asked", () => { + const raise = merge({ + kind: "set_level", + target: { _tag: "level", agentId: "lead", level: "L1" }, + resolved: { _tag: "none" }, + reason: "Raise Tech lead to L1, from the owner's promotion card.", + requestedBy: { agentId: "kin-promotion", threadId: "kin-promotion" }, + provenance: { + startedBy: { humanId: "kin-default-owner" }, + startedByRole: "owner", + chain: [], + ceilingBelowOwner: false, + }, + } as unknown as Partial); + expect(kinApprovalCardView(full(raise, { leadName: "Tech lead" }))).toMatchObject({ + title: "Raise Tech lead to L1", + asked: { text: "You asked for this.", warning: false }, + reason: null, + decidable: true, + }); + }); + + it("anyone else sees who it waits on and never a button", () => { + const card = kinApprovalCardView({ + _tag: "redacted", + actionId: "act_1", + orgId: "kin-default", + kind: "merge_pull_request", + repo: "GLDRoger/t3code", + number: 212, + title: "Fix the payments test", + state: "awaiting_approval", + waitingOn: "Nishchay", + canApprove: false, + } as KinApprovalView); + expect(card).toMatchObject({ + eyebrow: "Waiting on Nishchay", + title: "Merge #212 in GLDRoger/t3code", + facts: [], + decidable: false, + }); + }); +}); + +describe("kinCardView approval", () => { + const widget = (overrides: Record) => + ({ + orgId: "kin-default", + chatId: "chat", + widgetId: "kin-approval:act_1", + messageId: "kin-approval:act_1", + widgetClass: "native", + type: "approval", + revision: 2, + state: { actionId: "act_1", revision: 0, state: "awaiting_approval" }, + source: null, + feed: null, + awaiting: [], + pinnedAt: null, + closedAt: null, + updatedAt: "2026-11-10T09:00:00.000Z", + ...overrides, + }) as unknown as KinWidget; + const view = (w: KinWidget) => kinCardView(w, "env" as EnvironmentId, () => true); + + it("reads only a server card whose id names its action", () => { + expect(view(widget({}))).toEqual({ + kind: "approval", + approval: { actionId: "act_1", state: "awaiting_approval", closed: false, revision: 2 }, + }); + expect(view(widget({ state: { actionId: "act_2" } })).kind).toBe("unknown"); + expect(view(widget({ widgetId: "w1" })).kind).toBe("unknown"); + }); +}); + +describe("kinApprovalFailure", () => { + it("says what to do next, and nothing when the owner canceled", () => { + expect(kinApprovalFailure(null, "E_USER_CANCELED")).toBeNull(); + expect(kinApprovalFailure(null, "E_KEY_INVALIDATED")).toMatchObject({ reenrol: true }); + const host = (reason: KinApprovalError["reason"]) => + kinApprovalFailure(new KinApprovalError({ reason, message: "x" })); + expect(host("head_moved")).toMatchObject({ refresh: true, reenrol: false }); + expect(host("unknown_key")).toMatchObject({ refresh: false, reenrol: true }); + expect(host("replayed")).toMatchObject({ text: "This was already decided.", refresh: true }); + expect(kinApprovalFailure(new Error("socket closed"))).toMatchObject({ + text: "Kin didn't answer. Try again.", + }); + }); +}); diff --git a/packages/client-runtime/src/kin/kinApprovalPresentation.ts b/packages/client-runtime/src/kin/kinApprovalPresentation.ts new file mode 100644 index 0000000000000..cf306e156f4c3 --- /dev/null +++ b/packages/client-runtime/src/kin/kinApprovalPresentation.ts @@ -0,0 +1,473 @@ +import { + KinActionId, + KinApprovalError, + KinPendingActionState, + kinApprovalActionIdOf, + type KinApprovalView, + type KinCheckRun, + type KinPendingAction, + type KinWidget, + type PullRequestMergeMethod, +} from "@t3tools/contracts"; +import * as Option from "effect/Option"; +import * as Schema from "effect/Schema"; + +import { kinSentences } from "./kinScreenState.ts"; + +/** What a chat message's approval widget says: which action, and where it stood when drawn. */ +export interface KinApprovalWidgetView { + readonly actionId: KinActionId; + readonly state: KinPendingActionState | null; + readonly closed: boolean; + /** Bumps whenever the host redraws the card, so a reader knows to read the action again. */ + readonly revision: number; +} + +const WidgetState = Schema.Struct({ + actionId: KinActionId, + state: Schema.optional(KinPendingActionState), +}); +const decodeWidgetState = Schema.decodeUnknownOption(WidgetState); + +/** Null when the widget isn't a server-drawn approval card for the action its id names. */ +export function kinApprovalWidgetView(widget: KinWidget): KinApprovalWidgetView | null { + const actionId = kinApprovalActionIdOf(widget.widgetId); + const state = decodeWidgetState(widget.state); + if (actionId === null || Option.isNone(state) || state.value.actionId !== actionId) return null; + return { + actionId, + state: state.value.state ?? null, + closed: widget.closedAt !== null, + revision: widget.revision, + }; +} + +/** Where the card is in Approve or Decline on this device; `null` while nothing is running. */ +export type KinApprovalBusy = "approving" | "declining"; + +export interface KinApprovalFact { + readonly key: string; + readonly label: string; + readonly value: string; + /** Long-press copies it; shown whole, never cut. */ + readonly selectable: boolean; +} + +export interface KinApprovalCheckRow { + readonly key: string; + readonly name: string; + readonly status: KinCheckRun["status"]; + readonly label: string; +} + +export interface KinApprovalCardView { + readonly actionId: KinActionId; + readonly eyebrow: string; + readonly title: string; + readonly subtitle: string | null; + readonly facts: ReadonlyArray; + readonly checks: ReadonlyArray; + /** Who asked; `warning` when the request didn't come from the owner alone. */ + readonly asked: { readonly text: string; readonly warning: boolean } | null; + readonly reason: { readonly label: string; readonly text: string } | null; + /** The settled outcome, or what is happening now. */ + readonly status: string | null; + readonly settled: boolean; + /** Approve and Decline are offered: the viewer approves, and the action still waits. */ + readonly decidable: boolean; + /** Why Approve is off while Decline stays available. */ + readonly approveBlocked: string | null; + readonly accessibilityLabel: string; +} + +// Agents write titles, reasons and branch names, so every shown string is clamped plain text. +const clamp = (text: string, max: number) => { + const chars = Array.from(text.replace(/\s+/g, " ").trim()); + return chars.length > max ? `${chars.slice(0, max - 1).join("")}…` : chars.join(""); +}; + +const METHOD: Record = { + squash: "Squash", + merge: "Merge commit", + rebase: "Rebase", +}; + +const CHECK_LABEL: Record = { + passed: "Passed", + failed: "Failed", + pending: "Pending", + skipped: "Skipped", +}; + +const count = (n: number, one: string, many = `${one}s`) => `${n} ${n === 1 ? one : many}`; + +function checksSummary(checks: ReadonlyArray): string { + if (checks.length === 0) return "None reported"; + const by = (status: KinCheckRun["status"]) => checks.filter((c) => c.status === status).length; + return [ + by("passed") > 0 ? `${by("passed")} passed` : null, + by("failed") > 0 ? `${by("failed")} failed` : null, + by("pending") > 0 ? `${by("pending")} pending` : null, + by("skipped") > 0 ? `${by("skipped")} skipped` : null, + ] + .filter((part) => part !== null) + .join(", "); +} + +type Settled = Exclude; + +/** One line per state; merges and level raises read differently only while they run or land. */ +function statusLine(action: KinPendingAction, state: KinPendingActionState): string | null { + const merge = action.kind === "merge_pull_request"; + const lines: Record = { + approved: merge ? "Approved. Merging soon." : "Approved. Applying soon.", + executing: merge ? "Approved. Merging now." : "Approved. Applying now.", + succeeded: merge ? "Merged." : "Done.", + failed: + action.stateReason?.startsWith("head_moved") === true + ? "A new commit landed after you approved, so it didn't merge. Approve the new request instead." + : "Approved, but it didn't run. Approve a new request to try again.", + interrupted: "Approved, but it didn't finish. Approve a new request to try again.", + rejected: "Declined.", + expired: "Expired before anyone decided.", + voided: "The approval lapsed before it ran.", + cancelled: "Withdrawn.", + }; + return state === "awaiting_approval" ? null : lines[state]; +} + +/** Plain status for a card drawn without its facts: web, desktop, or a redacted view. */ +export const KIN_APPROVAL_STATE_TEXT: Record = { + awaiting_approval: "Waiting for approval.", + approved: "Approved.", + executing: "Approved.", + succeeded: "Done.", + failed: "Didn't run.", + interrupted: "Didn't finish.", + rejected: "Declined.", + expired: "Expired.", + voided: "Lapsed.", + cancelled: "Withdrawn.", +}; + +// Requesters the server reserves for requests a person made, not a lead (approvals spec §8). +const PERSON_REQUESTERS = new Set(["kin-promotion", "kin-approver-keys"]); + +function askedLine(view: Extract) { + const { provenance, requestedBy } = view.action; + if (provenance.ceilingBelowOwner) { + const name = view.afterNonOwnerName === undefined ? null : clamp(view.afterNonOwnerName, 60); + const text = + provenance.afterNonOwnerMessage !== undefined + ? `Asked for after ${name || "someone else"}'s message.` + : provenance.startedBy === "github" + ? "Asked for after activity on GitHub." + : provenance.startedBy === "schedule" + ? "Asked for by a scheduled check." + : "Asked for after someone else's message."; + return { text, warning: true }; + } + if (PERSON_REQUESTERS.has(requestedBy.agentId)) + return { text: "You asked for this.", warning: false }; + const lead = view.leadName === undefined ? "" : clamp(view.leadName, 60); + return { text: `Asked by ${lead || "your lead"}.`, warning: false }; +} + +function fullView( + view: Extract, + input: { readonly decided: KinPendingActionState | null; readonly busy: KinApprovalBusy | null }, +): KinApprovalCardView { + const { action } = view; + // A decision this device just made shows at once; the host's newer state wins once it lands. + const state = + action.state === "awaiting_approval" && input.decided !== null ? input.decided : action.state; + const settled = state !== "awaiting_approval"; + const lead = view.leadName === undefined ? "" : clamp(view.leadName, 60); + let title: string; + let subtitle: string | null = null; + const facts: Array = []; + let checks: ReadonlyArray = []; + let approveBlocked: string | null = null; + const fact = (key: string, label: string, value: string, selectable = false) => + facts.push({ key, label, value, selectable }); + + if (action.target._tag === "pull_request" && action.resolved._tag === "pull_request") { + const { target, resolved } = action; + title = `Merge #${target.number} into ${clamp(resolved.base, 80)}`; + subtitle = clamp(resolved.title, 200) || null; + fact("repo", "Repository", target.repo); + // The full SHA, as the Face ID prompt shows it: an agent could grind a matching short one. + fact("commit", "Commit", resolved.headSha, true); + fact("branches", "Branches", `${clamp(resolved.base, 80)} ← ${clamp(resolved.head, 80)}`); + fact( + "method", + "Method", + `${METHOD[target.mergeMethod]}${target.deleteBranchAfter ? ", then delete the branch" : ""}`, + ); + fact( + "changes", + "Changes", + `${count(resolved.files, "file")}, +${resolved.additions} −${resolved.deletions}`, + ); + fact("checks", "Checks", checksSummary(resolved.checks)); + checks = resolved.checks + .filter((check) => check.required) + .map((check, index) => ({ + key: `${index}:${check.name}`, + name: clamp(check.name, 80), + status: check.status, + label: CHECK_LABEL[check.status], + })); + const required = resolved.checks.filter((check) => check.required); + approveBlocked = required.some((check) => check.status === "failed") + ? "A required check failed." + : required.some((check) => check.status === "pending") + ? "Waiting for checks." + : null; + } else if (action.target._tag === "level") { + const name = lead || action.target.agentId; + title = `Raise ${name} to ${action.target.level}`; + fact("lead", "Lead", name); + fact("level", "New level", action.target.level); + fact("where", "Applies to", action.target.chatId === undefined ? "All chats" : "One chat"); + } else { + title = "Approve this request"; + } + + const asked = askedLine(view); + const reason = PERSON_REQUESTERS.has(action.requestedBy.agentId) + ? null + : clamp(action.reason, 500) + ? { label: `${lead || "Your lead"} says`, text: clamp(action.reason, 500) } + : null; + const status = + input.busy === "approving" + ? "Waiting for Face ID…" + : input.busy === "declining" + ? "Declining…" + : statusLine(action, state); + const decidable = !settled && input.busy === null; + return { + actionId: action.id, + eyebrow: settled ? "Approval" : "Approval needed", + title, + subtitle, + facts, + checks, + asked, + reason, + status, + settled, + decidable, + approveBlocked: decidable ? approveBlocked : null, + accessibilityLabel: kinSentences([ + settled ? "Approval" : "Approval needed", + title, + subtitle, + ...facts.map((f) => `${f.label}: ${f.value}`), + asked.text, + reason === null ? null : `${reason.label}: ${reason.text}`, + status, + ]), + }; +} + +function redactedView(view: Extract): KinApprovalCardView { + const settled = view.state !== "awaiting_approval"; + const waitingOn = clamp(view.waitingOn, 60) || "the owner"; + const title = + view.kind === "merge_pull_request" && view.number !== null + ? `Merge #${view.number}${view.repo === null ? "" : ` in ${view.repo}`}` + : view.kind === "set_level" + ? "Change a lead's level" + : "A request for the owner"; + const subtitle = view.title === null ? null : clamp(view.title, 200) || null; + const eyebrow = settled ? "Approval" : `Waiting on ${waitingOn}`; + const status = settled ? KIN_APPROVAL_STATE_TEXT[view.state] : null; + return { + actionId: view.actionId, + eyebrow, + title, + subtitle, + facts: [], + checks: [], + asked: null, + reason: null, + status, + settled, + decidable: false, + approveBlocked: null, + accessibilityLabel: kinSentences([eyebrow, title, subtitle, status]), + }; +} + +/** + * The approval card, drawn only from the host's record of the action. `decided` is the state this + * device's own Approve or Decline just returned, shown until the host's redraw catches up. + */ +export function kinApprovalCardView( + view: KinApprovalView, + input: { + readonly decided?: KinPendingActionState | null; + readonly busy?: KinApprovalBusy | null; + } = {}, +): KinApprovalCardView { + return view._tag === "full" + ? fullView(view, { decided: input.decided ?? null, busy: input.busy ?? null }) + : redactedView(view); +} + +/** What the phone's key module rejects with; mirrors `KinApprovalKeyErrorCode`. */ +export type KinApprovalDeviceCode = + | "E_MODULE_UNAVAILABLE" + | "E_NO_SECURE_HARDWARE" + | "E_UNSUPPORTED_OS" + | "E_BIOMETRY_UNAVAILABLE" + | "E_BIOMETRY_LOCKOUT" + | "E_KEY_EXISTS" + | "E_KEY_NOT_FOUND" + | "E_KEY_INVALIDATED" + | "E_USER_CANCELED" + | "E_AUTH_FAILED" + | "E_BUSY" + | "E_NOT_A_GRANT" + | "E_NO_ACTIVITY" + | "E_OBSCURED" + | "E_ATTESTATION_FAILED" + | "E_INVALID_INPUT" + | "E_KEYCHAIN" + | "E_KEYSTORE"; + +/** Approve or Decline didn't land. `reenrol` means the fix is setting up this phone's key again. */ +export interface KinApprovalFailure { + readonly text: string; + /** Read the action again: the host changed it. */ + readonly refresh: boolean; + readonly reenrol: boolean; +} + +const DEVICE_TEXT: Record = { + // Canceling Face ID or the sheet is a choice, not a failure. + E_USER_CANCELED: null, + E_MODULE_UNAVAILABLE: { + text: "This build of the app can't approve. Update it, then try again.", + refresh: false, + reenrol: false, + }, + E_NO_SECURE_HARDWARE: { + text: "This device has no secure hardware for an approval key.", + refresh: false, + reenrol: false, + }, + E_UNSUPPORTED_OS: { + text: "Approving needs a newer version of the operating system.", + refresh: false, + reenrol: false, + }, + E_BIOMETRY_UNAVAILABLE: { + text: "Turn on Face ID for this app in Settings, then try again.", + refresh: false, + reenrol: false, + }, + E_BIOMETRY_LOCKOUT: { + text: "Face ID is locked. Unlock your phone with its passcode, then try again.", + refresh: false, + reenrol: false, + }, + E_KEY_EXISTS: { text: "This phone already has an approval key.", refresh: false, reenrol: false }, + E_KEY_NOT_FOUND: { + text: "This phone has no approval key. Set up approvals again.", + refresh: false, + reenrol: true, + }, + E_KEY_INVALIDATED: { + text: "Face ID changed since this phone's key was made. Set up approvals again.", + refresh: false, + reenrol: true, + }, + E_AUTH_FAILED: { text: "Face ID didn't match. Try again.", refresh: false, reenrol: false }, + E_BUSY: { text: "Another approval is open. Finish it first.", refresh: false, reenrol: false }, + E_NOT_A_GRANT: { + text: "Your phone refused to sign this request. Nothing was approved.", + refresh: true, + reenrol: false, + }, + E_NO_ACTIVITY: { + text: "Open the app and unlock your phone, then try again.", + refresh: false, + reenrol: false, + }, + E_OBSCURED: { + text: "Something covered the approval sheet, so nothing was signed. Try again.", + refresh: false, + reenrol: false, + }, + E_ATTESTATION_FAILED: { + text: "Your phone couldn't prove its key to Apple. Check your connection and try again.", + refresh: false, + reenrol: false, + }, + E_INVALID_INPUT: { + text: "Your phone refused to sign this request. Nothing was approved.", + refresh: true, + reenrol: false, + }, + E_KEYCHAIN: { text: "The keychain didn't answer. Try again.", refresh: false, reenrol: false }, + E_KEYSTORE: { text: "The keystore didn't answer. Try again.", refresh: false, reenrol: false }, +}; + +const isApprovalError = Schema.is(KinApprovalError); + +/** Plain text for what went wrong, or null when nothing needs saying (the user canceled). */ +export function kinApprovalFailure( + cause: unknown, + deviceCode: KinApprovalDeviceCode | null = null, +): KinApprovalFailure | null { + if (deviceCode !== null) return DEVICE_TEXT[deviceCode]; + if (!isApprovalError(cause)) + return { text: "Kin didn't answer. Try again.", refresh: false, reenrol: false }; + switch (cause.reason) { + case "stale": + case "head_moved": + case "target_mismatch": + return { + text: "This changed since you opened it. Check it again before you approve.", + refresh: true, + reenrol: false, + }; + case "invalid_state": + case "replayed": + return { text: "This was already decided.", refresh: true, reenrol: false }; + case "unknown_key": + case "revoked_key": + case "unattested": + return { + text: "This phone's approval key isn't active. Set up approvals again.", + refresh: false, + reenrol: true, + }; + case "time_window": + return { + text: "Your phone's clock is off. Set it automatically, then try again.", + refresh: false, + reenrol: false, + }; + case "not_owner": + case "session_mismatch": + return { text: "Only the owner can decide this.", refresh: false, reenrol: false }; + case "not_found": + return { text: "This request is gone.", refresh: true, reenrol: false }; + case "unavailable": + return { + text: clamp(cause.message, 200) || "Kin can't approve this right now. Try again later.", + refresh: false, + reenrol: false, + }; + default: + return { + text: "Kin refused this approval. Nothing changed.", + refresh: true, + reenrol: false, + }; + } +} diff --git a/packages/client-runtime/src/kin/kinCardPresentation.ts b/packages/client-runtime/src/kin/kinCardPresentation.ts index 447e03789c273..f9ad3f63b0962 100644 --- a/packages/client-runtime/src/kin/kinCardPresentation.ts +++ b/packages/client-runtime/src/kin/kinCardPresentation.ts @@ -13,6 +13,7 @@ import { import * as Option from "effect/Option"; import * as Schema from "effect/Schema"; +import { kinApprovalWidgetView, type KinApprovalWidgetView } from "./kinApprovalPresentation.ts"; import { kinLinkLabel, kinSafeWebUrl } from "./kinLinks.ts"; import { kinSentences } from "./kinScreenState.ts"; import { kinChoiceCardView, type KinChoiceCardView } from "./kinChoicePresentation.ts"; @@ -58,6 +59,7 @@ export type KinCardView = | { readonly kind: "digest"; readonly digest: KinDigestCardView } | KinLevelsCardView | { readonly kind: "memory_changes"; readonly changes: KinMemoryChangesCardView } + | { readonly kind: "approval"; readonly approval: KinApprovalWidgetView } | { readonly kind: "missing" } | { readonly kind: "unknown" }; @@ -405,6 +407,10 @@ export function kinCardView( case "shadow_review": case "promotion": return kinLevelsCardView(widget) ?? { kind: "unknown" }; + case "approval": { + const approval = kinApprovalWidgetView(widget); + return approval === null ? { kind: "unknown" } : { kind: "approval", approval }; + } case KIN_MEMORY_CHANGES_CARD: { const changes = kinMemoryChangesView(widget); return changes === null ? { kind: "unknown" } : { kind: "memory_changes", changes }; From a48d730bf3d717161c2bb8ffeb707396c3d47213 Mon Sep 17 00:00:00 2001 From: GLDRoger <130458023+GLDRoger@users.noreply.github.com> Date: Tue, 10 Nov 2026 12:00:53 +0530 Subject: [PATCH 3/8] feat(mobile): approve Kin merges and level raises with Face ID The owner sees an approval card in the lead's chat, in Waiting on you and on the lead's levels screen. Every fact on the card comes from kin.approvals.get. Approve takes the server's challenge, checks it against the card the owner read, signs it with the Secure Enclave key behind Face ID and submits it. Decline rejects at the shown revision. A new Approvals screen enrols the key through the existing challenge, attested register and desktop confirm flow. Simulators get a plain "can't approve" state instead of a keychain error. Co-Authored-By: Claude Opus 5.5 --- .../src/features/chats/KinLevelsScreen.tsx | 13 +- .../src/features/chats/KinWaitingScreen.tsx | 77 +++-- .../chats/approvals/KinApprovalsScreen.tsx | 235 +++++++++++++++ .../chats/approvals/approverKeyRecord.ts | 43 +++ .../chats/approvals/useKinApproverKey.ts | 283 +++++++++++++++++ apps/mobile/src/features/chats/routes.tsx | 6 + .../src/features/chats/state/kinClient.ts | 59 ++++ .../chats/widgets/KinApprovalCard.tsx | 284 ++++++++++++++++++ .../features/chats/widgets/KinWidgetView.tsx | 9 + 9 files changed, 987 insertions(+), 22 deletions(-) create mode 100644 apps/mobile/src/features/chats/approvals/KinApprovalsScreen.tsx create mode 100644 apps/mobile/src/features/chats/approvals/approverKeyRecord.ts create mode 100644 apps/mobile/src/features/chats/approvals/useKinApproverKey.ts create mode 100644 apps/mobile/src/features/chats/widgets/KinApprovalCard.tsx diff --git a/apps/mobile/src/features/chats/KinLevelsScreen.tsx b/apps/mobile/src/features/chats/KinLevelsScreen.tsx index a46b4d2f7bd40..b19609b7c495a 100644 --- a/apps/mobile/src/features/chats/KinLevelsScreen.tsx +++ b/apps/mobile/src/features/chats/KinLevelsScreen.tsx @@ -25,6 +25,7 @@ import { ScreenScrollView } from "../../components/ui/ScreenScrollView"; import { appAtomRegistry } from "../../state/atom-registry"; import { useAtomCommand } from "../../state/use-atom-command"; import { kinClient } from "./state/kinClient"; +import { KinApprovalCard } from "./widgets/KinApprovalCard"; import { kinChatTitle, kinDirectory } from "@t3tools/client-runtime/kin/kinScreenState"; import { useKinHostAt } from "./state/useKinHost"; import { @@ -170,7 +171,7 @@ function KinLevelsBody(props: { text: change.kind === "lower" ? `Lowered to ${change.level}.` - : `Raise to ${change.level} requested. It applies once you sign the approval.`, + : `Raise to ${change.level} requested. Approve it below with Face ID.`, error: false, }); }; @@ -272,6 +273,16 @@ function KinLevelsBody(props: { ))} )} + {result.value.pendingRaises + .filter((raise) => raise.state === "awaiting_approval") + .map((raise) => ( + + ))} {view.chats.length === 0 ? null : ( diff --git a/apps/mobile/src/features/chats/KinWaitingScreen.tsx b/apps/mobile/src/features/chats/KinWaitingScreen.tsx index 91305afbe699a..d47aa20f3c4a1 100644 --- a/apps/mobile/src/features/chats/KinWaitingScreen.tsx +++ b/apps/mobile/src/features/chats/KinWaitingScreen.tsx @@ -1,5 +1,8 @@ import { useNavigation } from "@react-navigation/native"; +import { kinApprovalActionIdOf } from "@t3tools/contracts"; +import { View } from "react-native"; +import { Button } from "../../components/ui/Button"; import { EmptyState } from "../../components/ui/EmptyState"; import { ListRow } from "../../components/ui/ListRow"; import { ListSection } from "../../components/ui/ListSection"; @@ -11,8 +14,9 @@ import { kinWaitingRowView, } from "@t3tools/client-runtime/kin/kinScreenState"; import { useKinInbox } from "./state/useKinInbox"; +import { KinApprovalCard } from "./widgets/KinApprovalCard"; -/** Placeholder Waiting on you until the native cards land: one row per item, oldest first. */ +/** Waiting on you, oldest first: approvals as their full cards, everything else as a row. */ export function KinWaitingScreen() { const navigation = useNavigation(); const { host, state, retry } = useKinInbox(); @@ -30,28 +34,59 @@ export function KinWaitingScreen() { /> ); } + const openChat = (item: (typeof view.waiting)[number]) => + navigation.navigate("KinChat", { + environmentId: ready.environmentId, + orgId: item.orgId, + chatId: item.chatId, + }); + const approvals = view.waiting.flatMap((item) => { + const actionId = + item.reason === "approval" && item.widgetId !== null + ? kinApprovalActionIdOf(item.widgetId) + : null; + return actionId === null ? [] : [{ item, actionId }]; + }); + const rest = view.waiting.filter( + (item) => !approvals.some((approval) => approval.item.waitingId === item.waitingId), + ); return ( - - {view.waiting.map((item) => { - const row = kinWaitingRowView(item, ready.inbox.value.chats, agentNames); - return ( - - navigation.navigate("KinChat", { - environmentId: ready.environmentId, - orgId: item.orgId, - chatId: item.chatId, - }) - } + <> + {approvals.map(({ item, actionId }) => ( + + - ); - })} - + + + + ) : ( + pending.map((key) => ( + appAtomRegistry.refresh(atom)} + /> + )) + )} + + ); +} + +function ConfirmKey(props: { + readonly environmentId: EnvironmentId; + readonly approverKey: KinApproverKey; + readonly onDone: () => void; +}) { + const { approverKey } = props; + const confirm = useAtomCommand(kinClient.confirmKey, { reportFailure: false }); + const [code, setCode] = useState(""); + const [busy, setBusy] = useState(false); + const [error, setError] = useState(null); + const valid = /^\d{6}$/.test(code); + + const submit = async () => { + if (!valid || busy) return; + setBusy(true); + setError(null); + const result = await confirm({ + environmentId: props.environmentId, + input: { orgId: approverKey.orgId, thumbprint: approverKey.thumbprint, code }, + }); + setBusy(false); + if (AsyncResult.isFailure(result)) { + const cause = squashAtomCommandFailure(result); + // The server writes these refusals for the owner ("The code doesn't match the phone."). + setError(isApprovalError(cause) ? cause.message : "Kin didn't answer. Try again."); + return; + } + props.onDone(); + }; + + return ( +
{ + event.preventDefault(); + void submit(); + }} + > + +
+ setCode(event.target.value.replace(/\D/g, "").slice(0, 6))} + /> + +
+ {error === null ? null : ( +

+ {error} +

+ )} +
+ ); +} diff --git a/apps/web/src/kin/KinCards.tsx b/apps/web/src/kin/KinCards.tsx index 69fc252d3584b..6cfbd0298dff5 100644 --- a/apps/web/src/kin/KinCards.tsx +++ b/apps/web/src/kin/KinCards.tsx @@ -27,6 +27,10 @@ import { type KinDeferralActionId, type KinDeferralCardView, } from "@t3tools/client-runtime/kin/kinDeferralPresentation"; +import { + KIN_APPROVAL_STATE_TEXT, + type KinApprovalWidgetView, +} from "@t3tools/client-runtime/kin/kinApprovalPresentation"; import type { KinLevelsCardView } from "@t3tools/client-runtime/kin/kinLevelsPresentation"; import { kinMemoryUndoFailureText, @@ -134,6 +138,8 @@ export const KinCard = memo(function KinCard(props: { case "shadow_review": case "promotion": return ; + case "approval": + return ; case "missing": case "unknown": return ( @@ -517,6 +523,21 @@ function KinLevelsCard(props: { readonly view: KinLevelsCardView }) { ); } +/** Only the phone's approval key signs, so here the card says where it stands and where to go. */ +function KinApprovalCard(props: { readonly approval: KinApprovalWidgetView }) { + const { approval } = props; + const open = !approval.closed; + const status = approval.state === null ? null : KIN_APPROVAL_STATE_TEXT[approval.state]; + return ( + + {open ? :

{status}

} +
+ ); +} + /** Approvals need the phone's device key, so the browser points there instead. */ export function ApproveOnPhone() { return ( diff --git a/apps/web/src/kin/KinPage.tsx b/apps/web/src/kin/KinPage.tsx index 8de40b24c6041..8025028a1282e 100644 --- a/apps/web/src/kin/KinPage.tsx +++ b/apps/web/src/kin/KinPage.tsx @@ -28,6 +28,7 @@ import { WorkspacePageHeader } from "../components/WorkspacePageHeader"; import { isElectron } from "../env"; import { cn } from "../lib/utils"; import { KinAvatar } from "./KinAvatar"; +import { KinApproverKeyConfirm } from "./KinApproverKeys"; import { ApproveOnPhone } from "./KinCards"; import { startKinOutbox } from "./kinOutbox"; import { useKinInbox } from "./useKinHost"; @@ -176,6 +177,7 @@ function KinChatList(props: { directory={props.directory} environmentId={state.environmentId} /> + ); if (rows.length === 0) { diff --git a/apps/web/src/kin/kinClient.ts b/apps/web/src/kin/kinClient.ts index 3b73c3651b2cf..c9e57690ba31c 100644 --- a/apps/web/src/kin/kinClient.ts +++ b/apps/web/src/kin/kinClient.ts @@ -13,8 +13,10 @@ import { environmentSessionGenerationAtom, } from "@t3tools/client-runtime/state/runtime"; import { + KIN_APPROVAL_WS_METHODS, KIN_CHAT_WS_METHODS, type EnvironmentId, + type KinApprovalsOrgInput, type KinChatHistoryInput, type KinOrgsListInput, } from "@t3tools/contracts"; @@ -60,6 +62,11 @@ function guardedRead(command: { const readOrgs = guardedRead(orgsRead); const readHistory = guardedRead(historyRead); +const approverKeysRead = createEnvironmentRpcCommand(connectionAtomRuntime, { + label: "kin:approver-keys:read", + tag: KIN_APPROVAL_WS_METHODS.listKeys, +}); +const readApproverKeys = guardedRead(approverKeysRead); // Hosts that answered `kin.orgs.list` this run: their `unavailable` is an outage to wait out. const knownKinHosts = new Set(); @@ -130,6 +137,18 @@ export const kinClient = { key: ({ input }) => `${input.messageId}|${input.emoji}`, }, }), + /** The org's approver keys, so the desktop can confirm the first phone's. */ + approverKeys: createEnvironmentQueryAtomFamily(connectionAtomRuntime, { + label: "kin:approver-keys", + execute: Effect.fn("KinWebClient.approverKeys")(function* (input: KinApprovalsOrgInput) { + return yield* readApproverKeys(input); + }), + staleTimeMs: 10_000, + }), + confirmKey: createEnvironmentRpcCommand(connectionAtomRuntime, { + label: "kin:approver-key:confirm", + tag: KIN_APPROVAL_WS_METHODS.confirmKey, + }), memoryUndo: createEnvironmentRpcCommand(connectionAtomRuntime, { label: "kin:memory:undo", tag: "kin.memory.undo", From ebd7d22f5a5a29a9fda3e7b9a89c884adaa1ba06 Mon Sep 17 00:00:00 2001 From: GLDRoger <130458023+GLDRoger@users.noreply.github.com> Date: Tue, 10 Nov 2026 12:07:35 +0530 Subject: [PATCH 5/8] fix(mobile): approval enrolment compiles under the React Compiler Co-Authored-By: Claude Opus 5.5 --- .../chats/approvals/useKinApproverKey.ts | 25 +++++++++++++------ 1 file changed, 17 insertions(+), 8 deletions(-) diff --git a/apps/mobile/src/features/chats/approvals/useKinApproverKey.ts b/apps/mobile/src/features/chats/approvals/useKinApproverKey.ts index b77d835145420..e4d57f39a9d25 100644 --- a/apps/mobile/src/features/chats/approvals/useKinApproverKey.ts +++ b/apps/mobile/src/features/chats/approvals/useKinApproverKey.ts @@ -125,7 +125,7 @@ export function useEnrolApproverKey() { readonly replace: boolean; }): Promise => { const { environmentId, orgId } = input; - try { + return orDeviceFailure(async () => { if (input.replace) { await ApprovalKey.deleteKey(); await clearApproverKeyRecord(); @@ -165,16 +165,25 @@ export function useEnrolApproverKey() { }); appAtomRegistry.refresh(kinClient.approverKeys({ environmentId, input: { orgId } })); return { ok: true }; - } catch (error) { - const code = deviceCodeOf(error); - const outcome = failedFrom(error, code); - return outcome._tag === "canceled" - ? null - : { ok: false, text: outcome.failure.text, keyExists: code === "E_KEY_EXISTS" }; - } + }); }; } +// Outside the hook: the React Compiler can't compile value blocks inside try/catch. +async function orDeviceFailure( + run: () => Promise, +): Promise { + try { + return await run(); + } catch (error) { + const code = deviceCodeOf(error); + const outcome = failedFrom(error, code); + return outcome._tag === "canceled" + ? null + : { ok: false, text: outcome.failure.text, keyExists: code === "E_KEY_EXISTS" }; + } +} + function hostText(cause: unknown) { return kinApprovalFailure(cause)?.text ?? "Kin didn't answer. Try again."; } From 2886f21eba33116d6c344dcb26db5ac58944678e Mon Sep 17 00:00:00 2001 From: GLDRoger <130458023+GLDRoger@users.noreply.github.com> Date: Tue, 10 Nov 2026 12:43:00 +0530 Subject: [PATCH 6/8] fix(kin): the host confirms the first phone, and a second phone enrols from the first - `t3 kin approvals confirm-key` lists pending attested keys and takes the phone's code in one attempt-limited transaction bound to the org, key, session and challenge; `--recover` revokes the person's other keys, audited. The desktop loopback path and `kin.approvals.confirmKey` are gone. - Codes live in kin_approver_key_confirmations (K031) as an HMAC, so the CLI, a separate process, can check them and a SQLite write can't forge one. - `listKeys` returns pending enrolments; the active phone signs them from its Approvals screen. Approval controls are gated on their permission atoms. - Approval cards read the action inside their transaction, never reopen or go back a revision, reconcile per org, and log through toPersistenceSqlError. - GrantVerifier's name lookups get a deterministic ORDER BY. Co-Authored-By: Claude Opus 5.5 --- .../chats/approvals/KinApprovalsScreen.tsx | 96 +++-- .../chats/approvals/useKinApproverKey.ts | 23 +- .../chats/widgets/KinApprovalCard.tsx | 34 +- .../src/kin/approvals/ApproverKeyStore.ts | 253 ++++++++++++ .../src/kin/approvals/ApproverKeys.test.ts | 210 ++++++---- apps/server/src/kin/approvals/ApproverKeys.ts | 374 ++++-------------- .../src/kin/approvals/GrantVerifier.test.ts | 16 +- .../server/src/kin/approvals/GrantVerifier.ts | 22 +- .../src/kin/approvals/HostKeyCeremony.ts | 243 ++++++++++++ apps/server/src/kin/approvals/KeySeal.ts | 56 ++- .../src/kin/approvals/rpcHandlers.test.ts | 24 +- apps/server/src/kin/approvals/rpcHandlers.ts | 18 +- .../server/src/kin/chat/approvalCards.test.ts | 145 +++++++ apps/server/src/kin/chat/approvalCards.ts | 335 +++++++++------- apps/server/src/kin/cli/approvals.ts | 203 ++++++++++ apps/server/src/kin/cli/lead.ts | 2 + .../src/kin/persistence/KinMigrations.test.ts | 11 +- .../src/kin/persistence/KinMigrations.ts | 2 + .../K033_ApproverKeyConfirmations.ts | 22 ++ apps/web/src/kin/KinApproverKeys.tsx | 144 ------- apps/web/src/kin/KinPage.tsx | 2 - apps/web/src/kin/kinClient.ts | 19 - docs/kin/specs/approvals.md | 19 +- ops/kin/host/README.md | 21 + .../src/kin/kinApprovalPresentation.test.ts | 35 +- .../src/kin/kinApprovalPresentation.ts | 21 +- .../src/state/commandPermissions.test.ts | 20 + packages/contracts/src/kinApprovals.ts | 23 +- packages/contracts/src/kinRpcs.ts | 1 - 29 files changed, 1580 insertions(+), 814 deletions(-) create mode 100644 apps/server/src/kin/approvals/ApproverKeyStore.ts create mode 100644 apps/server/src/kin/approvals/HostKeyCeremony.ts create mode 100644 apps/server/src/kin/chat/approvalCards.test.ts create mode 100644 apps/server/src/kin/cli/approvals.ts create mode 100644 apps/server/src/kin/persistence/migrations/K033_ApproverKeyConfirmations.ts delete mode 100644 apps/web/src/kin/KinApproverKeys.tsx diff --git a/apps/mobile/src/features/chats/approvals/KinApprovalsScreen.tsx b/apps/mobile/src/features/chats/approvals/KinApprovalsScreen.tsx index c88899c849e1b..967f1dd97b80c 100644 --- a/apps/mobile/src/features/chats/approvals/KinApprovalsScreen.tsx +++ b/apps/mobile/src/features/chats/approvals/KinApprovalsScreen.tsx @@ -16,6 +16,7 @@ import { ErrorBanner } from "../../../components/ui/ErrorBanner"; import { ScreenContent } from "../../../components/ui/ScreenContent"; import { ScreenScrollView } from "../../../components/ui/ScreenScrollView"; import { kinClient } from "../state/kinClient"; +import { KinApprovalCard } from "../widgets/KinApprovalCard"; import { useEnrolApproverKey, useKinApproverKey } from "./useKinApproverKey"; type KinApprovalsParams = { readonly environmentId: string; readonly orgId: string }; @@ -63,7 +64,9 @@ function ApprovalsBody(props: { readonly environmentId: EnvironmentId; readonly const { environmentId, orgId } = props; const { status, refresh } = useKinApproverKey(environmentId, orgId); const enrol = useEnrolApproverKey(); - const canEnrol = useAtomValue(kinClient.registerKey.permissionAtom(environmentId)); + const canChallenge = useAtomValue(kinClient.keyChallenge.permissionAtom(environmentId)); + const canRegister = useAtomValue(kinClient.registerKey.permissionAtom(environmentId)); + const canEnrol = canChallenge && canRegister; const [working, setWorking] = useState(false); const [problem, setProblem] = useState<{ readonly text: string; @@ -71,7 +74,7 @@ function ApprovalsBody(props: { readonly environmentId: EnvironmentId; readonly } | null>(null); const start = async (replace: boolean) => { - if (working) return; + if (working || !canEnrol) return; setWorking(true); setProblem(null); const result = await enrol({ environmentId, orgId, replace }); @@ -126,8 +129,35 @@ function ApprovalsBody(props: { readonly environmentId: EnvironmentId; readonly const actions = (primary: ReactNode) => ( {primary} ); + const cantEnrolLine = canEnrol ? null : ( + + This device can't set up approvals. Pair it again from the Kin host. + + ); const remake = (label: string) => - actions( - - ) : ( - pending.map((key) => ( - appAtomRegistry.refresh(atom)} - /> - )) - )} - - ); -} - -function ConfirmKey(props: { - readonly environmentId: EnvironmentId; - readonly approverKey: KinApproverKey; - readonly onDone: () => void; -}) { - const { approverKey } = props; - const confirm = useAtomCommand(kinClient.confirmKey, { reportFailure: false }); - const [code, setCode] = useState(""); - const [busy, setBusy] = useState(false); - const [error, setError] = useState(null); - const valid = /^\d{6}$/.test(code); - - const submit = async () => { - if (!valid || busy) return; - setBusy(true); - setError(null); - const result = await confirm({ - environmentId: props.environmentId, - input: { orgId: approverKey.orgId, thumbprint: approverKey.thumbprint, code }, - }); - setBusy(false); - if (AsyncResult.isFailure(result)) { - const cause = squashAtomCommandFailure(result); - // The server writes these refusals for the owner ("The code doesn't match the phone."). - setError(isApprovalError(cause) ? cause.message : "Kin didn't answer. Try again."); - return; - } - props.onDone(); - }; - - return ( -
{ - event.preventDefault(); - void submit(); - }} - > - -
- setCode(event.target.value.replace(/\D/g, "").slice(0, 6))} - /> - -
- {error === null ? null : ( -

- {error} -

- )} -
- ); -} diff --git a/apps/web/src/kin/KinPage.tsx b/apps/web/src/kin/KinPage.tsx index 8025028a1282e..8de40b24c6041 100644 --- a/apps/web/src/kin/KinPage.tsx +++ b/apps/web/src/kin/KinPage.tsx @@ -28,7 +28,6 @@ import { WorkspacePageHeader } from "../components/WorkspacePageHeader"; import { isElectron } from "../env"; import { cn } from "../lib/utils"; import { KinAvatar } from "./KinAvatar"; -import { KinApproverKeyConfirm } from "./KinApproverKeys"; import { ApproveOnPhone } from "./KinCards"; import { startKinOutbox } from "./kinOutbox"; import { useKinInbox } from "./useKinHost"; @@ -177,7 +176,6 @@ function KinChatList(props: { directory={props.directory} environmentId={state.environmentId} /> - ); if (rows.length === 0) { diff --git a/apps/web/src/kin/kinClient.ts b/apps/web/src/kin/kinClient.ts index c9e57690ba31c..3b73c3651b2cf 100644 --- a/apps/web/src/kin/kinClient.ts +++ b/apps/web/src/kin/kinClient.ts @@ -13,10 +13,8 @@ import { environmentSessionGenerationAtom, } from "@t3tools/client-runtime/state/runtime"; import { - KIN_APPROVAL_WS_METHODS, KIN_CHAT_WS_METHODS, type EnvironmentId, - type KinApprovalsOrgInput, type KinChatHistoryInput, type KinOrgsListInput, } from "@t3tools/contracts"; @@ -62,11 +60,6 @@ function guardedRead(command: { const readOrgs = guardedRead(orgsRead); const readHistory = guardedRead(historyRead); -const approverKeysRead = createEnvironmentRpcCommand(connectionAtomRuntime, { - label: "kin:approver-keys:read", - tag: KIN_APPROVAL_WS_METHODS.listKeys, -}); -const readApproverKeys = guardedRead(approverKeysRead); // Hosts that answered `kin.orgs.list` this run: their `unavailable` is an outage to wait out. const knownKinHosts = new Set(); @@ -137,18 +130,6 @@ export const kinClient = { key: ({ input }) => `${input.messageId}|${input.emoji}`, }, }), - /** The org's approver keys, so the desktop can confirm the first phone's. */ - approverKeys: createEnvironmentQueryAtomFamily(connectionAtomRuntime, { - label: "kin:approver-keys", - execute: Effect.fn("KinWebClient.approverKeys")(function* (input: KinApprovalsOrgInput) { - return yield* readApproverKeys(input); - }), - staleTimeMs: 10_000, - }), - confirmKey: createEnvironmentRpcCommand(connectionAtomRuntime, { - label: "kin:approver-key:confirm", - tag: KIN_APPROVAL_WS_METHODS.confirmKey, - }), memoryUndo: createEnvironmentRpcCommand(connectionAtomRuntime, { label: "kin:memory:undo", tag: "kin.memory.undo", diff --git a/docs/kin/specs/approvals.md b/docs/kin/specs/approvals.md index fd07f8f54bb4d..330464e042ee8 100644 --- a/docs/kin/specs/approvals.md +++ b/docs/kin/specs/approvals.md @@ -204,12 +204,13 @@ export const KinApproverKey = Schema.Struct({ Registration: -1. The phone calls `kin.approvals.keyChallenge()` (`access:write`), which returns a single-use 32-byte nonce bound to that session and valid for 5 minutes. It passes the nonce to `createKey`, then calls `kin.approvals.registerKey({publicJwk, platform, challenge, attestation?, deviceLabel})` over the same session. The server consumes the nonce, stores the key as `pending` and returns a 6-digit code derived from `sha256(thumbprint ‖ serverNonce)`, where `serverNonce` is that challenge. Challenges and codes live in server memory: a code is good for 10 minutes and five tries, and after a restart the phone makes and registers a new key. A thumbprint registers only once. +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 live in server memory, so after a restart the phone asks for a new one. An attested key's code is stored with it in `kin_approver_key_confirmations` (K031), so the host CLI below, a separate process, can check it: a code is good for 10 minutes and five tries, and the row holds only an HMAC (`KinKeySeal.confirmation`, keyed by the seal secret) over the org, thumbprint, public JWK, person, hardware, registering session, `sha256(challenge)` and the code. A row edited or inserted in SQLite therefore never verifies. A thumbprint registers only once. - **Android:** `attestation.certificateChain` is required. The server checks it offline: the chain verifies up to one of Google's two hardware attestation roots (the legacy RSA root and the newer ECDSA root), each pinned by its public key, and no certificate is on Google's attestation revocation list; the leaf's public key equals `publicJwk` and is EC P-256; the KeyDescription is read from the leaf only, and a chain where any other certificate carries one is refused; 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 with `ecCurve` P-256 and `keySize` 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; `allApplications` absent from both authorization lists; `attestationApplicationId` names exactly one package, 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. Invalidation on biometric re-enrolment is checked only on the client (`KeyInfo` after creation, README); attestation can't prove it. 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:** `attestation` is `{format: "apple-app-attest", keyId, attestationObject}`. `createKey` makes it natively: a fresh App Attest key, attested over the client data hash `sha256(challenge ‖ 0x04 ‖ x ‖ y)` of the Secure Enclave key it just made. The module computes that hash itself, so JS can't get an attestation over a key or data it chose. The server follows Apple's documented verification: the `x5c` chain verifies to the pinned Apple App Attest root; the nonce extension (OID `1.2.840.113635.100.8.2`) equals `sha256(authData ‖ clientDataHash)`, where the server recomputes `clientDataHash` from the nonce it issued and `publicJwk`; the credential certificate's public key hashes to `keyId`; `authData`'s RP ID hash is `sha256(".")` for the Kin bundle id; the counter is 0; the aaguid is `appattest` followed by seven zero bytes for production builds, and `appattestdevelop` only on a server configured to accept development builds; the credential id equals `keyId`. All pass: `attested: true`, `hardware: "secure_enclave"`. No attestation (a simulator or an unsupported device) or any failed check: `attested: false`, `hardware: "software"`. The attestation object's `fmt` must be `apple-appattest` (the CBOR field, distinct from the client's `format` label `apple-app-attest`). `keyId` is `sha256` of the credential certificate's public key as the 65-byte X9.63 point, not its SPKI. Every certificate in `x5c` must be valid at verification time. The App Attest key is used only here; nothing later asserts with it, so the attestation's receipt isn't needed. App Attest proves the app, not its version: once several native builds have shipped, the server keeps a minimum native build (or a version allowlist) and refuses registration from older ones. On iOS `attested: true` means a genuine Kin app instance asked for this public key. It does not prove the approver key is in the Secure Enclave or gated by biometrics, and it does not detect a jailbroken phone; Android's attestation does prove hardware storage and a verified, locked boot. The owner accepted this weaker meaning for phase 1 (2026-11-09), since without it no iPhone could approve. `hardware: "secure_enclave"` is claimed by the platform, not proven. - - **Either platform:** the server never makes a key with `attested: false` `active`. It is listed as "can't be used for approvals" and can only be revoked; `confirmKey` refuses it, and no `register_approver_key` action can be requested for it. This is what stops tampered JS from deleting the hardware key, making a P-256 key in JS and registering it: the 6-digit code would match, because it derives from whatever key was registered, but that key can't be attested. -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. Its `device_key` target carries the new key's `hardware` and `attested` from the server's record, so the phone's prompt shows them (`Add approver key NzbLsXh8uDCcd-6MNwXF4W_7noWXFZAfHkxZsRGC9Xs (Secure Enclave, attested)`), and the module refuses a target that isn't attested. 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. + - **Either platform:** the server never makes a key with `attested: false` `active`. It is listed as "can't be used for approvals" and can only be revoked; it gets no stored code, so the host can't confirm it, and no `register_approver_key` action can be requested for it. This is what stops tampered JS from deleting the hardware key, making a P-256 key in JS and registering it: the 6-digit code would match, because it derives from whatever key was registered, but that key can't be attested. +2. **First key in an org:** confirmed on the Kin host by the owner, in a shell as the server's OS user: `t3 kin approvals confirm-key` (`apps/server/src/kin/cli/approvals.ts`, `approvals/HostKeyCeremony.ts`; steps in `ops/kin/host/README.md`). No RPC confirms a key, so no client, remote session, tunnel or agent can; the shell on the host is the guard, and the code only proves the owner is looking at that phone. The CLI lists each pending attested key with its device label, platform, hardware, full thumbprint, org, person, registering session and code expiry. The owner picks one and types the code the phone shows. One transaction counts the try (the first statement is the write, so it holds SQLite's lock), checks the code against that exact org, key, session and challenge through the stored HMAC, activates and seals only that key, deletes the code and writes `key_confirmed`. A wrong code, an expired one, a sixth try, or the right code named with another key or session is refused (`bad_code`), and the try still counts. It works only while the org has no active key. The Kin host is headless Linux and the owner's desktop is a remote client, so the earlier rule (the desktop app's loopback `desktop-bootstrap` session) could never pass there; it is gone, with `kin.approvals.confirmKey`. +3. **Later keys:** confirmed by a grant of kind `register_approver_key` signed by an existing active key. Its `device_key` target carries the new key's `hardware` and `attested` from the server's record, so the phone's prompt shows them (`Add approver key NzbLsXh8uDCcd-6MNwXF4W_7noWXFZAfHkxZsRGC9Xs (Secure Enclave, attested)`), and the module refuses a target that isn't attested. 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. The card belongs to no lead, so it isn't posted in a chat: `listKeys` returns the org's awaiting `enrolments`, and the owner's active phone draws each from `kin.approvals.get` on its Approvals screen (device label, full thumbprint, hardware and attestation) and signs it with Face ID. The CLI refuses a later key unless `--recover` is given. + - **Lost device:** `t3 kin approvals confirm-key --recover` on the host, with the new phone's code, revokes every other key the same person holds (voiding approvals they signed that haven't run, and cancelling their pending registrations), writes `key_revoked` for each, then activates the new key and writes `key_confirmed` with `result: "host recovery"`, all in the code's transaction. 4. Revoking (`kin.approvals.revokeKey`, from settings or the desktop) sets `revoked` and voids every `approved` action whose grant that key signed. Revoking a T3 device session (`revokeClient`) also revokes keys registered from it. Kin reads `auth_sessions.revoked_at` at startup and before it trusts, lists or activates a key, rather than hooking T3's auth code. Revoking also cancels a pending `register_approver_key` action for the key. Expiry is not revocation: a key outlives the session that registered it. A DPoP relay session renews hourly under a new session id but the same DPoP key, so each key also stores that key's thumbprint (`proof_key_thumbprint`), and revoking any session of that DPoP key revokes the key (below). The server's attestation allowlist comes from `KIN_ANDROID_PACKAGE`, `KIN_ANDROID_SIGNING_CERT_SHA256` (comma-separated hex), `KIN_IOS_APP_ID` (`.`) and `KIN_IOS_APP_ATTEST_DEVELOPMENT` (accept `appattestdevelop`; default false). With none set, every key registers unattested. Google's roots and Apple's App Attest root are pinned in `apps/server/src/kin/approvals/attestation/roots.ts`. Google's revocation list is fetched from `https://android.googleapis.com/attestation/status` and cached for an hour. If it can't be fetched, Android registration fails and the phone retries; it never stores a key whose chain went unchecked. @@ -274,7 +275,7 @@ export const KinGrantPayload = Schema.Struct({ `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))`; `jti` is at least 16 bytes (22 base64url characters) and `nonce` is 32 bytes (43 characters) → `malformed`. The device parsers refuse the same. -2. `kid` is an `active` and attested key in `payload.orgId`, and `payload.approver.kid` equals it → `unknown_key` / `revoked_key`. "Attested" also needs the row's `seal`: an HMAC-SHA256, keyed by the server secret `kin-approver-key-seal`, over the org, thumbprint, public JWK, person and hardware, written by `confirmKey` and `register_approver_key` in the same `UPDATE` that activates the key and cleared on revoke (`approvals/KeySeal.ts`). An unattested key never activates, and a row inserted or edited in SQLite carries no valid seal, so either one found active means the database was edited; it fails `unknown_key`. The attestation evidence itself is checked once, at registration, and not stored, so the seal is what carries that verdict forward. It defends against a SQLite write only: whatever can read the secrets directory can forge one. +2. `kid` is an `active` and attested key in `payload.orgId`, and `payload.approver.kid` equals it → `unknown_key` / `revoked_key`. "Attested" also needs the row's `seal`: an HMAC-SHA256, keyed by the server secret `kin-approver-key-seal`, over the org, thumbprint, public JWK, person and hardware, written by the host ceremony and `register_approver_key` in the same `UPDATE` that activates the key and cleared on revoke (`approvals/KeySeal.ts`). An unattested key never activates, and a row inserted or edited in SQLite carries no valid seal, so either one found active means the database was edited; it fails `unknown_key`. The attestation evidence itself is checked once, at registration, and not stored, so the seal is what carries that verdict forward. It defends against a SQLite write only: whatever can read the secrets directory can forge one. 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.) @@ -560,7 +561,7 @@ The check only sees what the server's OS user is set up with. An agent running a | Replay | Captured grant sent again, or for another PR | `jti` UNIQUE, nonce and `targetDigest` binding, executions PK | | Bait and switch | New commit pushed after the owner looks | Nonce rotation, check 9, executor precheck, `sha` on the merge call, `dismiss_stale_reviews_on_push` | | Double run | Restart mid-merge, duplicate webhook, deferral fires twice | Idempotency key, executions PK, reconciliation | -| Stolen phone | Thief has the unlocked phone | Per-use biometric on the key; `.biometryCurrentSet` / enrollment invalidation; revoke from desktop | +| Stolen phone | Thief has the unlocked phone | Per-use biometric on the key; `.biometryCurrentSet` / enrollment invalidation; `kin approvals confirm-key --recover` on the host | | Compromised Kin server or agent with shell | Reads the keychain merge token | Token can't review; ruleset needs the owner's code-owner review at the current SHA, which only the phone can make | | Agent with shell reads the App's key | On Linux, or any host where agents share the server's OS user, reads `kin-github-app` from the keychain and mints installation tokens itself | **Not stopped in phase 1.** Those tokens aren't narrowed by `installationToken`, so they carry the App's full table, `contents: write` on every installed repo included. Phase 1 relies on the ruleset needing the owner's review; the fix is a separate executor OS user (open question 4) | | Bot self-approval | Bot approves its own PR | GitHub forbids author approval; bot isn't a code owner | @@ -596,7 +597,7 @@ Upstream hooks (one line each): - HTTP route for `/kin/mcp` — the same router hook the chat spec uses for Kin routes. - `apps/mobile/app.config.ts` — `["./plugins/withKinApprovalKey.cjs", { appAttestEnvironment }]` in `plugins`. -RPCs and scopes: `kin.approvals.list` (stream) and `get` → `orchestration:read`; `challenge`, `submitGrant`, `reject` → `orchestration:operate`; `keyChallenge`, `registerKey`, `confirmKey`, `listKeys`, `revokeKey`, `kin.audit.list`, `kin.audit.verify` → `access:write`. Scopes are only the outer gate; the person and signature checks above are the real ones. +RPCs and scopes: `kin.approvals.list` (stream) and `get` → `orchestration:read`; `challenge`, `submitGrant`, `reject` → `orchestration:operate`; `keyChallenge`, `registerKey`, `listKeys`, `revokeKey`, `kin.audit.list`, `kin.audit.verify` → `access:write`. Scopes are only the outer gate; the person and signature checks above are the real ones. ## Interfaces to other specs @@ -629,7 +630,7 @@ RPCs and scopes: `kin.approvals.list` (stream) and `get` → `orchestration:read 18. `privileged execution is refused while the credential hygiene check fails`. 19. `the merge token is never written to logs, audit, env or child processes` — grep the captured logs and spawned env in an integration test. 20. `the audit chain detects an edited row` (`kin.audit.verify`). -21. `the first approver key can't be confirmed from a remote session`. +21. `the host confirms the first key only with its phone's code, key and session` (no RPC can), with expiry, the five-try limit and `--recover`. 22. Mobile (`apps/mobile/modules/kin-approval-key`, device test): `signing without biometrics fails`, `re-enrolling biometrics invalidates the key`, `DER signatures convert to compact and verify on the server`, `only one signature at a time, under the grant's own text`, `an overlay over the sheet can't approve`, `a double tap can't land on Approve`, `a cover removed after the first tap can't approve` (including about 50 randomised-timer hides: Approve never enables less than 0.7 s after the cover goes), `a cover mounted after Approve arms and hidden on the first tap can't approve on the second`, `the app's own web-view picture in picture closes before the sheet shows and while it is up`, `system UI doesn't lock the sheet out`. The module's README has the checklist; its grant parser's vectors run without a device. 23. GitHub (`scripts/kin-rulesets.ts --test-23 --repo /`, after `--check` passes there): it refuses a Kin repository (`KIN_GITHUB_REPOS` or `GLDRoger/t3code`, in any case), a name without `scratch`, and a repository whose `GET /repos` `full_name` differs from `--repo` (a rename or transfer redirect). It needs a `v*` tag on the scratch repo and an Actions workflow that runs the required checks on pull requests. It takes a scratch-only fine-grained token of the owner's, checked by `OwnerMergeClient.save`'s probes (`--probe-pr ` names an existing PR for the review probe) and not stored, and mints a `server` App token (the only holder allowed `contents: write`), which it revokes at the end. The bot opens a PR; once the Actions checks pass and GitHub reports `mergeable_state: "blocked"`: `the merge token can't submit a review` (403); for both the bot and the merge token, `can't merge without a code-owner review` (405 naming the review), `can't push to the default branch` (422 "Repository rule violations", and the ref hasn't moved), `can't create or move a v* tag` (same), `can't bypass either ruleset` (reading one needs only Metadata, so the read may succeed, but must report `current_user_can_bypass: "never"` and no bypass actors), and `can't read a ruleset's history or change a ruleset` (403, or 404, which GitHub uses to hide endpoints a token can't use; the change sends the desired body, and drift is checked again afterwards). The owner approves and GitHub reports `clean`. Then bait and switch: the bot pushes, the owner's review shows `DISMISSED`, and the merge token's merge of the new head is blocked. The owner approves again and the merge token merges, which shows the blocks came from the rules. After the owner's review at the current head, a `server` holder's `contents: write` token could merge too: the ruleset doesn't limit who merges (threat model, open question 7); test 23 doesn't merge with it. The logic is tested against a fake GitHub in `apps/server/src/kin/github/rulesetsSetup.test.ts`; A rate-limited answer (429, or a 403 with `x-ratelimit-remaining: 0` or `retry-after`) never counts as a block: the run stops and says to try again later. GitHub's exact refusal messages are assumed there and confirmed by the first real run. On the same scratch repo, confirm the section 10 probe assumptions by hand: `--merge-token` accepts a Contents + Metadata token and refuses each broader one listed there; the review probe leaves no PENDING review on the probe PR (`GET /pulls/{n}/reviews` lists none from the owner afterwards); and `permissions.push` is false for a Contents: Read token. Run the section 10 sync flow once: push a branch whose merge commit changes `.github/workflows` with the owner's credential, have a `server` App token add the same-tree commit (`POST /git/commits`, then the ref update), and confirm GitHub accepts it without the Workflows permission and that the owner's approval then reports the PR `clean`. Also ask: can an App installation token with Pull requests write and no Contents write enable auto-merge (`enablePullRequestAutoMerge`) on a reviewed PR? If it can, a lead could merge without `contents: write`, and open question 7 needs another answer. Test 23 runs as the server's OS user, which on Linux can read the App's private key and mint unnarrowed tokens (threat model); it proves what the narrowed tokens can't do, not what code running as that user can't. @@ -645,7 +646,7 @@ Acceptance for phase 1: on `GLDRoger/t3code`, the lead requests a merge of a bot **APPR-4 Grant verification.** `GrantVerifier.ts` implementing checks 1–10, `challenge`, `submitGrant`, `reject` RPCs, audit on every rejection. Depends on: APPR-2, APPR-5. Done when: tests 1–9 pass. Owner: backend. -**APPR-5 Approver keys.** Registry, `registerKey`/`confirmKey`/`listKeys`/`revokeKey`, App Attest and Keystore attestation verification (section 4), never activating an unattested key, desktop loopback confirmation with matching code, revoke-on-session-revoke, `register_approver_key` handler with `hardware` and `attested` in its target. Depends on: APPR-1, APPR-2. Done when: tests 4 and 21 pass. Owner: backend. +**APPR-5 Approver keys.** Registry, `registerKey`/`listKeys`/`revokeKey`, App Attest and Keystore attestation verification (section 4), never activating an unattested key, host CLI confirmation with matching code, revoke-on-session-revoke, `register_approver_key` handler with `hardware` and `attested` in its target. Depends on: APPR-1, APPR-2. Done when: tests 4 and 21 pass. Owner: backend. **APPR-6 Native approval key module.** `apps/mobile/modules/kin-approval-key` for iOS (Secure Enclave, `.biometryCurrentSet`, App Attest) and Android (Keystore, StrongBox fallback, `BiometricPrompt`, attestation chain); DER-to-compact; config plugin for `NSFaceIDUsageDescription` and the App Attest entitlement. Depends on: nothing. Done when: device tests in 22 pass on one iPhone and one Pixel, and a signature verifies with `p256.verify`. Owner: UI (native). diff --git a/ops/kin/host/README.md b/ops/kin/host/README.md index dad1bc62e2dad..727ba8f12a51d 100644 --- a/ops/kin/host/README.md +++ b/ops/kin/host/README.md @@ -106,6 +106,27 @@ Running it again with the same name and domain changes nothing and prints the ex - `kin lead projects --worker-project ...` replaces a live lead's worker projects, keeping its chat and history; pass no `--worker-project` to clear them. Its next tool call sees the change: new and follow-up work in a removed project is refused, but a worker already running there keeps running until it ends or you stop it. - `kin lead retire ` retires one. Its rows and chat stay. Its Kin tool calls are refused at once. A running server expires its queued events and ends its thread once any current wake-up finishes (up to 15 minutes; pause Kin to halt it sooner), or at its next start if it's stopped. +## Approve from the phone + +Merges and level raises need your signature from a phone's approval key. The first key in an org is confirmed only here, on the host, by you in a kin shell. No client, remote session or agent can confirm one. + +1. Pair the phone (above). On it, open Kin, then Approvals, and tap **Set up approvals**. It makes a key in the Secure Enclave and shows a 6-digit code and the key's thumbprint. The code works for 10 minutes and takes 5 tries. +2. In a kin shell: + + ```bash + KIN_ENABLED=true node ~/kin-current/apps/server/dist/bin.mjs kin approvals confirm-key --base-dir ~/.t3 + ``` + + It lists each phone waiting: device name, platform, hardware, the full key thumbprint, org and person, the session it registered from, and when its code runs out. Check the thumbprint against the phone, pick it (or pass `--key `), and type the code. + +3. On the phone, tap **Check again**. It now says "This phone approves for Kin". + +Only attested keys are listed. A simulator, or a phone that couldn't prove its key is in secure hardware, never appears and can't approve. The command is safe while `kin-server` runs, and `--code ` skips the prompt. + +**A second phone.** Set it up the same way. Instead of a host step, the phone that already approves shows a card for it under Approvals, with its name, thumbprint and hardware. Approve that card with Face ID. Running `confirm-key` for it is refused while another key is active. + +**A lost phone.** Set up the new phone, then run the same command with `--recover`. It revokes every other key you hold, voids anything they approved that hasn't run yet, and activates the new one. The audit log records each revoked key and the recovery (`key_revoked`, `key_confirmed`). + ## Reply latency Each wake-up logs one `Kin wake-up latency` line with every stage's ms since its first message was queued: claimed, memory prepared, provider launched, first token, reply posted, and whether it was warm. For p50 and p90 over the last 20 owner-message wake-ups, read the database without writing to it: diff --git a/packages/client-runtime/src/kin/kinApprovalPresentation.test.ts b/packages/client-runtime/src/kin/kinApprovalPresentation.test.ts index 36e4d1978aba1..5123e722588b5 100644 --- a/packages/client-runtime/src/kin/kinApprovalPresentation.test.ts +++ b/packages/client-runtime/src/kin/kinApprovalPresentation.test.ts @@ -62,7 +62,7 @@ const merge = (overrides: Partial = {}) => const full = ( action: KinPendingAction, - names: { leadName?: string; afterNonOwnerName?: string } = { + names: { leadName?: string; afterNonOwnerName?: string; keyDeviceLabel?: string } = { leadName: "Tech lead", afterNonOwnerName: "Priya", }, @@ -99,7 +99,9 @@ describe("kinApprovalCardView", () => { it("names who asked from the provenance the host recorded", () => { const asked = ( provenance: Partial, - names: { leadName?: string; afterNonOwnerName?: string } = { leadName: "Tech lead" }, + names: { leadName?: string; afterNonOwnerName?: string; keyDeviceLabel?: string } = { + leadName: "Tech lead", + }, ) => kinApprovalCardView( full( @@ -193,6 +195,35 @@ describe("kinApprovalCardView", () => { }); }); + it("a new phone's card shows its whole key and attested hardware before anyone signs", () => { + const thumbprint = "NzbLsXh8uDCcd-6MNwXF4W_7noWXFZAfHkxZsRGC9Xs"; + const enrol = merge({ + kind: "register_approver_key", + target: { _tag: "device_key", thumbprint, hardware: "secure_enclave", attested: true }, + resolved: { _tag: "none" }, + reason: 'Add approver key for "iPhone".', + requestedBy: { agentId: "kin-approver-keys", threadId: "kin-approver-keys" }, + provenance: { + startedBy: { humanId: "kin-default-owner" }, + startedByRole: "owner", + chain: [], + ceilingBelowOwner: false, + }, + } as unknown as Partial); + const card = kinApprovalCardView(full(enrol, { keyDeviceLabel: "Nishchay's iPhone" })); + expect(card).toMatchObject({ + title: "Let a new phone approve", + asked: { text: "You asked for this.", warning: false }, + reason: null, + decidable: true, + }); + expect(card.facts.map((fact) => [fact.label, fact.value])).toEqual([ + ["Phone", "Nishchay's iPhone"], + ["Key", thumbprint], + ["Hardware", "Secure Enclave, attested"], + ]); + }); + it("anyone else sees who it waits on and never a button", () => { const card = kinApprovalCardView({ _tag: "redacted", diff --git a/packages/client-runtime/src/kin/kinApprovalPresentation.ts b/packages/client-runtime/src/kin/kinApprovalPresentation.ts index cf306e156f4c3..f94476d715760 100644 --- a/packages/client-runtime/src/kin/kinApprovalPresentation.ts +++ b/packages/client-runtime/src/kin/kinApprovalPresentation.ts @@ -99,6 +99,12 @@ const CHECK_LABEL: Record = { skipped: "Skipped", }; +const KEY_HARDWARE: Record<"secure_enclave" | "strongbox" | "tee", string> = { + secure_enclave: "Secure Enclave", + strongbox: "StrongBox", + tee: "Secure hardware", +}; + const count = (n: number, one: string, many = `${one}s`) => `${n} ${n === 1 ? one : many}`; function checksSummary(checks: ReadonlyArray): string { @@ -230,6 +236,17 @@ function fullView( fact("lead", "Lead", name); fact("level", "New level", action.target.level); fact("where", "Applies to", action.target.chatId === undefined ? "All chats" : "One chat"); + } else if (action.target._tag === "device_key") { + const label = view.keyDeviceLabel === undefined ? "" : clamp(view.keyDeviceLabel, 80); + title = "Let a new phone approve"; + if (label) fact("phone", "Phone", label); + // Whole, as the Face ID prompt shows it: the new phone shows the same key on its screen. + fact("key", "Key", action.target.thumbprint, true); + fact( + "hardware", + "Hardware", + `${KEY_HARDWARE[action.target.hardware]}, ${action.target.attested ? "attested" : "not attested"}`, + ); } else { title = "Approve this request"; } @@ -280,7 +297,9 @@ function redactedView(view: Extract): Kin ? `Merge #${view.number}${view.repo === null ? "" : ` in ${view.repo}`}` : view.kind === "set_level" ? "Change a lead's level" - : "A request for the owner"; + : view.kind === "register_approver_key" + ? "Let a new phone approve" + : "A request for the owner"; const subtitle = view.title === null ? null : clamp(view.title, 200) || null; const eyebrow = settled ? "Approval" : `Waiting on ${waitingOn}`; const status = settled ? KIN_APPROVAL_STATE_TEXT[view.state] : null; diff --git a/packages/client-runtime/src/state/commandPermissions.test.ts b/packages/client-runtime/src/state/commandPermissions.test.ts index cc1ced094b08e..b94139d32c8e0 100644 --- a/packages/client-runtime/src/state/commandPermissions.test.ts +++ b/packages/client-runtime/src/state/commandPermissions.test.ts @@ -17,6 +17,7 @@ import { AuthSourceControlWriteScope, ThreadId, EnvironmentId, + KIN_APPROVAL_WS_METHODS, KIN_LEVEL_WS_METHODS, KIN_PUSH_WS_METHODS, ORCHESTRATION_V2_WS_METHODS, @@ -133,6 +134,15 @@ describe("command permissions", () => { [KIN_LEVEL_WS_METHODS.lower, AuthSettingsWriteScope], [KIN_LEVEL_WS_METHODS.raise, AuthSettingsWriteScope], [KIN_LEVEL_WS_METHODS.shadowMemory, AuthSettingsWriteScope], + // Approving needs operate on the host that holds the action; key setup needs access:write. + [KIN_APPROVAL_WS_METHODS.get, AuthOrchestrationReadScope], + [KIN_APPROVAL_WS_METHODS.challenge, AuthOrchestrationOperateScope], + [KIN_APPROVAL_WS_METHODS.submitGrant, AuthOrchestrationOperateScope], + [KIN_APPROVAL_WS_METHODS.reject, AuthOrchestrationOperateScope], + [KIN_APPROVAL_WS_METHODS.keyChallenge, AuthAccessWriteScope], + [KIN_APPROVAL_WS_METHODS.registerKey, AuthAccessWriteScope], + [KIN_APPROVAL_WS_METHODS.listKeys, AuthAccessWriteScope], + [KIN_APPROVAL_WS_METHODS.revokeKey, AuthAccessWriteScope], ] as const)("guards %s with the destination %s grant", ([method, scope]) => Effect.scoped( Effect.gen(function* () { @@ -142,23 +152,33 @@ describe("command permissions", () => { tag: method, execute: () => Effect.die("unused"), }); + const permissions = createCommandPermissions(runtime, method); const others = [ AuthOrchestrationReadScope, AuthOrchestrationOperateScope, AuthSettingsWriteScope, + AuthAccessWriteScope, ].filter((other) => other !== scope); registry.set( sessions(env), AsyncResult.success({ ...grant(false), scopes: others, permissions: others }), ); expect(registry.get(command.permissionAtom(env))).toBe(false); + expect((yield* permissions.authorize(registry, env).pipe(Effect.flip))._tag).toBe( + "EnvironmentAuthorizationError", + ); registry.set( sessions(env), AsyncResult.success({ ...grant(false), scopes: [scope], permissions: [scope] }), ); expect(registry.get(command.permissionAtom(env))).toBe(true); + yield* permissions.authorize(registry, env); + // The grant belongs to the destination: another environment's session doesn't carry it. registry.set(sessions(other), AsyncResult.success(grant(false))); expect(registry.get(command.permissionAtom(other))).toBe(false); + expect((yield* permissions.authorize(registry, other).pipe(Effect.flip))._tag).toBe( + "EnvironmentAuthorizationError", + ); }), ), ); diff --git a/packages/contracts/src/kinApprovals.ts b/packages/contracts/src/kinApprovals.ts index da50a58e59edb..4423fe5c7ac29 100644 --- a/packages/contracts/src/kinApprovals.ts +++ b/packages/contracts/src/kinApprovals.ts @@ -411,6 +411,8 @@ export const KinApprovalView = Schema.Union([ /** Display names the server looked up: the lead it concerns, and `afterNonOwnerMessage`'s author. */ leadName: Schema.optional(KinText), afterNonOwnerName: Schema.optional(KinText), + /** For `register_approver_key`: the new key's device label, from the host's key record. */ + keyDeviceLabel: Schema.optional(KinText), }), Schema.TaggedStruct("redacted", { actionId: KinActionId, @@ -512,14 +514,15 @@ export const KinApprovalsKeyInput = Schema.Struct({ thumbprint: KinKeyThumbprint, }); export type KinApprovalsKeyInput = typeof KinApprovalsKeyInput.Type; -export const KinApprovalsConfirmKeyInput = Schema.Struct({ - ...KinApprovalsKeyInput.fields, - code: pattern(/^\d{6}$/, "a 6-digit code"), -}); -export type KinApprovalsConfirmKeyInput = typeof KinApprovalsConfirmKeyInput.Type; export const KinApprovalsOrgInput = Schema.Struct({ orgId: KinOrgId }); export type KinApprovalsOrgInput = typeof KinApprovalsOrgInput.Type; -export const KinApprovalsListKeysResult = Schema.Struct({ keys: Schema.Array(KinApproverKey) }); +export const KinApprovalsListKeysResult = Schema.Struct({ + keys: Schema.Array(KinApproverKey), + /** Pending `register_approver_key` actions: a new phone an active one has to approve. */ + enrolments: Schema.optional( + Schema.Array(Schema.Struct({ thumbprint: KinKeyThumbprint, actionId: KinActionId })), + ), +}); export type KinApprovalsListKeysResult = typeof KinApprovalsListKeysResult.Type; export const KinAuditListInput = Schema.Struct({ @@ -558,7 +561,6 @@ export class KinApprovalError extends Schema.TaggedError()("Ki "not_a_lead", "bad_challenge", "bad_code", - "not_local", "unattested", ]), ]), @@ -573,7 +575,6 @@ export const KIN_APPROVAL_WS_METHODS = { reject: "kin.approvals.reject", keyChallenge: "kin.approvals.keyChallenge", registerKey: "kin.approvals.registerKey", - confirmKey: "kin.approvals.confirmKey", listKeys: "kin.approvals.listKeys", revokeKey: "kin.approvals.revokeKey", auditList: "kin.audit.list", @@ -619,11 +620,6 @@ export const KinApprovalRpcs = [ success: KinApprovalsRegisterKeyResult, error, }), - Rpc.make(KIN_APPROVAL_WS_METHODS.confirmKey, { - payload: KinApprovalsConfirmKeyInput, - success: KinApproverKey, - error, - }), Rpc.make(KIN_APPROVAL_WS_METHODS.listKeys, { payload: KinApprovalsOrgInput, success: KinApprovalsListKeysResult, @@ -655,7 +651,6 @@ export const KIN_APPROVAL_RPC_SCOPES = { [KIN_APPROVAL_WS_METHODS.reject]: AuthOrchestrationOperateScope, [KIN_APPROVAL_WS_METHODS.keyChallenge]: AuthAccessWriteScope, [KIN_APPROVAL_WS_METHODS.registerKey]: AuthAccessWriteScope, - [KIN_APPROVAL_WS_METHODS.confirmKey]: AuthAccessWriteScope, [KIN_APPROVAL_WS_METHODS.listKeys]: AuthAccessWriteScope, [KIN_APPROVAL_WS_METHODS.revokeKey]: AuthAccessWriteScope, [KIN_APPROVAL_WS_METHODS.auditList]: AuthAccessWriteScope, diff --git a/packages/contracts/src/kinRpcs.ts b/packages/contracts/src/kinRpcs.ts index fd602a8d19584..028723075cc4e 100644 --- a/packages/contracts/src/kinRpcs.ts +++ b/packages/contracts/src/kinRpcs.ts @@ -163,7 +163,6 @@ export const KIN_RPC_AGGREGATES = { "kin.approvals.reject": "kin-approvals", "kin.approvals.keyChallenge": "kin-approvals", "kin.approvals.registerKey": "kin-approvals", - "kin.approvals.confirmKey": "kin-approvals", "kin.approvals.listKeys": "kin-approvals", "kin.approvals.revokeKey": "kin-approvals", "kin.audit.list": "kin-approvals", From ae562e9231951c1bce8c8f551bc0e07397a3c900 Mon Sep 17 00:00:00 2001 From: GLDRoger <130458023+GLDRoger@users.noreply.github.com> Date: Tue, 10 Nov 2026 13:10:57 +0530 Subject: [PATCH 7/8] fix(kin): a forged pending key can't be activated, and a second phone enrols without the GitHub check Registration now writes a pending seal: an HMAC, keyed by the seal secret, over the pending key's identity, holder (org, person, session, DPoP key) and attestation verdict. Every activation checks it on the row it updates and pins those fields in the UPDATE, so a pending row and enrolment written straight into SQLite stay pending even after the owner signs. The second-phone card gets the device label and hardware only while the pending seal verifies, and the approval challenge refuses otherwise. register_approver_key no longer takes the credential hygiene check: it writes nothing to GitHub, and the check neither authenticates an enrolment nor protects the seal secret. The migration is K033, after K031_LeadDeliveries and K032_WorkerEnvironment. Co-Authored-By: Claude Opus 5.5 --- .../src/kin/approvals/ActionExecutor.test.ts | 48 +++++++++++++- .../src/kin/approvals/ApproverKeyStore.ts | 50 ++++++++++---- .../src/kin/approvals/ApproverKeys.test.ts | 64 ++++++++++++++++++ apps/server/src/kin/approvals/ApproverKeys.ts | 19 ++++-- .../src/kin/approvals/GrantVerifier.test.ts | 36 ++++++++++ .../server/src/kin/approvals/GrantVerifier.ts | 37 ++++++----- .../src/kin/approvals/HostKeyCeremony.ts | 41 +++++++----- apps/server/src/kin/approvals/KeySeal.ts | 30 ++++++++- .../server/src/kin/approvals/grant.testkit.ts | 27 ++++++++ .../approvals/handlers/registerApproverKey.ts | 7 +- .../src/kin/persistence/KinMigrations.test.ts | 66 ++++++++++++++++++- .../K033_ApproverKeyConfirmations.ts | 2 + docs/kin/specs/approvals.md | 12 ++-- .../src/kin/kinApprovalPresentation.test.ts | 23 ++++++- .../src/kin/kinApprovalPresentation.ts | 10 +-- packages/contracts/src/kinApprovals.ts | 6 +- 16 files changed, 408 insertions(+), 70 deletions(-) diff --git a/apps/server/src/kin/approvals/ActionExecutor.test.ts b/apps/server/src/kin/approvals/ActionExecutor.test.ts index faf9ca5d69d63..c932fac8422e5 100644 --- a/apps/server/src/kin/approvals/ActionExecutor.test.ts +++ b/apps/server/src/kin/approvals/ActionExecutor.test.ts @@ -44,7 +44,12 @@ import * as Audit from "./Audit.ts"; import * as CredentialHygiene from "./CredentialHygiene.ts"; import { KinExecutionNotices } from "./ExecutionNotices.ts"; import { BOOTSTRAP_OWNER, KinOrgRoles } from "./GrantPorts.ts"; -import { insertActiveKey, makeApprovalKey, signCompact } from "./grant.testkit.ts"; +import { + insertActiveKey, + insertPendingKey, + makeApprovalKey, + signCompact, +} from "./grant.testkit.ts"; import * as KeySeal from "./KeySeal.ts"; import * as ApprovalsLayer from "./layer.ts"; import { makeDeleteBranchHandler } from "./handlers/deleteBranch.ts"; @@ -414,7 +419,7 @@ let jtiCounter = 0; /** Creates an action and approves it through `PendingActions`, as check 10 does. */ const approved = (input: { - readonly kind: "merge_pull_request" | "delete_branch"; + readonly kind: "merge_pull_request" | "delete_branch" | "register_approver_key"; readonly target: KinActionTarget; readonly resolved: KinResolvedTarget; readonly source: string; @@ -1493,6 +1498,45 @@ describe("KinActionExecutor", () => { }, ); + it.effect( + "a second phone activates once the first signs, with the credential check failing", + () => { + const lapses: Array = []; + return Effect.gen(function* () { + yield* TestClock.setTime(NOW); + const context = yield* Layer.build(production(ApprovalsLayer.executorLayer, lapses)); + yield* Effect.gen(function* () { + const { sql } = yield* seed; + const enrol = (key: ReturnType, source: string) => + approved({ + kind: "register_approver_key", + target: { _tag: "device_key", thumbprint: key.kid, hardware: "tee", attested: true }, + resolved: { _tag: "none" }, + source, + }); + const stateOfKey = (key: ReturnType) => + sql<{ state: string; sealed: number }>`SELECT state, seal IS NOT NULL AS sealed + FROM kin_approver_keys WHERE thumbprint = ${key.kid}`; + const phone = makeApprovalKey(); + yield* insertPendingKey({ key: phone, orgId, humanId: owner }); + // A row written into SQLite with no pending seal, and a card for it the owner signs. + const forged = makeApprovalKey(); + yield* insertPendingKey({ key: forged, orgId, humanId: owner, sealed: false }); + const ref = yield* enrol(phone, "second-phone"); + const forgedRef = yield* enrol(forged, "forged-phone"); + yield* TestClock.adjust("1 second"); + assert.deepInclude(yield* stateOf(ref), { state: "succeeded" }); + assert.deepStrictEqual(yield* stateOfKey(phone), [{ state: "active", sealed: 1 }]); + assert.deepInclude(yield* stateOf(forgedRef), { state: "failed" }); + assert.deepStrictEqual(yield* stateOfKey(forged), [{ state: "pending", sealed: 0 }]); + assert.isEmpty( + (yield* auditEntries).filter((entry) => entry.event === "credential_check_failed"), + ); + }).pipe(Effect.provide(context)); + }).pipe(Effect.scoped); + }, + ); + it.effect("a configured host holds GitHub kinds on the missing identity probe", () => { const lapses: Array = []; const github = fakeGitHub(() => ({ status: 404, body: { message: "Not Found" } })); diff --git a/apps/server/src/kin/approvals/ApproverKeyStore.ts b/apps/server/src/kin/approvals/ApproverKeyStore.ts index 09570cce44229..1370abcd02182 100644 --- a/apps/server/src/kin/approvals/ApproverKeyStore.ts +++ b/apps/server/src/kin/approvals/ApproverKeyStore.ts @@ -39,6 +39,7 @@ export type KeyRow = { readonly confirmed_at: number | null; readonly revoked_at: number | null; readonly seal: string | null; + readonly pending_seal: string | null; }; export type ConfirmationRow = { @@ -67,7 +68,16 @@ export const sealFields = (row: KeyRow) => ({ hardware: row.hardware, }); -/** `attested` holds for an active key only while the seal written at activation verifies. */ +export const pendingSealFields = (row: KeyRow) => ({ + ...sealFields(row), + deviceLabel: row.device_label, + platform: row.platform, + attested: row.attested, + sessionId: row.session_id, + proofKeyThumbprint: row.proof_key_thumbprint, +}); + +/** `attested` holds for a pending or active key only while its pending seal or seal verifies. */ const toKeyWith = (row: KeyRow, sealed: boolean) => decodeKey({ orgId: row.org_id, @@ -77,7 +87,7 @@ const toKeyWith = (row: KeyRow, sealed: boolean) => deviceLabel: row.device_label, platform: row.platform, hardware: row.hardware, - attested: row.attested === 1 && (row.state !== "active" || sealed), + attested: row.attested === 1 && (row.state === "revoked" || sealed), ...(row.session_id === null ? {} : { sessionId: row.session_id }), state: row.state, createdAt: iso(row.created_at), @@ -105,15 +115,26 @@ export const makeKeyStore = Effect.gen(function* () { const sql = yield* SqlClient.SqlClient; const seal = yield* KinKeySeal; + /** Registration's verdict, intact: a pending attested row whose pending seal verifies. */ + const pendingVouched = (row: KeyRow) => + row.state === "pending" && + row.attested === 1 && + seal.verifyPending(pendingSealFields(row), row.pending_seal); + const toKey = Effect.fn("ApproverKeyStore.toKey")(function* (row: KeyRow) { - if (row.state !== "active" || row.attested !== 1) return yield* toKeyWith(row, false); - const sealed = seal.verify(sealFields(row), row.seal); + if (row.state === "revoked" || row.attested !== 1) return yield* toKeyWith(row, false); + const sealed = + row.state === "active" ? seal.verify(sealFields(row), row.seal) : pendingVouched(row); // Only a write that skipped the server, such as one straight into SQLite, leaves this. if (!sealed) - yield* Effect.logWarning("Kin approver key's seal doesn't verify; it can't sign.", { - orgId: row.org_id, - thumbprint: row.thumbprint, - }); + yield* Effect.logWarning( + "Kin approver key's seal doesn't verify; it can't sign or activate.", + { + orgId: row.org_id, + thumbprint: row.thumbprint, + state: row.state, + }, + ); return yield* toKeyWith(row, sealed); }); @@ -132,18 +153,24 @@ export const makeKeyStore = Effect.gen(function* () { sql`DELETE FROM kin_approver_key_confirmations WHERE org_id = ${ref.orgId} AND thumbprint = ${ref.thumbprint}`; - /** The UPDATE that makes a pending attested key active, sealing exactly the row it read. */ + /** + * The UPDATE that makes a pending attested key active, sealing exactly the row it read. It runs + * only when that row's pending seal verifies, and pins every field the pending seal covers. + */ const activate = Effect.fn("ApproverKeyStore.activate")(function* ( row: KeyRow, now: number, onlyFirst: boolean, ) { + if (!pendingVouched(row) || row.pending_seal === null) return undefined; const [active] = yield* sql`UPDATE kin_approver_keys SET state = 'active', confirmed_at = ${now}, seal = ${seal.seal(sealFields(row))} WHERE org_id = ${row.org_id} AND thumbprint = ${row.thumbprint} - AND state = 'pending' AND attested = 1 + AND state = 'pending' AND attested = 1 AND pending_seal = ${row.pending_seal} AND public_jwk_json = ${row.public_jwk_json} AND human_id = ${row.human_id} - AND hardware = ${row.hardware} + AND hardware = ${row.hardware} AND device_label = ${row.device_label} + AND platform = ${row.platform} AND session_id IS ${row.session_id} + AND proof_key_thumbprint IS ${row.proof_key_thumbprint} AND ${ onlyFirst ? sql`NOT EXISTS (SELECT 1 FROM kin_approver_keys @@ -239,6 +266,7 @@ export const makeKeyStore = Effect.gen(function* () { sql, seal, toKey, + pendingVouched, select, hasActiveKey, activate, diff --git a/apps/server/src/kin/approvals/ApproverKeys.test.ts b/apps/server/src/kin/approvals/ApproverKeys.test.ts index 93a892e27abdb..90ffa91716609 100644 --- a/apps/server/src/kin/approvals/ApproverKeys.test.ts +++ b/apps/server/src/kin/approvals/ApproverKeys.test.ts @@ -32,9 +32,11 @@ import { KinHostKeyCeremony, layer as hostCeremonyLayer } from "./HostKeyCeremon import * as KeySeal from "./KeySeal.ts"; import { KinAttestationTrust } from "./attestation/AttestationTrust.ts"; import { androidChain, makeTrustFixture } from "./attestation/testFixtures.ts"; +import { makeApprovalKey } from "./grant.testkit.ts"; import { makeRegisterApproverKeyHandler } from "./handlers/registerApproverKey.ts"; import { KinPendingActions, + kinTargetDigest, layer as pendingActionsLayer, type KinPendingActionCreateInput, } from "./PendingActions.ts"; @@ -611,6 +613,68 @@ describe("ApproverKeys", () => { ); }).pipe(Effect.provide(layer)), ); + + it.effect("a pending key and enrolment forged in SQLite never activate, even once signed", () => + Effect.gen(function* () { + const { keys, actions, ceremony, sql } = yield* seed; + const first = yield* confirmFirst(keys); + const genuine = yield* registerAndroid(keys, caller("sess-phone-2", "phone")); + const [real] = yield* sql<{ action_id: string; pending_seal: string }>` + SELECT a.action_id, k.pending_seal FROM kin_pending_actions a + JOIN kin_approver_keys k ON k.thumbprint = json_extract(a.target_json, '$.thumbprint') + WHERE a.kind = 'register_approver_key'`; + // A software key posing as attested, carrying a real pending row's seal, and its own action. + const forged = makeApprovalKey(); + yield* sql`INSERT INTO kin_approver_keys (thumbprint, org_id, public_jwk_json, human_id, + device_label, platform, hardware, attested, session_id, state, created_at, pending_seal) + VALUES (${forged.kid}, ${orgId}, ${forged.publicJwkJson}, ${owner}, 'iPhone', 'ios', + 'secure_enclave', 1, 'sess-phone', 'pending', ${NOW}, ${real!.pending_seal})`; + const target = { + _tag: "device_key", + thumbprint: forged.kid, + hardware: "secure_enclave", + attested: true, + } as const; + yield* sql`INSERT INTO kin_pending_actions (action_id, org_id, idempotency_key, kind, + target_json, resolved_json, target_digest, nonce, revision, reason, + requested_by_agent_id, requested_by_thread_id, provenance_json, required_approvers_json, + state, created_at, updated_at, expires_at) + SELECT 'act_forged', org_id, ${"f".repeat(64)}, kind, ${JSON.stringify(target)}, resolved_json, + ${kinTargetDigest("register_approver_key", target, { _tag: "none" })}, nonce, revision, + reason, requested_by_agent_id, requested_by_thread_id, provenance_json, + required_approvers_json, state, created_at, updated_at, expires_at + FROM kin_pending_actions WHERE action_id = ${real!.action_id}`; + const forgedRef = { orgId, thumbprint: forged.kid }; + // It reads as unattested, and the host never lists it. + assert.isFalse(Option.getOrThrow(yield* keys.get(forgedRef)).attested); + assert.isTrue(Option.getOrThrow(yield* keys.get(genuine.key)).attested); + assert.deepStrictEqual( + (yield* ceremony.listPending()).map((row) => row.thumbprint), + [genuine.key.thumbprint], + ); + + // The owner signs the forged card; the grant binds its thumbprint, but activation refuses. + const action = Option.getOrThrow( + yield* actions.get({ orgId, actionId: "act_forged" as KinPendingAction["id"] }), + ); + const approved = yield* approveWith(actions, action, first.key.thumbprint, "jti-forged"); + assert.strictEqual(approved._tag, "approved"); + if (approved._tag !== "approved") return; + const handler = yield* makeRegisterApproverKeyHandler; + assert.isTrue(Exit.isFailure(yield* Effect.exit(handler.run(action, approved.grant)))); + assert.isFalse(yield* keys.activateByGrant(forgedRef)); + // A missing pending seal is refused the same way. + yield* sql`UPDATE kin_approver_keys SET pending_seal = NULL WHERE thumbprint = ${forged.kid}`; + assert.isFalse(yield* keys.activateByGrant(forgedRef)); + const [row] = yield* sql<{ state: string; seal: string | null }>` + SELECT state, seal FROM kin_approver_keys WHERE thumbprint = ${forged.kid}`; + assert.deepStrictEqual(row, { state: "pending", seal: null }); + // A genuine row edited after registration loses its seal's backing too. + yield* sql`UPDATE kin_approver_keys SET device_label = 'Owner phone' + WHERE thumbprint = ${genuine.key.thumbprint}`; + assert.isFalse(yield* keys.activateByGrant(genuine.key)); + }).pipe(Effect.provide(layer)), + ); }); function registerAndroidWith(keys: ApproverKeys["Service"], from: KinKeyCaller, challenge: string) { diff --git a/apps/server/src/kin/approvals/ApproverKeys.ts b/apps/server/src/kin/approvals/ApproverKeys.ts index 513dfc64f4607..6b6b4a12d5205 100644 --- a/apps/server/src/kin/approvals/ApproverKeys.ts +++ b/apps/server/src/kin/approvals/ApproverKeys.ts @@ -38,6 +38,7 @@ import type { PersonIdentity } from "../chat/KinIdentity.ts"; import { internal, makeKeyStore, + pendingSealFields, sealFields, type KeyRef, type KeyRow, @@ -221,7 +222,7 @@ const make = Effect.gen(function* () { reason: result.reason, }); } - const row: KeyRow = { + const unsealed: KeyRow = { thumbprint, org_id: input.orgId, public_jwk_json: stableStringify(input.publicJwk), @@ -238,7 +239,12 @@ const make = Effect.gen(function* () { confirmed_at: null, revoked_at: null, seal: null, + pending_seal: null, }; + // Vouches for this verdict and holder, so a row written into SQLite can't pose as attested. + const row: KeyRow = result.attested + ? { ...unsealed, pending_seal: seal.pendingSeal(pendingSealFields(unsealed)) } + : unsealed; const key = yield* toKey(row); const code = kinKeyConfirmationCode(thumbprint, challenge); const target = result.attested @@ -358,9 +364,14 @@ const make = Effect.gen(function* () { function* (ref: KeyRef) { yield* reconcileSessions(ref.orgId); const now = yield* Clock.currentTimeMillis; - const row = yield* select(ref); - if (row === undefined || row.state !== "pending" || row.attested !== 1) return false; - return (yield* store.activate(row, now, false)) !== undefined; + // `activate` checks the pending seal on the row this transaction read, then pins it. + return yield* sql.withTransaction( + Effect.gen(function* () { + const row = yield* select(ref); + if (row === undefined) return false; + return (yield* store.activate(row, now, false)) !== undefined; + }), + ); }, Effect.catch(internal("ApproverKeys.activateByGrant")), ); diff --git a/apps/server/src/kin/approvals/GrantVerifier.test.ts b/apps/server/src/kin/approvals/GrantVerifier.test.ts index 40a5867c9bfa5..d5e2921d3044b 100644 --- a/apps/server/src/kin/approvals/GrantVerifier.test.ts +++ b/apps/server/src/kin/approvals/GrantVerifier.test.ts @@ -465,6 +465,42 @@ describe("GrantVerifier", () => { }).pipe(Effect.provide(h.layer)); }); + it.effect("a new phone's card claims hardware only while its pending seal verifies", () => { + const h = harness(); + return Effect.gen(function* () { + const world = yield* seed; + const first = yield* register(world.keys, ownerPhone); + yield* world.ceremony.confirm({ + orgId, + thumbprint: first.key.thumbprint, + sessionId: ownerPhone.session.sessionId, + code: first.code, + recover: false, + }); + const second = yield* register(world.keys, ownerLaptop); + const [enrolment] = (yield* world.keys.listKeys(ownerPhone, { orgId })).enrolments ?? []; + const input = { actionId: enrolment!.actionId }; + assert.deepInclude(yield* world.grants.view(ownerPhone, input), { + _tag: "full", + keyDeviceLabel: "Pixel 9", + keyHardware: "strongbox", + }); + const challenge = yield* world.grants.challenge(ownerPhone, input); + assert.deepInclude(challenge.payload.target, { thumbprint: second.key.thumbprint }); + // The same row with its pending seal gone, as a SQLite write would leave it. + yield* world.sql`UPDATE kin_approver_keys SET pending_seal = NULL + WHERE thumbprint = ${second.key.thumbprint}`; + const view = yield* world.grants.view(ownerPhone, input); + assert.strictEqual(view._tag, "full"); + assert.notProperty(view, "keyHardware"); + assert.notProperty(view, "keyDeviceLabel"); + assert.strictEqual( + reasonOf(yield* Effect.exit(world.grants.challenge(ownerPhone, input))), + "invalid_state", + ); + }).pipe(Effect.provide(h.layer)); + }); + it.effect("a phone with no active approver key gets no challenge and can't approve", () => { const h = harness(); return Effect.gen(function* () { diff --git a/apps/server/src/kin/approvals/GrantVerifier.ts b/apps/server/src/kin/approvals/GrantVerifier.ts index 955dc90e5283c..92e92a08b05e9 100644 --- a/apps/server/src/kin/approvals/GrantVerifier.ts +++ b/apps/server/src/kin/approvals/GrantVerifier.ts @@ -380,6 +380,20 @@ const make = Effect.gen(function* () { return { actionId: action.id, state: "approved" as const }; }); + /** + * The new key a `device_key` card shows, only while the server vouches for it: registration's + * pending seal verifies (or, once active, its seal) and its hardware is what the card names. + */ + const newKey = Effect.fn("GrantVerifier.newKey")(function* (action: KinPendingAction) { + if (action.target._tag !== "device_key") return undefined; + const target = action.target; + const key = yield* keys.get({ orgId: action.orgId, thumbprint: target.thumbprint }); + if (Option.isNone(key)) return undefined; + const { state, attested, hardware, deviceLabel } = key.value; + if (state === "revoked" || !attested || hardware !== target.hardware) return undefined; + return { hardware: target.hardware, label: deviceLabel.trim() || undefined }; + }); + /** The key this person signs with: this session's, else their most recently confirmed one. */ const signingKey = Effect.fn("GrantVerifier.signingKey")(function* ( caller: KinKeyCaller, @@ -406,6 +420,11 @@ const make = Effect.gen(function* () { 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."); + if (found.target._tag === "device_key" && (yield* newKey(found)) === undefined) + return yield* fail( + "invalid_state", + "Kin can't vouch for this phone's key. Decline it, then set up the new phone again.", + ); let action = found; let resolved = found.resolved; if (pinsHead(found.kind)) { @@ -448,16 +467,6 @@ const make = Effect.gen(function* () { return row?.name.trim() || undefined; }); - /** What a new phone calls itself, from the host's key record; shown beside its fingerprint. */ - const newKeyLabel = Effect.fn("GrantVerifier.newKeyLabel")(function* ( - orgId: KinOrgId, - thumbprint: string, - ) { - const [row] = yield* sql<{ label: string }>`SELECT device_label AS label FROM kin_approver_keys - WHERE org_id = ${orgId} AND thumbprint = ${thumbprint} ORDER BY thumbprint LIMIT 1`; - return row?.label.trim() || undefined; - }); - /** The person the card waits on: the owner of the lead it concerns (phase 1's only approver). */ const ownerName = Effect.fn("GrantVerifier.ownerName")(function* (action: KinPendingAction) { const lead = leadOf(action); @@ -481,17 +490,15 @@ const make = Effect.gen(function* () { after === undefined ? undefined : yield* displayName("kin_people", action.orgId, after.humanId); - const keyDeviceLabel = - action.target._tag === "device_key" - ? yield* newKeyLabel(action.orgId, action.target.thumbprint) - : undefined; + const vouched = yield* newKey(action); return { _tag: "full" as const, action, canApprove: true as const, ...(leadName === undefined ? {} : { leadName }), ...(afterNonOwnerName === undefined ? {} : { afterNonOwnerName }), - ...(keyDeviceLabel === undefined ? {} : { keyDeviceLabel }), + ...(vouched === undefined ? {} : { keyHardware: vouched.hardware }), + ...(vouched?.label === undefined ? {} : { keyDeviceLabel: vouched.label }), }; } // Anyone else sees what waits and on whom, never the facts a challenge would sign. diff --git a/apps/server/src/kin/approvals/HostKeyCeremony.ts b/apps/server/src/kin/approvals/HostKeyCeremony.ts index 7edbd2b4942b2..f4b049f4c7924 100644 --- a/apps/server/src/kin/approvals/HostKeyCeremony.ts +++ b/apps/server/src/kin/approvals/HostKeyCeremony.ts @@ -83,23 +83,18 @@ const make = Effect.gen(function* () { function* () { yield* store.reconcileSessions(undefined); const now = yield* Clock.currentTimeMillis; - const rows = yield* sql<{ - org_id: KinOrgId; - thumbprint: KinKeyThumbprint; - human_id: string; - device_label: string; - platform: string; - hardware: string; - session_id: string; - subject: string | null; - client: string | null; - created_at: number; - expires_at: number; - attempts: number; - has_active: number; - }>`SELECT k.org_id, k.thumbprint, k.human_id, k.device_label, k.platform, k.hardware, - c.session_id, s.subject, s.client_label AS client, k.created_at, c.expires_at, - c.attempts, + const rows = yield* sql< + KeyRow & { + org_id: KinOrgId; + thumbprint: KinKeyThumbprint; + session_id: string; + subject: string | null; + client: string | null; + expires_at: number; + attempts: number; + has_active: number; + } + >`SELECT k.*, s.subject, s.client_label AS client, c.expires_at, c.attempts, EXISTS (SELECT 1 FROM kin_approver_keys a WHERE a.org_id = k.org_id AND a.state = 'active') AS has_active FROM kin_approver_key_confirmations c @@ -108,7 +103,8 @@ const make = Effect.gen(function* () { WHERE k.state = 'pending' AND k.attested = 1 AND k.session_id = c.session_id AND c.expires_at > ${now} AND c.attempts < ${MAX_CODE_ATTEMPTS} ORDER BY k.org_id, k.created_at, k.thumbprint`; - return rows.map((row): KinPendingEnrolment => ({ + // A row whose pending seal doesn't verify was never vouched for by registration. + return rows.filter(store.pendingVouched).map((row): KinPendingEnrolment => ({ orgId: row.org_id, thumbprint: row.thumbprint, humanId: row.human_id, @@ -182,6 +178,15 @@ const make = Effect.gen(function* () { if (counted.attempts >= MAX_CODE_ATTEMPTS) yield* store.deleteConfirmation(ref); return refused(refuse("bad_code", "That code doesn't match this phone's key.")); } + if (!store.pendingVouched(row)) { + yield* store.deleteConfirmation(ref); + return refused( + refuse( + "unattested", + "Kin can't vouch for this key's record. Make a new key on the phone.", + ), + ); + } const others = yield* othersOf(input); if (needsRecover(others, input)) return refused(alreadyActive); // Recovery: the lost phone's keys, and this person's other pending ones, stop counting first. diff --git a/apps/server/src/kin/approvals/KeySeal.ts b/apps/server/src/kin/approvals/KeySeal.ts index 5dd5fb13a4a8c..5324660b6b49e 100644 --- a/apps/server/src/kin/approvals/KeySeal.ts +++ b/apps/server/src/kin/approvals/KeySeal.ts @@ -22,6 +22,18 @@ export type KinSealedKeyFields = { readonly hardware: string; }; +/** + * What registration vouches for when the attestation verified: the key, who holds it, and the + * attestation's verdict. A pending row that doesn't match its pending seal never activates. + */ +export type KinPendingKeyFields = KinSealedKeyFields & { + readonly deviceLabel: string; + readonly platform: string; + readonly attested: number; + readonly sessionId: string | null; + readonly proofKeyThumbprint: string | null; +}; + /** The exact enrolment a phone's code confirms: one key, from one session, for one challenge. */ export type KinConfirmationFields = KinSealedKeyFields & { readonly sessionId: string; @@ -38,6 +50,9 @@ export class KinKeySeal extends Context.Service< { readonly seal: (key: KinSealedKeyFields) => string; readonly verify: (key: KinSealedKeyFields, seal: string | null) => boolean; + /** What `kin_approver_keys.pending_seal` holds, written when the attestation verified. */ + readonly pendingSeal: (key: KinPendingKeyFields) => string; + readonly verifyPending: (key: KinPendingKeyFields, seal: string | null) => boolean; /** What `kin_approver_key_confirmations.verifier` holds; checked with `verify`'s compare. */ readonly confirmation: (fields: KinConfirmationFields) => string; readonly verifyConfirmation: (fields: KinConfirmationFields, verifier: string) => boolean; @@ -50,7 +65,7 @@ const make = ( secret: Uint8Array, marker: { readonly adopted: Effect.Effect; readonly markAdopted: Effect.Effect }, ) => { - const mac = (fields: Record) => + const mac = (fields: Record) => NodeCrypto.createHmac("sha256", secret).update(stableStringify(fields)).digest("base64url"); const keyFields = (key: KinSealedKeyFields) => ({ orgId: key.orgId, @@ -61,6 +76,17 @@ const make = ( }); const seal = (key: KinSealedKeyFields) => mac({ v: 1, use: "kin-approver-key", ...keyFields(key) }); + const pendingSeal = (key: KinPendingKeyFields) => + mac({ + v: 1, + use: "kin-approver-key-pending", + ...keyFields(key), + deviceLabel: key.deviceLabel, + platform: key.platform, + attested: key.attested, + sessionId: key.sessionId, + proofKeyThumbprint: key.proofKeyThumbprint, + }); const confirmation = (fields: KinConfirmationFields) => mac({ v: 1, @@ -78,6 +104,8 @@ const make = ( return KinKeySeal.of({ seal, verify: (key, stored) => stored !== null && same(seal(key), stored), + pendingSeal, + verifyPending: (key, stored) => stored !== null && same(pendingSeal(key), stored), confirmation, verifyConfirmation: (fields, verifier) => same(confirmation(fields), verifier), adoptOnce: Effect.fn("KinKeySeal.adoptOnce")(function* ( diff --git a/apps/server/src/kin/approvals/grant.testkit.ts b/apps/server/src/kin/approvals/grant.testkit.ts index 5e837d3e024b2..6924f9267c5df 100644 --- a/apps/server/src/kin/approvals/grant.testkit.ts +++ b/apps/server/src/kin/approvals/grant.testkit.ts @@ -62,3 +62,30 @@ export const insertActiveKey = Effect.fn("grant.testkit.insertActiveKey")(functi VALUES (${fields.thumbprint}, ${fields.orgId}, ${fields.publicJwkJson}, ${fields.humanId}, 'Pixel 9', 'android', 'tee', 1, 'active', 0, ${seal})`; }); + +/** A pending attested key as registration writes it, its pending seal included unless not. */ +export const insertPendingKey = Effect.fn("grant.testkit.insertPendingKey")(function* (input: { + readonly key: ApprovalKey; + readonly orgId: string; + readonly humanId: string; + readonly sealed?: boolean; +}) { + const sql = yield* SqlClient.SqlClient; + const fields = { + orgId: input.orgId, + thumbprint: input.key.kid, + publicJwkJson: input.key.publicJwkJson, + humanId: input.humanId, + hardware: "tee", + deviceLabel: "Pixel 9", + platform: "android", + attested: 1, + sessionId: null, + proofKeyThumbprint: null, + }; + const pendingSeal = input.sealed === false ? null : (yield* KinKeySeal).pendingSeal(fields); + yield* sql`INSERT INTO kin_approver_keys (thumbprint, org_id, public_jwk_json, human_id, + device_label, platform, hardware, attested, state, created_at, pending_seal) + VALUES (${fields.thumbprint}, ${fields.orgId}, ${fields.publicJwkJson}, ${fields.humanId}, + 'Pixel 9', 'android', 'tee', 1, 'pending', 0, ${pendingSeal})`; +}); diff --git a/apps/server/src/kin/approvals/handlers/registerApproverKey.ts b/apps/server/src/kin/approvals/handlers/registerApproverKey.ts index dea2e44a58144..7fe5471c5acc7 100644 --- a/apps/server/src/kin/approvals/handlers/registerApproverKey.ts +++ b/apps/server/src/kin/approvals/handlers/registerApproverKey.ts @@ -28,7 +28,8 @@ export const makeRegisterApproverKeyHandler = Effect.gen(function* () { const precheck = Effect.fn("registerApproverKey.precheck")(function* (action: KinPendingAction) { const { target, key } = yield* pendingKey(action); if (key.state !== "pending") return yield* refuse("The key isn't waiting to be added."); - // The card showed the target; the stored key must still be what it described. + // The card showed the target; the stored key must still be what it described, and `attested` + // holds only while registration's pending seal verifies (spec section 4). if (!key.attested || key.hardware !== target.hardware) return yield* refuse("The key doesn't match what was approved."); }); @@ -55,10 +56,10 @@ export const makeRegisterApproverKeyHandler = Effect.gen(function* () { return key.state === "active" ? ("done" as const) : ("not_done" as const); }); - // Gated like the GitHub kinds (spec section 12). + // No GitHub write, like set_level: the hygiene check guards GitHub credentials, not keys. return { kind: "register_approver_key" as const, - credentialCheck: true, + credentialCheck: false, precheck, run, reconcile, diff --git a/apps/server/src/kin/persistence/KinMigrations.test.ts b/apps/server/src/kin/persistence/KinMigrations.test.ts index 86fac821df72c..cab02c8137e1f 100644 --- a/apps/server/src/kin/persistence/KinMigrations.test.ts +++ b/apps/server/src/kin/persistence/KinMigrations.test.ts @@ -95,6 +95,12 @@ const upstreamHistory = Effect.gen(function* () { `; }); +const undoApproverKeyConfirmations = Effect.gen(function* () { + const sql = yield* SqlClient.SqlClient; + yield* sql`DROP TABLE kin_approver_key_confirmations`; + yield* sql`ALTER TABLE kin_approver_keys DROP COLUMN pending_seal`; +}); + describe("Kin migrations", () => { it.effect( "creates K001, K002 and K003 in their own track after upstream and reruns without changes", @@ -535,6 +541,7 @@ describe("Kin migrations", () => { const sql = yield* SqlClient.SqlClient; yield* sql`DROP TABLE kin_auth_paired_sessions`; yield* sql`DROP TABLE kin_approver_key_confirmations`; + yield* sql`ALTER TABLE kin_approver_keys DROP COLUMN pending_seal`; yield* sql`ALTER TABLE kin_approver_keys DROP COLUMN seal`; for (const column of [ "enqueued_at", @@ -606,12 +613,16 @@ describe("Kin migrations", () => { ]; for (const column of workerColumns) yield* sql`ALTER TABLE kin_workers DROP COLUMN ${sql(column)}`; + yield* undoApproverKeyConfirmations; yield* sql`DELETE FROM kin_sql_migrations WHERE migration_id >= 32`; assert.deepStrictEqual((yield* kinHistory).at(-1), { migration_id: 31, name: "LeadDeliveries", }); - assert.deepStrictEqual(yield* runKinMigrations(), [[32, "WorkerEnvironment"]]); + assert.deepStrictEqual(yield* runKinMigrations(), [ + [32, "WorkerEnvironment"], + [33, "ApproverKeyConfirmations"], + ]); const columns = yield* sql<{ name: string }>` SELECT name FROM pragma_table_info('kin_workers')`; for (const column of workerColumns) @@ -623,6 +634,59 @@ describe("Kin migrations", () => { }).pipe(Effect.provide(layer)), ); + it.effect( + "K033 upgrades a database at K032_WorkerEnvironment and keeps its K031 and K032 rows", + () => + Effect.gen(function* () { + const sql = yield* SqlClient.SqlClient; + const timestamp = 1_700_000_000_000; + yield* sql`INSERT INTO kin_orgs (org_id, name, created_at) VALUES ('org', 'Kin', ${timestamp})`; + const delivery = { + org_id: "org", + event_id: "event", + kind: "reminder", + agent_id: "lead", + chat_id: "chat", + widget_id: "widget", + widget_type: "reminder", + state_json: "{}", + fallback_body: "Reminder", + deadline_at: timestamp, + status: "pending", + message_id: null, + created_at: timestamp, + updated_at: timestamp, + }; + yield* sql`INSERT INTO kin_lead_deliveries ${sql.insert(delivery)}`; + yield* undoApproverKeyConfirmations; + yield* sql`DELETE FROM kin_sql_migrations WHERE migration_id = 33`; + assert.deepStrictEqual((yield* kinHistory).slice(-2), [ + { migration_id: 31, name: "LeadDeliveries" }, + { migration_id: 32, name: "WorkerEnvironment" }, + ]); + assert.deepStrictEqual(yield* runKinMigrations(), [[33, "ApproverKeyConfirmations"]]); + assert.deepStrictEqual((yield* kinHistory).slice(-3), [ + { migration_id: 31, name: "LeadDeliveries" }, + { migration_id: 32, name: "WorkerEnvironment" }, + { migration_id: 33, name: "ApproverKeyConfirmations" }, + ]); + assert.deepStrictEqual(yield* sql`SELECT * FROM kin_lead_deliveries`, [delivery]); + assert.deepStrictEqual( + yield* sql`SELECT name FROM pragma_table_info('kin_workers') WHERE name = 'environment_id'`, + [{ name: "environment_id" }], + ); + assert.deepStrictEqual( + yield* sql`SELECT name FROM pragma_table_info('kin_approver_keys') WHERE name = 'pending_seal'`, + [{ name: "pending_seal" }], + ); + assert.deepStrictEqual( + yield* sql`SELECT name FROM sqlite_master WHERE name = 'kin_approver_key_confirmations'`, + [{ name: "kin_approver_key_confirmations" }], + ); + assert.deepStrictEqual(yield* runKinMigrations(), []); + }).pipe(Effect.provide(layer)), + ); + it.effect("refuses to start when a registered migration sits below the latest applied one", () => Effect.gen(function* () { const sql = yield* SqlClient.SqlClient; diff --git a/apps/server/src/kin/persistence/migrations/K033_ApproverKeyConfirmations.ts b/apps/server/src/kin/persistence/migrations/K033_ApproverKeyConfirmations.ts index 7d40145968529..8f432bd268af7 100644 --- a/apps/server/src/kin/persistence/migrations/K033_ApproverKeyConfirmations.ts +++ b/apps/server/src/kin/persistence/migrations/K033_ApproverKeyConfirmations.ts @@ -3,6 +3,7 @@ import * as SqlClient from "effect/sql/SqlClient"; // The phone's 6-digit code, kept where the host's `kin approvals confirm-key` CLI can consume it. // `verifier` is an HMAC over the row's tuple and the code, so a row written into SQLite can't pass. +// `pending_seal` is registration's HMAC over a pending key's holder and attestation verdict. export default Effect.gen(function* () { const sql = yield* SqlClient.SqlClient; yield* sql` @@ -19,4 +20,5 @@ export default Effect.gen(function* () { FOREIGN KEY (org_id, thumbprint) REFERENCES kin_approver_keys(org_id, thumbprint) ) `; + yield* sql`ALTER TABLE kin_approver_keys ADD COLUMN pending_seal TEXT`; }); diff --git a/docs/kin/specs/approvals.md b/docs/kin/specs/approvals.md index 330464e042ee8..90c86095c5287 100644 --- a/docs/kin/specs/approvals.md +++ b/docs/kin/specs/approvals.md @@ -204,12 +204,12 @@ export const KinApproverKey = Schema.Struct({ Registration: -1. The phone calls `kin.approvals.keyChallenge()` (`access:write`), which returns a single-use 32-byte nonce bound to that session and valid for 5 minutes. It passes the nonce to `createKey`, then calls `kin.approvals.registerKey({publicJwk, platform, challenge, attestation?, deviceLabel})` over the same session. The server consumes the nonce, stores the key as `pending` and returns a 6-digit code derived from `sha256(thumbprint ‖ serverNonce)`, where `serverNonce` is that challenge. Challenges live in server memory, so after a restart the phone asks for a new one. An attested key's code is stored with it in `kin_approver_key_confirmations` (K031), so the host CLI below, a separate process, can check it: a code is good for 10 minutes and five tries, and the row holds only an HMAC (`KinKeySeal.confirmation`, keyed by the seal secret) over the org, thumbprint, public JWK, person, hardware, registering session, `sha256(challenge)` and the code. A row edited or inserted in SQLite therefore never verifies. A thumbprint registers only once. +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 live in server memory, so after a restart the phone asks for a new one. An attested key's code is stored with it in `kin_approver_key_confirmations` (K033), so the host CLI below, a separate process, can check it: a code is good for 10 minutes and five tries, and the row holds only an HMAC (`KinKeySeal.confirmation`, keyed by the seal secret) over the org, thumbprint, public JWK, person, hardware, registering session, `sha256(challenge)` and the code. A row edited or inserted in SQLite therefore never verifies. An attested key's row also gets a `pending_seal` (`KinKeySeal.pendingSeal`, same secret) over the org, thumbprint, public JWK, person, device label, platform, hardware, `attested`, registering session and DPoP key thumbprint: what registration vouched for. Every activation, by the host or by grant, checks it on the row it updates and pins those fields in that `UPDATE`; a pending row whose pending seal is missing or doesn't verify reads as unattested, never activates, and isn't listed on the host. A thumbprint registers only once. - **Android:** `attestation.certificateChain` is required. The server checks it offline: the chain verifies up to one of Google's two hardware attestation roots (the legacy RSA root and the newer ECDSA root), each pinned by its public key, and no certificate is on Google's attestation revocation list; the leaf's public key equals `publicJwk` and is EC P-256; the KeyDescription is read from the leaf only, and a chain where any other certificate carries one is refused; 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 with `ecCurve` P-256 and `keySize` 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; `allApplications` absent from both authorization lists; `attestationApplicationId` names exactly one package, 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. Invalidation on biometric re-enrolment is checked only on the client (`KeyInfo` after creation, README); attestation can't prove it. 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:** `attestation` is `{format: "apple-app-attest", keyId, attestationObject}`. `createKey` makes it natively: a fresh App Attest key, attested over the client data hash `sha256(challenge ‖ 0x04 ‖ x ‖ y)` of the Secure Enclave key it just made. The module computes that hash itself, so JS can't get an attestation over a key or data it chose. The server follows Apple's documented verification: the `x5c` chain verifies to the pinned Apple App Attest root; the nonce extension (OID `1.2.840.113635.100.8.2`) equals `sha256(authData ‖ clientDataHash)`, where the server recomputes `clientDataHash` from the nonce it issued and `publicJwk`; the credential certificate's public key hashes to `keyId`; `authData`'s RP ID hash is `sha256(".")` for the Kin bundle id; the counter is 0; the aaguid is `appattest` followed by seven zero bytes for production builds, and `appattestdevelop` only on a server configured to accept development builds; the credential id equals `keyId`. All pass: `attested: true`, `hardware: "secure_enclave"`. No attestation (a simulator or an unsupported device) or any failed check: `attested: false`, `hardware: "software"`. The attestation object's `fmt` must be `apple-appattest` (the CBOR field, distinct from the client's `format` label `apple-app-attest`). `keyId` is `sha256` of the credential certificate's public key as the 65-byte X9.63 point, not its SPKI. Every certificate in `x5c` must be valid at verification time. The App Attest key is used only here; nothing later asserts with it, so the attestation's receipt isn't needed. App Attest proves the app, not its version: once several native builds have shipped, the server keeps a minimum native build (or a version allowlist) and refuses registration from older ones. On iOS `attested: true` means a genuine Kin app instance asked for this public key. It does not prove the approver key is in the Secure Enclave or gated by biometrics, and it does not detect a jailbroken phone; Android's attestation does prove hardware storage and a verified, locked boot. The owner accepted this weaker meaning for phase 1 (2026-11-09), since without it no iPhone could approve. `hardware: "secure_enclave"` is claimed by the platform, not proven. - **Either platform:** the server never makes a key with `attested: false` `active`. It is listed as "can't be used for approvals" and can only be revoked; it gets no stored code, so the host can't confirm it, and no `register_approver_key` action can be requested for it. This is what stops tampered JS from deleting the hardware key, making a P-256 key in JS and registering it: the 6-digit code would match, because it derives from whatever key was registered, but that key can't be attested. 2. **First key in an org:** confirmed on the Kin host by the owner, in a shell as the server's OS user: `t3 kin approvals confirm-key` (`apps/server/src/kin/cli/approvals.ts`, `approvals/HostKeyCeremony.ts`; steps in `ops/kin/host/README.md`). No RPC confirms a key, so no client, remote session, tunnel or agent can; the shell on the host is the guard, and the code only proves the owner is looking at that phone. The CLI lists each pending attested key with its device label, platform, hardware, full thumbprint, org, person, registering session and code expiry. The owner picks one and types the code the phone shows. One transaction counts the try (the first statement is the write, so it holds SQLite's lock), checks the code against that exact org, key, session and challenge through the stored HMAC, activates and seals only that key, deletes the code and writes `key_confirmed`. A wrong code, an expired one, a sixth try, or the right code named with another key or session is refused (`bad_code`), and the try still counts. It works only while the org has no active key. The Kin host is headless Linux and the owner's desktop is a remote client, so the earlier rule (the desktop app's loopback `desktop-bootstrap` session) could never pass there; it is gone, with `kin.approvals.confirmKey`. -3. **Later keys:** confirmed by a grant of kind `register_approver_key` signed by an existing active key. Its `device_key` target carries the new key's `hardware` and `attested` from the server's record, so the phone's prompt shows them (`Add approver key NzbLsXh8uDCcd-6MNwXF4W_7noWXFZAfHkxZsRGC9Xs (Secure Enclave, attested)`), and the module refuses a target that isn't attested. 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. The card belongs to no lead, so it isn't posted in a chat: `listKeys` returns the org's awaiting `enrolments`, and the owner's active phone draws each from `kin.approvals.get` on its Approvals screen (device label, full thumbprint, hardware and attestation) and signs it with Face ID. The CLI refuses a later key unless `--recover` is given. +3. **Later keys:** confirmed by a grant of kind `register_approver_key` signed by an existing active key. Its `device_key` target carries the new key's `hardware` and `attested` from the server's record, so the phone's prompt shows them (`Add approver key NzbLsXh8uDCcd-6MNwXF4W_7noWXFZAfHkxZsRGC9Xs (Secure Enclave, attested)`), and the module refuses a target that isn't attested. 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`, its pending seal verifies and it is on the hardware the card showed. It writes nothing to GitHub, so it skips the credential hygiene check (section 12). The card belongs to no lead, so it isn't posted in a chat: `listKeys` returns the org's awaiting `enrolments`, and the owner's active phone draws each from `kin.approvals.get` on its Approvals screen (device label, full thumbprint, hardware and attestation) and signs it with Face ID. `get` returns the device label and hardware (`keyDeviceLabel`, `keyHardware`) only while the pending seal verifies; otherwise the card shows the thumbprint alone, Approve is blocked, and `approvalChallenge` refuses, since the action's target is only what the database says. The CLI refuses a later key unless `--recover` is given. - **Lost device:** `t3 kin approvals confirm-key --recover` on the host, with the new phone's code, revokes every other key the same person holds (voiding approvals they signed that haven't run, and cancelling their pending registrations), writes `key_revoked` for each, then activates the new key and writes `key_confirmed` with `result: "host recovery"`, all in the code's transaction. 4. Revoking (`kin.approvals.revokeKey`, from settings or the desktop) sets `revoked` and voids every `approved` action whose grant that key signed. Revoking a T3 device session (`revokeClient`) also revokes keys registered from it. Kin reads `auth_sessions.revoked_at` at startup and before it trusts, lists or activates a key, rather than hooking T3's auth code. Revoking also cancels a pending `register_approver_key` action for the key. Expiry is not revocation: a key outlives the session that registered it. A DPoP relay session renews hourly under a new session id but the same DPoP key, so each key also stores that key's thumbprint (`proof_key_thumbprint`), and revoking any session of that DPoP key revokes the key (below). @@ -275,7 +275,7 @@ export const KinGrantPayload = Schema.Struct({ `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))`; `jti` is at least 16 bytes (22 base64url characters) and `nonce` is 32 bytes (43 characters) → `malformed`. The device parsers refuse the same. -2. `kid` is an `active` and attested key in `payload.orgId`, and `payload.approver.kid` equals it → `unknown_key` / `revoked_key`. "Attested" also needs the row's `seal`: an HMAC-SHA256, keyed by the server secret `kin-approver-key-seal`, over the org, thumbprint, public JWK, person and hardware, written by the host ceremony and `register_approver_key` in the same `UPDATE` that activates the key and cleared on revoke (`approvals/KeySeal.ts`). An unattested key never activates, and a row inserted or edited in SQLite carries no valid seal, so either one found active means the database was edited; it fails `unknown_key`. The attestation evidence itself is checked once, at registration, and not stored, so the seal is what carries that verdict forward. It defends against a SQLite write only: whatever can read the secrets directory can forge one. +2. `kid` is an `active` and attested key in `payload.orgId`, and `payload.approver.kid` equals it → `unknown_key` / `revoked_key`. "Attested" also needs the row's `seal`: an HMAC-SHA256, keyed by the server secret `kin-approver-key-seal`, over the org, thumbprint, public JWK, person and hardware, written by the host ceremony and `register_approver_key` in the same `UPDATE` that activates the key and cleared on revoke (`approvals/KeySeal.ts`). An unattested key never activates, and a row inserted or edited in SQLite carries no valid seal, so either one found active means the database was edited; it fails `unknown_key`. The attestation evidence itself is checked once, at registration, and not stored, so the pending seal carries that verdict to activation and the seal carries it after. It defends against a SQLite write only: whatever can read the secrets directory can forge one. 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.) @@ -314,12 +314,12 @@ interface KinActionHandler { A `run` that can't tell whether its side effect landed (no answer, a 5xx, an unreadable 200, a defect) fails `unknown_outcome`; the executor then reconciles and never calls `run` again. Owner writes give up after 30 seconds, which counts as no answer. -Handlers register through `KinActionHandlers` (a Context service, built from one list in `approvals/layer.ts`). This spec ships `merge_pull_request`, `delete_branch` and `register_approver_key`; the lead spec registers `set_level` and `change_rules`; the triggers spec registers `memory_purge`. An approved action whose kind has no handler is voided (`unsupported_kind`) without a claim. On a host without the GitHub App and scope configured, `merge_pull_request` and `delete_branch` have no handler but are held instead, so their grants lapse like any other held grant. Each held action gets one audit entry per hold reason (`execution_held` with `held: not_configured`, `held: paused` and so on, or `credential_check_failed`), and when the sweep voids one whose grant lapsed while held, the owner's notice names the reason. The executor, its ledger and its handlers stay out of `approvals/layer.ts`'s output: context lookups go by key string, and that output reaches every service holding `kin.services`. +Handlers register through `KinActionHandlers` (a Context service, built from one list in `approvals/layer.ts`). This spec ships `merge_pull_request`, `delete_branch` and `register_approver_key`; the lead spec registers `set_level` and `change_rules`; the triggers spec registers `memory_purge`. `register_approver_key` and `set_level` write nothing to GitHub, so they skip the credential hygiene check (section 12). An approved action whose kind has no handler is voided (`unsupported_kind`) without a claim. On a host without the GitHub App and scope configured, `merge_pull_request` and `delete_branch` have no handler but are held instead, so their grants lapse like any other held grant. Each held action gets one audit entry per hold reason (`execution_held` with `held: not_configured`, `held: paused` and so on, or `credential_check_failed`), and when the sweep voids one whose grant lapsed while held, the owner's notice names the reason. The executor, its ledger and its handlers stay out of `approvals/layer.ts`'s output: context lookups go by key string, and that output reaches every service holding `kin.services`. Run order for an `approved` action: 1. Stop switch (lead spec) off → else stay `approved` until the grant lapses, then the sweep voids it. -2. Approver still owner (`KinOrgRoles`), and for GitHub kinds (and `register_approver_key`, section 12) `CredentialHygiene.requirePassing` passes → else stay `approved` (one `credential_check_failed` entry per action and failure set) until the grant lapses. Checking before the claim keeps a misconfigured host from spending the grant. +2. Approver still owner (`KinOrgRoles`), and for GitHub kinds (section 12) `CredentialHygiene.requirePassing` passes → else stay `approved` (one `credential_check_failed` entry per action and failure set) until the grant lapses. Checking before the claim keeps a misconfigured host from spending the grant. 3. Before the claim, the stored grant must verify again: its signature against its key's public JWK, that key's seal (check 2), and its payload binding this action's org, id, revision, `jti`, approver and facts (check 7) → else `voided: grant_unverified`. A grant row or an `approved` state written straight into SQLite stops here. 4. **Claim:** `INSERT INTO kin_executions(action_id, …)` and CAS `approved → executing` in one transaction. The insert also requires the grant unconsumed and alive, the signing key usable, and the org not paused. A failed insert means it already ran, is running or may not run: refuse. 5. A fresh hygiene pass for the kinds step 2 checks, and the signing key and the approver's owner role checked again, then `precheck` with the bot's read-only `server` token (each read gives up after 15 seconds, which ends the action `failed`): PR open, `head.sha == grant.headSha`, `base.ref == grant.base`, and no `merge_queue` rule on the base (`GET /repos/{o}/{r}/rules/branches/{base}`; phase 1 refuses merge queues: `merge_queue_unsupported`). Whether the repo allows the method is left to GitHub, whose 405 ends the action `failed: not_mergeable`. Any failure from here on is `failed`: the grant is spent. @@ -541,7 +541,7 @@ At startup and hourly, the executor checks every GitHub identity reachable from A merge token in its last 7 days passes with the `merge_token_expiring` warning, which drives the expiry card. `requirePassing` returns a `CredentialHygienePass`, which `OwnerMergeClient.token` requires (section 6). The merge token itself is probed once, at `save` (section 10); the hourly check reads only its stored login and expiry. GitHub lets the owner widen a fine-grained token's permissions without changing its value, so a token widened after `save` (for example to Pull requests: write) goes unnoticed until it's saved again. Rerunning the read-only probes in the hourly check is a follow-up. -The identity probe is the `T3GitHubIdentity` port. `@t3tools/source-control-github` exports only its driver, so `GitHubRequestPolicy.credential` can't be reached from `apps/server` without a one-line export there. APPR-9 wires the executor with `identityUnavailableLayer`, which fails every probe, so no privileged action runs on a real host until APPR-16 adds that export and the live layer. That includes `register_approver_key`, which passes the same check, so a second device can't be enrolled until APPR-16 lands, nor on a host without GitHub configured. The port's `identities` has a required field per source (`t3`, `ghAccounts`, `gitCredential`, `ssh`), so the live layer must report all four. It reads `gh` accounts from `gh auth status --hostname github.com`, and the git helper's login from `git credential fill` for `https://github.com` followed by `GET /user` with the returned password, never logging it. For `ssh` it runs `ssh -T -o BatchMode=yes -o StrictHostKeyChecking=yes git@github.com` (`GITHUB_SSH_PROBE`) with a timeout, then the same once per private key in `~/.ssh` with `-o IdentitiesOnly=yes -i `, and reports each answer's combined output; the check parses them , so the live layer can't misread one, and an empty list fails. A deploy key's greeting names `owner/repo`, which fails as `non_bot_identity`. Keys behind another `Host` alias in `~/.ssh/config` aren't probed. A source it can't read fails the probe, which fails the check closed (`identity_unknown`). +The identity probe is the `T3GitHubIdentity` port. `@t3tools/source-control-github` exports only its driver, so `GitHubRequestPolicy.credential` can't be reached from `apps/server` without a one-line export there. APPR-9 wires the executor with `identityUnavailableLayer`, which fails every probe, so no privileged action runs on a real host until APPR-16 adds that export and the live layer. `register_approver_key` doesn't take the check (owner's decision, 2026-11-10): it writes nothing to GitHub, and a passing check would neither authenticate an enrolment nor protect the seal secret. Its signature and attestation checks are unchanged, so a second phone enrols once the first signs, with or without GitHub configured. The port's `identities` has a required field per source (`t3`, `ghAccounts`, `gitCredential`, `ssh`), so the live layer must report all four. It reads `gh` accounts from `gh auth status --hostname github.com`, and the git helper's login from `git credential fill` for `https://github.com` followed by `GET /user` with the returned password, never logging it. For `ssh` it runs `ssh -T -o BatchMode=yes -o StrictHostKeyChecking=yes git@github.com` (`GITHUB_SSH_PROBE`) with a timeout, then the same once per private key in `~/.ssh` with `-o IdentitiesOnly=yes -i `, and reports each answer's combined output; the check parses them , so the live layer can't misread one, and an empty list fails. A deploy key's greeting names `owner/repo`, which fails as `non_bot_identity`. Keys behind another `Host` alias in `~/.ssh/config` aren't probed. A source it can't read fails the probe, which fails the check closed (`identity_unknown`). The check only sees what the server's OS user is set up with. An agent running as that user can still read anything that user can: it can find an SSH agent socket on disk and set `SSH_AUTH_SOCK` itself, read the merge token and the App's private key from the keychain (open question 4), or use credentials outside these sources. The real fix is a separate executor OS user. diff --git a/packages/client-runtime/src/kin/kinApprovalPresentation.test.ts b/packages/client-runtime/src/kin/kinApprovalPresentation.test.ts index 5123e722588b5..0696acf1fc684 100644 --- a/packages/client-runtime/src/kin/kinApprovalPresentation.test.ts +++ b/packages/client-runtime/src/kin/kinApprovalPresentation.test.ts @@ -62,7 +62,12 @@ const merge = (overrides: Partial = {}) => const full = ( action: KinPendingAction, - names: { leadName?: string; afterNonOwnerName?: string; keyDeviceLabel?: string } = { + names: { + leadName?: string; + afterNonOwnerName?: string; + keyDeviceLabel?: string; + keyHardware?: "secure_enclave"; + } = { leadName: "Tech lead", afterNonOwnerName: "Priya", }, @@ -99,7 +104,12 @@ describe("kinApprovalCardView", () => { it("names who asked from the provenance the host recorded", () => { const asked = ( provenance: Partial, - names: { leadName?: string; afterNonOwnerName?: string; keyDeviceLabel?: string } = { + names: { + leadName?: string; + afterNonOwnerName?: string; + keyDeviceLabel?: string; + keyHardware?: "secure_enclave"; + } = { leadName: "Tech lead", }, ) => @@ -210,18 +220,25 @@ describe("kinApprovalCardView", () => { ceilingBelowOwner: false, }, } as unknown as Partial); - const card = kinApprovalCardView(full(enrol, { keyDeviceLabel: "Nishchay's iPhone" })); + const card = kinApprovalCardView( + full(enrol, { keyDeviceLabel: "Nishchay's iPhone", keyHardware: "secure_enclave" }), + ); expect(card).toMatchObject({ title: "Let a new phone approve", asked: { text: "You asked for this.", warning: false }, reason: null, decidable: true, + approveBlocked: null, }); expect(card.facts.map((fact) => [fact.label, fact.value])).toEqual([ ["Phone", "Nishchay's iPhone"], ["Key", thumbprint], ["Hardware", "Secure Enclave, attested"], ]); + // A key the server can't vouch for: the target's hardware claim is never shown or signed. + const unvouched = kinApprovalCardView(full(enrol, {})); + expect(unvouched.facts.map((fact) => [fact.label, fact.value])).toEqual([["Key", thumbprint]]); + expect(unvouched.approveBlocked).toMatch(/can't vouch/); }); it("anyone else sees who it waits on and never a button", () => { diff --git a/packages/client-runtime/src/kin/kinApprovalPresentation.ts b/packages/client-runtime/src/kin/kinApprovalPresentation.ts index f94476d715760..8b66a3de50497 100644 --- a/packages/client-runtime/src/kin/kinApprovalPresentation.ts +++ b/packages/client-runtime/src/kin/kinApprovalPresentation.ts @@ -242,11 +242,11 @@ function fullView( if (label) fact("phone", "Phone", label); // Whole, as the Face ID prompt shows it: the new phone shows the same key on its screen. fact("key", "Key", action.target.thumbprint, true); - fact( - "hardware", - "Hardware", - `${KEY_HARDWARE[action.target.hardware]}, ${action.target.attested ? "attested" : "not attested"}`, - ); + // Only what the server vouches for; the target alone is just what the database says. + if (view.keyHardware === undefined) + approveBlocked = + "Kin can't vouch for this phone's key. Decline it and set the phone up again."; + else fact("hardware", "Hardware", `${KEY_HARDWARE[view.keyHardware]}, attested`); } else { title = "Approve this request"; } diff --git a/packages/contracts/src/kinApprovals.ts b/packages/contracts/src/kinApprovals.ts index 4423fe5c7ac29..09a2bf2da5ae3 100644 --- a/packages/contracts/src/kinApprovals.ts +++ b/packages/contracts/src/kinApprovals.ts @@ -411,8 +411,12 @@ export const KinApprovalView = Schema.Union([ /** Display names the server looked up: the lead it concerns, and `afterNonOwnerMessage`'s author. */ leadName: Schema.optional(KinText), afterNonOwnerName: Schema.optional(KinText), - /** For `register_approver_key`: the new key's device label, from the host's key record. */ + /** + * For `register_approver_key`, present only while the server vouches for the new key's record + * (registration's pending seal verifies): its device label and attested hardware. + */ keyDeviceLabel: Schema.optional(KinText), + keyHardware: Schema.optional(Schema.Literals(["secure_enclave", "strongbox", "tee"])), }), Schema.TaggedStruct("redacted", { actionId: KinActionId, From 5f475647365a780b0fb10e6ac74bb7d5d93356ab Mon Sep 17 00:00:00 2001 From: GLDRoger <130458023+GLDRoger@users.noreply.github.com> Date: Tue, 10 Nov 2026 14:01:30 +0530 Subject: [PATCH 8/8] fix(kin): approver key seals cover created_at created_at is the `since` bound for the session-revocation check, so a database edit that moved it past a repaired revocation could keep a key usable. Both the pending seal and the active seal now cover it, the activating UPDATE pins it, and execution checks it with the rest of the seal. Co-Authored-By: Claude Opus 5.5 --- apps/server/src/kin/approvals/ActionExecutor.test.ts | 3 +++ apps/server/src/kin/approvals/ActionExecutor.ts | 4 +++- apps/server/src/kin/approvals/ApproverKeyStore.ts | 2 ++ apps/server/src/kin/approvals/ApproverKeys.test.ts | 11 +++++++++++ apps/server/src/kin/approvals/GrantVerifier.test.ts | 4 +++- apps/server/src/kin/approvals/KeySeal.ts | 3 +++ apps/server/src/kin/approvals/grant.testkit.ts | 2 ++ docs/kin/specs/approvals.md | 4 ++-- 8 files changed, 29 insertions(+), 4 deletions(-) diff --git a/apps/server/src/kin/approvals/ActionExecutor.test.ts b/apps/server/src/kin/approvals/ActionExecutor.test.ts index c932fac8422e5..2bcc0fcc42419 100644 --- a/apps/server/src/kin/approvals/ActionExecutor.test.ts +++ b/apps/server/src/kin/approvals/ActionExecutor.test.ts @@ -780,6 +780,9 @@ describe("KinActionExecutor", () => { yield* refuse("unbound-head", { payload: (payload) => ({ ...payload, headSha: MOVED }) }); yield* refuse("forged-signature", { forged: true }); const sql = yield* SqlClient.SqlClient; + // `created_at` bounds the session-revocation check, so the seal covers it. + yield* sql`UPDATE kin_approver_keys SET created_at = created_at + 1 WHERE org_id = ${orgId}`; + yield* refuse("moved-created-at"); yield* sql`DELETE FROM kin_approver_keys WHERE org_id = ${orgId}`; yield* insertKey(orgId, { sealed: false }); yield* refuse("unsealed-key"); diff --git a/apps/server/src/kin/approvals/ActionExecutor.ts b/apps/server/src/kin/approvals/ActionExecutor.ts index 061be1664a24c..adb70824c96ad 100644 --- a/apps/server/src/kin/approvals/ActionExecutor.ts +++ b/apps/server/src/kin/approvals/ActionExecutor.ts @@ -120,8 +120,9 @@ export const make = Effect.gen(function* () { public_jwk_json: string; human_id: string; hardware: string; + created_at: number; seal: string | null; - }>`SELECT public_jwk_json, human_id, hardware, seal FROM kin_approver_keys + }>`SELECT public_jwk_json, human_id, hardware, created_at, seal FROM kin_approver_keys WHERE org_id = ${action.orgId} AND thumbprint = ${grant.keyThumbprint} ORDER BY thumbprint LIMIT 1`; if (key === undefined || key.human_id !== grant.approverHumanId) return false; @@ -132,6 +133,7 @@ export const make = Effect.gen(function* () { publicJwkJson: key.public_jwk_json, humanId: key.human_id, hardware: key.hardware, + createdAt: key.created_at, }, key.seal, ); diff --git a/apps/server/src/kin/approvals/ApproverKeyStore.ts b/apps/server/src/kin/approvals/ApproverKeyStore.ts index 1370abcd02182..d4942f6cb3ba3 100644 --- a/apps/server/src/kin/approvals/ApproverKeyStore.ts +++ b/apps/server/src/kin/approvals/ApproverKeyStore.ts @@ -66,6 +66,7 @@ export const sealFields = (row: KeyRow) => ({ publicJwkJson: row.public_jwk_json, humanId: row.human_id, hardware: row.hardware, + createdAt: row.created_at, }); export const pendingSealFields = (row: KeyRow) => ({ @@ -171,6 +172,7 @@ export const makeKeyStore = Effect.gen(function* () { AND hardware = ${row.hardware} AND device_label = ${row.device_label} AND platform = ${row.platform} AND session_id IS ${row.session_id} AND proof_key_thumbprint IS ${row.proof_key_thumbprint} + AND created_at = ${row.created_at} AND ${ onlyFirst ? sql`NOT EXISTS (SELECT 1 FROM kin_approver_keys diff --git a/apps/server/src/kin/approvals/ApproverKeys.test.ts b/apps/server/src/kin/approvals/ApproverKeys.test.ts index 90ffa91716609..5136d51e99cf0 100644 --- a/apps/server/src/kin/approvals/ApproverKeys.test.ts +++ b/apps/server/src/kin/approvals/ApproverKeys.test.ts @@ -673,6 +673,17 @@ describe("ApproverKeys", () => { yield* sql`UPDATE kin_approver_keys SET device_label = 'Owner phone' WHERE thumbprint = ${genuine.key.thumbprint}`; assert.isFalse(yield* keys.activateByGrant(genuine.key)); + // `created_at` bounds the session-revocation check, so moving it voids both seals. + const moved = yield* registerAndroid(keys, caller("sess-phone-3", "phone")); + yield* sql`UPDATE kin_approver_keys SET created_at = created_at + 1 + WHERE thumbprint = ${moved.key.thumbprint}`; + assert.isFalse(Option.getOrThrow(yield* keys.get(moved.key)).attested); + assert.isFalse(yield* keys.activateByGrant(moved.key)); + assert.strictEqual(Option.getOrThrow(yield* keys.get(moved.key)).state, "pending"); + assert.isTrue((yield* keys.requireActive(first.key)).attested); + yield* sql`UPDATE kin_approver_keys SET created_at = created_at + 1 + WHERE thumbprint = ${first.key.thumbprint}`; + assert.isFalse((yield* keys.requireActive(first.key)).attested); }).pipe(Effect.provide(layer)), ); }); diff --git a/apps/server/src/kin/approvals/GrantVerifier.test.ts b/apps/server/src/kin/approvals/GrantVerifier.test.ts index d5e2921d3044b..8f879caa94d58 100644 --- a/apps/server/src/kin/approvals/GrantVerifier.test.ts +++ b/apps/server/src/kin/approvals/GrantVerifier.test.ts @@ -1268,7 +1268,8 @@ describe("GrantVerifier", () => { public_jwk_json: string; human_id: string; hardware: string; - }>`SELECT public_jwk_json, human_id, hardware + created_at: number; + }>`SELECT public_jwk_json, human_id, hardware, created_at FROM kin_approver_keys WHERE org_id = ${orgId} AND thumbprint = ${ownerKey.key.thumbprint}`; const seal = (yield* KeySeal.KinKeySeal.pipe(Effect.provide(KeySeal.layerTest()))).seal({ orgId: "org_02", @@ -1276,6 +1277,7 @@ describe("GrantVerifier", () => { publicJwkJson: copied!.public_jwk_json, humanId: copied!.human_id, hardware: copied!.hardware, + createdAt: copied!.created_at, }); yield* sql`INSERT INTO kin_approver_keys (thumbprint, org_id, public_jwk_json, human_id, device_label, platform, hardware, attested, state, created_at, confirmed_at, seal) diff --git a/apps/server/src/kin/approvals/KeySeal.ts b/apps/server/src/kin/approvals/KeySeal.ts index 5324660b6b49e..02330a9eaa56d 100644 --- a/apps/server/src/kin/approvals/KeySeal.ts +++ b/apps/server/src/kin/approvals/KeySeal.ts @@ -20,6 +20,8 @@ export type KinSealedKeyFields = { readonly publicJwkJson: string; readonly humanId: string; readonly hardware: string; + /** The `since` bound for session revocations, so moving it can't hide a repaired revoke. */ + readonly createdAt: number; }; /** @@ -73,6 +75,7 @@ const make = ( publicJwkJson: key.publicJwkJson, humanId: key.humanId, hardware: key.hardware, + createdAt: key.createdAt, }); const seal = (key: KinSealedKeyFields) => mac({ v: 1, use: "kin-approver-key", ...keyFields(key) }); diff --git a/apps/server/src/kin/approvals/grant.testkit.ts b/apps/server/src/kin/approvals/grant.testkit.ts index 6924f9267c5df..04c77ab16e531 100644 --- a/apps/server/src/kin/approvals/grant.testkit.ts +++ b/apps/server/src/kin/approvals/grant.testkit.ts @@ -55,6 +55,7 @@ export const insertActiveKey = Effect.fn("grant.testkit.insertActiveKey")(functi publicJwkJson: input.key.publicJwkJson, humanId: input.humanId, hardware: "tee", + createdAt: 0, }; const seal = input.sealed === false ? null : (yield* KinKeySeal).seal(fields); yield* sql`INSERT INTO kin_approver_keys (thumbprint, org_id, public_jwk_json, human_id, @@ -77,6 +78,7 @@ export const insertPendingKey = Effect.fn("grant.testkit.insertPendingKey")(func publicJwkJson: input.key.publicJwkJson, humanId: input.humanId, hardware: "tee", + createdAt: 0, deviceLabel: "Pixel 9", platform: "android", attested: 1, diff --git a/docs/kin/specs/approvals.md b/docs/kin/specs/approvals.md index 90c86095c5287..04d199c1298df 100644 --- a/docs/kin/specs/approvals.md +++ b/docs/kin/specs/approvals.md @@ -204,7 +204,7 @@ export const KinApproverKey = Schema.Struct({ Registration: -1. The phone calls `kin.approvals.keyChallenge()` (`access:write`), which returns a single-use 32-byte nonce bound to that session and valid for 5 minutes. It passes the nonce to `createKey`, then calls `kin.approvals.registerKey({publicJwk, platform, challenge, attestation?, deviceLabel})` over the same session. The server consumes the nonce, stores the key as `pending` and returns a 6-digit code derived from `sha256(thumbprint ‖ serverNonce)`, where `serverNonce` is that challenge. Challenges live in server memory, so after a restart the phone asks for a new one. An attested key's code is stored with it in `kin_approver_key_confirmations` (K033), so the host CLI below, a separate process, can check it: a code is good for 10 minutes and five tries, and the row holds only an HMAC (`KinKeySeal.confirmation`, keyed by the seal secret) over the org, thumbprint, public JWK, person, hardware, registering session, `sha256(challenge)` and the code. A row edited or inserted in SQLite therefore never verifies. An attested key's row also gets a `pending_seal` (`KinKeySeal.pendingSeal`, same secret) over the org, thumbprint, public JWK, person, device label, platform, hardware, `attested`, registering session and DPoP key thumbprint: what registration vouched for. Every activation, by the host or by grant, checks it on the row it updates and pins those fields in that `UPDATE`; a pending row whose pending seal is missing or doesn't verify reads as unattested, never activates, and isn't listed on the host. A thumbprint registers only once. +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 live in server memory, so after a restart the phone asks for a new one. An attested key's code is stored with it in `kin_approver_key_confirmations` (K033), so the host CLI below, a separate process, can check it: a code is good for 10 minutes and five tries, and the row holds only an HMAC (`KinKeySeal.confirmation`, keyed by the seal secret) over the org, thumbprint, public JWK, person, hardware, `created_at`, registering session, `sha256(challenge)` and the code. A row edited or inserted in SQLite therefore never verifies. An attested key's row also gets a `pending_seal` (`KinKeySeal.pendingSeal`, same secret) over the org, thumbprint, public JWK, person, hardware, `created_at`, device label, platform, `attested`, registering session and DPoP key thumbprint: what registration vouched for. Every activation, by the host or by grant, checks it on the row it updates and pins those fields in that `UPDATE`; a pending row whose pending seal is missing or doesn't verify reads as unattested, never activates, and isn't listed on the host. A thumbprint registers only once. - **Android:** `attestation.certificateChain` is required. The server checks it offline: the chain verifies up to one of Google's two hardware attestation roots (the legacy RSA root and the newer ECDSA root), each pinned by its public key, and no certificate is on Google's attestation revocation list; the leaf's public key equals `publicJwk` and is EC P-256; the KeyDescription is read from the leaf only, and a chain where any other certificate carries one is refused; 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 with `ecCurve` P-256 and `keySize` 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; `allApplications` absent from both authorization lists; `attestationApplicationId` names exactly one package, 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. Invalidation on biometric re-enrolment is checked only on the client (`KeyInfo` after creation, README); attestation can't prove it. 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:** `attestation` is `{format: "apple-app-attest", keyId, attestationObject}`. `createKey` makes it natively: a fresh App Attest key, attested over the client data hash `sha256(challenge ‖ 0x04 ‖ x ‖ y)` of the Secure Enclave key it just made. The module computes that hash itself, so JS can't get an attestation over a key or data it chose. The server follows Apple's documented verification: the `x5c` chain verifies to the pinned Apple App Attest root; the nonce extension (OID `1.2.840.113635.100.8.2`) equals `sha256(authData ‖ clientDataHash)`, where the server recomputes `clientDataHash` from the nonce it issued and `publicJwk`; the credential certificate's public key hashes to `keyId`; `authData`'s RP ID hash is `sha256(".")` for the Kin bundle id; the counter is 0; the aaguid is `appattest` followed by seven zero bytes for production builds, and `appattestdevelop` only on a server configured to accept development builds; the credential id equals `keyId`. All pass: `attested: true`, `hardware: "secure_enclave"`. No attestation (a simulator or an unsupported device) or any failed check: `attested: false`, `hardware: "software"`. The attestation object's `fmt` must be `apple-appattest` (the CBOR field, distinct from the client's `format` label `apple-app-attest`). `keyId` is `sha256` of the credential certificate's public key as the 65-byte X9.63 point, not its SPKI. Every certificate in `x5c` must be valid at verification time. The App Attest key is used only here; nothing later asserts with it, so the attestation's receipt isn't needed. App Attest proves the app, not its version: once several native builds have shipped, the server keeps a minimum native build (or a version allowlist) and refuses registration from older ones. On iOS `attested: true` means a genuine Kin app instance asked for this public key. It does not prove the approver key is in the Secure Enclave or gated by biometrics, and it does not detect a jailbroken phone; Android's attestation does prove hardware storage and a verified, locked boot. The owner accepted this weaker meaning for phase 1 (2026-11-09), since without it no iPhone could approve. `hardware: "secure_enclave"` is claimed by the platform, not proven. - **Either platform:** the server never makes a key with `attested: false` `active`. It is listed as "can't be used for approvals" and can only be revoked; it gets no stored code, so the host can't confirm it, and no `register_approver_key` action can be requested for it. This is what stops tampered JS from deleting the hardware key, making a P-256 key in JS and registering it: the 6-digit code would match, because it derives from whatever key was registered, but that key can't be attested. @@ -275,7 +275,7 @@ export const KinGrantPayload = Schema.Struct({ `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))`; `jti` is at least 16 bytes (22 base64url characters) and `nonce` is 32 bytes (43 characters) → `malformed`. The device parsers refuse the same. -2. `kid` is an `active` and attested key in `payload.orgId`, and `payload.approver.kid` equals it → `unknown_key` / `revoked_key`. "Attested" also needs the row's `seal`: an HMAC-SHA256, keyed by the server secret `kin-approver-key-seal`, over the org, thumbprint, public JWK, person and hardware, written by the host ceremony and `register_approver_key` in the same `UPDATE` that activates the key and cleared on revoke (`approvals/KeySeal.ts`). An unattested key never activates, and a row inserted or edited in SQLite carries no valid seal, so either one found active means the database was edited; it fails `unknown_key`. The attestation evidence itself is checked once, at registration, and not stored, so the pending seal carries that verdict to activation and the seal carries it after. It defends against a SQLite write only: whatever can read the secrets directory can forge one. +2. `kid` is an `active` and attested key in `payload.orgId`, and `payload.approver.kid` equals it → `unknown_key` / `revoked_key`. "Attested" also needs the row's `seal`: an HMAC-SHA256, keyed by the server secret `kin-approver-key-seal`, over the org, thumbprint, public JWK, person, hardware and `created_at` (the bound of the session-revocation check), written by the host ceremony and `register_approver_key` in the same `UPDATE` that activates the key and cleared on revoke (`approvals/KeySeal.ts`). An unattested key never activates, and a row inserted or edited in SQLite carries no valid seal, so either one found active means the database was edited; it fails `unknown_key`. The attestation evidence itself is checked once, at registration, and not stored, so the pending seal carries that verdict to activation and the seal carries it after. It defends against a SQLite write only: whatever can read the secrets directory can forge one. 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.)