From 41889324dc8c7ceaa434e6bf114593889c78de4a Mon Sep 17 00:00:00 2001 From: Surajsm60720 <1ds22is166@dsce.edu.in> Date: Sun, 8 Nov 2026 07:07:10 +0530 Subject: [PATCH 1/9] feat(kin): audit events for cancelled and expired actions (APPR-10) Every terminal move gets its own audit event, so the trail never has to describe an expiry as a rejection. Co-Authored-By: Claude Opus 5.5 --- docs/kin/specs/approvals.md | 2 ++ packages/contracts/src/kinApprovals.ts | 2 ++ 2 files changed, 4 insertions(+) diff --git a/docs/kin/specs/approvals.md b/docs/kin/specs/approvals.md index fb8d3c95c4dbb..9943ff6bc5982 100644 --- a/docs/kin/specs/approvals.md +++ b/docs/kin/specs/approvals.md @@ -397,6 +397,8 @@ export const KinAuditEntry = Schema.Struct({ "grant_accepted", "grant_rejected", "action_rejected", + "action_cancelled", + "action_expired", "action_voided", "execution_started", "execution_finished", diff --git a/packages/contracts/src/kinApprovals.ts b/packages/contracts/src/kinApprovals.ts index a3aa39dcb6985..84c7532cec0c4 100644 --- a/packages/contracts/src/kinApprovals.ts +++ b/packages/contracts/src/kinApprovals.ts @@ -328,6 +328,8 @@ export const KinAuditEvent = Schema.Literals([ "grant_accepted", "grant_rejected", "action_rejected", + "action_cancelled", + "action_expired", "action_voided", "execution_started", "execution_finished", From c761ebc2a7f18e0a9aa202d360ce41b025c9b3f2 Mon Sep 17 00:00:00 2001 From: Surajsm60720 <1ds22is166@dsce.edu.in> Date: Sun, 8 Nov 2026 07:20:58 +0530 Subject: [PATCH 2/9] feat(kin): hash-chained approval audit log (APPR-10) Audit.ts appends per-org entries chained by sha256(prevHash || stableStringify(entry without hash)), joins the caller's transaction so each PendingActions transition commits with its entry, and verifies the chain, reporting the first edited, deleted, reordered or inserted row. kin.audit.list and kin.audit.verify replace the APPR-1 stubs, owner-only behind access:write. Co-Authored-By: Claude Opus 5.5 --- apps/server/src/kin/approvals/Audit.test.ts | 466 ++++++++++++++++++ apps/server/src/kin/approvals/Audit.ts | 194 ++++++++ .../src/kin/approvals/PendingActions.test.ts | 6 +- .../src/kin/approvals/PendingActions.ts | 190 +++++-- apps/server/src/kin/approvals/rpcHandlers.ts | 63 ++- docs/kin/specs/approvals.md | 4 + 6 files changed, 869 insertions(+), 54 deletions(-) create mode 100644 apps/server/src/kin/approvals/Audit.test.ts create mode 100644 apps/server/src/kin/approvals/Audit.ts diff --git a/apps/server/src/kin/approvals/Audit.test.ts b/apps/server/src/kin/approvals/Audit.test.ts new file mode 100644 index 0000000000000..bdd20562b2f5e --- /dev/null +++ b/apps/server/src/kin/approvals/Audit.test.ts @@ -0,0 +1,466 @@ +import { assert, describe, it } from "@effect/vitest"; +import { + AuthSessionId, + AuthStandardClientScopes, + KinEventId, + KinKeyThumbprint, + KinOrgId, + KinPersonId, + type KinAuditEvent, + type KinPendingAction, +} from "@t3tools/contracts"; +import { stableStringify } from "@t3tools/shared/relaySigning"; +import * as ConfigProvider from "effect/ConfigProvider"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; +import * as Option from "effect/Option"; +import * as Schema from "effect/Schema"; +import * as SqlClient from "effect/sql/SqlClient"; +import * as TestClock from "effect/testing/TestClock"; + +import type { AuthenticatedSession } from "../../auth/EnvironmentAuth.ts"; +import * as Sqlite from "../../persistence/Sqlite.ts"; +import * as Kin from "../layer.ts"; +import * as KinPersistence from "../persistence/KinPersistence.ts"; +import { KinAudit, kinAuditHash, layer as auditLayer } from "./Audit.ts"; +import { + KinPendingActions, + layer as pendingActionsLayer, + type KinPendingActionCreateInput, +} from "./PendingActions.ts"; +import { makeKinApprovalHandlers } from "./rpcHandlers.ts"; + +const database = Layer.provideMerge(KinPersistence.layer, Sqlite.layerMemory); +const layer = pendingActionsLayer.pipe( + Layer.provideMerge(auditLayer), + Layer.provideMerge(database), +); + +const org = Schema.decodeSync(KinOrgId)("org_01"); +const otherOrg = Schema.decodeSync(KinOrgId)("org_02"); +const defaultOrg = Schema.decodeSync(KinOrgId)("kin-default"); +const decodeEventId = Schema.decodeSync(KinEventId); +const owner = Schema.decodeSync(KinPersonId)("h_owner"); +const kid = Schema.decodeSync(KinKeyThumbprint)("Y0ZkXVc6eNfxv3xVNHZJp1x7m3kQqb2O8s5vB1aWc9E"); +const sessionId = AuthSessionId.make("phone-session"); +const headSha = "a".repeat(40); +const mergeSha = "f".repeat(40); + +const request = { + orgId: "org_01", + kind: "merge_pull_request", + target: { + _tag: "pull_request", + host: "github.com", + repo: "GLDRoger/t3code", + number: 212, + mergeMethod: "squash", + deleteBranchAfter: false, + }, + resolved: { + _tag: "pull_request", + headSha, + base: "main", + head: "kin/fix-212", + title: "Fix 212", + additions: 3, + deletions: 1, + files: 1, + checks: [{ name: "ci", required: true, status: "passed" }], + }, + targetDigest: "1".repeat(64), + reason: "CI is green.", + requestedBy: { agentId: "lead", threadId: "thread-lead" }, + provenance: { startedBy: "github", startedByRole: "none", chain: [] }, + source: decodeEventId("webhook-delivery-1"), +} as unknown as KinPendingActionCreateInput; + +const grant = (action: KinPendingAction, jti: string) => ({ + orgId: action.orgId, + actionId: action.id, + revision: action.revision, + nonce: action.nonce, + jti, + approverHumanId: owner, + keyThumbprint: kid, + compact: `compact-${jti}`, + iat: 0, + exp: 600, + sessionId, + deviceLabel: "Owner's iPhone", +}); + +const seed = Effect.gen(function* () { + const sql = yield* SqlClient.SqlClient; + yield* sql`INSERT INTO kin_orgs (org_id, name, created_at) VALUES + ('org_01', 'Kin', '2026-11-07T00:00:00.000Z'), + ('org_02', 'Other', '2026-11-07T00:00:00.000Z')`; + return yield* KinAudit; +}); + +// Five entries in org_01, so each tamper case has a row in the middle to break. +const seedChain = Effect.gen(function* () { + const audit = yield* seed; + for (const event of [ + "key_registered", + "key_confirmed", + "grant_rejected", + "key_revoked", + "credential_check_failed", + ] as const) { + yield* audit.append({ orgId: org, event, result: event }); + } + return audit; +}); + +describe("KinAudit", () => { + it.effect("the audit chain detects an edited row", () => + Effect.gen(function* () { + const audit = yield* seedChain; + const sql = yield* SqlClient.SqlClient; + assert.deepStrictEqual(yield* audit.verify({ orgId: org }), { + ok: true, + checked: 5, + firstBadSeq: null, + }); + + // Editing the canonical entry, as someone hiding a failure would. + yield* sql`UPDATE kin_audit SET entry_json = replace(entry_json, '"result":"grant_rejected"', + '"result":"grant_accepted"') WHERE org_id = ${org} AND seq = 3`; + assert.deepStrictEqual(yield* audit.verify({ orgId: org }), { + ok: false, + checked: 2, + firstBadSeq: 3, + }); + }).pipe(Effect.provide(layer)), + ); + + it.effect.each([ + { + name: "an edited column", + tamper: (sql: SqlClient.SqlClient) => + sql`UPDATE kin_audit SET event = 'grant_accepted' WHERE org_id = ${org} AND seq = 3`, + }, + { + name: "a rehashed edit", + // The edited row's own hash is recomputed, so only the next row's prevHash gives it away. + tamper: (sql: SqlClient.SqlClient) => + Effect.gen(function* () { + const [row] = yield* sql<{ entry_json: string }>` + SELECT entry_json FROM kin_audit WHERE org_id = ${org} AND seq = 3`; + const { hash: _hash, ...unhashed } = JSON.parse(row!.entry_json); + const edited = { ...unhashed, result: "grant_accepted" }; + const hash = kinAuditHash(edited); + yield* sql`UPDATE kin_audit SET entry_json = ${stableStringify({ ...edited, hash })}, + hash = ${hash} WHERE org_id = ${org} AND seq = 3`; + }), + firstBadSeq: 4, + }, + { + name: "a deleted row", + tamper: (sql: SqlClient.SqlClient) => + sql`DELETE FROM kin_audit WHERE org_id = ${org} AND seq = 3`, + }, + { + name: "reordered rows", + tamper: (sql: SqlClient.SqlClient) => + Effect.gen(function* () { + yield* sql`UPDATE kin_audit SET seq = 100 WHERE org_id = ${org} AND seq = 3`; + yield* sql`UPDATE kin_audit SET seq = 3 WHERE org_id = ${org} AND seq = 4`; + yield* sql`UPDATE kin_audit SET seq = 4 WHERE org_id = ${org} AND seq = 100`; + }), + }, + { + name: "an inserted row", + // A forged entry chained correctly onto seq 2, with every later row shifted down by one. + tamper: (sql: SqlClient.SqlClient) => + Effect.gen(function* () { + const [prev] = yield* sql<{ hash: string }>` + SELECT hash FROM kin_audit WHERE org_id = ${org} AND seq = 2`; + yield* sql`UPDATE kin_audit SET seq = seq + 100 WHERE org_id = ${org} AND seq >= 3`; + yield* sql`UPDATE kin_audit SET seq = seq - 99 WHERE org_id = ${org} AND seq >= 103`; + const unhashed = { + id: "aud_forged", + orgId: org, + seq: 3, + at: "2026-11-08T00:00:00.000Z", + event: "grant_accepted", + prevHash: prev!.hash, + }; + const hash = kinAuditHash(unhashed); + yield* sql`INSERT INTO kin_audit (id, org_id, seq, at, event, entry_json, prev_hash, hash) + VALUES ('aud_forged', ${org}, 3, ${Date.parse(unhashed.at)}, 'grant_accepted', + ${stableStringify({ ...unhashed, hash })}, ${prev!.hash}, ${hash})`; + }), + firstBadSeq: 4, + }, + ])("verify catches $name", ({ tamper, firstBadSeq = 3 }) => + Effect.gen(function* () { + const audit = yield* seedChain; + const sql = yield* SqlClient.SqlClient; + yield* audit.append({ orgId: otherOrg, event: "key_registered" }); + yield* tamper(sql); + assert.deepStrictEqual(yield* audit.verify({ orgId: org }), { + ok: false, + checked: firstBadSeq - 1, + firstBadSeq, + }); + // Chains are per org: the other org's stays intact. + assert.deepStrictEqual(yield* audit.verify({ orgId: otherOrg }), { + ok: true, + checked: 1, + firstBadSeq: null, + }); + }).pipe(Effect.provide(layer)), + ); + + it.effect("concurrent appends form one gapless chain per org", () => + Effect.gen(function* () { + const audit = yield* seed; + const appended = yield* Effect.all( + Array.from({ length: 40 }, (_, index) => + audit.append({ orgId: index % 2 === 0 ? org : otherOrg, event: "key_registered" }), + ), + { concurrency: "unbounded" }, + ); + for (const orgId of [org, otherOrg]) { + const seqs = appended + .filter((entry) => entry.orgId === orgId) + .map((entry) => entry.seq) + .toSorted((left, right) => left - right); + assert.deepStrictEqual( + seqs, + Array.from({ length: 20 }, (_, index) => index + 1), + ); + assert.deepStrictEqual(yield* audit.verify({ orgId }), { + ok: true, + checked: 20, + firstBadSeq: null, + }); + } + }).pipe(Effect.provide(layer)), + ); + + it.effect("lists entries a page at a time", () => + Effect.gen(function* () { + const audit = yield* seedChain; + const first = yield* audit.list({ orgId: org, limit: 2 }); + assert.deepStrictEqual( + first.entries.map((entry) => entry.seq), + [1, 2], + ); + assert.isTrue(first.hasMore); + const last = yield* audit.list({ orgId: org, afterSeq: 4, limit: 2 }); + assert.deepStrictEqual( + last.entries.map((entry) => entry.event), + ["credential_check_failed"], + ); + assert.isFalse(last.hasMore); + const all = (yield* audit.list({ orgId: org, limit: 200 })).entries; + assert.strictEqual(last.entries[0]!.prevHash, all[3]!.hash); + assert.deepStrictEqual((yield* audit.list({ orgId: otherOrg, limit: 10 })).entries, []); + }).pipe(Effect.provide(layer)), + ); +}); + +describe("KinPendingActions audit trail", () => { + it.effect("a merge leaves a complete trail: request, grant, device, SHA and merge commit", () => + Effect.gen(function* () { + const audit = yield* seed; + const actions = yield* KinPendingActions; + const { action } = yield* actions.create(request); + yield* actions.create(request); // replayed webhook: no second entry + const refreshed = Option.getOrThrow( + yield* actions.refresh({ + orgId: org, + actionId: action.id, + revision: 0, + resolved: { ...request.resolved, headSha: "b".repeat(40) } as typeof request.resolved, + targetDigest: "2".repeat(64), + }), + ); + assert.deepStrictEqual(yield* actions.approve(grant(action, "jti-old")), { _tag: "stale" }); + const approved = yield* actions.approve(grant(refreshed, "jti-1")); + assert.strictEqual(approved._tag, "approved"); + if (approved._tag !== "approved") return; + assert.isTrue( + yield* actions.claim({ + orgId: org, + actionId: action.id, + revision: 1, + grantId: approved.grant.id, + }), + ); + assert.isTrue( + yield* actions.finish({ + orgId: org, + actionId: action.id, + outcome: "succeeded", + mergeCommitSha: mergeSha, + }), + ); + + const { entries } = yield* audit.list({ orgId: org, limit: 50 }); + assert.deepStrictEqual( + entries.map((entry) => entry.event), + [ + "action_requested", + "action_refreshed", + "grant_rejected", + "grant_accepted", + "execution_started", + "execution_finished", + ] satisfies ReadonlyArray, + ); + const [requested, refreshedEntry, rejected, accepted, started, finished] = entries; + assert.deepStrictEqual(requested!.target, request.target); + assert.deepStrictEqual(requested!.provenance, request.provenance); + assert.strictEqual(requested!.headSha, headSha); + assert.strictEqual(refreshedEntry!.headSha, "b".repeat(40)); + assert.include(rejected!, { grantJti: "jti-old", result: "stale", sessionId }); + assert.include(accepted!, { + actionId: action.id, + kind: "merge_pull_request", + headSha: "b".repeat(40), + grantJti: "jti-1", + keyThumbprint: kid, + sessionId, + deviceLabel: "Owner's iPhone", + }); + assert.include(started!, { grantJti: "jti-1", headSha: "b".repeat(40) }); + assert.strictEqual(finished!.result, mergeSha); + // The audit holds the jti and thumbprint, never the signed token. + assert.notInclude(JSON.stringify(entries), "compact-jti"); + assert.deepStrictEqual(yield* audit.verify({ orgId: org }), { + ok: true, + checked: 6, + firstBadSeq: null, + }); + }).pipe(Effect.provide(layer)), + ); + + it.effect("terminal moves, the sweep and reconciliation each leave their own entry", () => + Effect.gen(function* () { + const audit = yield* seed; + const actions = yield* KinPendingActions; + const create = (source: string) => + actions + .create({ ...request, source: decodeEventId(source) }) + .pipe(Effect.map(({ action }) => action)); + const rejected = yield* create("a"); + const cancelled = yield* create("b"); + const reconciled = yield* create("c"); + const waiting = yield* create("d"); + const lapsing = yield* create("e"); + const ref = (action: KinPendingAction) => ({ + orgId: org, + actionId: action.id, + revision: 0, + }); + assert.isTrue(yield* actions.transition({ ...ref(rejected), to: "rejected", sessionId })); + assert.isTrue(yield* actions.transition({ ...ref(cancelled), to: "cancelled" })); + assert.isFalse(yield* actions.transition({ ...ref(cancelled), to: "rejected" })); + const approved = yield* actions.approve(grant(reconciled, "jti-r")); + if (approved._tag !== "approved") return assert.fail("not approved"); + yield* actions.claim({ ...ref(reconciled), grantId: approved.grant.id }); + yield* actions.finish({ + orgId: org, + actionId: reconciled.id, + outcome: "interrupted", + error: "still open after restart", + reconciled: true, + }); + + assert.strictEqual((yield* actions.approve(grant(lapsing, "jti-l")))._tag, "approved"); + yield* TestClock.adjust("8 days"); + const swept = yield* actions.sweep(); + assert.strictEqual(swept.expired.length + swept.voided.length, 2); + + const { entries } = yield* audit.list({ orgId: org, limit: 50 }); + const byAction = (action: KinPendingAction) => + entries.filter((entry) => entry.actionId === action.id).map((entry) => entry.event); + assert.deepStrictEqual(byAction(rejected), ["action_requested", "action_rejected"]); + assert.deepStrictEqual(byAction(cancelled), ["action_requested", "action_cancelled"]); + assert.deepStrictEqual(byAction(reconciled), [ + "action_requested", + "grant_accepted", + "execution_started", + "execution_reconciled", + ]); + assert.deepStrictEqual(byAction(waiting), ["action_requested", "action_expired"]); + assert.deepStrictEqual(byAction(lapsing), [ + "action_requested", + "grant_accepted", + "action_voided", + ]); + assert.strictEqual( + entries.find((entry) => entry.event === "execution_reconciled")!.result, + "interrupted: still open after restart", + ); + assert.strictEqual( + entries.find((entry) => entry.event === "action_voided")!.result, + "grant_expired", + ); + assert.strictEqual( + entries.find((entry) => entry.event === "action_rejected")!.sessionId, + sessionId, + ); + }).pipe(Effect.provide(layer)), + ); + + it.effect("a transition rolls back when its audit entry can't be written", () => + Effect.gen(function* () { + yield* seed; + const actions = yield* KinPendingActions; + const sql = yield* SqlClient.SqlClient; + const { action } = yield* actions.create(request); + yield* sql`CREATE TRIGGER kin_audit_refuse BEFORE INSERT ON kin_audit + BEGIN SELECT RAISE(ABORT, 'audit refused'); END`; + const failure = yield* actions + .transition({ orgId: org, actionId: action.id, revision: 0, to: "rejected" }) + .pipe(Effect.flip); + assert.strictEqual(failure._tag, "PersistenceSqlError"); + assert.strictEqual( + Option.getOrThrow(yield* actions.get({ orgId: org, actionId: action.id })).state, + "awaiting_approval", + ); + }).pipe(Effect.provide(layer)), + ); +}); + +describe("kin.audit RPCs", () => { + it.effect("only the org owner can list or verify the audit", () => + Effect.gen(function* () { + const kin = yield* Kin.KinServer.pipe( + Effect.provide( + Kin.layer.pipe( + Layer.provide(ConfigProvider.layer(ConfigProvider.fromUnknown({ KIN_ENABLED: true }))), + ), + ), + ); + assert.isTrue(Option.isSome(kin.services)); + const handlersFor = (scopes: AuthenticatedSession["scopes"]) => + makeKinApprovalHandlers({ + sessionId, + subject: "browser", + method: "browser-session-cookie", + scopes, + }).pipe(Effect.provideService(Kin.KinServer, kin)); + const ownerHandlers = yield* handlersFor(AuthStandardClientScopes); + assert.deepStrictEqual(yield* ownerHandlers["kin.audit.verify"]({ orgId: defaultOrg }), { + ok: true, + checked: 0, + firstBadSeq: null, + }); + assert.include( + yield* ownerHandlers["kin.audit.list"]({ orgId: otherOrg, limit: 10 }).pipe(Effect.flip), + { reason: "not_owner" }, + ); + const memberHandlers = yield* handlersFor([]); + assert.include( + yield* memberHandlers["kin.audit.verify"]({ orgId: defaultOrg }).pipe(Effect.flip), + { reason: "not_owner" }, + ); + }).pipe(Effect.provide(Sqlite.layerMemory)), + ); +}); diff --git a/apps/server/src/kin/approvals/Audit.ts b/apps/server/src/kin/approvals/Audit.ts new file mode 100644 index 0000000000000..8c3d1f856fe85 --- /dev/null +++ b/apps/server/src/kin/approvals/Audit.ts @@ -0,0 +1,194 @@ +// @effect-diagnostics nodeBuiltinImport:off -- a synchronous SHA-256 for the hash chain. +import * as NodeCrypto from "node:crypto"; + +import { + KinAuditEntry, + type KinAuditListInput, + type KinAuditListResult, + type KinAuditVerifyResult, + type KinOrgId, +} from "@t3tools/contracts"; +import { stableStringify } from "@t3tools/shared/relaySigning"; +import * as Clock from "effect/Clock"; +import * as Context from "effect/Context"; +import * as DateTime from "effect/DateTime"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; +import * as Option from "effect/Option"; +import * as Schema from "effect/Schema"; +import * as SecureRandom from "effect/crypto/SecureRandom"; +import * as SqlClient from "effect/sql/SqlClient"; + +import { + PersistenceDecodeError, + type PersistenceSqlError, + toPersistenceSqlError, +} from "../../persistence/Errors.ts"; + +/** `prevHash` of each org's first entry. */ +const KIN_AUDIT_GENESIS_HASH = "0".repeat(64); +const VERIFY_PAGE = 500; + +export type KinAuditAppendInput = Omit; +type Errors = PersistenceSqlError | PersistenceDecodeError; + +const { hash: _hash, ...unhashedFields } = KinAuditEntry.fields; +const encodeUnhashed = Schema.encodeEffect(Schema.Struct(unhashedFields)); +const decodeEntry = Schema.decodeUnknownEffect(KinAuditEntry); +const decodeEntryOption = Schema.decodeUnknownOption(KinAuditEntry); + +/** Spec section 11: sha256(prevHash ‖ stableStringify(entry without hash)). */ +export const kinAuditHash = (unhashed: { readonly prevHash: string }): string => + NodeCrypto.createHash("sha256") + .update(unhashed.prevHash + stableStringify(unhashed)) + .digest("hex"); + +type AuditRow = { + readonly id: string; + readonly org_id: string; + readonly seq: number; + readonly at: number; + readonly event: string; + readonly entry_json: string; + readonly prev_hash: string; + readonly hash: string; +}; + +const parseJson = (text: string): unknown => { + try { + return JSON.parse(text); + } catch { + return undefined; + } +}; + +// One row against its predecessor: canonical bytes, columns, position and both hashes. +const rowIsIntact = (row: AuditRow, expectedSeq: number, prevHash: string): boolean => { + const parsed = parseJson(row.entry_json); + if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) return false; + if (stableStringify(parsed) !== row.entry_json) return false; + const decoded = decodeEntryOption(parsed); + if (Option.isNone(decoded)) return false; + const entry = decoded.value; + const { hash, ...unhashed } = parsed as typeof KinAuditEntry.Encoded; + return ( + row.seq === expectedSeq && + entry.seq === row.seq && + entry.id === row.id && + entry.orgId === row.org_id && + entry.event === row.event && + entry.at.epochMilliseconds === row.at && + entry.prevHash === prevHash && + row.prev_hash === prevHash && + hash === row.hash && + kinAuditHash(unhashed) === row.hash + ); +}; + +export class KinAudit extends Context.Service< + KinAudit, + { + /** + * Appends one entry to the org's chain. Joins the caller's transaction when there is one, + * so a transition and its entry commit or roll back together. Server code only: no RPC or + * MCP tool reaches it. + */ + readonly append: (input: KinAuditAppendInput) => Effect.Effect; + readonly list: (input: KinAuditListInput) => Effect.Effect; + /** Recomputes the chain from seq 1 and reports the first entry that doesn't hold. */ + readonly verify: (input: { + readonly orgId: KinOrgId; + }) => Effect.Effect; + } +>()("t3/kin/approvals/Audit/KinAudit") {} + +export const make = Effect.gen(function* () { + const sql = yield* SqlClient.SqlClient; + + const append = Effect.fn("KinAudit.append")( + function* (input: KinAuditAppendInput) { + // The writer runs BEGIN IMMEDIATE behind one permit, so reading the head and inserting + // the next seq can't interleave with another append; UNIQUE(org_id, seq) backs that up. + return yield* sql.withTransaction( + Effect.gen(function* () { + const now = yield* Clock.currentTimeMillis; + const [head] = yield* sql<{ seq: number; hash: string }>` + SELECT seq, hash FROM kin_audit WHERE org_id = ${input.orgId} + ORDER BY seq DESC LIMIT 1`; + const prevHash = head?.hash ?? KIN_AUDIT_GENESIS_HASH; + const unhashed = yield* encodeUnhashed({ + ...input, + id: `aud_${SecureRandom.ulidUnsafe()}`, + seq: (head?.seq ?? 0) + 1, + at: DateTime.makeUnsafe(now), + prevHash, + }); + const hash = kinAuditHash(unhashed); + const encoded = { ...unhashed, hash }; + yield* sql`INSERT INTO kin_audit ${sql.insert({ + id: encoded.id, + org_id: encoded.orgId, + seq: encoded.seq, + at: now, + event: encoded.event, + entry_json: stableStringify(encoded), + prev_hash: prevHash, + hash, + })}`; + return yield* decodeEntry(encoded); + }), + ); + }, + Effect.mapError(toError("KinAudit.append")), + ); + + const list = Effect.fn("KinAudit.list")( + function* (input: KinAuditListInput) { + const rows = yield* sql<{ entry_json: string }>` + SELECT entry_json FROM kin_audit + WHERE org_id = ${input.orgId} AND seq > ${input.afterSeq ?? 0} + ORDER BY seq LIMIT ${input.limit + 1}`; + const entries = yield* Effect.forEach(rows.slice(0, input.limit), (row) => + decodeEntry(parseJson(row.entry_json)), + ); + return { entries, hasMore: rows.length > input.limit }; + }, + Effect.mapError(toError("KinAudit.list")), + ); + + const verify = Effect.fn("KinAudit.verify")( + function* (input: { readonly orgId: KinOrgId }) { + let checked = 0; + let prevHash = KIN_AUDIT_GENESIS_HASH; + while (true) { + // Every verified row has seq === checked, so this resumes right after the last one. + const rows = yield* sql`SELECT * FROM kin_audit + WHERE org_id = ${input.orgId} AND seq > ${checked} + ORDER BY seq LIMIT ${VERIFY_PAGE}`; + if (rows.length === 0) return { ok: true, checked, firstBadSeq: null }; + for (const row of rows) { + if (!rowIsIntact(row, checked + 1, prevHash)) { + return { ok: false, checked, firstBadSeq: checked + 1 }; + } + checked += 1; + prevHash = row.hash; + } + } + }, + Effect.mapError(toError("KinAudit.verify")), + ); + + return KinAudit.of({ append, list, verify }); +}); + +const isDecodeError = Schema.is(PersistenceDecodeError); +function toError(operation: string) { + return (cause: unknown): Errors => + isDecodeError(cause) + ? cause + : Schema.isSchemaError(cause) + ? PersistenceDecodeError.fromSchemaError(operation, cause) + : toPersistenceSqlError(operation)(cause); +} + +export const layer = Layer.effect(KinAudit, make); diff --git a/apps/server/src/kin/approvals/PendingActions.test.ts b/apps/server/src/kin/approvals/PendingActions.test.ts index 159ae9c2a0dce..5e188c03146fd 100644 --- a/apps/server/src/kin/approvals/PendingActions.test.ts +++ b/apps/server/src/kin/approvals/PendingActions.test.ts @@ -21,9 +21,13 @@ import { layer as pendingActionsLayer, type KinPendingActionCreateInput, } from "./PendingActions.ts"; +import * as Audit from "./Audit.ts"; const database = Layer.provideMerge(KinPersistence.layer, Sqlite.layerMemory); -const layer = pendingActionsLayer.pipe(Layer.provideMerge(database)); +const layer = pendingActionsLayer.pipe( + Layer.provideMerge(Audit.layer), + Layer.provideMerge(database), +); const decodeEventId = Schema.decodeSync(KinEventId); const owner = Schema.decodeSync(KinPersonId)("h_owner"); diff --git a/apps/server/src/kin/approvals/PendingActions.ts b/apps/server/src/kin/approvals/PendingActions.ts index 6cf784a1455cb..61d0cdd891a48 100644 --- a/apps/server/src/kin/approvals/PendingActions.ts +++ b/apps/server/src/kin/approvals/PendingActions.ts @@ -14,6 +14,7 @@ import { KinProvenance, KinResolvedTarget, ThreadId, + type AuthSessionId, type Hex64, type KinKeyThumbprint, } from "@t3tools/contracts"; @@ -34,6 +35,7 @@ import { type PersistenceSqlError, toPersistenceSqlError, } from "../../persistence/Errors.ts"; +import { KinAudit } from "./Audit.ts"; const AWAITING_TTL_MS = 7 * 24 * 60 * 60 * 1000; // A grant lapses at min(exp, acceptedAt + 15 min) (approvals spec section 5). @@ -142,6 +144,24 @@ const toAction = (row: ActionRow) => expiresAt: iso(row.expires_at), }); +type FactsRow = { action_id: string; kind: string; resolved_json: string }; +const decodeFacts = Schema.decodeUnknownEffect( + Schema.Struct({ + actionId: KinActionId, + kind: KinActionKind, + resolved: StoredAction.fields.resolved, + }), +); +// What every audit entry about an action carries, read from the row the statement touched. +const auditFacts = (row: FactsRow) => + decodeFacts({ actionId: row.action_id, kind: row.kind, resolved: row.resolved_json }).pipe( + Effect.map(({ actionId, kind, resolved }) => ({ + actionId, + kind, + ...(resolved._tag === "none" ? {} : { headSha: resolved.headSha }), + })), + ); + class Rollback extends Schema.TaggedError()("Rollback", {}) {} export class KinPendingActions extends Context.Service< @@ -164,6 +184,7 @@ export class KinPendingActions extends Context.Service< input: RevisionRef & { readonly to: "rejected" | "cancelled" | "expired" | "voided"; readonly reason?: string; + readonly sessionId?: AuthSessionId; }, ) => Effect.Effect; /** Check 10: the grant row and `awaiting_approval → approved` in one transaction. */ @@ -176,6 +197,8 @@ export class KinPendingActions extends Context.Service< readonly compact: string; readonly iat: number; readonly exp: number; + readonly sessionId?: AuthSessionId; + readonly deviceLabel?: string; }, ) => Effect.Effect; /** The executor's single claim: the `kin_executions` insert plus `approved → executing`. */ @@ -188,6 +211,8 @@ export class KinPendingActions extends Context.Service< readonly githubRequestId?: string; readonly mergeCommitSha?: string; readonly error?: string; + /** Startup reconciliation decided the outcome, not a live run. */ + readonly reconciled?: boolean; }, ) => Effect.Effect; /** Expires unapproved actions past `expiresAt` and voids approvals whose grant lapsed. */ @@ -200,6 +225,7 @@ export class KinPendingActions extends Context.Service< const make = Effect.gen(function* () { const sql = yield* SqlClient.SqlClient; + const audit = yield* KinAudit; const select = (ref: ActionRef) => sql`SELECT * FROM kin_pending_actions @@ -242,11 +268,24 @@ const make = Effect.gen(function* () { }; // Decoding the full record validates it before it reaches the table. const action = yield* toAction(row); - const inserted = yield* sql` - INSERT INTO kin_pending_actions ${sql.insert(row)} - ON CONFLICT (org_id, idempotency_key) DO NOTHING - RETURNING action_id`; - if (inserted.length > 0) return { action, created: true }; + const created = yield* sql.withTransaction( + Effect.gen(function* () { + const inserted = yield* sql` + INSERT INTO kin_pending_actions ${sql.insert(row)} + ON CONFLICT (org_id, idempotency_key) DO NOTHING + RETURNING action_id`; + if (inserted.length === 0) return false; + yield* audit.append({ + orgId: action.orgId, + event: "action_requested", + ...(yield* auditFacts(row)), + target: action.target, + provenance: action.provenance, + }); + return true; + }), + ); + if (created) return { action, created: true }; const [existing] = yield* sql`SELECT * FROM kin_pending_actions WHERE org_id = ${input.orgId} AND idempotency_key = ${idempotencyKey}`; if (existing === undefined) { @@ -265,13 +304,24 @@ const make = Effect.gen(function* () { input: RevisionRef & { readonly resolved: KinResolvedTarget; readonly targetDigest: Hex64 }, ) { const now = yield* Clock.currentTimeMillis; - const [row] = yield* sql`UPDATE kin_pending_actions - SET resolved_json = ${yield* encodeResolved(input.resolved)}, target_digest = ${input.targetDigest}, - nonce = ${newNonce()}, revision = revision + 1, updated_at = ${now} - WHERE org_id = ${input.orgId} AND action_id = ${input.actionId} - AND state = 'awaiting_approval' AND revision = ${input.revision} - RETURNING *`; - return row === undefined ? Option.none() : Option.some(yield* toAction(row)); + const resolvedJson = yield* encodeResolved(input.resolved); + return yield* sql.withTransaction( + Effect.gen(function* () { + const [row] = yield* sql`UPDATE kin_pending_actions + SET resolved_json = ${resolvedJson}, target_digest = ${input.targetDigest}, + nonce = ${newNonce()}, revision = revision + 1, updated_at = ${now} + WHERE org_id = ${input.orgId} AND action_id = ${input.actionId} + AND state = 'awaiting_approval' AND revision = ${input.revision} + RETURNING *`; + if (row === undefined) return Option.none(); + yield* audit.append({ + orgId: input.orgId, + event: "action_refreshed", + ...(yield* auditFacts(row)), + }); + return Option.some(yield* toAction(row)); + }), + ); }, Effect.mapError(toError("KinPendingActions.refresh")), ); @@ -281,16 +331,29 @@ const make = Effect.gen(function* () { input: RevisionRef & { readonly to: "rejected" | "cancelled" | "expired" | "voided"; readonly reason?: string; + readonly sessionId?: AuthSessionId; }, ) { const from = input.to === "voided" ? "approved" : "awaiting_approval"; const now = yield* Clock.currentTimeMillis; - const rows = yield* sql`UPDATE kin_pending_actions - SET state = ${input.to}, state_reason = ${input.reason ?? null}, updated_at = ${now} - WHERE org_id = ${input.orgId} AND action_id = ${input.actionId} - AND state = ${from} AND revision = ${input.revision} - RETURNING action_id`; - return rows.length > 0; + return yield* sql.withTransaction( + Effect.gen(function* () { + const [row] = yield* sql`UPDATE kin_pending_actions + SET state = ${input.to}, state_reason = ${input.reason ?? null}, updated_at = ${now} + WHERE org_id = ${input.orgId} AND action_id = ${input.actionId} + AND state = ${from} AND revision = ${input.revision} + RETURNING action_id, kind, resolved_json`; + if (row === undefined) return false; + yield* audit.append({ + orgId: input.orgId, + event: `action_${input.to}`, + ...(yield* auditFacts(row)), + ...(input.sessionId === undefined ? {} : { sessionId: input.sessionId }), + ...(input.reason === undefined ? {} : { result: input.reason }), + }); + return true; + }), + ); }, Effect.mapError(toError("KinPendingActions.transition")), ); @@ -305,11 +368,19 @@ const make = Effect.gen(function* () { readonly compact: string; readonly iat: number; readonly exp: number; + readonly sessionId?: AuthSessionId; + readonly deviceLabel?: string; }, ) { const now = yield* Clock.currentTimeMillis; const grantId = `grt_${SecureRandom.ulidUnsafe()}`; - return yield* sql + const who = { + grantJti: input.jti, + keyThumbprint: input.keyThumbprint, + ...(input.sessionId === undefined ? {} : { sessionId: input.sessionId }), + ...(input.deviceLabel === undefined ? {} : { deviceLabel: input.deviceLabel }), + }; + const result = yield* sql .withTransaction( Effect.gen(function* () { const [inserted] = yield* sql` @@ -329,13 +400,19 @@ const make = Effect.gen(function* () { ? { _tag: "stale" as const } : { _tag: "replayed" as const }; } - const won = yield* sql`UPDATE kin_pending_actions + const [won] = yield* sql`UPDATE kin_pending_actions SET state = 'approved', updated_at = ${now} WHERE org_id = ${input.orgId} AND action_id = ${input.actionId} AND state = 'awaiting_approval' AND revision = ${input.revision} AND nonce = ${input.nonce} - RETURNING action_id`; - if (won.length === 0) return yield* new Rollback(); + RETURNING action_id, kind, resolved_json`; + if (won === undefined) return yield* new Rollback(); + yield* audit.append({ + orgId: input.orgId, + event: "grant_accepted", + ...(yield* auditFacts(won)), + ...who, + }); const grant = yield* decodeGrant({ id: grantId, orgId: input.orgId, @@ -354,6 +431,17 @@ const make = Effect.gen(function* () { }), ) .pipe(Effect.catchTags({ Rollback: () => Effect.succeed({ _tag: "stale" as const }) })); + // A refused grant still leaves a trace (spec section 11); the rolled-back attempt can't. + if (result._tag !== "approved") { + yield* audit.append({ + orgId: input.orgId, + event: "grant_rejected", + actionId: input.actionId, + ...who, + result: result._tag, + }); + } + return result; }, Effect.mapError(toError("KinPendingActions.approve")), ); @@ -373,13 +461,23 @@ const make = Effect.gen(function* () { ON CONFLICT DO NOTHING RETURNING action_id`; if (claimed.length === 0) return false; - const won = yield* sql`UPDATE kin_pending_actions + const [won] = yield* sql`UPDATE kin_pending_actions SET state = 'executing', updated_at = ${now} WHERE org_id = ${input.orgId} AND action_id = ${input.actionId} AND state = 'approved' AND revision = ${input.revision} - RETURNING action_id`; - if (won.length === 0) return yield* new Rollback(); - yield* sql`UPDATE kin_grants SET consumed_at = ${now} WHERE grant_id = ${input.grantId}`; + RETURNING action_id, kind, resolved_json`; + if (won === undefined) return yield* new Rollback(); + const [grant] = yield* sql<{ jti: string; key_thumbprint: KinKeyThumbprint }>` + UPDATE kin_grants SET consumed_at = ${now} WHERE grant_id = ${input.grantId} + RETURNING jti, key_thumbprint`; + yield* audit.append({ + orgId: input.orgId, + event: "execution_started", + ...(yield* auditFacts(won)), + ...(grant === undefined + ? {} + : { grantJti: grant.jti, keyThumbprint: grant.key_thumbprint }), + }); return true; }), ) @@ -395,17 +493,18 @@ const make = Effect.gen(function* () { readonly githubRequestId?: string; readonly mergeCommitSha?: string; readonly error?: string; + readonly reconciled?: boolean; }, ) { const now = yield* Clock.currentTimeMillis; return yield* sql .withTransaction( Effect.gen(function* () { - const won = yield* sql`UPDATE kin_pending_actions + const [won] = yield* sql`UPDATE kin_pending_actions SET state = ${input.outcome}, state_reason = ${input.error ?? null}, updated_at = ${now} WHERE org_id = ${input.orgId} AND action_id = ${input.actionId} AND state = 'executing' - RETURNING action_id`; - if (won.length === 0) return false; + RETURNING action_id, kind, resolved_json`; + if (won === undefined) return false; const recorded = yield* sql`UPDATE kin_executions SET finished_at = ${now}, outcome = ${input.outcome}, github_request_id = ${input.githubRequestId ?? null}, @@ -413,6 +512,15 @@ const make = Effect.gen(function* () { WHERE org_id = ${input.orgId} AND action_id = ${input.actionId} AND finished_at IS NULL RETURNING action_id`; if (recorded.length === 0) return yield* new Rollback(); + yield* audit.append({ + orgId: input.orgId, + event: input.reconciled === true ? "execution_reconciled" : "execution_finished", + ...(yield* auditFacts(won)), + result: + input.outcome === "succeeded" + ? (input.mergeCommitSha ?? "succeeded") + : `${input.outcome}: ${input.error ?? "no reason given"}`, + }); return true; }), ) @@ -426,12 +534,13 @@ const make = Effect.gen(function* () { const now = yield* Clock.currentTimeMillis; return yield* sql.withTransaction( Effect.gen(function* () { - const expired = yield* sql<{ org_id: KinOrgId; action_id: KinActionId }>` + type SweptRow = FactsRow & { org_id: KinOrgId; action_id: KinActionId }; + const expired = yield* sql` UPDATE kin_pending_actions SET state = 'expired', state_reason = 'expired', updated_at = ${now} WHERE state = 'awaiting_approval' AND expires_at <= ${now} - RETURNING org_id, action_id`; - const voided = yield* sql<{ org_id: KinOrgId; action_id: KinActionId }>` + RETURNING org_id, action_id, kind, resolved_json`; + const voided = yield* sql` UPDATE kin_pending_actions SET state = 'voided', state_reason = 'grant_expired', updated_at = ${now} WHERE state = 'approved' AND EXISTS ( @@ -439,8 +548,21 @@ const make = Effect.gen(function* () { WHERE g.action_id = kin_pending_actions.action_id AND g.revision = kin_pending_actions.revision AND g.consumed_at IS NULL AND MIN(g.exp * 1000, g.accepted_at + ${GRANT_ACCEPTED_TTL_MS}) <= ${now}) - RETURNING org_id, action_id`; - const refs = (rows: ReadonlyArray<{ org_id: KinOrgId; action_id: KinActionId }>) => + RETURNING org_id, action_id, kind, resolved_json`; + const record = (event: "action_expired" | "action_voided", result: string) => + Effect.forEach( + event === "action_expired" ? expired : voided, + (row) => + auditFacts(row).pipe( + Effect.flatMap((facts) => + audit.append({ orgId: row.org_id, event, ...facts, result }), + ), + ), + { discard: true }, + ); + yield* record("action_expired", "expired"); + yield* record("action_voided", "grant_expired"); + const refs = (rows: ReadonlyArray) => rows.map((row) => ({ orgId: row.org_id, actionId: row.action_id })); return { expired: refs(expired), voided: refs(voided) }; }), diff --git a/apps/server/src/kin/approvals/rpcHandlers.ts b/apps/server/src/kin/approvals/rpcHandlers.ts index 0b07100bddb46..a3d61391173fe 100644 --- a/apps/server/src/kin/approvals/rpcHandlers.ts +++ b/apps/server/src/kin/approvals/rpcHandlers.ts @@ -1,30 +1,55 @@ -import { KinApprovalError, KinApprovalRpcs } from "@t3tools/contracts"; +import { KinApprovalError, KinApprovalRpcs, type KinOrgId } from "@t3tools/contracts"; +import * as Context from "effect/Context"; import * as Effect from "effect/Effect"; +import * as Option from "effect/Option"; import * as Stream from "effect/Stream"; import * as RpcGroup from "effect/rpc/RpcGroup"; import type { AuthenticatedSession } from "../../auth/EnvironmentAuth.ts"; +import { KinIdentity } from "../chat/KinIdentity.ts"; +import { KinServer } from "../KinServer.ts"; +import * as Audit from "./Audit.ts"; const group = RpcGroup.make(...KinApprovalRpcs); -// Every method refuses until its task lands (APPR-3, -4, -5, -10); nothing here can approve. +// Every method refuses until its task lands (APPR-3, -4, -5); nothing here can approve. const unavailable = Effect.fail( new KinApprovalError({ reason: "unavailable", message: "Kin approvals are unavailable." }), ); +const failed = () => + new KinApprovalError({ reason: "unavailable", message: "Kin audit is unavailable." }); -export const makeKinApprovalHandlers = (_session: AuthenticatedSession) => - Effect.sync(() => - group.of({ - "kin.approvals.list": () => Stream.fromEffect(unavailable), - "kin.approvals.get": () => unavailable, - "kin.approvals.challenge": () => unavailable, - "kin.approvals.submitGrant": () => unavailable, - "kin.approvals.reject": () => unavailable, - "kin.approvals.keyChallenge": () => unavailable, - "kin.approvals.registerKey": () => unavailable, - "kin.approvals.confirmKey": () => unavailable, - "kin.approvals.listKeys": () => unavailable, - "kin.approvals.revokeKey": () => unavailable, - "kin.audit.list": () => unavailable, - "kin.audit.verify": () => unavailable, - }), - ); +export const makeKinApprovalHandlers = Effect.fn("makeKinApprovalHandlers")(function* ( + session: AuthenticatedSession, +) { + const kin = yield* Effect.serviceOption(KinServer); + const audit = yield* Audit.make; + // Owner-only (spec section 11). Phase 1 identity resolves a session to the org owner or to no one. + const asOwner = Effect.fn("KinApprovals.asOwner")(function* (orgId: KinOrgId) { + if (Option.isNone(kin) || Option.isNone(kin.value.services)) return yield* unavailable; + const people = yield* Context.get(kin.value.services.value, KinIdentity).resolve(session); + if (!people.some((person) => person.orgId === orgId)) { + return yield* new KinApprovalError({ reason: "not_owner", message: "Owner only." }); + } + return audit; + }); + return group.of({ + "kin.approvals.list": () => Stream.fromEffect(unavailable), + "kin.approvals.get": () => unavailable, + "kin.approvals.challenge": () => unavailable, + "kin.approvals.submitGrant": () => unavailable, + "kin.approvals.reject": () => unavailable, + "kin.approvals.keyChallenge": () => unavailable, + "kin.approvals.registerKey": () => unavailable, + "kin.approvals.confirmKey": () => unavailable, + "kin.approvals.listKeys": () => unavailable, + "kin.approvals.revokeKey": () => unavailable, + "kin.audit.list": (input) => + asOwner(input.orgId).pipe( + Effect.flatMap((owner) => owner.list(input).pipe(Effect.mapError(failed))), + ), + "kin.audit.verify": (input) => + asOwner(input.orgId).pipe( + Effect.flatMap((owner) => owner.verify(input).pipe(Effect.mapError(failed))), + ), + }); +}); diff --git a/docs/kin/specs/approvals.md b/docs/kin/specs/approvals.md index 9943ff6bc5982..edd17f8c9879d 100644 --- a/docs/kin/specs/approvals.md +++ b/docs/kin/specs/approvals.md @@ -425,6 +425,10 @@ export const KinAuditEntry = Schema.Struct({ Append-only (`kin_audit`, no `UPDATE` or `DELETE` statements in the repository code). The hash chain makes edits visible; `kin.audit.verify` recomputes it. Rejected grants are audited with their failure reason and the sending session, so a forged approval leaves a trace. `kin.audit.list` is owner-only. The audit stores the grant's `jti` and the key thumbprint, never tokens or keychain contents. +`apps/server/src/kin/approvals/Audit.ts` (`KinAudit`) is the only writer. `append` joins the caller's transaction, so `PendingActions.ts` writes each transition's entry atomically with the transition: `action_requested` on insert (not on an idempotent replay), `action_refreshed`, `grant_accepted`, the four terminal `action_*` moves (the sweep included), `execution_started` with the claim, and `execution_finished`, or `execution_reconciled` when startup reconciliation decides the outcome. `approve` also writes `grant_rejected` for `stale` and `replayed`, after its transaction rolls back. Rejections decided before `approve` (checks 1–9), key events and `credential_check_failed` are written by APPR-4, APPR-5 and APPR-8 through `KinAudit.append`. No RPC or MCP tool writes or deletes entries. + +Each org has its own chain. The first entry's `prevHash` is 64 zeros, and `seq` counts from 1 with no gaps. Appends are serialized by SQLite's single `BEGIN IMMEDIATE` writer, with `UNIQUE(org_id, seq)` as a backstop. `entry_json` holds `stableStringify` of the whole entry. `verify` walks the chain in `seq` order and reports the first entry whose bytes, columns, position, `prevHash` or `hash` don't hold, which catches an edited, deleted, reordered or inserted row. The chain has no secret and no outside anchor, so it can't show a truncated tail or a chain recomputed from the edit onward by someone with write access to the database. It catches tampering, not a compromised server. + ### 12. Credential hygiene check At startup and hourly, the executor checks which GitHub identity T3 itself uses (`GitHubRequestPolicy.credential("github.com")`, then `GET /user`). If it is the owner's personal login, or `GH_TOKEN`/`GITHUB_TOKEN` is set in the server environment, the executor writes `credential_check_failed`, refuses privileged execution, and posts a card to the owner. Agent CLIs run as children of the server and inherit its `gh` login and environment, so on the Kin machine that identity must be the bot. The triggers spec's Kin host setup owns making it so. From 51b67a3a9f09cf5244c991483f19d270d0d774df Mon Sep 17 00:00:00 2001 From: Surajsm60720 <1ds22is166@dsce.edu.in> Date: Sun, 8 Nov 2026 07:50:03 +0530 Subject: [PATCH 3/9] fix(kin): owner-only audit, corrupt-row markers, org-scoped grant_rejected, append-only kin_audit (APPR-10) - asOwner checks the resolved person is KinIdentity's org owner, not just an org member. - KinAudit.list decodes each row on its own; a bad row lists as { seq, corrupt: true }. - approve writes grant_rejected only when the action exists in that org. - K008 adds BEFORE UPDATE/DELETE triggers so kin_audit is append-only. Co-Authored-By: Claude Opus 5.5 --- apps/server/src/kin/approvals/Audit.test.ts | 130 ++++++++++++++++-- apps/server/src/kin/approvals/Audit.ts | 12 +- .../src/kin/approvals/PendingActions.ts | 24 ++-- apps/server/src/kin/approvals/rpcHandlers.ts | 11 +- apps/server/src/kin/chat/KinIdentity.ts | 3 + .../persistence/migrations/K008_Approvals.ts | 9 ++ packages/contracts/src/kinApprovals.ts | 8 +- 7 files changed, 170 insertions(+), 27 deletions(-) diff --git a/apps/server/src/kin/approvals/Audit.test.ts b/apps/server/src/kin/approvals/Audit.test.ts index bdd20562b2f5e..4c0632fc577b8 100644 --- a/apps/server/src/kin/approvals/Audit.test.ts +++ b/apps/server/src/kin/approvals/Audit.test.ts @@ -2,15 +2,19 @@ import { assert, describe, it } from "@effect/vitest"; import { AuthSessionId, AuthStandardClientScopes, + KinActionId, KinEventId, KinKeyThumbprint, KinOrgId, KinPersonId, + type KinAuditEntry, type KinAuditEvent, + type KinAuditListInput, type KinPendingAction, } from "@t3tools/contracts"; import { stableStringify } from "@t3tools/shared/relaySigning"; import * as ConfigProvider from "effect/ConfigProvider"; +import * as Context from "effect/Context"; import * as Effect from "effect/Effect"; import * as Layer from "effect/Layer"; import * as Option from "effect/Option"; @@ -20,6 +24,7 @@ import * as TestClock from "effect/testing/TestClock"; import type { AuthenticatedSession } from "../../auth/EnvironmentAuth.ts"; import * as Sqlite from "../../persistence/Sqlite.ts"; +import { KinIdentity } from "../chat/KinIdentity.ts"; import * as Kin from "../layer.ts"; import * as KinPersistence from "../persistence/KinPersistence.ts"; import { KinAudit, kinAuditHash, layer as auditLayer } from "./Audit.ts"; @@ -39,8 +44,11 @@ const layer = pendingActionsLayer.pipe( const org = Schema.decodeSync(KinOrgId)("org_01"); const otherOrg = Schema.decodeSync(KinOrgId)("org_02"); const defaultOrg = Schema.decodeSync(KinOrgId)("kin-default"); +const unknownOrg = Schema.decodeSync(KinOrgId)("org_unknown"); +const missingAction = Schema.decodeSync(KinActionId)("act_missing"); const decodeEventId = Schema.decodeSync(KinEventId); const owner = Schema.decodeSync(KinPersonId)("h_owner"); +const member = Schema.decodeSync(KinPersonId)("kin-default-member"); const kid = Schema.decodeSync(KinKeyThumbprint)("Y0ZkXVc6eNfxv3xVNHZJp1x7m3kQqb2O8s5vB1aWc9E"); const sessionId = AuthSessionId.make("phone-session"); const headSha = "a".repeat(40); @@ -98,6 +106,22 @@ const seed = Effect.gen(function* () { return yield* KinAudit; }); +// Tests that read entries back expect none to be corrupt. +const listIntact = (audit: KinAudit["Service"], input: KinAuditListInput) => + audit.list(input).pipe( + Effect.map((page) => ({ + ...page, + entries: page.entries.filter((entry): entry is KinAuditEntry => !("corrupt" in entry)), + })), + ); + +// The append-only triggers refuse every edit; tamper cases drop them to play the attacker. +const allowTampering = (sql: SqlClient.SqlClient) => + Effect.gen(function* () { + yield* sql`DROP TRIGGER kin_audit_no_update`; + yield* sql`DROP TRIGGER kin_audit_no_delete`; + }); + // Five entries in org_01, so each tamper case has a row in the middle to break. const seedChain = Effect.gen(function* () { const audit = yield* seed; @@ -125,6 +149,7 @@ describe("KinAudit", () => { }); // Editing the canonical entry, as someone hiding a failure would. + yield* allowTampering(sql); yield* sql`UPDATE kin_audit SET entry_json = replace(entry_json, '"result":"grant_rejected"', '"result":"grant_accepted"') WHERE org_id = ${org} AND seq = 3`; assert.deepStrictEqual(yield* audit.verify({ orgId: org }), { @@ -199,6 +224,7 @@ describe("KinAudit", () => { const audit = yield* seedChain; const sql = yield* SqlClient.SqlClient; yield* audit.append({ orgId: otherOrg, event: "key_registered" }); + yield* allowTampering(sql); yield* tamper(sql); assert.deepStrictEqual(yield* audit.verify({ orgId: org }), { ok: false, @@ -214,6 +240,25 @@ describe("KinAudit", () => { }).pipe(Effect.provide(layer)), ); + it.effect("the database refuses to update or delete audit rows", () => + Effect.gen(function* () { + const audit = yield* seedChain; + const sql = yield* SqlClient.SqlClient; + for (const edit of [ + sql`UPDATE kin_audit SET event = 'grant_accepted' WHERE org_id = ${org} AND seq = 3`, + sql`DELETE FROM kin_audit WHERE org_id = ${org} AND seq = 3`, + ]) { + const failure = yield* Effect.flip(edit); + assert.include(String(failure.reason.cause), "kin_audit is append-only"); + } + assert.deepStrictEqual(yield* audit.verify({ orgId: org }), { + ok: true, + checked: 5, + firstBadSeq: null, + }); + }).pipe(Effect.provide(layer)), + ); + it.effect("concurrent appends form one gapless chain per org", () => Effect.gen(function* () { const audit = yield* seed; @@ -244,21 +289,38 @@ describe("KinAudit", () => { it.effect("lists entries a page at a time", () => Effect.gen(function* () { const audit = yield* seedChain; - const first = yield* audit.list({ orgId: org, limit: 2 }); + const first = yield* listIntact(audit, { orgId: org, limit: 2 }); assert.deepStrictEqual( first.entries.map((entry) => entry.seq), [1, 2], ); assert.isTrue(first.hasMore); - const last = yield* audit.list({ orgId: org, afterSeq: 4, limit: 2 }); + const last = yield* listIntact(audit, { orgId: org, afterSeq: 4, limit: 2 }); assert.deepStrictEqual( last.entries.map((entry) => entry.event), ["credential_check_failed"], ); assert.isFalse(last.hasMore); - const all = (yield* audit.list({ orgId: org, limit: 200 })).entries; + const all = (yield* listIntact(audit, { orgId: org, limit: 200 })).entries; assert.strictEqual(last.entries[0]!.prevHash, all[3]!.hash); - assert.deepStrictEqual((yield* audit.list({ orgId: otherOrg, limit: 10 })).entries, []); + assert.deepStrictEqual( + (yield* listIntact(audit, { orgId: otherOrg, limit: 10 })).entries, + [], + ); + }).pipe(Effect.provide(layer)), + ); + + it.effect("a corrupt row lists as a marker instead of failing the page", () => + Effect.gen(function* () { + const audit = yield* seedChain; + const sql = yield* SqlClient.SqlClient; + yield* allowTampering(sql); + yield* sql`UPDATE kin_audit SET entry_json = '{not json' WHERE org_id = ${org} AND seq = 3`; + const { entries } = yield* audit.list({ orgId: org, limit: 10 }); + assert.deepStrictEqual( + entries.map((entry) => ("corrupt" in entry ? `corrupt:${entry.seq}` : entry.event)), + ["key_registered", "key_confirmed", "corrupt:3", "key_revoked", "credential_check_failed"], + ); }).pipe(Effect.provide(layer)), ); }); @@ -300,7 +362,7 @@ describe("KinPendingActions audit trail", () => { }), ); - const { entries } = yield* audit.list({ orgId: org, limit: 50 }); + const { entries } = yield* listIntact(audit, { orgId: org, limit: 50 }); assert.deepStrictEqual( entries.map((entry) => entry.event), [ @@ -376,7 +438,7 @@ describe("KinPendingActions audit trail", () => { const swept = yield* actions.sweep(); assert.strictEqual(swept.expired.length + swept.voided.length, 2); - const { entries } = yield* audit.list({ orgId: org, limit: 50 }); + const { entries } = yield* listIntact(audit, { orgId: org, limit: 50 }); const byAction = (action: KinPendingAction) => entries.filter((entry) => entry.actionId === action.id).map((entry) => entry.event); assert.deepStrictEqual(byAction(rejected), ["action_requested", "action_rejected"]); @@ -408,6 +470,28 @@ describe("KinPendingActions audit trail", () => { }).pipe(Effect.provide(layer)), ); + it.effect("a grant for an unknown org or action stays stale and writes no entry", () => + Effect.gen(function* () { + const audit = yield* seed; + const actions = yield* KinPendingActions; + const { action } = yield* actions.create(request); + for (const forged of [ + { ...grant(action, "jti-org"), orgId: unknownOrg }, + { ...grant(action, "jti-cross"), orgId: otherOrg }, + { ...grant(action, "jti-missing"), actionId: missingAction }, + ]) { + assert.deepStrictEqual(yield* actions.approve(forged), { _tag: "stale" }); + } + for (const orgId of [org, otherOrg, unknownOrg]) { + const { entries } = yield* listIntact(audit, { orgId, limit: 10 }); + assert.deepStrictEqual( + entries.filter((entry) => entry.event === "grant_rejected"), + [], + ); + } + }).pipe(Effect.provide(layer)), + ); + it.effect("a transition rolls back when its audit entry can't be written", () => Effect.gen(function* () { yield* seed; @@ -438,14 +522,15 @@ describe("kin.audit RPCs", () => { ), ), ); - assert.isTrue(Option.isSome(kin.services)); - const handlersFor = (scopes: AuthenticatedSession["scopes"]) => + if (Option.isNone(kin.services)) return assert.fail("Kin services missing"); + const services = kin.services.value; + const handlersFor = (scopes: AuthenticatedSession["scopes"], server = kin) => makeKinApprovalHandlers({ sessionId, subject: "browser", method: "browser-session-cookie", scopes, - }).pipe(Effect.provideService(Kin.KinServer, kin)); + }).pipe(Effect.provideService(Kin.KinServer, server)); const ownerHandlers = yield* handlersFor(AuthStandardClientScopes); assert.deepStrictEqual(yield* ownerHandlers["kin.audit.verify"]({ orgId: defaultOrg }), { ok: true, @@ -456,11 +541,34 @@ describe("kin.audit RPCs", () => { yield* ownerHandlers["kin.audit.list"]({ orgId: otherOrg, limit: 10 }).pipe(Effect.flip), { reason: "not_owner" }, ); - const memberHandlers = yield* handlersFor([]); + const anonymousHandlers = yield* handlersFor([]); assert.include( - yield* memberHandlers["kin.audit.verify"]({ orgId: defaultOrg }).pipe(Effect.flip), + yield* anonymousHandlers["kin.audit.verify"]({ orgId: defaultOrg }).pipe(Effect.flip), { reason: "not_owner" }, ); + + // A real non-owner person in the owner's org: membership alone must not open the audit. + const sql = yield* SqlClient.SqlClient; + yield* sql`INSERT INTO kin_people (person_id, org_id, handle, display_name, github_login, created_at) + VALUES (${member}, ${defaultOrg}, 'member', 'Member', NULL, '2026-11-08T00:00:00.000Z')`; + const identity = Context.get(services, KinIdentity); + const asMember = { + ...kin, + services: Option.some( + Context.add(services, KinIdentity, { + ...identity, + resolve: () => + Effect.succeed([{ _tag: "person" as const, orgId: defaultOrg, personId: member }]), + }), + ), + }; + const memberHandlers = yield* handlersFor(AuthStandardClientScopes, asMember); + for (const call of [ + memberHandlers["kin.audit.verify"]({ orgId: defaultOrg }), + memberHandlers["kin.audit.list"]({ orgId: defaultOrg, limit: 10 }), + ]) { + assert.include(yield* Effect.flip(call), { reason: "not_owner" }); + } }).pipe(Effect.provide(Sqlite.layerMemory)), ); }); diff --git a/apps/server/src/kin/approvals/Audit.ts b/apps/server/src/kin/approvals/Audit.ts index 8c3d1f856fe85..4a095ed4d489a 100644 --- a/apps/server/src/kin/approvals/Audit.ts +++ b/apps/server/src/kin/approvals/Audit.ts @@ -144,12 +144,16 @@ export const make = Effect.gen(function* () { const list = Effect.fn("KinAudit.list")( function* (input: KinAuditListInput) { - const rows = yield* sql<{ entry_json: string }>` - SELECT entry_json FROM kin_audit + const rows = yield* sql<{ seq: number; entry_json: string }>` + SELECT seq, entry_json FROM kin_audit WHERE org_id = ${input.orgId} AND seq > ${input.afterSeq ?? 0} ORDER BY seq LIMIT ${input.limit + 1}`; - const entries = yield* Effect.forEach(rows.slice(0, input.limit), (row) => - decodeEntry(parseJson(row.entry_json)), + // One bad row becomes a marker instead of failing every page that includes it. + const entries = rows.slice(0, input.limit).map((row) => + Option.getOrElse(decodeEntryOption(parseJson(row.entry_json)), () => ({ + seq: row.seq, + corrupt: true as const, + })), ); return { entries, hasMore: rows.length > input.limit }; }, diff --git a/apps/server/src/kin/approvals/PendingActions.ts b/apps/server/src/kin/approvals/PendingActions.ts index 3a9831b9f00ce..4e9c19d105aa5 100644 --- a/apps/server/src/kin/approvals/PendingActions.ts +++ b/apps/server/src/kin/approvals/PendingActions.ts @@ -433,15 +433,23 @@ const make = Effect.gen(function* () { }), ) .pipe(Effect.catchTags({ Rollback: () => Effect.succeed({ _tag: "stale" as const }) })); - // A refused grant still leaves a trace (spec section 11); the rolled-back attempt can't. + // A refused grant still leaves a trace (spec section 11), but only on the chain of the org + // that owns the action: an unknown org or action stays `stale` and writes nothing. if (result._tag !== "approved") { - yield* audit.append({ - orgId: input.orgId, - event: "grant_rejected", - actionId: input.actionId, - ...who, - result: result._tag, - }); + yield* sql.withTransaction( + Effect.gen(function* () { + const [owned] = yield* sql`SELECT 1 FROM kin_pending_actions + WHERE org_id = ${input.orgId} AND action_id = ${input.actionId}`; + if (owned === undefined) return; + yield* audit.append({ + orgId: input.orgId, + event: "grant_rejected", + actionId: input.actionId, + ...who, + result: result._tag, + }); + }), + ); } return result; }, diff --git a/apps/server/src/kin/approvals/rpcHandlers.ts b/apps/server/src/kin/approvals/rpcHandlers.ts index a3d61391173fe..b315eb723fb2c 100644 --- a/apps/server/src/kin/approvals/rpcHandlers.ts +++ b/apps/server/src/kin/approvals/rpcHandlers.ts @@ -23,11 +23,16 @@ export const makeKinApprovalHandlers = Effect.fn("makeKinApprovalHandlers")(func ) { const kin = yield* Effect.serviceOption(KinServer); const audit = yield* Audit.make; - // Owner-only (spec section 11). Phase 1 identity resolves a session to the org owner or to no one. + // Owner-only (spec section 11): membership in the org is not enough. const asOwner = Effect.fn("KinApprovals.asOwner")(function* (orgId: KinOrgId) { if (Option.isNone(kin) || Option.isNone(kin.value.services)) return yield* unavailable; - const people = yield* Context.get(kin.value.services.value, KinIdentity).resolve(session); - if (!people.some((person) => person.orgId === orgId)) { + const identity = Context.get(kin.value.services.value, KinIdentity); + const people = yield* identity.resolve(session); + const { owner } = identity; + const isOwner = people.some( + (person) => person.orgId === owner.orgId && person.personId === owner.personId, + ); + if (owner.orgId !== orgId || !isOwner) { return yield* new KinApprovalError({ reason: "not_owner", message: "Owner only." }); } return audit; diff --git a/apps/server/src/kin/chat/KinIdentity.ts b/apps/server/src/kin/chat/KinIdentity.ts index 0ebd03cccca45..287dca14a70b4 100644 --- a/apps/server/src/kin/chat/KinIdentity.ts +++ b/apps/server/src/kin/chat/KinIdentity.ts @@ -65,6 +65,8 @@ type AgentThreadInput = { export class KinIdentity extends Context.Service< KinIdentity, { + /** The org owner bootstrapped at startup; the only person allowed owner-only actions. */ + readonly owner: PersonIdentity; readonly resolve: ( session: AuthenticatedSession, ) => Effect.Effect>; @@ -94,6 +96,7 @@ export class KinIdentity extends Context.Service< ); const lock = yield* Semaphore.make(1); return KinIdentity.of({ + owner: { _tag: "person", orgId: owner.orgId, personId: owner.personId }, resolve: Effect.fn("KinIdentity.resolve")(function (session) { return Effect.succeed( AuthStandardClientScopes.every((scope) => session.scopes.includes(scope)) diff --git a/apps/server/src/kin/persistence/migrations/K008_Approvals.ts b/apps/server/src/kin/persistence/migrations/K008_Approvals.ts index 678103b3b66b6..28e83d5c030ed 100644 --- a/apps/server/src/kin/persistence/migrations/K008_Approvals.ts +++ b/apps/server/src/kin/persistence/migrations/K008_Approvals.ts @@ -99,4 +99,13 @@ export default Effect.gen(function* () { UNIQUE (org_id, seq) ) `; + // The hash chain detects edits; these refuse them outright. + yield* sql` + CREATE TRIGGER kin_audit_no_update BEFORE UPDATE ON kin_audit + BEGIN SELECT RAISE(ABORT, 'kin_audit is append-only'); END + `; + yield* sql` + CREATE TRIGGER kin_audit_no_delete BEFORE DELETE ON kin_audit + BEGIN SELECT RAISE(ABORT, 'kin_audit is append-only'); END + `; }); diff --git a/packages/contracts/src/kinApprovals.ts b/packages/contracts/src/kinApprovals.ts index 80b81aef9ec69..58aa939edd802 100644 --- a/packages/contracts/src/kinApprovals.ts +++ b/packages/contracts/src/kinApprovals.ts @@ -466,8 +466,14 @@ export const KinAuditListInput = Schema.Struct({ limit: PositiveInt.check(Schema.isLessThanOrEqualTo(200)), }); export type KinAuditListInput = typeof KinAuditListInput.Type; +/** A stored row that no longer decodes; `kin.audit.verify` reports where the chain breaks. */ +export const KinAuditCorruptEntry = Schema.Struct({ + seq: PositiveInt, + corrupt: Schema.Literal(true), +}); +export type KinAuditCorruptEntry = typeof KinAuditCorruptEntry.Type; export const KinAuditListResult = Schema.Struct({ - entries: Schema.Array(KinAuditEntry), + entries: Schema.Array(Schema.Union([KinAuditEntry, KinAuditCorruptEntry])), hasMore: Schema.Boolean, }); export type KinAuditListResult = typeof KinAuditListResult.Type; From cf84c9cebb9d2529ebd1614761067a3c04f4ea3e Mon Sep 17 00:00:00 2001 From: Surajsm60720 <1ds22is166@dsce.edu.in> Date: Sun, 8 Nov 2026 07:51:27 +0530 Subject: [PATCH 4/9] docs(kin): audit spec covers append-only triggers and the grant_rejected path (APPR-10) Co-Authored-By: Claude Opus 5.5 --- docs/kin/specs/approvals.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/kin/specs/approvals.md b/docs/kin/specs/approvals.md index 67cd8f8d72540..78e4d83163596 100644 --- a/docs/kin/specs/approvals.md +++ b/docs/kin/specs/approvals.md @@ -427,9 +427,9 @@ export const KinAuditEntry = Schema.Struct({ }); ``` -Append-only (`kin_audit`, no `UPDATE` or `DELETE` statements in the repository code). The hash chain makes edits visible; `kin.audit.verify` recomputes it. Rejected grants are audited with their failure reason and the sending session, so a forged approval leaves a trace. `kin.audit.list` is owner-only. The audit stores the grant's `jti` and the key thumbprint, never tokens or keychain contents. +Append-only: `BEFORE UPDATE` and `BEFORE DELETE` triggers on `kin_audit` abort every edit, and the repository code has no such statements. The hash chain makes edits that bypass the triggers visible; `kin.audit.verify` recomputes it. Rejected grants are audited with their failure reason and the sending session, so a forged approval leaves a trace. `kin.audit.list` and `kin.audit.verify` are owner-only: the session must resolve to the org's owner, not just a person in the org. `list` returns a row that no longer decodes as `{ seq, corrupt: true }` instead of failing the page. The audit stores the grant's `jti` and the key thumbprint, never tokens or keychain contents. -`apps/server/src/kin/approvals/Audit.ts` (`KinAudit`) is the only writer. `append` joins the caller's transaction, so `PendingActions.ts` writes each transition's entry atomically with the transition: `action_requested` on insert (not on an idempotent replay), `action_refreshed`, `grant_accepted`, the four terminal `action_*` moves (the sweep included), `execution_started` with the claim, and `execution_finished`, or `execution_reconciled` when startup reconciliation decides the outcome. `approve` also writes `grant_rejected` for `stale` and `replayed`, after its transaction rolls back. Rejections decided before `approve` (checks 1–9), key events and `credential_check_failed` are written by APPR-4, APPR-5 and APPR-8 through `KinAudit.append`. No RPC or MCP tool writes or deletes entries. +`apps/server/src/kin/approvals/Audit.ts` (`KinAudit`) is the only writer. `append` joins the caller's transaction, so `PendingActions.ts` writes each transition's entry atomically with the transition: `action_requested` on insert (not on an idempotent replay), `action_refreshed`, `grant_accepted`, the four terminal `action_*` moves (the sweep included), `execution_started` with the claim, and `execution_finished`, or `execution_reconciled` when startup reconciliation decides the outcome. `approve` also writes `grant_rejected` for `stale` and `replayed`, after its transaction ends: when no grant row was inserted the transaction commits empty, and only a lost compare-and-set on the action rolls the inserted grant back. The entry goes on the chain of the org that owns the action; a grant naming an unknown org or action stays `stale` and writes nothing. Rejections decided before `approve` (checks 1–9), key events and `credential_check_failed` are written by APPR-4, APPR-5 and APPR-8 through `KinAudit.append`. No RPC or MCP tool writes or deletes entries. Each org has its own chain. The first entry's `prevHash` is 64 zeros, and `seq` counts from 1 with no gaps. Appends are serialized by SQLite's single `BEGIN IMMEDIATE` writer, with `UNIQUE(org_id, seq)` as a backstop. `entry_json` holds `stableStringify` of the whole entry. `verify` walks the chain in `seq` order and reports the first entry whose bytes, columns, position, `prevHash` or `hash` don't hold, which catches an edited, deleted, reordered or inserted row. The chain has no secret and no outside anchor, so it can't show a truncated tail or a chain recomputed from the edit onward by someone with write access to the database. It catches tampering, not a compromised server. From bb0e4be6972528b5c9becdf07eccfe225aceca83 Mon Sep 17 00:00:00 2001 From: Surajsm60720 <1ds22is166@dsce.edu.in> Date: Sun, 8 Nov 2026 07:55:19 +0530 Subject: [PATCH 5/9] test(kin): mock KinIdentity.owner and split member audit assertions (APPR-10) Co-Authored-By: Claude Opus 5.5 --- apps/server/src/kin/approvals/Audit.test.ts | 14 ++++++++------ apps/server/src/kin/lead/WakeupRunner.test.ts | 8 +++++++- 2 files changed, 15 insertions(+), 7 deletions(-) diff --git a/apps/server/src/kin/approvals/Audit.test.ts b/apps/server/src/kin/approvals/Audit.test.ts index 4c0632fc577b8..7c6370529d0b3 100644 --- a/apps/server/src/kin/approvals/Audit.test.ts +++ b/apps/server/src/kin/approvals/Audit.test.ts @@ -563,12 +563,14 @@ describe("kin.audit RPCs", () => { ), }; const memberHandlers = yield* handlersFor(AuthStandardClientScopes, asMember); - for (const call of [ - memberHandlers["kin.audit.verify"]({ orgId: defaultOrg }), - memberHandlers["kin.audit.list"]({ orgId: defaultOrg, limit: 10 }), - ]) { - assert.include(yield* Effect.flip(call), { reason: "not_owner" }); - } + assert.include( + yield* memberHandlers["kin.audit.verify"]({ orgId: defaultOrg }).pipe(Effect.flip), + { reason: "not_owner" }, + ); + assert.include( + yield* memberHandlers["kin.audit.list"]({ orgId: defaultOrg, limit: 10 }).pipe(Effect.flip), + { reason: "not_owner" }, + ); }).pipe(Effect.provide(Sqlite.layerMemory)), ); }); diff --git a/apps/server/src/kin/lead/WakeupRunner.test.ts b/apps/server/src/kin/lead/WakeupRunner.test.ts index 8bbee9125bf2b..259da2ddf280e 100644 --- a/apps/server/src/kin/lead/WakeupRunner.test.ts +++ b/apps/server/src/kin/lead/WakeupRunner.test.ts @@ -13,6 +13,7 @@ import { MessageId, KinWakeupId, KinAgentId, + KinPersonId, ThreadId, RunId, RunAttemptId, @@ -814,7 +815,12 @@ describe("WakeupRunner", () => { return Effect.gen(function* () { yield* seed; const failing = KinLead.layer.pipe( - Layer.provide(Layer.mock(KinIdentity.KinIdentity)({ isAgentThread: () => false })), + Layer.provide( + Layer.mock(KinIdentity.KinIdentity)({ + owner: { _tag: "person", orgId, personId: KinPersonId.make("owner") }, + isAgentThread: () => false, + }), + ), Layer.provide( Layer.mergeAll( Layer.mock(ThreadLaunch.ThreadLaunchService)({}), From b47605d926d4cc685c64396d05a6d38bba36064d Mon Sep 17 00:00:00 2001 From: Surajsm60720 <1ds22is166@dsce.edu.in> Date: Sun, 8 Nov 2026 10:01:29 +0530 Subject: [PATCH 6/9] fix(kin): provide SqlClient to the makeKinHandlers auth test now audit reads SQL Co-Authored-By: Claude Opus 5.5 --- apps/server/src/kin/chat/rpcHandlers.test.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/apps/server/src/kin/chat/rpcHandlers.test.ts b/apps/server/src/kin/chat/rpcHandlers.test.ts index 8a0052e54ccf9..2ee3c4da5bd98 100644 --- a/apps/server/src/kin/chat/rpcHandlers.test.ts +++ b/apps/server/src/kin/chat/rpcHandlers.test.ts @@ -497,7 +497,7 @@ it.effect("denies settings-only sessions before Kin handlers execute", () => (yield* client["kin.orgs.list"]({}).pipe(Effect.flip))._tag, "EnvironmentAuthorizationError", ); - }), + }).pipe(Effect.provide(Sqlite.layerMemory)), ); it.effect("drops a failed waiting read without ending the chat list stream", () => From 60a358b14fc397f488b6bbb397799a754db38b2e Mon Sep 17 00:00:00 2001 From: Surajsm60720 <1ds22is166@dsce.edu.in> Date: Sun, 8 Nov 2026 20:40:15 +0530 Subject: [PATCH 7/9] fix(kin): keep audit handlers off the judge's import graph approvals/rpcHandlers.ts imported KinServer, whose service union reaches floor/JudgeShadow.ts through KinChatService. The kin aggregator now passes the Kin services in. Co-Authored-By: Claude Opus 5.5 --- apps/server/src/kin/approvals/Audit.test.ts | 29 ++++++++------------ apps/server/src/kin/approvals/rpcHandlers.ts | 8 +++--- apps/server/src/kin/rpcHandlers.ts | 8 +++++- 3 files changed, 23 insertions(+), 22 deletions(-) diff --git a/apps/server/src/kin/approvals/Audit.test.ts b/apps/server/src/kin/approvals/Audit.test.ts index 7c6370529d0b3..1f46f1f1f9658 100644 --- a/apps/server/src/kin/approvals/Audit.test.ts +++ b/apps/server/src/kin/approvals/Audit.test.ts @@ -524,13 +524,11 @@ describe("kin.audit RPCs", () => { ); if (Option.isNone(kin.services)) return assert.fail("Kin services missing"); const services = kin.services.value; - const handlersFor = (scopes: AuthenticatedSession["scopes"], server = kin) => - makeKinApprovalHandlers({ - sessionId, - subject: "browser", - method: "browser-session-cookie", - scopes, - }).pipe(Effect.provideService(Kin.KinServer, server)); + const handlersFor = (scopes: AuthenticatedSession["scopes"], kinServices = kin.services) => + makeKinApprovalHandlers( + { sessionId, subject: "browser", method: "browser-session-cookie", scopes }, + kinServices, + ); const ownerHandlers = yield* handlersFor(AuthStandardClientScopes); assert.deepStrictEqual(yield* ownerHandlers["kin.audit.verify"]({ orgId: defaultOrg }), { ok: true, @@ -552,16 +550,13 @@ describe("kin.audit RPCs", () => { yield* sql`INSERT INTO kin_people (person_id, org_id, handle, display_name, github_login, created_at) VALUES (${member}, ${defaultOrg}, 'member', 'Member', NULL, '2026-11-08T00:00:00.000Z')`; const identity = Context.get(services, KinIdentity); - const asMember = { - ...kin, - services: Option.some( - Context.add(services, KinIdentity, { - ...identity, - resolve: () => - Effect.succeed([{ _tag: "person" as const, orgId: defaultOrg, personId: member }]), - }), - ), - }; + const asMember = Option.some( + Context.add(services, KinIdentity, { + ...identity, + resolve: () => + Effect.succeed([{ _tag: "person" as const, orgId: defaultOrg, personId: member }]), + }), + ); const memberHandlers = yield* handlersFor(AuthStandardClientScopes, asMember); assert.include( yield* memberHandlers["kin.audit.verify"]({ orgId: defaultOrg }).pipe(Effect.flip), diff --git a/apps/server/src/kin/approvals/rpcHandlers.ts b/apps/server/src/kin/approvals/rpcHandlers.ts index b315eb723fb2c..1d956fe798ae2 100644 --- a/apps/server/src/kin/approvals/rpcHandlers.ts +++ b/apps/server/src/kin/approvals/rpcHandlers.ts @@ -7,7 +7,6 @@ import * as RpcGroup from "effect/rpc/RpcGroup"; import type { AuthenticatedSession } from "../../auth/EnvironmentAuth.ts"; import { KinIdentity } from "../chat/KinIdentity.ts"; -import { KinServer } from "../KinServer.ts"; import * as Audit from "./Audit.ts"; const group = RpcGroup.make(...KinApprovalRpcs); @@ -20,13 +19,14 @@ const failed = () => export const makeKinApprovalHandlers = Effect.fn("makeKinApprovalHandlers")(function* ( session: AuthenticatedSession, + // Passed in rather than read from `KinServer`, whose service union reaches the judge. + kin: Option.Option>, ) { - const kin = yield* Effect.serviceOption(KinServer); const audit = yield* Audit.make; // Owner-only (spec section 11): membership in the org is not enough. const asOwner = Effect.fn("KinApprovals.asOwner")(function* (orgId: KinOrgId) { - if (Option.isNone(kin) || Option.isNone(kin.value.services)) return yield* unavailable; - const identity = Context.get(kin.value.services.value, KinIdentity); + if (Option.isNone(kin)) return yield* unavailable; + const identity = Context.get(kin.value, KinIdentity); const people = yield* identity.resolve(session); const { owner } = identity; const isOwner = people.some( diff --git a/apps/server/src/kin/rpcHandlers.ts b/apps/server/src/kin/rpcHandlers.ts index 9aca38a00947f..3b4a8126c880f 100644 --- a/apps/server/src/kin/rpcHandlers.ts +++ b/apps/server/src/kin/rpcHandlers.ts @@ -1,17 +1,23 @@ import { KinRpcs } from "@t3tools/contracts"; import * as Effect from "effect/Effect"; +import * as Option from "effect/Option"; import * as RpcGroup from "effect/rpc/RpcGroup"; import type { AuthenticatedSession } from "../auth/EnvironmentAuth.ts"; import { makeKinApprovalHandlers } from "./approvals/rpcHandlers.ts"; import { makeKinChatHandlers } from "./chat/rpcHandlers.ts"; +import { KinServer } from "./KinServer.ts"; const group = RpcGroup.make(...KinRpcs); export const makeKinHandlers = Effect.fn("makeKinHandlers")(function* ( session: AuthenticatedSession, ) { + const kin = yield* Effect.serviceOption(KinServer); return group.of({ ...(yield* makeKinChatHandlers(session)), - ...(yield* makeKinApprovalHandlers(session)), + ...(yield* makeKinApprovalHandlers( + session, + Option.flatMap(kin, (kin) => kin.services), + )), }); }); From 2f010d1d66f2c090e9e80ab3dc1015792d72f59c Mon Sep 17 00:00:00 2001 From: Surajsm60720 <1ds22is166@dsce.edu.in> Date: Sun, 8 Nov 2026 21:42:11 +0530 Subject: [PATCH 8/9] fix(server): report kin audit as disabled when Kin is off Co-Authored-By: Claude Opus 5.5 --- apps/server/src/kin/approvals/Audit.test.ts | 10 ++++++++++ apps/server/src/kin/approvals/rpcHandlers.ts | 6 +++++- 2 files changed, 15 insertions(+), 1 deletion(-) diff --git a/apps/server/src/kin/approvals/Audit.test.ts b/apps/server/src/kin/approvals/Audit.test.ts index 1f46f1f1f9658..1a5c9a16daf7f 100644 --- a/apps/server/src/kin/approvals/Audit.test.ts +++ b/apps/server/src/kin/approvals/Audit.test.ts @@ -566,6 +566,16 @@ describe("kin.audit RPCs", () => { yield* memberHandlers["kin.audit.list"]({ orgId: defaultOrg, limit: 10 }).pipe(Effect.flip), { reason: "not_owner" }, ); + + const kinOff = yield* handlersFor(AuthStandardClientScopes, Option.none()); + assert.include(yield* kinOff["kin.audit.verify"]({ orgId: defaultOrg }).pipe(Effect.flip), { + reason: "disabled", + }); + yield* sql`ALTER TABLE kin_audit RENAME TO kin_audit_gone`; + assert.include( + yield* ownerHandlers["kin.audit.list"]({ orgId: defaultOrg, limit: 10 }).pipe(Effect.flip), + { reason: "unavailable" }, + ); }).pipe(Effect.provide(Sqlite.layerMemory)), ); }); diff --git a/apps/server/src/kin/approvals/rpcHandlers.ts b/apps/server/src/kin/approvals/rpcHandlers.ts index 1d956fe798ae2..3a9ba24e48a4f 100644 --- a/apps/server/src/kin/approvals/rpcHandlers.ts +++ b/apps/server/src/kin/approvals/rpcHandlers.ts @@ -14,6 +14,10 @@ const group = RpcGroup.make(...KinApprovalRpcs); const unavailable = Effect.fail( new KinApprovalError({ reason: "unavailable", message: "Kin approvals are unavailable." }), ); +const disabled = new KinApprovalError({ + reason: "disabled", + message: "Kin is not running on this host.", +}); const failed = () => new KinApprovalError({ reason: "unavailable", message: "Kin audit is unavailable." }); @@ -25,7 +29,7 @@ export const makeKinApprovalHandlers = Effect.fn("makeKinApprovalHandlers")(func const audit = yield* Audit.make; // Owner-only (spec section 11): membership in the org is not enough. const asOwner = Effect.fn("KinApprovals.asOwner")(function* (orgId: KinOrgId) { - if (Option.isNone(kin)) return yield* unavailable; + if (Option.isNone(kin)) return yield* disabled; const identity = Context.get(kin.value, KinIdentity); const people = yield* identity.resolve(session); const { owner } = identity; From 4cb4ebe21ece72057810ce82cb6356436d8ebe4b Mon Sep 17 00:00:00 2001 From: GLDRoger <130458023+GLDRoger@users.noreply.github.com> Date: Sun, 8 Nov 2026 23:58:34 +0530 Subject: [PATCH 9/9] fix(kin): a lost grant_rejected trace no longer turns a refusal into an error The post-transaction grant_rejected append logs and keeps the decided result. A claim without its grant row rolls back instead of writing an entry without the jti. Co-Authored-By: Claude Opus 5.5 --- apps/server/src/kin/approvals/Audit.test.ts | 5 +++ .../src/kin/approvals/PendingActions.ts | 39 +++++++++++-------- 2 files changed, 28 insertions(+), 16 deletions(-) diff --git a/apps/server/src/kin/approvals/Audit.test.ts b/apps/server/src/kin/approvals/Audit.test.ts index 1a5c9a16daf7f..90a2a5c9193b2 100644 --- a/apps/server/src/kin/approvals/Audit.test.ts +++ b/apps/server/src/kin/approvals/Audit.test.ts @@ -508,6 +508,11 @@ describe("KinPendingActions audit trail", () => { Option.getOrThrow(yield* actions.get({ orgId: org, actionId: action.id })).state, "awaiting_approval", ); + // A refused grant stays refused when only its trace can't be written. + assert.deepStrictEqual( + yield* actions.approve(grant({ ...action, revision: 7 }, "jti-unwritten")), + { _tag: "stale" }, + ); }).pipe(Effect.provide(layer)), ); }); diff --git a/apps/server/src/kin/approvals/PendingActions.ts b/apps/server/src/kin/approvals/PendingActions.ts index fece67c1e9f1e..db1aaff750892 100644 --- a/apps/server/src/kin/approvals/PendingActions.ts +++ b/apps/server/src/kin/approvals/PendingActions.ts @@ -436,20 +436,27 @@ const make = Effect.gen(function* () { // A refused grant still leaves a trace (spec section 11), but only on the chain of the org // that owns the action: an unknown org or action stays `stale` and writes nothing. if (result._tag !== "approved") { - yield* sql.withTransaction( - Effect.gen(function* () { - const [owned] = yield* sql`SELECT 1 FROM kin_pending_actions + yield* sql + .withTransaction( + Effect.gen(function* () { + const [owned] = yield* sql`SELECT 1 FROM kin_pending_actions WHERE org_id = ${input.orgId} AND action_id = ${input.actionId}`; - if (owned === undefined) return; - yield* audit.append({ - orgId: input.orgId, - event: "grant_rejected", - actionId: input.actionId, - ...who, - result: result._tag, - }); - }), - ); + if (owned === undefined) return; + yield* audit.append({ + orgId: input.orgId, + event: "grant_rejected", + actionId: input.actionId, + ...who, + result: result._tag, + }); + }), + ) + .pipe( + // The refusal is already decided; a lost trace must not turn it into an error. + Effect.catch((error) => + Effect.logWarning("Kin audit: grant_rejected not written", error), + ), + ); } return result; }, @@ -481,13 +488,13 @@ const make = Effect.gen(function* () { const [grant] = yield* sql<{ jti: string; key_thumbprint: KinKeyThumbprint }>` UPDATE kin_grants SET consumed_at = ${now} WHERE grant_id = ${input.grantId} RETURNING jti, key_thumbprint`; + if (grant === undefined) return yield* new Rollback(); yield* audit.append({ orgId: input.orgId, event: "execution_started", ...(yield* auditFacts(won)), - ...(grant === undefined - ? {} - : { grantJti: grant.jti, keyThumbprint: grant.key_thumbprint }), + grantJti: grant.jti, + keyThumbprint: grant.key_thumbprint, }); return true; }),