diff --git a/.changeset/owner-individual-safety-review.md b/.changeset/owner-individual-safety-review.md new file mode 100644 index 0000000000..2828de8a46 --- /dev/null +++ b/.changeset/owner-individual-safety-review.md @@ -0,0 +1,6 @@ +--- +"@schlessera/brain-ui-sdk": minor +"@schlessera/brain-ui-server": minor +--- + +Add password-mode owner review of individual finalized safety triggers with durable retries and live authority checks, implementing the approved pre-1.0 change to unconditional restriction. diff --git a/api-report/ui-sdk.txt b/api-report/ui-sdk.txt index 03f9098063..4815058a91 100644 --- a/api-report/ui-sdk.txt +++ b/api-report/ui-sdk.txt @@ -319,6 +319,9 @@ export "." (./src/index.ts) type SafetyIdentity type SafetyPage type SafetyRecord + type SafetyReviewBody + type SafetyReviewReceipt + type SafetyReviewResponse type SafetySessionKey type SafetyTarget type SafetyUnavailable @@ -962,6 +965,9 @@ export "./client" (./src/client/index.ts) type SafetyIdentity type SafetyPage type SafetyRecord + type SafetyReviewBody + type SafetyReviewReceipt + type SafetyReviewResponse type SafetySessionKey type SafetyTarget type SafetyUnavailable @@ -1741,6 +1747,9 @@ export "./protocol" (./src/protocol.ts) type SafetyIdentity type SafetyPage type SafetyRecord + type SafetyReviewBody + type SafetyReviewReceipt + type SafetyReviewResponse type SafetySessionKey type SafetyTarget type SafetyUnavailable @@ -2030,6 +2039,10 @@ export "./schemas" (./src/schemas.ts) resolutionEffectSchema safetyCapabilitiesSchema safetyPageSchema + safetyProjectionSchema + safetyReviewBodySchema + safetyReviewReceiptSchema + safetyReviewResponseSchema safetySessionKeySchema safetyUpdateSchema serverActivityDeltaSchema @@ -2641,6 +2654,9 @@ export "./server" (./src/server/index.ts) type SafetyIdentity type SafetyPage type SafetyRecord + type SafetyReviewBody + type SafetyReviewReceipt + type SafetyReviewResponse type SafetySessionKey type SafetyTarget type SafetyUnavailable @@ -9300,13 +9316,16 @@ signatures (every public export and the types it is made of) cursorLifetimeMs: 300000; frameBytes: 262144; pageRecords: 100; + receiptLifetimeMs?: 86400000 | undefined; + reviewBodyBytes?: 16384 | undefined; + reviewLifetimeMs?: 900000 | undefined; }; originRules: false; read: true; - readOnlyReason: "review_unavailable"; + readOnlyReason: "owner_required" | "review_unavailable" | null; recipientRules: false; repositoryRules: false; - review: false; + review: boolean; version: 1; }; SESSION_DRAFT_LIMITS (packages/ui-sdk/src/protocol.ts) @@ -10755,6 +10774,12 @@ signatures (every public export and the types it is made of) export type SafetyPage = z.infer; SafetyRecord (packages/ui-sdk/src/safety.ts) export type SafetyRecord = z.infer; + SafetyReviewBody (packages/ui-sdk/src/safety.ts) + export type SafetyReviewBody = z.infer; + SafetyReviewReceipt (packages/ui-sdk/src/safety.ts) + export type SafetyReviewReceipt = z.infer; + SafetyReviewResponse (packages/ui-sdk/src/safety.ts) + export type SafetyReviewResponse = z.infer; SafetySessionKey (packages/ui-sdk/src/safety.ts) export type SafetySessionKey = z.infer; SafetyTarget (packages/ui-sdk/src/safety.ts) @@ -17995,13 +18020,19 @@ signatures (every public export and the types it is made of) cursorLifetimeMs: z.ZodLiteral<300000>; frameBytes: z.ZodLiteral<262144>; pageRecords: z.ZodLiteral<100>; + receiptLifetimeMs: z.ZodOptional>; + reviewBodyBytes: z.ZodOptional>; + reviewLifetimeMs: z.ZodOptional>; }, z.core.$strict>; originRules: z.ZodLiteral; read: z.ZodLiteral; - readOnlyReason: z.ZodLiteral<"review_unavailable">; + readOnlyReason: z.ZodNullable>; recipientRules: z.ZodLiteral; repositoryRules: z.ZodLiteral; - review: z.ZodLiteral; + review: z.ZodBoolean; version: z.ZodLiteral<1>; }, z.core.$strict>; safetyIdentitySchema (packages/ui-sdk/src/safety.ts) @@ -18303,6 +18334,327 @@ signatures (every public export and the types it is made of) turnId: z.ZodString; verdict: z.ZodLiteral<"safe">; }, z.core.$strict>], "kind">; + safetyReviewBodySchema (packages/ui-sdk/src/safety.ts) + const safetyReviewBodySchema: z.ZodObject<{ + expectedEvidenceRevision: z.ZodString; + occurrenceId: z.ZodString; + session: z.ZodObject<{ + historyGeneration: z.ZodString; + historyOwnerId: z.ZodString; + sessionId: z.ZodString; + }, z.core.$strict>; + verdict: z.ZodLiteral<"safe">; + version: z.ZodLiteral<1>; + }, z.core.$strict>; + safetyReviewReceiptSchema (packages/ui-sdk/src/safety.ts) + const safetyReviewReceiptSchema: z.ZodObject<{ + occurrenceId: z.ZodString; + operationId: z.ZodNullable; + projection: z.ZodNullable; + epochs: z.ZodArray; + backendId: z.ZodString; + endSequence: z.ZodNullable; + id: z.ZodString; + mandatory: z.ZodArray; + reason: z.ZodNullable; + startSequence: z.ZodString; + status: z.ZodEnum<{ + complete: "complete"; + incomplete: "incomplete"; + unknown: "unknown"; + }>; + }, z.core.$strict>>; + exclusions: z.ZodArray; + state: z.ZodEnum<{ + complete: "complete"; + incomplete: "incomplete"; + unknown: "unknown"; + }>; + }, z.core.$strict>; + earliestUnresolvedId: z.ZodNullable; + evidenceRevision: z.ZodString; + pendingCount: z.ZodNumber; + reasons: z.ZodArray>; + restriction: z.ZodEnum<{ + normal: "normal"; + restricted: "restricted"; + }>; + session: z.ZodNullable>; + unresolvedCount: z.ZodNumber; + }, z.core.$strict>>; + reason: z.ZodNullable; + requestId: z.ZodNullable; + session: z.ZodObject<{ + historyGeneration: z.ZodString; + historyOwnerId: z.ZodString; + sessionId: z.ZodString; + }, z.core.$strict>; + stage: z.ZodEnum<{ + prepared: "prepared"; + refused: "refused"; + verdict_committed: "verdict_committed"; + }>; + verdict: z.ZodEnum<{ + committed: "committed"; + unresolved: "unresolved"; + }>; + version: z.ZodLiteral<1>; + }, z.core.$strict>; + safetyReviewResponseSchema (packages/ui-sdk/src/safety.ts) + const safetyReviewResponseSchema: z.ZodUnion; + epochs: z.ZodArray; + backendId: z.ZodString; + endSequence: z.ZodNullable; + id: z.ZodString; + mandatory: z.ZodArray; + reason: z.ZodNullable; + startSequence: z.ZodString; + status: z.ZodEnum<{ + complete: "complete"; + incomplete: "incomplete"; + unknown: "unknown"; + }>; + }, z.core.$strict>>; + exclusions: z.ZodArray; + state: z.ZodEnum<{ + complete: "complete"; + incomplete: "incomplete"; + unknown: "unknown"; + }>; + }, z.core.$strict>; + earliestUnresolvedId: z.ZodNullable; + evidenceRevision: z.ZodString; + pendingCount: z.ZodNumber; + reasons: z.ZodArray>; + restriction: z.ZodEnum<{ + normal: "normal"; + restricted: "restricted"; + }>; + session: z.ZodNullable>; + unresolvedCount: z.ZodNumber; + }, z.core.$strict>>; + receipt: z.ZodObject<{ + occurrenceId: z.ZodString; + operationId: z.ZodNullable; + projection: z.ZodNullable; + epochs: z.ZodArray; + backendId: z.ZodString; + endSequence: z.ZodNullable; + id: z.ZodString; + mandatory: z.ZodArray; + reason: z.ZodNullable; + startSequence: z.ZodString; + status: z.ZodEnum<{ + complete: "complete"; + incomplete: "incomplete"; + unknown: "unknown"; + }>; + }, z.core.$strict>>; + exclusions: z.ZodArray; + state: z.ZodEnum<{ + complete: "complete"; + incomplete: "incomplete"; + unknown: "unknown"; + }>; + }, z.core.$strict>; + earliestUnresolvedId: z.ZodNullable; + evidenceRevision: z.ZodString; + pendingCount: z.ZodNumber; + reasons: z.ZodArray>; + restriction: z.ZodEnum<{ + normal: "normal"; + restricted: "restricted"; + }>; + session: z.ZodNullable>; + unresolvedCount: z.ZodNumber; + }, z.core.$strict>>; + reason: z.ZodNullable; + requestId: z.ZodNullable; + session: z.ZodObject<{ + historyGeneration: z.ZodString; + historyOwnerId: z.ZodString; + sessionId: z.ZodString; + }, z.core.$strict>; + stage: z.ZodEnum<{ + prepared: "prepared"; + refused: "refused"; + verdict_committed: "verdict_committed"; + }>; + verdict: z.ZodEnum<{ + committed: "committed"; + unresolved: "unresolved"; + }>; + version: z.ZodLiteral<1>; + }, z.core.$strict>; + version: z.ZodLiteral<1>; + }, z.core.$strict>, z.ZodObject<{ + code: z.ZodEnum<{ + capacity: "capacity"; + not_finalized: "not_finalized"; + recording_failed: "recording_failed"; + request_conflict: "request_conflict"; + request_expired: "request_expired"; + resync_required: "resync_required"; + retired: "retired"; + stale_revision: "stale_revision"; + unauthorized: "unauthorized"; + unavailable: "unavailable"; + }>; + currentProjection: z.ZodNullable; + epochs: z.ZodArray; + backendId: z.ZodString; + endSequence: z.ZodNullable; + id: z.ZodString; + mandatory: z.ZodArray; + reason: z.ZodNullable; + startSequence: z.ZodString; + status: z.ZodEnum<{ + complete: "complete"; + incomplete: "incomplete"; + unknown: "unknown"; + }>; + }, z.core.$strict>>; + exclusions: z.ZodArray; + state: z.ZodEnum<{ + complete: "complete"; + incomplete: "incomplete"; + unknown: "unknown"; + }>; + }, z.core.$strict>; + earliestUnresolvedId: z.ZodNullable; + evidenceRevision: z.ZodString; + pendingCount: z.ZodNumber; + reasons: z.ZodArray>; + restriction: z.ZodEnum<{ + normal: "normal"; + restricted: "restricted"; + }>; + session: z.ZodNullable>; + unresolvedCount: z.ZodNumber; + }, z.core.$strict>>; + reason: z.ZodString; + receipt: z.ZodObject<{ + occurrenceId: z.ZodString; + operationId: z.ZodNullable; + projection: z.ZodNullable; + epochs: z.ZodArray; + backendId: z.ZodString; + endSequence: z.ZodNullable; + id: z.ZodString; + mandatory: z.ZodArray; + reason: z.ZodNullable; + startSequence: z.ZodString; + status: z.ZodEnum<{ + complete: "complete"; + incomplete: "incomplete"; + unknown: "unknown"; + }>; + }, z.core.$strict>>; + exclusions: z.ZodArray; + state: z.ZodEnum<{ + complete: "complete"; + incomplete: "incomplete"; + unknown: "unknown"; + }>; + }, z.core.$strict>; + earliestUnresolvedId: z.ZodNullable; + evidenceRevision: z.ZodString; + pendingCount: z.ZodNumber; + reasons: z.ZodArray>; + restriction: z.ZodEnum<{ + normal: "normal"; + restricted: "restricted"; + }>; + session: z.ZodNullable>; + unresolvedCount: z.ZodNumber; + }, z.core.$strict>>; + reason: z.ZodNullable; + requestId: z.ZodNullable; + session: z.ZodObject<{ + historyGeneration: z.ZodString; + historyOwnerId: z.ZodString; + sessionId: z.ZodString; + }, z.core.$strict>; + stage: z.ZodEnum<{ + prepared: "prepared"; + refused: "refused"; + verdict_committed: "verdict_committed"; + }>; + verdict: z.ZodEnum<{ + committed: "committed"; + unresolved: "unresolved"; + }>; + version: z.ZodLiteral<1>; + }, z.core.$strict>; + retryable: z.ZodLiteral; + version: z.ZodLiteral<1>; + }, z.core.$strict>]>; safetySessionKeySchema (packages/ui-sdk/src/safety.ts) const safetySessionKeySchema: z.ZodObject<{ historyGeneration: z.ZodString; @@ -19448,13 +19800,19 @@ signatures (every public export and the types it is made of) cursorLifetimeMs: z.ZodLiteral<300000>; frameBytes: z.ZodLiteral<262144>; pageRecords: z.ZodLiteral<100>; + receiptLifetimeMs: z.ZodOptional>; + reviewBodyBytes: z.ZodOptional>; + reviewLifetimeMs: z.ZodOptional>; }, z.core.$strict>; originRules: z.ZodLiteral; read: z.ZodLiteral; - readOnlyReason: z.ZodLiteral<"review_unavailable">; + readOnlyReason: z.ZodNullable>; recipientRules: z.ZodLiteral; repositoryRules: z.ZodLiteral; - review: z.ZodLiteral; + review: z.ZodBoolean; version: z.ZodLiteral<1>; }, z.core.$strict>>>; sessionDraftLimits: z.ZodCatch; frameBytes: z.ZodLiteral<262144>; pageRecords: z.ZodLiteral<100>; + receiptLifetimeMs: z.ZodOptional>; + reviewBodyBytes: z.ZodOptional>; + reviewLifetimeMs: z.ZodOptional>; }, z.core.$strict>; originRules: z.ZodLiteral; read: z.ZodLiteral; - readOnlyReason: z.ZodLiteral<"review_unavailable">; + readOnlyReason: z.ZodNullable>; recipientRules: z.ZodLiteral; repositoryRules: z.ZodLiteral; - review: z.ZodLiteral; + review: z.ZodBoolean; version: z.ZodLiteral<1>; }, z.core.$strict>>>; sessionDraftLimits: z.ZodCatch; export type SafetyUnavailable = z.infer; export type SafetyCapabilities = z.infer; +/** Individual review only. No principal, channel, range or standing rule input. */ +export const safetyReviewBodySchema = z.strictObject({ version:z.literal(1), session:safetySessionKeySchema, occurrenceId:id, + expectedEvidenceRevision:revision, verdict:z.literal("safe") }); +export const safetyReviewReceiptSchema = z.strictObject({ version:z.literal(1), requestId:id.nullable(), operationId:id.nullable(), session:safetySessionKeySchema, + occurrenceId:id, stage:z.enum(["prepared","verdict_committed","refused"]), verdict:z.enum(["unresolved","committed"]), + projection:safetyProjectionSchema.nullable(), reason:text(512).nullable() }); +/** receipt is immutable on replay; currentProjection is a separate live read. */ +const reviewResultSchema = z.strictObject({ version:z.literal(1), receipt:safetyReviewReceiptSchema, currentProjection:safetyProjectionSchema.nullable() }); +export const safetyReviewResponseSchema = z.union([reviewResultSchema,reviewResultSchema.extend({ + code:z.enum(["unauthorized","unavailable","stale_revision","not_finalized","request_conflict","request_expired","retired","capacity","recording_failed","resync_required"]), + reason:text(512),retryable:z.literal(false), +})]); +export type SafetyReviewBody = z.infer; +export type SafetyReviewReceipt = z.infer; +export type SafetyReviewResponse = z.infer; + export const clientSafetyReadSchema = z.strictObject({type:z.literal("safety_read"),requestId:id,version:z.literal(1),target:safetyTargetSchema,cursor:z.string().max(512).nullable().optional(),limit:z.number().int().min(1).max(100).optional()}); export const clientSafetySubscribeSchema = z.strictObject({type:z.literal("safety_subscribe"),requestId:id,version:z.literal(1),identity:safetyIdentitySchema,afterRevision:revision,snapshotId:id}); export const clientSafetyUnsubscribeSchema = z.strictObject({type:z.literal("safety_unsubscribe"),version:z.literal(1)}); diff --git a/packages/ui-sdk/src/schemas.ts b/packages/ui-sdk/src/schemas.ts index 2c2889d167..d1a6a348ef 100644 --- a/packages/ui-sdk/src/schemas.ts +++ b/packages/ui-sdk/src/schemas.ts @@ -1,4 +1,4 @@ -export { safetySessionKeySchema, safetyPageSchema, safetyUpdateSchema, safetyCapabilitiesSchema } from "./safety.js"; +export { safetyProjectionSchema, safetyReviewBodySchema, safetyReviewReceiptSchema, safetyReviewResponseSchema, safetySessionKeySchema, safetyPageSchema, safetyUpdateSchema, safetyCapabilitiesSchema } from "./safety.js"; import { clientSafetyReadSchema, clientSafetySubscribeSchema, clientSafetyUnsubscribeSchema, serverSafetyHistorySchema, serverSafetyUpdateSchema, serverSafetyUnavailableSchema, safetyCapabilitiesSchema } from "./safety.js"; import { POLICY_CHANGE_REVIEW_SCHEMA } from "./tool-contracts/policy.js"; import type { HygieneAction, HygieneDiff, HygieneEffect, HygieneMediaMatches, HygieneMediaPlan, HygieneMediaProbe, HygieneMediaReceipt, HygieneMediaRefusal, HygieneReviewCommand, HygieneReviewMediaUndoCommand, HygieneReviewRequest, HygienePreviewRequest, HygieneReviewState, HygieneReviewRead, HygieneWorktreeDetailsRead } from "./protocol.js"; diff --git a/packages/ui-sdk/tests/safety-review-contract.test.ts b/packages/ui-sdk/tests/safety-review-contract.test.ts new file mode 100644 index 0000000000..a518186878 --- /dev/null +++ b/packages/ui-sdk/tests/safety-review-contract.test.ts @@ -0,0 +1,25 @@ +import { expect, test } from "bun:test"; +import { safetyReviewBodySchema, safetyReviewResponseSchema, parseServerMessage } from "../src/schemas"; +import { SAFETY_READ_CAPABILITIES } from "../src/protocol"; + +const body = { version:1 as const, session:{sessionId:"ithaca",historyOwnerId:"voyage",historyGeneration:"1"}, + occurrenceId:"harbour-notice",expectedEvidenceRevision:"12",verdict:"safe" as const }; +test("individual review schema accepts one exact ID and refuses bulk, authority and revision ambiguity",()=>{ + expect(safetyReviewBodySchema.parse(body)).toEqual(body); + for (const value of [{...body,occurrenceIds:["A","B"]},{...body,principalId:"odysseus"},{...body,channel:"card"}, + {...body,rule:{}},{...body,expectedEvidenceRevision:"01"},{...body,expectedEvidenceRevision:"18446744073709551616"}, + {...body,session:{...body.session,historyGeneration:1}},{...body,occurrenceId:"A:B"}]) { + expect(safetyReviewBodySchema.safeParse(value).success,"OWNER_REVIEW_CONTRACT_IS_STRICT_AND_INDIVIDUAL").toBe(false); + } +}); +test("review responses and negotiated capabilities remain optional bounded sidecars",()=>{ + const receipt = {...body,requestId:"review",operationId:"operation",stage:"refused",verdict:"unresolved",projection:null,reason:"not_finalized"}; + delete (receipt as Partial).expectedEvidenceRevision; + expect(safetyReviewResponseSchema.safeParse({version:1,receipt,currentProjection:null}).success).toBe(true); + expect(safetyReviewResponseSchema.safeParse({version:1,receipt:{...receipt,reason:"x".repeat(513)},currentProjection:null}).success).toBe(false); + const hello = {type:"server_hello",protocolRev:5,capabilities:{sessionSafetyHistory:true}} as const; + expect(parseServerMessage(JSON.stringify(hello))).toEqual({ok:true,message:hello}); + expect(parseServerMessage(JSON.stringify({...hello,safetyCapabilities:SAFETY_READ_CAPABILITIES}))).toMatchObject({message:{safetyCapabilities:{review:false}}}); + expect(parseServerMessage(JSON.stringify({...hello,safetyCapabilities:{...SAFETY_READ_CAPABILITIES,review:true,readOnlyReason:null, + limits:{...SAFETY_READ_CAPABILITIES.limits,reviewBodyBytes:16384,reviewLifetimeMs:900000,receiptLifetimeMs:86400000}}}))).toMatchObject({message:{safetyCapabilities:{review:true,readOnlyReason:null}}}); +}); diff --git a/packages/ui-server/migrations/084_owner_safety_review.sql b/packages/ui-server/migrations/084_owner_safety_review.sql new file mode 100644 index 0000000000..07bd5bc97c --- /dev/null +++ b/packages/ui-server/migrations/084_owner_safety_review.sql @@ -0,0 +1,27 @@ +-- Individual verdicts use the same canonical history membership as the +-- aggregate, including durably adopted provisional collections. Preserve the +-- finalized-only, principal, generation and permanent retirement boundaries. +DROP TRIGGER safety_decision_identity; +CREATE TRIGGER safety_decision_identity BEFORE INSERT ON safety_decisions + WHEN NOT EXISTS ( + SELECT 1 FROM safety_records r JOIN safety_collections c ON c.id=r.collection_id + JOIN safety_sessions s ON s.session_id=NEW.session_id + WHERE r.id=NEW.occurrence_id AND r.kind='occurrence' + AND s.history_owner_id=NEW.history_owner_id AND s.generation=NEW.generation + AND s.principal_id=NEW.principal_id AND c.principal_id=NEW.principal_id + AND c.generation=s.generation + AND (c.session_id=s.session_id OR (c.generation=s.generation AND ( + c.history_owner_id=COALESCE((SELECT owner_id FROM dialogue_aliases WHERE id=s.history_owner_id),s.history_owner_id) + OR c.history_owner_id IN (SELECT id FROM dialogue_aliases WHERE owner_id= + COALESCE((SELECT owner_id FROM dialogue_aliases WHERE id=s.history_owner_id),s.history_owner_id))))) + AND NOT EXISTS (SELECT 1 FROM safety_retired_turns WHERE turn_id=c.turn_id) + AND NOT EXISTS (SELECT 1 FROM chat_retired_identities WHERE kind='session' AND id=s.session_id) + AND NOT EXISTS (SELECT 1 FROM chat_retired_identities WHERE kind='dialogue_owner' AND id=s.history_owner_id) + AND NOT EXISTS (SELECT 1 FROM chat_retired_identities WHERE kind='dialogue_owner' AND id= + COALESCE((SELECT owner_id FROM dialogue_aliases WHERE id=s.history_owner_id),s.history_owner_id)) + AND NOT EXISTS (SELECT 1 FROM dialogue_owners WHERE id= + COALESCE((SELECT owner_id FROM dialogue_aliases WHERE id=s.history_owner_id),s.history_owner_id) + AND (principal_id!=NEW.principal_id OR CAST(generation AS TEXT)!=NEW.generation)) + AND COALESCE((SELECT x.state FROM safety_records x WHERE x.occurrence_id=r.id AND x.kind='exposure' + ORDER BY length(x.sequence) DESC,x.sequence DESC LIMIT 1),r.state)='finalized' + ) BEGIN SELECT RAISE(ABORT,'safety decision identity or exposure mismatch'); END; diff --git a/packages/ui-server/src/app.ts b/packages/ui-server/src/app.ts index 8b03cc28c8..12c3f5a92d 100644 --- a/packages/ui-server/src/app.ts +++ b/packages/ui-server/src/app.ts @@ -1,5 +1,7 @@ import { SafetyHistory } from "./governance/safety-history.js"; import { createSessionSafetyRoutes } from "./routes/session-safety.js"; +import { createOwnerSafetyReviewRoutes } from "./routes/owner-safety-review.js"; +import { OwnerSafetyReviews } from "./governance/owner-safety-reviews.js"; import { occurrence } from "./governance/occurrence.js"; import { isWithin } from "@schlessera/brain-common/internal/safe-path"; import { STORAGE_SETTLEMENT_MS } from "./db/settlement.js"; @@ -24,7 +26,7 @@ import { createPolicyProposalRoutes } from "./routes/policy-proposals.js"; import { createTurnBudgets } from "./brain/turn-budgets.js"; import { maintenanceProviderMeter } from "./brain/provider-meter.js"; import { createTrackRoutes } from "./routes/tracks.js"; -import { createAccountPartitionKeys } from "./middleware/account-partition.js"; +import { createAccountPartitionKeys, deriveAccountPartitionKey } from "./middleware/account-partition.js"; import { Hono } from "hono"; import { HTTPException } from "hono/http-exception"; import type { Database } from "bun:sqlite"; @@ -755,8 +757,13 @@ export async function createApp(options: CreateAppOptions = {}): Promise { stopApifyReconciler(); apifyHost.close(); apifyLedger?.close(); apifyLedger = undefined; }); const safetyHistory = new SafetyHistory(db, principal => { const current=resolvePrincipal(db,principal.id); return !!current && isUsablePrincipal(current,Date.now()); }, () => writer.idle()); + const accountSeed = await accountWrites(db).partitionSeed(); + const accountKeys = createAccountPartitionKeys(db, config.brainPath, authMode, accountSeed); + const ownerSafetyReviews = new OwnerSafetyReviews(db, activity.governanceWrites, authMode, + deriveAccountPartitionKey(accountSeed,realpathSync(config.brainPath),"owner")); const host = new WsHost({ safetyHistory, + ownerSafetyReviews, turnReverts: reverts, workerLock, computeTools: computeHost, @@ -1020,7 +1027,6 @@ export async function createApp(options: CreateAppOptions = {}): Promise { const accountKey = accountKeys(c.get("principal")); return c.json(accountKey ? { vpn: true, accountKey } : { vpn: true }); @@ -1164,6 +1170,7 @@ export async function createApp(options: CreateAppOptions = {}): Promisehost.isPrincipalValid(principal))); + app.route("/api", createOwnerSafetyReviewRoutes(ownerSafetyReviews,auth.trustProxy)); app.route("/api", createPolicyProposalRoutes(host)); app.route("/api", createAgentPolicyRoutes(host, () => activity.runtime.snapshot().workerHost?.limits ?? null)); app.route("/api", createDraftRoutes(drafts)); diff --git a/packages/ui-server/src/governance/owner-safety-reviews.ts b/packages/ui-server/src/governance/owner-safety-reviews.ts new file mode 100644 index 0000000000..e69c4d213d --- /dev/null +++ b/packages/ui-server/src/governance/owner-safety-reviews.ts @@ -0,0 +1,57 @@ +/** Browser-only authority around the host's existing immutable verdict store. */ +import { Database } from "bun:sqlite"; +import { SAFETY_READ_CAPABILITIES, type SafetyCapabilities, type SafetyReviewBody, type SafetyReviewResponse } from "@schlessera/brain-ui-sdk/protocol"; +import { safetyProjectionSchema, safetyReviewResponseSchema } from "@schlessera/brain-ui-sdk/schemas"; +import { isUsablePrincipal, resolvePrincipal, type Principal } from "../db/principals.js"; +import type { AuthMode } from "../middleware/auth.js"; +import type { GovernanceWrites } from "./event-writes.js"; +import { safetyReviewTarget, type SafetyReviewAuthority, type SafetyReviewer } from "./safety-reviews.js"; + +export class OwnerSafetyUnavailable extends Error { + constructor(readonly code: "unauthorized" | "unavailable" | "capacity") { super(code); } +} +function epoch(p: Principal, brainKey: string): SafetyReviewAuthority { + return { id:p.id, kind:p.kind, authMethod:p.authMethod, credentialId:p.credentialId, createdAt:p.createdAt, expiresAt:p.expiresAt, brainKey }; +} + +export class OwnerSafetyReviews { + private readonly pending = new Map(); + constructor(private readonly db: Database, private readonly writes: GovernanceWrites, private readonly mode: AuthMode, private readonly brainKey: string) {} + + authorized(principal: Principal): boolean { + if (this.mode !== "password" || principal.kind !== "owner" || !["password","passkey"].includes(principal.authMethod)) return false; + const current = resolvePrincipal(this.db, principal.id); + return !!current && JSON.stringify(epoch(current,this.brainKey)) === JSON.stringify(epoch(principal,this.brainKey)) && isUsablePrincipal(current, Date.now()); + } + capabilities(principal: Principal): SafetyCapabilities { + const review = this.authorized(principal); + return { ...SAFETY_READ_CAPABILITIES, review, readOnlyReason:review ? null : "owner_required", + limits:{ ...SAFETY_READ_CAPABILITIES.limits, reviewBodyBytes:16384, reviewLifetimeMs:900000, receiptLifetimeMs:86400000 } }; + } + private current(principal: Principal, body: SafetyReviewBody) { + if (!this.authorized(principal)) throw new OwnerSafetyUnavailable("unauthorized"); + if (safetyReviewTarget(this.db,body,principal.id)) throw new OwnerSafetyUnavailable("unavailable"); + return this.writes.safety(null, body.session.sessionId); + } + delivery(principal: Principal, body: SafetyReviewBody) { + return safetyProjectionSchema.parse(Database.prototype.transaction.call(this.db, ()=>this.current(principal,body)).deferred()); + } + async review(principal: Principal, body: SafetyReviewBody, requestId: string | null): Promise { + this.delivery(principal, body); + const count = this.pending.get(principal.id) ?? 0; + if (count >= 32 || [...this.pending.values()].reduce((a,b)=>a+b,0) >= 256) throw new OwnerSafetyUnavailable("capacity"); + this.pending.set(principal.id, count + 1); + try { + const actor: SafetyReviewer = { principalId:principal.id, channel:"owner_history", authority:epoch(principal,this.brainKey) }; + // The worker checks this epoch against its live principal row inside the + // acquired transaction, before even a terminal receipt can be replayed. + const receipt = requestId === null ? await this.writes.safetyPrepareReview(body, actor) + : await this.writes.safetyCommitReview(requestId, body, actor); + const currentProjection = this.delivery(principal,body); + return safetyReviewResponseSchema.parse({version:1,receipt,currentProjection}); + } finally { + const left = this.pending.get(principal.id)! - 1; + if (left) this.pending.set(principal.id,left); else this.pending.delete(principal.id); + } + } +} diff --git a/packages/ui-server/src/governance/safety-reviews.ts b/packages/ui-server/src/governance/safety-reviews.ts index 8494639532..7086e9ecee 100644 --- a/packages/ui-server/src/governance/safety-reviews.ts +++ b/packages/ui-server/src/governance/safety-reviews.ts @@ -1,18 +1,22 @@ -/** Host-only verdict persistence. The owner-authenticated transport is a later - * layer: nothing here mounts a route, infers a human, or advertises review. */ +/** Host-only verdict persistence. The browser service stamps live authority; + * this module mounts no route and never infers a human from a caller body. */ import type { Database } from "bun:sqlite"; import { z } from "zod"; +import { safetyReviewBodySchema as bodySchema } from "@schlessera/brain-ui-sdk/schemas"; +import { isUsablePrincipal, resolvePrincipal, type Principal } from "../db/principals.js"; import { assertLive, ChatRetiredError } from "../ws/chat-lifecycle.js"; -import { advance as advanceSafetyRevision, safetyProjection, SafetyUnavailable, type SafetyProjection } from "./safety-store.js"; +import { advance as advanceSafetyRevision, safetyProjection, safetyScopeTurns, SafetyUnavailable, type SafetyProjection } from "./safety-store.js"; const id = z.string().regex(/^[A-Za-z0-9_-]{1,128}$/); -const revision = z.string().regex(/^(0|[1-9][0-9]{0,19})$/).refine(v => BigInt(v) <= 18446744073709551615n); -const session = z.object({ sessionId: id, historyOwnerId: id, historyGeneration: revision }).strict(); -const bodySchema = z.object({ version: z.literal(1), session, occurrenceId: id, - expectedEvidenceRevision: revision, verdict: z.literal("safe") }).strict(); export type SafetyReviewBody = z.infer; /** Stamped by the host after authority checks, never read from a browser body. */ -export interface SafetyReviewer { principalId: string; channel: "owner_history" | "owner_settings" } +export type SafetyReviewAuthority = Pick & { brainKey: string }; +export interface SafetyReviewer { + principalId: string; channel: "owner_history" | "owner_settings"; + /** Only the password-mode browser service supplies this host-owned epoch. + * Legacy host-only storage callers do not establish human authority. */ + authority?: SafetyReviewAuthority; +} export interface SafetyReviewReceipt { version: 1; requestId: string | null; operationId: string | null; session: SafetyReviewBody["session"]; occurrenceId: string; @@ -34,10 +38,18 @@ function clock(now: () => number): number { function reviewer(actor: SafetyReviewer): void { if (!id.safeParse(actor.principalId).success || !["owner_history", "owner_settings"].includes(actor.channel)) throw new SafetyUnavailable("Invalid host reviewer"); } -function fingerprint(body: SafetyReviewBody): string { +function fingerprint(body: SafetyReviewBody, actor: SafetyReviewer): string { // Schema parsing pins object/key order; semantically identical JSON retries // do not depend on the caller's property insertion order. - return new Bun.CryptoHasher("sha256").update(JSON.stringify(body)).digest("hex"); + return new Bun.CryptoHasher("sha256").update(JSON.stringify(actor.authority ? { body, authority: actor.authority } : body)).digest("hex"); +} +function authorized(db: Database, actor: SafetyReviewer, at: number): boolean { + if (!actor.authority) return true; + const current = resolvePrincipal(db, actor.principalId), epoch = actor.authority; + return /^[A-Za-z0-9_-]{22}$/.test(epoch.brainKey) && !!current && current.id === epoch.id && current.kind === "owner" && epoch.kind === "owner" + && ["password", "passkey"].includes(current.authMethod) && current.authMethod === epoch.authMethod + && current.createdAt === epoch.createdAt && current.expiresAt === epoch.expiresAt + && current.credentialId === epoch.credentialId && isUsablePrincipal(current, at); } function receipt(body: SafetyReviewBody, requestId: string | null, operationId: string | null, reason: string | null, projection: SafetyProjection | null, committed = false): SafetyReviewReceipt { @@ -46,23 +58,27 @@ function receipt(body: SafetyReviewBody, requestId: string | null, operationId: verdict: committed ? "committed" : "unresolved", projection, reason }; } /** Unknown/foreign identity never creates a session or reveals its projection. */ -function target(db: Database, body: SafetyReviewBody, actor: SafetyReviewer): "retired" | "unavailable" | null { +export function safetyReviewTarget(db: Database, body: SafetyReviewBody, principalId: string): "retired" | "unavailable" | null { const s = db.query(`SELECT principal_id FROM safety_sessions WHERE session_id=? AND history_owner_id=? AND generation=?`) .get(body.session.sessionId, body.session.historyOwnerId, body.session.historyGeneration) as { principal_id: string | null } | null; - if (!s || s.principal_id !== actor.principalId) return "unavailable"; - try { assertLive(db, [["session", body.session.sessionId], ["dialogue_owner", body.session.historyOwnerId]]); } + if (!s || s.principal_id !== principalId) return "unavailable"; + const canonical = (db.query("SELECT owner_id FROM dialogue_aliases WHERE id=?").get(body.session.historyOwnerId) as {owner_id:string}|null)?.owner_id ?? body.session.historyOwnerId; + try { assertLive(db, [["session", body.session.sessionId], ["dialogue_owner", body.session.historyOwnerId], ["dialogue_owner",canonical]]); } catch (error) { if (error instanceof ChatRetiredError) return "retired"; throw error; } - const owner = db.query("SELECT generation,principal_id FROM dialogue_owners WHERE id=?").get(body.session.historyOwnerId) as { generation: number; principal_id: string } | null; - if (owner && (String(owner.generation) !== body.session.historyGeneration || owner.principal_id !== actor.principalId)) return "unavailable"; + const owner = db.query("SELECT generation,principal_id FROM dialogue_owners WHERE id=?").get(canonical) as { generation: number; principal_id: string } | null; + if (owner && (String(owner.generation) !== body.session.historyGeneration || owner.principal_id !== principalId)) return "unavailable"; return null; } -function eligible(db: Database, body: SafetyReviewBody): string | null { - const r = db.query(`SELECT r.state,COALESCE((SELECT x.state FROM safety_records x +function eligible(db: Database, body: SafetyReviewBody, actor: SafetyReviewer): string | null { + const r = db.query(`SELECT c.turn_id,c.principal_id,c.generation,r.state,COALESCE((SELECT x.state FROM safety_records x WHERE x.occurrence_id=r.id AND x.kind='exposure' ORDER BY length(x.sequence) DESC,x.sequence DESC LIMIT 1),r.state) final_state FROM safety_records r JOIN safety_collections c ON c.id=r.collection_id - WHERE r.id=? AND r.kind='occurrence' AND c.session_id=? AND c.history_owner_id=? AND c.generation=?`) - .get(body.occurrenceId, body.session.sessionId, body.session.historyOwnerId, body.session.historyGeneration) as { final_state: string } | null; - if (!r) return "unavailable"; + WHERE r.id=? AND r.kind='occurrence'`) + .get(body.occurrenceId) as { turn_id: string; principal_id: string | null; generation: string; final_state: string } | null; + // The aggregate also includes adopted provisional collections. Use its + // canonical membership; a direct session_id filter strands those events. + if (!r || r.principal_id !== actor.principalId || r.generation !== body.session.historyGeneration || !safetyScopeTurns(db, null, body.session.sessionId).has(r.turn_id) + || db.query("SELECT 1 FROM safety_retired_turns WHERE turn_id=?").get(r.turn_id)) return "unavailable"; if (db.query("SELECT 1 FROM safety_decisions WHERE occurrence_id=?").get(body.occurrenceId)) return "already_resolved"; return r.final_state === "finalized" ? null : "not_finalized"; } @@ -78,7 +94,8 @@ export function prepareSafetyReview(db: Database, value: SafetyReviewBody, actor // The writer queue and BEGIN IMMEDIATE may both wait. Time belongs to // this acquired transaction, never to submission on the app connection. const observedAt = clock(now); - const reason = target(db, body, actor); + if (!authorized(db, actor, observedAt)) return receipt(body, null, null, "unauthorized", null); + const reason = safetyReviewTarget(db, body, actor.principalId); if (reason) return receipt(body, null, null, reason, null); prune(db, observedAt); const totals = db.query(`SELECT COUNT(*) n,COALESCE(SUM(reserved_bytes),0) bytes, @@ -89,14 +106,15 @@ export function prepareSafetyReview(db: Database, value: SafetyReviewBody, actor return receipt(body, null, null, "capacity", null); const requestId = crypto.randomUUID(), operationId = crypto.randomUUID(); const projection = safetyProjection(db, null, body.session.sessionId); - const problem = eligible(db, body) ?? (projection.evidenceRevision !== body.expectedEvidenceRevision ? "stale_revision" : null); + const problem = eligible(db, body, actor) ?? (projection.evidenceRevision !== body.expectedEvidenceRevision ? "stale_revision" : null); const at = clock(now); + if (!authorized(db, actor, at)) return receipt(body, null, null, "unauthorized", null); const result = receipt(body, requestId, operationId, problem, problem ? null : projection); const json = JSON.stringify(result); if (Buffer.byteLength(json) > RECEIPT_BYTES) throw new SafetyUnavailable("Safety review receipt capacity"); db.query("INSERT INTO safety_review_requests VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?)").run(requestId, operationId, body.session.sessionId, body.session.historyOwnerId, body.session.historyGeneration, body.occurrenceId, - actor.principalId, actor.channel, fingerprint(body), at, at + REQUEST_MS, problem ? at : null, json, RECEIPT_BYTES); + actor.principalId, actor.channel, fingerprint(body, actor), at, at + REQUEST_MS, problem ? at : null, json, RECEIPT_BYTES); return result; }).immediate(); } @@ -104,20 +122,21 @@ export function commitSafetyReview(db: Database, requestId: string, value: Safet locallyPending: boolean, locallyFailed: boolean = false, now: () => number = Date.now): SafetyReviewReceipt { const body = bodySchema.parse(value); id.parse(requestId); reviewer(actor); return db.transaction(() => { + if (actor.authority && !authorized(db, actor, clock(now))) return receipt(body, requestId, null, "unauthorized", null); // Retirement and exact host ownership precede even successful receipt replay. - const invalid = target(db, body, actor); + const invalid = safetyReviewTarget(db, body, actor.principalId); if (invalid) return receipt(body, requestId, null, invalid, null); const row = db.query("SELECT * FROM safety_review_requests WHERE id=?").get(requestId) as RequestRow | null; if (!row || row.principal_id !== actor.principalId || row.channel !== actor.channel) return receipt(body, requestId, null, "unavailable", null); - if (row.body_hash !== fingerprint(body)) return receipt(body, requestId, row.operation_id, "request_conflict", null); + if (row.body_hash !== fingerprint(body, actor)) return receipt(body, requestId, row.operation_id, "request_conflict", null); if (row.terminal_at !== null) { if (clock(now) >= row.terminal_at + RECEIPT_MS) return receipt(body, requestId, row.operation_id, "request_expired", null); return JSON.parse(row.receipt) as SafetyReviewReceipt; } let projection = safetyProjection(db, null, body.session.sessionId); - const eligibility = eligible(db, body), at = clock(now); - const reason = at < row.issued_at || at >= row.expires_at ? "request_expired" : eligibility + const eligibility = eligible(db, body, actor), at = clock(now); + const reason = !authorized(db, actor, at) ? "unauthorized" : at < row.issued_at || at >= row.expires_at ? "request_expired" : eligibility ?? (locallyFailed || projection.reasons.some(r => r === "recording_failed" || r === "capacity") ? "recording_failed" : null) ?? (locallyPending || projection.pendingCount ? "recording_pending" : null) ?? (projection.evidenceRevision !== body.expectedEvidenceRevision ? "stale_revision" : null); diff --git a/packages/ui-server/src/routes/owner-safety-review.ts b/packages/ui-server/src/routes/owner-safety-review.ts new file mode 100644 index 0000000000..0dc47a337b --- /dev/null +++ b/packages/ui-server/src/routes/owner-safety-review.ts @@ -0,0 +1,59 @@ +import { Hono } from "hono"; +import { safetyReviewBodySchema } from "@schlessera/brain-ui-sdk/schemas"; +import type { AppEnv } from "../app-env.js"; +import { OwnerSafetyReviews, OwnerSafetyUnavailable } from "../governance/owner-safety-reviews.js"; +import { readJsonBody } from "../middleware/body-limit.js"; +import { requireJson } from "../middleware/origin.js"; +import { requireOwner } from "../middleware/require-owner.js"; + +/** These browser mutations require a present exact Origin, even for clients + * claiming same-origin fetch metadata. Unrelated routes keep their policy. */ +export function createOwnerSafetyReviewRoutes(reviews: OwnerSafetyReviews, trustProxy: boolean): Hono { + const app = new Hono(); + const prefix = "/sessions/:id/safety/reviews"; + app.use(`${prefix}/*`, async (c,next)=>{ + c.header("Cache-Control","no-store"); + const principal = c.get("principal"); + if (!principal || !reviews.authorized(principal)) return c.json({code:"unauthorized",reason:"owner_required",retryable:false},403); + const origin = c.req.header("origin"); + try { + const expected = new URL(c.req.url); + const proto = trustProxy ? c.req.header("x-forwarded-proto")?.split(",",1)[0]?.trim() : undefined; + if (proto) expected.protocol = `${proto}:`; + if (!origin || !["http:","https:"].includes(expected.protocol) || origin !== expected.origin) + return c.json({code:"unauthorized",reason:"cross_origin_rejected",retryable:false},403); + } catch { return c.json({code:"unauthorized",reason:"cross_origin_rejected",retryable:false},403); } + return next(); + }, requireOwner(), requireJson()); + for (const action of ["prepare","commit"] as const) { + app.post(action === "prepare" ? `${prefix}/prepare` : `${prefix}/:requestId/commit`, async c=>{ + try { + const value = await readJsonBody(c,16384); + if (value instanceof Response) return c.json({code:"capacity",reason:"request_too_large",retryable:false},413); + const parsed = safetyReviewBodySchema.safeParse(value), requestId = action === "prepare" ? null : c.req.param("requestId"); + if (!parsed.success || parsed.data.session.sessionId !== c.req.param("id") || requestId !== null && !/^[A-Za-z0-9_-]{1,128}$/.test(requestId ?? "") + || c.req.url.length > 8192 || new URL(c.req.url).search) + return c.json({code:"unavailable",reason:"invalid_request",retryable:false},400); + const principal = c.get("principal")!; + const response = await reviews.review(principal,parsed.data,requestId!); + // No await separates this live identity/aggregate read from delivery. + response.currentProjection = reviews.delivery(principal,parsed.data); + if (Buffer.byteLength(JSON.stringify(response)) > 262144) throw new OwnerSafetyUnavailable("capacity"); + const reason = response.receipt.reason; + if (!reason) return c.json(response); + const refusals = { + unauthorized:["unauthorized",403], unavailable:["unavailable",404], retired:["unavailable",404], + capacity:["capacity",503], recording_failed:["recording_failed",503], recording_pending:["resync_required",409], + stale_revision:["stale_revision",409], not_finalized:["not_finalized",409], request_conflict:["request_conflict",409], request_expired:["request_expired",409], + } as const; + const [code,status] = refusals[reason as keyof typeof refusals] ?? ["unavailable",409]; + return c.json({...response,code,reason,retryable:false},status); + } catch (error) { + if (error instanceof SyntaxError) return c.json({code:"unavailable",reason:"invalid_request",retryable:false},400); + const code = error instanceof OwnerSafetyUnavailable ? error.code : "unavailable"; + return c.json({code,reason:code,retryable:false},code === "unauthorized" ? 403 : code === "capacity" ? 503 : 404); + } + }); + } + return app; +} diff --git a/packages/ui-server/src/ws/connection.ts b/packages/ui-server/src/ws/connection.ts index 32c8c0f4b8..06b7a33ad8 100644 --- a/packages/ui-server/src/ws/connection.ts +++ b/packages/ui-server/src/ws/connection.ts @@ -88,7 +88,7 @@ export function createWsHandlers(host: WsHost, principal: Principal) { type: "server_hello", protocolRev: PROTOCOL_REV, principalKey: answerQueueKey(principal.id), - ...(host.safetyHistory ? {safetyCapabilities: SAFETY_READ_CAPABILITIES} : {}), + ...(host.safetyHistory ? {safetyCapabilities: host.ownerSafetyReviews?.capabilities(principal) ?? SAFETY_READ_CAPABILITIES} : {}), capabilities: { ...(host.safetyHistory ? {sessionSafetyHistory:true} : {}), multiSession: true, diff --git a/packages/ui-server/src/ws/host.ts b/packages/ui-server/src/ws/host.ts index fb90ec7dfd..7e7a98f0ad 100644 --- a/packages/ui-server/src/ws/host.ts +++ b/packages/ui-server/src/ws/host.ts @@ -74,6 +74,8 @@ export interface WsHostOptions { safetyTrust?: import("../governance/effective-safety.js").LiveTrustRevision; /** @internal Concrete read-only host evidence reader. */ safetyHistory?: import("../governance/safety-history.js").SafetyHistory; + /** @internal Live password-mode owner review capability; no model tool. */ + ownerSafetyReviews?: import("../governance/owner-safety-reviews.js").OwnerSafetyReviews; /** @internal Concrete user history service mounted by this host, not agent authority. */ turnReverts?: import("../brain/turn-revert.js").TurnReverts; /** @internal The brain/git lock the host shares, when the app built a service that needs it first. */ @@ -359,11 +361,14 @@ export class WsHost { readonly dialogue: DialogueJournal; /** @internal Concrete read-only host evidence reader. */ readonly safetyHistory?: import("../governance/safety-history.js").SafetyHistory; + /** @internal Browser-only individual verdict service. */ + readonly ownerSafetyReviews?: import("../governance/owner-safety-reviews.js").OwnerSafetyReviews; private readonly historyReads = new Set<{ sessionId: string; changed: boolean; resultTurnId?: string }>(); constructor(options: WsHostOptions) { this.safetyTrust = options.safetyTrust; this.safetyHistory = options.safetyHistory; + this.ownerSafetyReviews = options.ownerSafetyReviews; this.turnReverts = options.turnReverts; this.workerLock = options.workerLock ?? createKeyedLock(); this.journal = options.journal; diff --git a/packages/ui-server/tests/fixtures/owner-review-races.ts b/packages/ui-server/tests/fixtures/owner-review-races.ts new file mode 100644 index 0000000000..97c176050d --- /dev/null +++ b/packages/ui-server/tests/fixtures/owner-review-races.ts @@ -0,0 +1,9 @@ +import type { Database } from "bun:sqlite"; +import { retireChat, type RetireChatInput } from "../../src/ws/chat-lifecycle"; +export const url = import.meta.url; +export function setup(db: Database) { + return { + expire(id: string, at: number) { db.query("UPDATE principals SET expires_at=? WHERE id=?").run(at, id); }, + retire(input: RetireChatInput) { return retireChat(db,input); }, + }; +} diff --git a/packages/ui-server/tests/helpers/http-mount-lifetimes.ts b/packages/ui-server/tests/helpers/http-mount-lifetimes.ts index 7f9d5b606a..83d8e004f2 100644 --- a/packages/ui-server/tests/helpers/http-mount-lifetimes.ts +++ b/packages/ui-server/tests/helpers/http-mount-lifetimes.ts @@ -91,6 +91,8 @@ export const mountLifetimes: Record{const current=resolvePrincipal(db,p.id);return !!current&&isUsablePrincipal(current,Date.now());}; let clock=Date.now(),wait:Promise|undefined,entered:(()=>void)|undefined,starts=0; const settled=async()=>{await writer.idle();entered?.();await wait;}; const history=new SafetyHistory(db,valid,settled,()=>clock); const backend=makeFakeBackend({id:"claude",startTurn:async()=>{starts++;throw new Error("Read invoked mutation");}}); - const host=new WsHost({registry:createStaticBackendRegistry([backend]),catalog:createSessionCatalog(()=>db),safetyHistory:history,isPrincipalValid:valid}); + const host=new WsHost({registry:createStaticBackendRegistry([backend]),catalog:createSessionCatalog(()=>db),safetyHistory:history,ownerSafetyReviews:reviews,isPrincipalValid:valid}); const bindingId=crypto.randomUUID(); await writes.safetyBegin({turnId:"voyage",bindingId,sessionId:null,principalId:principal.id,backendId:"claude",at:0});await writes.safetyReady("voyage","claude",1); const bind=async()=>{db.query("INSERT INTO sessions(id,created_at,last_active_at,backend_id) VALUES('ithaca',0,0,'claude')").run(); db.query("INSERT INTO chat_session_owners VALUES('ithaca',?,0)").run(principal.id);safetyCatalogCreated(db,"ithaca",principal.id,"voyage");await writes.bind("voyage","ithaca");}; if(bound)await bind(); const secret="odysseus-safety-history-loopback-secret"; - const auth={host:"127.0.0.1",mode:"password",passwordHash:"unused",cookieSecret:secret,trustProxy:false,trustProxyHops:1,proxyAuthHeader:"x-user"} as AuthRuntime; + const auth={host:"127.0.0.1",mode,passwordHash:"unused",cookieSecret:secret,trustProxy:mode==="proxy"||mode==="tailscale",trustProxyHops:1,proxyAuthHeader:"x-user"} as AuthRuntime; const app=new Hono(); - app.get("/ws",async(c,next)=>{const p=await isWsAuthorized(c,"password",auth,db);if(!p)return c.json({error:"unauthorized"},401);c.set("principal",p);return next();},createWsUpgrade(host)); - app.use("/api/*",authGuard("password",auth,db));app.route("/api",createSessionSafetyRoutes(history,valid)); + app.get("/ws",async(c,next)=>{const p=await isWsAuthorized(c,mode,auth,db);if(!p)return c.json({error:"unauthorized"},401);c.set("principal",p);return next();},createWsUpgrade(host)); + app.use("/api/*",authGuard(mode,auth,db));app.route("/api",createSessionSafetyRoutes(history,valid)); + if(reviews)app.route("/api",createOwnerSafetyReviewRoutes(reviews,false)); const server=Bun.serve({hostname:"127.0.0.1",port:0,fetch:app.fetch,websocket}); const cookieFor=async(p:Principal)=>(await generateSignedCookie("brain_ui_session",p.id,secret)).split(";")[0]!; const cookie=await cookieFor(principal),sockets:WebSocket[]=[]; @@ -54,10 +62,10 @@ export async function safetyHistoryFixture(bound=true){ const until=(predicate:(m:ServerMessage)=>boolean)=>new Promise((resolve,reject)=>{ const check=()=>{const index=frames.findIndex(predicate);if(index<0)return;const frame=frames.splice(index,1)[0]!;clearTimeout(timer);listeners.delete(check);resolve(frame);}; const timer=setTimeout(()=>{listeners.delete(check);reject(new Error("Safety frame deadline"));},3000);listeners.add(check);check();}); - await until(m=>m.type==="server_hello");ws.send(JSON.stringify({type:"client_hello",protocolRev:5,capabilities:{sessionSafetyHistory:true}})); - return {ws,frames,until,send:(v:unknown)=>ws.send(JSON.stringify(v))}; + const hello=await until(m=>m.type==="server_hello");ws.send(JSON.stringify({type:"client_hello",protocolRev:5,capabilities:{sessionSafetyHistory:true}})); + return {ws,frames,until,hello,send:(v:unknown)=>ws.send(JSON.stringify(v))}; }; - return {root,path,url:`ws://127.0.0.1:${server.port}/ws`,cookie,db,writer,writes,principal,history,host,bindingId,add,bind,get,connect,cookieFor,starts:()=>starts, + return {root,path,url:`ws://127.0.0.1:${server.port}/ws`,cookie,db,writer,writes,principal,history,reviews,brainKey,auth,host,bindingId,add,bind,get,connect,cookieFor,starts:()=>starts, advance(ms:number){clock+=ms;}, hold(){let release!:()=>void;wait=new Promise(r=>{release=r;});const arrived=new Promise(r=>{entered=r;});return {arrived,release(){wait=undefined;entered=undefined;release();}};}, async close(){for(const s of sockets)s.close();server.stop(true);await host.close();await writer.close();db.close();rmSync(root,{recursive:true,force:true});}, diff --git a/packages/ui-server/tests/http-inventory.test.ts b/packages/ui-server/tests/http-inventory.test.ts index fcf5e513d3..d8e610644d 100644 --- a/packages/ui-server/tests/http-inventory.test.ts +++ b/packages/ui-server/tests/http-inventory.test.ts @@ -20,7 +20,7 @@ test("real app method/path inventory equals the complete classified HTTP specifi expect(proseCounts).toEqual([declared.length, declared.length]); } const middleware = [...new Set(t.routes.filter((r) => r.method === "ALL").map((r) => r.path))].sort(); - expect(middleware).toEqual(["/*", "/api/*", "/api/apify*", "/api/auth/passkey/*", "/api/auth/principals/*", "/api/brain/briefing", "/api/brain/list", "/api/brain/search", "/api/brain/stats", "/api/brain/stats/history", "/api/graph/*", "/api/internal/inbox/poke", "/api/sessions/:sessionId/turns/:turnId/revert*", "/api/storage*", "/api/storage/maintenance*", "/api/storage/removals*"]); + expect(middleware).toEqual(["/*", "/api/*", "/api/apify*", "/api/auth/passkey/*", "/api/auth/principals/*", "/api/brain/briefing", "/api/brain/list", "/api/brain/search", "/api/brain/stats", "/api/brain/stats/history", "/api/graph/*", "/api/internal/inbox/poke", "/api/sessions/:id/safety/reviews/*", "/api/sessions/:sessionId/turns/:turnId/revert*", "/api/storage*", "/api/storage/maintenance*", "/api/storage/removals*"]); expect(t.routes.filter((r) => r.method === "ALL" && r.path === "/*")).toHaveLength(staticRoot ? 3 : 2); expect(t.routes.some((r) => r.method === "HEAD" || r.method === "OPTIONS")).toBe(false); } finally { await t.close(); } diff --git a/packages/ui-server/tests/http-supported-mounts.test.ts b/packages/ui-server/tests/http-supported-mounts.test.ts index 90ccdfaa1b..3e98554673 100644 --- a/packages/ui-server/tests/http-supported-mounts.test.ts +++ b/packages/ui-server/tests/http-supported-mounts.test.ts @@ -16,6 +16,12 @@ import { documentedRoutes, httpCoverageMatrix } from "./helpers/http-spec"; const SECRET = "http-contract-fixture-secret-0123456789"; const json = (method: string, body: unknown): RequestInit => ({ method, headers: { "content-type": "application/json" }, body: JSON.stringify(body) }); type Check = { path?: string; init?: RequestInit; status?: number; body?: object; verify?: (response: Response, t: HttpContractApp) => Promise }; +const safetyReviewBody = { version: 1, session: { sessionId: "fixture-session", historyOwnerId: "missing-history", historyGeneration: "1" }, occurrenceId: "missing-occurrence", expectedEvidenceRevision: "0", verdict: "safe" }; +const unavailableSafetyReview: NonNullable = async (response, t) => { + expect(response.headers.get("cache-control")).toBe("no-store"); + expect(t.app.db.query("SELECT COUNT(*) n FROM safety_review_requests").get()).toEqual({ n: 0 }); + expect(t.app.db.query("SELECT COUNT(*) n FROM safety_decisions").get()).toEqual({ n: 0 }); +}; // Each supported operation reaches its real handler with a live owner cookie. // More detailed existing behavior checks are linked by the coverage matrix; @@ -111,6 +117,10 @@ const checks: Record = { "GET /api/journal/configuration-coverage": { path: "/api/journal/configuration-coverage", status: 200, body: { state: "unknown" } }, // Imported history: the session exists, and the host proves nothing about it. "GET /api/sessions/:id/safety": {path:"/api/sessions/fixture-session/safety",status:404,body:{version:1,reason:"unavailable"},verify:async r=>{expect(r.headers.get("cache-control")).toBe("no-store");}}, + "POST /api/sessions/:id/safety/reviews/prepare": { path: "/api/sessions/fixture-session/safety/reviews/prepare", init: json("POST", safetyReviewBody), status: 404, + body: { code: "unavailable", reason: "unavailable", retryable: false }, verify: unavailableSafetyReview }, + "POST /api/sessions/:id/safety/reviews/:requestId/commit": { path: "/api/sessions/fixture-session/safety/reviews/missing-request/commit", init: json("POST", safetyReviewBody), status: 404, + body: { code: "unavailable", reason: "unavailable", retryable: false }, verify: unavailableSafetyReview }, "GET /api/sessions/:id/attachment-reads": { path: "/api/sessions/fixture-session/attachment-reads", body: { sessionId: "fixture-session", reads: [] }, verify: async (r) => { expect(r.headers.get("cache-control")).toBe("no-store"); } }, "GET /api/sessions/:id/recovery": { path: "/api/sessions/fixture-session/recovery", body: { sessionId: "fixture-session", revision: 0, latest: { requestId: null, turnId: null, state: "unknown", outcome: null }, pending: [] }, verify: async (r) => { expect(r.headers.get("cache-control")).toBe("no-store"); } }, "GET /api/push/public-key": { verify: async (r) => { const b = await r.json(); expect(b.publicKey.length).toBeGreaterThan(0); expect(Object.keys(b)).toEqual(["publicKey"]); } }, diff --git a/packages/ui-server/tests/owner-safety-review.test.ts b/packages/ui-server/tests/owner-safety-review.test.ts new file mode 100644 index 0000000000..f6dfa874ff --- /dev/null +++ b/packages/ui-server/tests/owner-safety-review.test.ts @@ -0,0 +1,401 @@ +import { expect, test } from "bun:test"; +import { safetyHistoryFixture } from "./helpers/safety-history-fixture"; +import type { SafetyPage } from "@schlessera/brain-ui-sdk/protocol"; +import { createPrincipal, revokePrincipal } from "../src/db/principals"; +import * as account from "../src/db/account-writes"; +import * as held from "./fixtures/held-publication-writer"; +import * as races from "./fixtures/owner-review-races"; +import { occurrence } from "../src/governance/occurrence"; +import { openDialogue, bindDialogue } from "../src/ws/dialogue-storage"; +import { retireChat } from "../src/ws/chat-lifecycle"; +import { OwnerSafetyReviews } from "../src/governance/owner-safety-reviews"; +import * as reviewClock from "./fixtures/safety-review-clock"; +import * as slowWriter from "./fixtures/write-worker-probe"; +import type { SafetyReviewReceipt } from "../src/governance/safety-reviews"; +import { mkdirSync } from "node:fs"; +import { join } from "node:path"; +import { Hono } from "hono"; +import type { AppEnv } from "../src/app-env"; +import { authGuard } from "../src/middleware/auth"; +import { createAccountPartitionKeys } from "../src/middleware/account-partition"; +import { createOwnerSafetyReviewRoutes } from "../src/routes/owner-safety-review"; + +type Fixture = Awaited>; +const origin = (f: Fixture) => new URL(f.url.replace("ws:","http:")).origin; +function post(f: Fixture, suffix: string, body: unknown, overrides: Record = {}) { + const headers = new Headers({cookie:f.cookie,"content-type":"application/json",origin:origin(f)}); + for (const [key,value] of Object.entries(overrides)) { if (value === null) headers.delete(key); else headers.set(key,value); } + return fetch(`${origin(f)}/api/sessions/ithaca/safety/reviews${suffix}`,{method:"POST",headers,body:JSON.stringify(body)}); +} +function bodyFor(f: Fixture, id: string) { + const state = f.writes.safety(null,"ithaca"); + return {version:1 as const,session:state.session!,occurrenceId:id,expectedEvidenceRevision:state.evidenceRevision,verdict:"safe" as const}; +} +async function prepared(f: Fixture, id: string) { + const body = bodyFor(f,id), response = await post(f,"/prepare",body); + expect(response.status,"OWNER_REVIEW_PREPARE_TARGET_IS_ELIGIBLE").toBe(200); + return {body,handle:(await response.json()).receipt.requestId as string}; +} +async function hold(f: Fixture) { + const channel = f.writer.channel(held,undefined); await channel.ready; + expect(await channel.call("level")).toBe(2); + const entered = new Int32Array(new SharedArrayBuffer(4)), release = new Int32Array(new SharedArrayBuffer(4)); + const pending = channel.call("hold",entered,release), wait = Atomics.waitAsync(entered,0,0,5000); + if (wait.async) await wait.value; + expect(Atomics.load(entered,0)).toBe(1); + return {pending,release(){Atomics.store(release,0,1);Atomics.notify(release,0);}}; +} +function count(f: Fixture) { return (f.db.query("SELECT COUNT(*) n FROM safety_decisions").get() as {n:number}).n; } + +test("a signed owner reviews only A and exact replay preserves its fact after later B/C", async () => { + const f = await safetyHistoryFixture(true, true); + const post = (suffix: string, body: unknown) => fetch(f.url.replace("ws:", "http:").replace("/ws", `/api/sessions/ithaca/safety/reviews${suffix}`), { + method: "POST", headers: { cookie: f.cookie, "content-type": "application/json", origin: f.url.replace("ws:", "http:").replace("/ws", "") }, body: JSON.stringify(body), + }); + try { + const a = await f.add("A"); + const page = await (await f.get()).json() as SafetyPage; + const body = { version: 1, session: page.identity, occurrenceId: a.id, expectedEvidenceRevision: page.projection.evidenceRevision, verdict: "safe" }; + const prepared = await post("/prepare", body); + expect(prepared.status, "OWNER_REVIEW_PREPARE_REACHES_REAL_HTTP").toBe(200); + const handle = (await prepared.json()).receipt.requestId; + const committed = await post(`/${handle}/commit`, body); + expect(committed.status).toBe(200); + const first = await committed.json(); + expect(first.receipt.verdict).toBe("committed"); + expect(first.currentProjection.restriction).toBe("normal"); + await f.add("B"); await f.add("C"); + const retry = await (await post(`/${handle}/commit`, body)).json(); + expect(retry.receipt, "OWNER_REVIEW_REPLAY_IS_THE_ORIGINAL_DURABLE_FACT").toEqual(first.receipt); + expect(retry.currentProjection.unresolvedCount, "OWNER_REVIEW_A_NEVER_RESOLVES_LATER_B_C").toBe(2); + expect(retry.currentProjection.restriction).toBe("restricted"); + expect(f.db.query("SELECT COUNT(*) n FROM safety_decisions").get()).toEqual({ n: 1 }); + } finally { await f.close(); } +}); + +test("owner mutation requires a present matching Origin and bounded exact JSON", async () => { + const f = await safetyHistoryFixture(true,true); + try { + const body = bodyFor(f,(await f.add("A")).id); + const rejectedHeaders: Record[] = [ + {origin:null}, {origin:"null"}, {origin:"https://troy.invalid"}, + {origin:"https://troy.invalid","sec-fetch-site":"same-origin"}, {"content-type":"text/plain"}, + ]; + for (const headers of rejectedHeaders) expect((await post(f,"/prepare",body,headers)).status,"OWNER_REVIEW_ORIGIN_AND_JSON_REQUIRED").toBe(headers["content-type"] ? 415 : 403); + for (const extra of [{principalId:f.principal.id},{channel:"owner_history"},{channel:"card"},{voice:true},{rule:{}},{throughSequence:"99"},{occurrenceIds:[body.occurrenceId]}]) { + expect((await post(f,"/prepare",{...body,...extra})).status,"OWNER_REVIEW_REJECTS_CALLER_AUTHORITY_AND_BULK_CLEAR").toBe(400); + } + expect((await post(f,"/prepare",{...body,session:{...body.session,sessionId:"other"}})).status).toBe(400); + expect((await post(f,"/prepare",{...body,padding:"x".repeat(16385)})).status).toBe(413); + expect((await post(f,"/prepare",body,{cookie:null})).status).toBe(401); + expect(count(f)).toBe(0); + expect(f.db.query("SELECT COUNT(*) n FROM safety_review_requests").get()).toEqual({n:0}); + } finally { await f.close(); } +}); + +test("signed delegated and foreign-owner cookies cannot mutate another history", async () => { + const f = await safetyHistoryFixture(true,true); + try { + const body = bodyFor(f,(await f.add("A")).id); + const agent = createPrincipal(f.db,{authMethod:"delegated",createdBy:f.principal.id,label:"Telemachus",ttlSeconds:3600}); + const foreign = createPrincipal(f.db,{authMethod:"password",label:"Penelope",ttlSeconds:3600}); + expect((await post(f,"/prepare",body,{cookie:await f.cookieFor(agent)})).status,"OWNER_REVIEW_DELEGATION_IS_NOT_HUMAN_AUTHORITY").toBe(403); + const denied = await post(f,"/prepare",body,{cookie:await f.cookieFor(foreign)}); + expect(denied.status).toBe(404); + expect(await denied.json()).toEqual({code:"unavailable",reason:"unavailable",retryable:false}); + const {handle} = await prepared(f,body.occurrenceId); + revokePrincipal(f.db,f.principal.id,Date.now()); + expect((await post(f,`/${handle}/commit`,body)).status,"OWNER_REVIEW_REVOKED_COOKIE_CANNOT_COMMIT").toBe(401); + expect(count(f)).toBe(0); + } finally { await f.close(); } +}); + +for (const mode of ["none","proxy","tailscale"] as const) test(`${mode} remains read only through the real auth middleware`, async () => { + const f = await safetyHistoryFixture(true,true,mode); + try { + const body = bodyFor(f,(await f.add("A")).id); + const response = await post(f,"/prepare",body,{"x-user":"Odysseus","x-forwarded-for":"100.64.0.1"}); + expect(response.status,"OWNER_REVIEW_AMBIENT_MODES_NEVER_MUTATE").toBe(403); + expect(count(f)).toBe(0); + expect(f.reviews!.capabilities(f.principal)).toMatchObject({review:false,readOnlyReason:"owner_required"}); + } finally { await f.close(); } +}); + +test("real WS advertises live owner capability, delivers verdict deltas and rejects forged mutation frames", async () => { + const f = await safetyHistoryFixture(true,true); + try { + const a = await f.add("A"), socket = await f.connect(); + expect(socket.hello).toMatchObject({type:"server_hello",safetyCapabilities:{review:true,readOnlyReason:null,originRules:false}}); + const agent = createPrincipal(f.db,{authMethod:"delegated",createdBy:f.principal.id,label:"Telemachus",ttlSeconds:3600}); + expect((await f.connect(await f.cookieFor(agent))).hello).toMatchObject({safetyCapabilities:{review:false,readOnlyReason:"owner_required"}}); + socket.send({type:"safety_commit",channel:"owner_history",principalId:f.principal.id,occurrenceId:a.id,verdict:"safe"}); + socket.send({type:"ping",probeId:"forged-mutation-barrier"}); await socket.until(m=>m.type==="pong"); + expect(count(f),"OWNER_REVIEW_NO_MODEL_OR_VOICE_FRAME_AUTHORITY").toBe(0); + socket.send({type:"safety_read",version:1,requestId:"initial",target:{sessionId:"ithaca"}}); + const frame = await socket.until(m=>m.type==="safety_history"); + if (frame.type !== "safety_history") throw new Error("Missing safety history"); + socket.send({type:"safety_subscribe",version:1,requestId:"live",identity:frame.page.identity,afterRevision:frame.page.highWater,snapshotId:frame.page.snapshotId}); + socket.send({type:"ping",probeId:"subscribed"}); await socket.until(m=>m.type==="pong"); + const {body,handle} = await prepared(f,a.id); + expect((await post(f,`/${handle}/commit`,body)).status).toBe(200); + f.history.poll(); + const update = await socket.until(m=>m.type==="safety_update"); + expect(update).toMatchObject({update:{projection:{unresolvedCount:0,restriction:"normal"},records:[{kind:"safe_decision",occurrenceId:a.id}]}}); + expect(f.starts()).toBe(0); + } finally { await f.close(); } +}); + +test("open and unknown exposure refuse until a proved finalization, regardless of client verdict", async () => { + const f = await safetyHistoryFixture(true,true); + try { + let openId = ""; + for (const state of ["open","interrupted_unknown"] as const) { + const o = occurrence(f.bindingId,"tool_web_input",state,state); + if(state === "open")openId=o.id; + await f.writes.record({kind:"taint",turnId:"voyage",sessionId:"ithaca",actor:"interactive",model:null,profile:"governed",payload:{source:"web_fetch",tool:"WebFetch",detail:null,occurrence:o}}); + const response = await post(f,"/prepare",bodyFor(f,o.id)); + expect(response.status,"OWNER_REVIEW_NONFINAL_INPUT_REFUSES_PREPARATION").toBe(409); + expect((await response.json()).receipt).toMatchObject({reason:"not_finalized",projection:null,verdict:"unresolved"}); + } + expect(count(f)).toBe(0); + expect(f.writes.safety(null,"ithaca").unresolvedCount).toBe(2); + await f.writes.record({kind:"taint_exposure",turnId:"voyage",sessionId:"ithaca",actor:"interactive",model:null,profile:"governed",payload:{occurrenceId:openId,state:"finalized"}}); + const p = await prepared(f,openId); + expect((await post(f,`/${p.handle}/commit`,p.body)).status).toBe(200); + expect(f.writes.safety(null,"ithaca").unresolvedCount).toBe(1); + } finally { await f.close(); } +}); + +test("SQLite retains finalized, principal and generation fences beneath the public transport", async () => { + const f = await safetyHistoryFixture(true,true); + try { + const open = occurrence(f.bindingId,"tool_web_input","open","open"); + await f.writes.record({kind:"taint",turnId:"voyage",sessionId:"ithaca",actor:"interactive",model:null,profile:"governed",payload:{source:"web_fetch",tool:"WebFetch",detail:null,occurrence:open}}); + const a = await f.add("A"), session = f.writes.safety(null,"ithaca").session!; + const insert = f.db.query("INSERT INTO safety_decisions VALUES(?,?,?,?,?,?,?,?,?,?,?)"); + const attempt = (id:string,principal:string,generation:string)=>()=>insert.run(crypto.randomUUID(),id,"ithaca",session.historyOwnerId,generation,"1000000",principal,crypto.randomUUID(),Date.now(),"safe","owner_history"); + expect(attempt(open.id,f.principal.id,session.historyGeneration),"OWNER_REVIEW_SQL_FINALIZED_BACKSTOP").toThrow("safety decision identity or exposure mismatch"); + expect(attempt(a.id,"foreign-owner",session.historyGeneration),"OWNER_REVIEW_SQL_PRINCIPAL_BACKSTOP").toThrow("safety decision identity or exposure mismatch"); + expect(attempt(a.id,f.principal.id,"2"),"OWNER_REVIEW_SQL_GENERATION_BACKSTOP").toThrow("safety decision identity or exposure mismatch"); + expect(count(f)).toBe(0); + } finally { await f.close(); } +}); + +test("request capacity refuses fresh preparation while prepaid retained verdicts remain usable", async () => { + const f = await safetyHistoryFixture(true,true); + try { + const a = await f.add("A"), handles: Awaited>[] = []; + for(let i=0;i<32;i++)handles.push(await prepared(f,a.id)); + const refused = await post(f,"/prepare",handles[0]!.body); + expect(refused.status).toBe(503); + expect(await refused.json()).toMatchObject({code:"capacity",reason:"capacity",retryable:false,receipt:{stage:"refused",projection:null}}); + const p = handles[0]!; + expect((await post(f,`/${p.handle}/commit`,p.body)).status).toBe(200); + expect(count(f)).toBe(1); + expect(f.db.query("SELECT COUNT(*) n FROM safety_review_requests").get()).toEqual({n:32}); + } finally { await f.close(); } +}); + +test("new B/C between prepare and commit force a fresh review of A and leave B/C unresolved", async () => { + const f = await safetyHistoryFixture(true,true); + try { + const a = await f.add("A"), stale = await prepared(f,a.id); + await f.add("B"); await f.add("C"); + const refused = await (await post(f,`/${stale.handle}/commit`,stale.body)).json(); + expect(refused.receipt,"OWNER_REVIEW_STALE_PREPARE_CANNOT_RESOLVE").toMatchObject({reason:"stale_revision",projection:null,verdict:"unresolved"}); + expect(count(f)).toBe(0); + const fresh = await prepared(f,a.id); + const result = await (await post(f,`/${fresh.handle}/commit`,fresh.body)).json(); + expect(result.receipt.verdict).toBe("committed"); + expect(result.currentProjection).toMatchObject({restriction:"restricted",unresolvedCount:2}); + } finally { await f.close(); } +}); + +test("unknown handles, conflicting retries and changed authority never mint another decision", async () => { + const f = await safetyHistoryFixture(true,true); + try { + const a = await f.add("A"), b = await f.add("B"), p = await prepared(f,a.id); + expect((await (await post(f,"/unknown/commit",p.body)).json()).receipt.reason).toBe("unavailable"); + expect((await (await post(f,`/${p.handle}/commit`,{...p.body,occurrenceId:b.id})).json()).receipt.reason).toBe("request_conflict"); + f.db.query("UPDATE principals SET expires_at=expires_at+1000 WHERE id=?").run(f.principal.id); + expect((await (await post(f,`/${p.handle}/commit`,p.body)).json()).receipt.reason,"OWNER_REVIEW_PREPARED_HANDLE_BINDS_AUTH_EPOCH").toBe("request_conflict"); + expect(count(f)).toBe(0); + } finally { await f.close(); } +}); + +for (const action of ["prepare","commit"] as const) test(`revocation in the FULL queue fences ${action} at its transaction`, async () => { + const f = await safetyHistoryFixture(true,true); + let barrier: Awaited> | undefined; + try { + const a = await f.add("A"), p = action === "commit" ? await prepared(f,a.id) : {body:bodyFor(f,a.id),handle:""}; + await f.get(); await f.writer.idle(); + const admin = f.writer.channel(account,undefined); await admin.ready; + barrier = await hold(f); + const revocation = admin.call("revokePrincipal",f.principal.id,Date.now()); + const submitted = Promise.withResolvers(); + const name = action === "commit" ? "safetyCommitReview" : "safetyPrepareReview"; + const original = f.writes[name].bind(f.writes); + // Observe submission after real cookie/body admission, not a mocked writer. + Object.assign(f.writes,{[name]:(...args: Parameters)=>{const result=Reflect.apply(original,f.writes,args);submitted.resolve();return result;}}); + const response = post(f,action === "commit" ? `/${p.handle}/commit` : "/prepare",p.body); + await submitted.promise; + expect(count(f)).toBe(0); barrier.release(); await barrier.pending; await revocation; + expect((await response).status,"OWNER_REVIEW_QUEUED_AUTHORITY_RECHECK").toBe(403); + expect(count(f),"OWNER_REVIEW_REVOKED_QUEUED_REQUEST_HAS_NO_EFFECT").toBe(0); + } finally { barrier?.release(); await f.close(); } +}); + +for (const change of ["expiry","retirement"] as const) test(`${change} while the real commit is queued leaves no verdict`, async () => { + const f = await safetyHistoryFixture(true,true); + let barrier: Awaited> | undefined; + try { + const p = await prepared(f,(await f.add("A")).id), control = f.writer.channel(races,undefined); await control.ready; + barrier = await hold(f); + const changed = change === "expiry" ? control.call("expire",f.principal.id,Date.now()-1) : control.call("retire",{ + operationId:"retire-voyage",principalId:f.principal.id,target:{sessionId:"ithaca"},expected:{backendId:"claude",generation:1},removableBackends:["claude"],at:Date.now(), + }); + const submitted = Promise.withResolvers(), original = f.writes.safetyCommitReview.bind(f.writes); + f.writes.safetyCommitReview = (...args)=>{const result=original(...args);submitted.resolve();return result;}; + const response = post(f,`/${p.handle}/commit`,p.body); await submitted.promise; + expect(count(f)).toBe(0); barrier.release(); await barrier.pending; await changed; + expect((await response).status,"OWNER_REVIEW_QUEUED_EXPIRY_AND_RETIREMENT_FENCE").toBe(change === "expiry" ? 403 : 404); + expect(count(f)).toBe(0); + } finally { barrier?.release(); await f.close(); } +}); + +test("a failed FULL verdict transaction never reports success or loosens admission", async () => { + const f = await safetyHistoryFixture(true,true); + try { + const p = await prepared(f,(await f.add("A")).id); + f.db.exec("CREATE TRIGGER refuse_verdict BEFORE INSERT ON safety_decisions BEGIN SELECT RAISE(ABORT,'Odysseus refuses the verdict'); END"); + expect((await post(f,`/${p.handle}/commit`,p.body)).status).toBe(404); + expect(count(f)).toBe(0); + expect(f.writes.safety(null,"ithaca")).toMatchObject({restriction:"restricted",unresolvedCount:1}); + expect(f.db.query("SELECT terminal_at FROM safety_review_requests WHERE id=?").get(p.handle)).toEqual({terminal_at:null}); + } finally { await f.close(); } +}); + +for (const change of ["revocation","retirement","recording-loss","new-input"] as const) test(`final HTTP delivery fences ${change} after the service wait`, async () => { + const f = await safetyHistoryFixture(true,true); + try { + const p = await prepared(f,(await f.add("A")).id), original = f.reviews!.review.bind(f.reviews); + f.reviews!.review = async (...args)=>{ + const response = await original(...args); + if (change === "revocation") revokePrincipal(f.db,f.principal.id,Date.now()); + if (change === "retirement") retireChat(f.db,{operationId:"delivery-retire",principalId:f.principal.id,target:{sessionId:"ithaca"},expected:{backendId:"claude",generation:1},removableBackends:["claude"],at:Date.now()}); + if (change === "recording-loss") await f.writes.safetyFail("voyage"); + if (change === "new-input") await f.add("B"); + return response; + }; + const response = await post(f,`/${p.handle}/commit`,p.body); + expect(response.status,"OWNER_REVIEW_FINAL_HTTP_AUTHORITY_FENCE").toBe(change === "revocation" ? 403 : change === "retirement" ? 404 : 200); + if (response.status === 200) { + const result = await response.json(); + expect(result.receipt.projection.restriction).toBe("normal"); + expect(result.currentProjection.restriction,"OWNER_REVIEW_FINAL_AGGREGATE_NEVER_REPLAYS_OLD_NORMAL").toBe("restricted"); + } + expect(count(f)).toBe(1); + } finally { await f.close(); } +}); + +test("canonical history can review an adopted provisional occurrence before its collection rebind", async () => { + const f = await safetyHistoryFixture(true,true); + try { + openDialogue(f.db,{conversationId:"target-voice",principalId:f.principal.id,epoch:1,providerId:"voice",sessionId:"ithaca"}); + const owner = openDialogue(f.db,{conversationId:"scout-voice",principalId:f.principal.id,epoch:1,providerId:"voice"}); + await f.writes.safetyBegin({turnId:"scout-turn",bindingId:"scout-binding",sessionId:null,principalId:f.principal.id,backendId:"claude",historyOwnerId:owner.id,at:0}); + await f.writes.safetyReady("scout-turn","claude",1); + const c = occurrence("scout-binding","tool_web_input","C","finalized"); + await f.writes.record({kind:"taint",turnId:"scout-turn",sessionId:null,actor:"interactive",model:null,profile:"governed",payload:{source:"web_fetch",tool:"WebFetch",detail:null,occurrence:c}}); + bindDialogue(f.db,"scout-voice",f.principal.id,"ithaca"); + expect(f.writes.safety(null,"ithaca").unresolvedCount).toBe(1); + const p = await prepared(f,c.id), response = await post(f,`/${p.handle}/commit`,p.body); + expect(response.status,"OWNER_REVIEW_CANONICAL_MEMBERSHIP_INCLUDES_ADOPTED_OCCURRENCE").toBe(200); + expect(count(f)).toBe(1); + expect(f.db.query("SELECT occurrence_id,session_id FROM safety_decisions").get()).toEqual({occurrence_id:c.id,session_id:"ithaca"}); + } finally { await f.close(); } +}); + +test("a password-mode passkey owner can review and a fresh service replays durable receipts", async () => { + const f = await safetyHistoryFixture(true,true); + try { + f.db.query("INSERT INTO passkey_credentials(id,public_key,counter,rp_id,backed_up,label,created_at) VALUES('odysseus-bow',?,0,'ithaca.invalid',0,'Odysseus',?)").run(new Uint8Array([1,2,3]),Date.now()); + f.db.query("UPDATE principals SET auth_method='passkey',credential_id='odysseus-bow' WHERE id=?").run(f.principal.id); + const a = await f.add("A"), p = await prepared(f,a.id); + const first = await (await post(f,`/${p.handle}/commit`,p.body)).json(); + expect(first.receipt.verdict,"OWNER_REVIEW_PASSKEY_IS_HUMAN_OWNER_AUTHORITY").toBe("committed"); + const current = (await import("../src/db/principals")).resolvePrincipal(f.db,f.principal.id)!; + const restarted = new OwnerSafetyReviews(f.db,f.writes,"password",f.brainKey); + const replay = await restarted.review(current,p.body,p.handle); + expect(replay.receipt).toEqual(first.receipt); + expect(count(f)).toBe(1); + } finally { await f.close(); } +}); + +test("a prepared browser handle expiring behind a FULL transaction cannot commit", async () => { + const f = await safetyHistoryFixture(true,true); + try { + const a = await f.add("A"), body = bodyFor(f,a.id), clock = f.writer.channel(reviewClock,undefined), slow = f.writer.channel(slowWriter,{table:"review_expiry_hold"}); + await clock.ready; await slow.ready; + const {id,kind,authMethod,credentialId,createdAt,expiresAt} = f.principal; + const actor = {principalId:id,channel:"owner_history" as const,authority:{id,kind,authMethod,credentialId,createdAt,expiresAt,brainKey:f.brainKey}}; + const issuedAt = Date.now()-899000; + const handle = (await clock.call("safetyPrepareReview",body,actor,issuedAt)).requestId!; + await f.get(); await f.writer.idle(); + const entered = new Int32Array(new SharedArrayBuffer(4)); + const holding = slow.call("slow","Odysseus",1400,entered), wait = Atomics.waitAsync(entered,0,0,5000); + if(wait.async)await wait.value; + expect(Atomics.load(entered,0)).toBe(1); + const submitted = Promise.withResolvers(), original = f.writes.safetyCommitReview.bind(f.writes); + f.writes.safetyCommitReview = (...args)=>{const result=original(...args);submitted.resolve(Date.now());return result;}; + const response = post(f,`/${handle}/commit`,body); + expect(await submitted.promise).toBeLessThan(issuedAt+900000); + expect(count(f)).toBe(0); await holding; + expect((await response).status).toBe(409); + const stored = f.db.query("SELECT receipt FROM safety_review_requests WHERE id=?").get(handle) as {receipt:string}; + expect(JSON.parse(stored.receipt).reason,"OWNER_REVIEW_EXPIRY_USES_ACQUIRED_TRANSACTION_CLOCK").toBe("request_expired"); + expect(count(f)).toBe(0); + } finally { await f.close(); } +}); + +test("a second authenticated brain root sharing the database cannot commit or replay the first root's handle", async () => { + const f = await safetyHistoryFixture(true,true); + let second: ReturnType | undefined; + try { + const p = await prepared(f,(await f.add("A")).id), otherRoot = join(f.root,"troy"); mkdirSync(otherRoot); + const otherKey = createAccountPartitionKeys(f.db,otherRoot,"password")(f.principal)!; + expect(otherKey).not.toBe(f.brainKey); + const app = new Hono();app.use("/api/*",authGuard("password",f.auth,f.db)); + app.route("/api",createOwnerSafetyReviewRoutes(new OwnerSafetyReviews(f.db,f.writes,"password",otherKey),false)); + second = Bun.serve({hostname:"127.0.0.1",port:0,fetch:app.fetch}); + const retry = ()=>fetch(`${second!.url.origin}/api/sessions/ithaca/safety/reviews/${p.handle}/commit`,{ + method:"POST",headers:{cookie:f.cookie,origin:second!.url.origin,"content-type":"application/json"},body:JSON.stringify(p.body), + }); + const denied = await retry(); + expect(denied.status,"OWNER_REVIEW_HANDLE_BINDS_THE_SERVED_BRAIN_ROOT").toBe(409); + expect((await denied.json()).receipt.reason).toBe("request_conflict");expect(count(f)).toBe(0); + expect((await post(f,`/${p.handle}/commit`,p.body)).status).toBe(200); + const replay = await retry(); + expect(replay.status).toBe(409);expect((await replay.json()).receipt.projection).toBeNull();expect(count(f)).toBe(1); + } finally {second?.stop(true);await f.close();} +}); + +test("delayed verdicts remain restrictive and resolving known evidence never repairs a coverage gap", async () => { + const f = await safetyHistoryFixture(true,true); + let barrier: Awaited> | undefined; + try { + f.db.query("UPDATE safety_collections SET gap='unobserved_history' WHERE turn_id='voyage'").run(); + const p = await prepared(f,(await f.add("A")).id); + barrier = await hold(f); + const submitted = Promise.withResolvers(), original = f.writes.safetyCommitReview.bind(f.writes); + f.writes.safetyCommitReview = (...args)=>{const result=original(...args);submitted.resolve();return result;}; + const response = post(f,`/${p.handle}/commit`,p.body); await submitted.promise; + expect(count(f)).toBe(0); + expect(f.writes.taint(null,"ithaca"),"OWNER_REVIEW_PENDING_VERDICT_NEVER_LOOSENS_ADMISSION").not.toBeNull(); + barrier.release(); await barrier.pending; + const committed = await (await response).json(); + expect(committed.receipt.verdict).toBe("committed"); + expect(committed.currentProjection).toMatchObject({unresolvedCount:0,restriction:"restricted",coverage:{state:"incomplete"}}); + expect(f.writes.taint(null,"ithaca")).not.toBeNull(); + } finally { barrier?.release(); await f.close(); } +});