diff --git a/.changeset/3952-safety-account-partition.md b/.changeset/3952-safety-account-partition.md
new file mode 100644
index 0000000000..227ed97293
--- /dev/null
+++ b/.changeset/3952-safety-account-partition.md
@@ -0,0 +1,5 @@
+---
+"@schlessera/brain-ui-server": minor
+---
+
+The owner can continue a chat from another device (#3952). Every sign-in mints its own owner principal, and a chat's safety history was bound to the one that started it, so a turn from any other login was refused as a safety principal mismatch. The history now belongs to the account: any owner login continues the chat, its turns join the same safety history and taint, and it can read and review that history. An agent, a proxy user or any other account is still refused. Stored rows are not rewritten.
diff --git a/docs/decisions/session-safety-reviews.md b/docs/decisions/session-safety-reviews.md
index 135f577f5e..e7f3f366fc 100644
--- a/docs/decisions/session-safety-reviews.md
+++ b/docs/decisions/session-safety-reviews.md
@@ -156,6 +156,25 @@ quiescence precondition. Only a capacity check classifies a failure as
`capacity`. No gap ever clears, and nothing here lets an unrecorded input
become clean.
+### A chat's safety history belongs to its account (#3952)
+
+Ruled by the maintainer on 2026-11-10. The owner mints a principal at every
+sign-in, so a chat's safety history binds to the account, not to the login
+that started it: another device's owner login continues the chat, reads its
+history and reviews its occurrences, and its turns join the same history and
+taint. `sameAccount` (`packages/ui-server/src/middleware/account-partition.ts`)
+decides it. A principal id always matches itself. Two different ids match
+only when both resolve to principals whose `accountScope` is the same
+partition in every auth mode, which today means two owner logins. An agent,
+ambient or system principal therefore matches only itself, and a missing or
+unresolvable principal (a pruned row, say) matches no other id. The decision
+trigger (`087_safety_account_partition.sql`) applies the same rule.
+
+Rows keep the principal that wrote them; nothing is rewritten. What belongs to
+one login stays exact: a turn's own collection, its catalog creation, read
+snapshots and cursors, review handles and their receipts, per-principal
+limits, and the principal a verdict names.
+
## Human authority and policy publication
Initially **only a live password-mode human owner** may commit a verdict or
diff --git a/docs/http-api.md b/docs/http-api.md
index c11c70b291..9eaf093af1 100644
--- a/docs/http-api.md
+++ b/docs/http-api.md
@@ -156,7 +156,7 @@ client code has a gap. Source owners are listed after the table.
| GET | `/api/journal/configuration-coverage` | S | Read the brain's current untraced configuration-input set | Latest complete inventoried turn only; explicit `unknown`, never an empty list. |
| GET | `/api/agent-policy` | I | Read shared admission policy and reported enforcing limits | Read-only Devices & agents facts; no editor or duplicate policy cache. |
| GET | `/api/policy-proposals/:turnId/:requestId` | I | Read one principal-owned policy request receipt | Same-request reconciliation only; never writes or reactivates approval. |
-| GET | `/api/sessions/:id/safety` | S | Read bounded revisioned host safety evidence | Exact authenticated history owner; immutable records, snapshot aggregate/high-water, scoped cursor, explicit coverage/unavailable, no mutation (#3604). |
+| GET | `/api/sessions/:id/safety` | S | Read bounded revisioned host safety evidence | Authenticated principal of the history owner's account (#3952); immutable records, snapshot aggregate/high-water, scoped cursor, explicit coverage/unavailable, no mutation (#3604). |
| POST | `/api/sessions/:id/safety/reviews/prepare` | S | Prepare review of one finalized safety occurrence | Live password-mode human owner, exact Origin and bounded JSON; host-issued body/brain/principal/generation-bound handle (#3603). |
| POST | `/api/sessions/:id/safety/reviews/:requestId/commit` | S | Commit or read back one individual safe verdict | Live owner rechecked on the acquired FULL transaction and final response; immutable receipt plus fresh aggregate, no bulk clear or standing rule (#3603). |
| GET | `/api/sessions/:id/attachment-reads` | S | Read a session's recorded attachment reads, outcome and scope only | Sent-row read states (#3589, #3155); preserve the session and message-reference filters, no text and no provider path. |
@@ -2057,9 +2057,14 @@ and `detailPruned`. Responses are `Cache-Control: no-store` and at most 262144
UTF-8 bytes. No request invokes a verdict, policy writer, backend turn or
provider transcript write.
-The exact live principal must own the retained history. There is no equivalence
-between separate owner logins, delegated credentials or ambient identities.
-The existing native-history and dialogue APIs keep their visibility rules.
+The live principal must belong to the retained history's account (#3952). A
+principal id always matches itself. Two different ids match only when both
+resolve to the same account partition in every auth mode, which today means
+two owner logins; a delegated, ambient or system principal matches only
+itself, and a missing or unresolvable principal matches no other id. A cursor
+stays with the one login that read it: another login's cursor is refused as
+expired (409). The existing native-history and dialogue APIs keep their
+visibility rules.
Unknown/unowned legacy safety collections return explicit unavailable; known
legacy collection gaps never imply normal. Revoked/expired callers receive
401, malformed queries 400, expired/generation-changed or membership-gap cursors 409, capacity
diff --git a/docs/integration-contract/http.md b/docs/integration-contract/http.md
index bf9d6ca408..497c34ad5f 100644
--- a/docs/integration-contract/http.md
+++ b/docs/integration-contract/http.md
@@ -330,6 +330,21 @@ retryable: true }`, changing nothing, while any safety producer or collection
is open. Each recovery is recorded with its trigger, actor, time and the cause
it cleared. Affected chats keep their gaps.
+
+
+### A chat's safety history belongs to its account (additive, #3952)
+
+A turn, a safety read (`GET /api/sessions/:id/safety`, WS `safety_read`) and
+an owner review of a chat now accept any principal of the chat's account, not
+only the principal that started it. A principal id always matches itself.
+Two different ids match only when both resolve to the same account partition,
+which today means two owner logins, so an agent, ambient or system principal
+matches only itself; a missing or unresolvable principal matches no other id.
+Another account's principal is refused exactly as before. Read
+snapshots, review handles, receipts and the verdict's `principalId` stay bound
+to the exact principal. Nothing previously accepted is refused, and stored
+rows are not rewritten ([decision](../decisions/session-safety-reviews.md#a-chats-safety-history-belongs-to-its-account-3952)).
+
### Root server warning (additive, #1638)
@@ -472,6 +487,8 @@ Queued continuations retain that snapshot without recopying source evidence or
importing later source activity. Actual catalog creator, principal,
history owner, aliases and generation govern binding. Retired session/owner/turn
identities refuse late callbacks even after private detail is removed.
+The principal binds as its account
+([additive, #3952](#account-bound-safety-history-additive-3952)).
Effective admission is restricted for any unresolved occurrence, incomplete or
unknown coverage, pending recording, failure or exhausted capacity. Only a
diff --git a/packages/ui-server/migrations/087_safety_account_partition.sql b/packages/ui-server/migrations/087_safety_account_partition.sql
new file mode 100644
index 0000000000..a507460a56
--- /dev/null
+++ b/packages/ui-server/migrations/087_safety_account_partition.sql
@@ -0,0 +1,42 @@
+-- A chat's safety history belongs to its account, not to the one login that
+-- started it (#3952). The owner mints a principal at every sign-in, so another
+-- device's owner login may review the chat's occurrences too. The verdict
+-- still names the exact principal that gave it.
+--
+-- Same account, as `sameAccount` in `src/middleware/account-partition.ts`
+-- decides it: a principal id always matches itself, and two different ids
+-- match only when both resolve to owner logins. An agent, ambient or system
+-- principal matches only itself, and a missing or unresolvable principal
+-- matches no other id. Every other boundary of 084 is unchanged, and no
+-- existing row is rewritten.
+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 OR (
+ EXISTS (SELECT 1 FROM principals WHERE id=s.principal_id AND kind='owner')
+ AND EXISTS (SELECT 1 FROM principals WHERE id=NEW.principal_id AND kind='owner')))
+ AND (c.principal_id=NEW.principal_id OR (
+ EXISTS (SELECT 1 FROM principals WHERE id=c.principal_id AND kind='owner')
+ AND EXISTS (SELECT 1 FROM principals WHERE id=NEW.principal_id AND kind='owner')))
+ 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 d WHERE d.id=
+ COALESCE((SELECT owner_id FROM dialogue_aliases WHERE id=s.history_owner_id),s.history_owner_id)
+ AND (CAST(d.generation AS TEXT)!=NEW.generation OR NOT (d.principal_id=NEW.principal_id OR (
+ EXISTS (SELECT 1 FROM principals WHERE id=d.principal_id AND kind='owner')
+ AND EXISTS (SELECT 1 FROM principals WHERE id=NEW.principal_id AND kind='owner')))))
+ 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/governance/safety-history.ts b/packages/ui-server/src/governance/safety-history.ts
index 762a28320b..ffbbf65a90 100644
--- a/packages/ui-server/src/governance/safety-history.ts
+++ b/packages/ui-server/src/governance/safety-history.ts
@@ -3,6 +3,7 @@ import { Database } from "bun:sqlite";
import type { SafetyIdentity, SafetyTarget, SafetyPage, SafetyRecord, SafetyUpdate, SafetyUnavailable as Unavailable } from "@schlessera/brain-ui-sdk/protocol";
import { safetyPageSchema, safetyUpdateSchema } from "@schlessera/brain-ui-sdk/schemas";
import type { Principal } from "../db/principals.js";
+import { sameAccount } from "../middleware/account-partition.js";
import { assertLive } from "../ws/chat-lifecycle.js";
import { safetyProjection } from "./safety-store.js";
import { safetyQueue } from "./safety-queue.js";
@@ -45,18 +46,19 @@ export class SafetyHistory {
if("sessionId" in target){
const s=this.db.query("SELECT session_id,history_owner_id,generation,principal_id FROM safety_sessions WHERE session_id=?").get(target.sessionId) as
{session_id:string;history_owner_id:string;generation:string;principal_id:string|null}|null;
- if(!s||s.principal_id!==principal.id)throw new SafetyReadUnavailable();
+ // Another login of the chat's account reads it; nobody else does (#3952).
+ if(!s||!sameAccount(this.db,s.principal_id,principal.id))throw new SafetyReadUnavailable();
const owner=this.db.query("SELECT principal_id,generation FROM dialogue_owners WHERE id=?").get(s.history_owner_id) as {principal_id:string;generation:number}|null;
- if(owner&&(owner.principal_id!==principal.id||String(owner.generation)!==s.generation))throw new SafetyReadUnavailable("generation_changed");
+ if(owner&&(!sameAccount(this.db,owner.principal_id,principal.id)||String(owner.generation)!==s.generation))throw new SafetyReadUnavailable("generation_changed");
try{assertLive(this.db,[["session",s.session_id],["dialogue_owner",s.history_owner_id]]);}catch{throw new SafetyReadUnavailable();}
return {sessionId:s.session_id,historyOwnerId:s.history_owner_id,historyGeneration:s.generation};
}
const c=this.db.query("SELECT session_id,principal_id,history_owner_id,generation FROM safety_collections WHERE id=? AND turn_id=?").get(target.bindingId,target.turnId) as
{session_id:string|null;principal_id:string|null;history_owner_id:string;generation:string}|null;
- if(!c||c.principal_id!==principal.id||this.db.query("SELECT 1 FROM safety_retired_turns WHERE turn_id=?").get(target.turnId))throw new SafetyReadUnavailable();
+ if(!c||!sameAccount(this.db,c.principal_id,principal.id)||this.db.query("SELECT 1 FROM safety_retired_turns WHERE turn_id=?").get(target.turnId))throw new SafetyReadUnavailable();
if(c.session_id)return this.authorize(principal,{sessionId:c.session_id});
const owner=this.db.query("SELECT generation,principal_id FROM dialogue_owners WHERE id=?").get(c.history_owner_id) as {generation:number;principal_id:string}|null;
- if(owner&&(String(owner.generation)!==c.generation||owner.principal_id!==principal.id))throw new SafetyReadUnavailable("generation_changed");
+ if(owner&&(String(owner.generation)!==c.generation||!sameAccount(this.db,owner.principal_id,principal.id)))throw new SafetyReadUnavailable("generation_changed");
try{assertLive(this.db,[["dialogue_owner",c.history_owner_id]]);}catch{throw new SafetyReadUnavailable();}
return {turnId:target.turnId,bindingId:target.bindingId};
}
diff --git a/packages/ui-server/src/governance/safety-reviews.ts b/packages/ui-server/src/governance/safety-reviews.ts
index 7086e9ecee..2d8f7648f0 100644
--- a/packages/ui-server/src/governance/safety-reviews.ts
+++ b/packages/ui-server/src/governance/safety-reviews.ts
@@ -4,6 +4,7 @@ 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 { sameAccount } from "../middleware/account-partition.js";
import { assertLive, ChatRetiredError } from "../ws/chat-lifecycle.js";
import { advance as advanceSafetyRevision, safetyProjection, safetyScopeTurns, SafetyUnavailable, type SafetyProjection } from "./safety-store.js";
@@ -57,16 +58,17 @@ function receipt(body: SafetyReviewBody, requestId: string | null, operationId:
stage: committed ? "verdict_committed" : reason ? "refused" : "prepared",
verdict: committed ? "committed" : "unresolved", projection, reason };
}
-/** Unknown/foreign identity never creates a session or reveals its projection. */
+/** Unknown/foreign identity never creates a session or reveals its projection.
+ * A chat belongs to its account: any owner login reviews it (#3952). */
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 !== principalId) return "unavailable";
+ if (!s || !sameAccount(db, 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(canonical) as { generation: number; principal_id: string } | null;
- if (owner && (String(owner.generation) !== body.session.historyGeneration || owner.principal_id !== principalId)) return "unavailable";
+ if (owner && (String(owner.generation) !== body.session.historyGeneration || !sameAccount(db, owner.principal_id, principalId))) return "unavailable";
return null;
}
function eligible(db: Database, body: SafetyReviewBody, actor: SafetyReviewer): string | null {
@@ -77,7 +79,7 @@ function eligible(db: Database, body: SafetyReviewBody, actor: SafetyReviewer):
.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)
+ if (!r || !sameAccount(db, 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";
diff --git a/packages/ui-server/src/governance/safety-store.ts b/packages/ui-server/src/governance/safety-store.ts
index 8c5ca6f425..e3d37ca8e9 100644
--- a/packages/ui-server/src/governance/safety-store.ts
+++ b/packages/ui-server/src/governance/safety-store.ts
@@ -4,6 +4,7 @@ import { safetyQueue } from "./safety-queue.js";
import { assertLive,ChatRetiredError } from "../ws/chat-lifecycle.js";
import { occurrence, type Occurrence } from "./occurrence.js";
import type { GovernanceEventRow } from "./events.js";
+import { sameAccount } from "../middleware/account-partition.js";
const SAFETY_DETECTORS = ["tool_web_input", "tool_file_input", "tool_search_output", "external_mcp_input", "attachment_input",
"compute_input", "unproxied_shell_input", "proxy_input", "explicit_untrusted_input"] as const;
@@ -210,12 +211,14 @@ export function beginSafetyCollection(db:Database,input:SafetyCollectionInput):s
if(owner){
const d=one<{id:string;principal_id:string;generation:number}|null>(db,`SELECT id,principal_id,generation FROM dialogue_owners
WHERE id=COALESCE((SELECT id FROM dialogue_owners WHERE session_id=?),(SELECT owner_id FROM dialogue_aliases WHERE id=?),?)`,input.sessionId,owner,owner);
- if(d){if(d.principal_id!==input.principalId)throw new SafetyUnavailable("Safety history ownership mismatch");owner=d.id;generation=actualGeneration(d.generation);
+ // A chat's history belongs to its account: another login of the same
+ // owner continues it, and nobody else does (#3952).
+ if(d){if(!sameAccount(db,d.principal_id,input.principalId))throw new SafetyUnavailable("Safety history ownership mismatch");owner=d.id;generation=actualGeneration(d.generation);
uncollectedOwner=!db.query("SELECT 1 FROM safety_collections WHERE history_owner_id=? AND generation=? LIMIT 1").get(owner,generation);
}
}
assertLive(db,[["dialogue_owner",owner]]);
- if(session?.principal_id&&session.principal_id!==input.principalId)throw new SafetyUnavailable("Safety principal mismatch");
+ if(session?.principal_id&&!sameAccount(db,session.principal_id,input.principalId))throw new SafetyUnavailable("Safety principal mismatch");
const n=one<{n:number}>(db, input.sessionId?"SELECT COUNT(*) n FROM safety_collections WHERE session_id=?":"SELECT COUNT(*) n FROM safety_collections WHERE session_id IS NULL",...(input.sessionId?[input.sessionId]:[]));
if(n.n>=(input.sessionId?SAFETY_LIMITS.epochs:SAFETY_LIMITS.unbound))throw new SafetyCapacityExhausted("Safety coverage capacity exhausted",input.sessionId?"chat":unboundScope(db));
if(input.sessionId===null){
@@ -236,7 +239,7 @@ export function beginSafetyCollection(db:Database,input:SafetyCollectionInput):s
if(input.sessionId)bindSafetyCollection(db,input.turnId,input.sessionId);
if(input.sourceSessionId){
const sourceOwner=one<{principal_id:string|null}|null>(db,"SELECT principal_id FROM safety_sessions WHERE session_id=?",input.sourceSessionId);
- if(sourceOwner?.principal_id&&sourceOwner.principal_id!==input.principalId)throw new SafetyUnavailable("Safety fork history ownership mismatch");
+ if(sourceOwner?.principal_id&&!sameAccount(db,sourceOwner.principal_id,input.principalId))throw new SafetyUnavailable("Safety fork history ownership mismatch");
safetyProjection(db,null,input.sourceSessionId); // Also validates retirement.
db.query("UPDATE safety_collections SET gap=CASE WHEN restricted_begin=1 THEN gap ELSE 'inherited_history_not_reconstructed' END WHERE id=?").run(input.bindingId);
const records=db.query(`SELECT r.* FROM safety_records r JOIN safety_collections c ON c.id=r.collection_id
@@ -262,7 +265,7 @@ export function bindSafetyCollection(db:Database,turnId:string,sessionId:string)
if(c.session_id&&c.session_id!==sessionId)throw new SafetyUnavailable("Safety binding is once-only");
const d=one<{id:string;principal_id:string;generation:number}|null>(db,"SELECT id,principal_id,generation FROM dialogue_owners WHERE session_id=?",sessionId);
const principal=d?.principal_id??s.principal_id??one<{principal_id:string}|null>(db,"SELECT principal_id FROM chat_session_owners WHERE session_id=?",sessionId)?.principal_id??null;
- if(c.principal_id&&principal&&c.principal_id!==principal)throw new SafetyUnavailable("Safety binding owner mismatch");
+ if(c.principal_id&&principal&&!sameAccount(db,principal,c.principal_id))throw new SafetyUnavailable("Safety binding owner mismatch");
if(c.history_owner_id&&d&&c.history_owner_id!==d.id&&c.history_owner_id!==s.history_owner_id){
const alias=one<{owner_id:string}|null>(db,"SELECT owner_id FROM dialogue_aliases WHERE id=?",c.history_owner_id);
if(alias?.owner_id!==d.id)throw new SafetyUnavailable("Contradictory safety history owner");
@@ -272,7 +275,7 @@ export function bindSafetyCollection(db:Database,turnId:string,sessionId:string)
// discovery row's placeholder generation.
const retained=c.history_owner_id?one<{id:string;principal_id:string;generation:number}|null>(db,
"SELECT id,principal_id,generation FROM dialogue_owners WHERE id=COALESCE((SELECT owner_id FROM dialogue_aliases WHERE id=?),?)",c.history_owner_id,c.history_owner_id):null;
- if(retained&&retained.principal_id!==c.principal_id)throw new SafetyUnavailable("Safety retained owner mismatch");
+ if(retained&&!sameAccount(db,retained.principal_id,c.principal_id))throw new SafetyUnavailable("Safety retained owner mismatch");
const owner=d?.id??retained?.id??s.history_owner_id,gen=d?actualGeneration(d.generation):retained?actualGeneration(retained.generation):s.generation;
if(retained&&actualGeneration(retained.generation)!==c.generation)throw new SafetyUnavailable("Safety history generation changed");
assertLive(db,[["session",sessionId],["dialogue_owner",owner]]);
diff --git a/packages/ui-server/src/middleware/account-partition.ts b/packages/ui-server/src/middleware/account-partition.ts
index de97db04a0..c2247255c8 100644
--- a/packages/ui-server/src/middleware/account-partition.ts
+++ b/packages/ui-server/src/middleware/account-partition.ts
@@ -2,7 +2,7 @@ import { createHash, randomBytes } from "node:crypto";
import { realpathSync } from "node:fs";
import { resolve } from "node:path";
import type { Database } from "bun:sqlite";
-import type { Principal } from "../db/principals.js";
+import { resolvePrincipal, type Principal } from "../db/principals.js";
import type { AuthMode } from "./auth.js";
/**
@@ -68,6 +68,31 @@ export function accountScope(principal: Principal, authMode: AuthMode): string |
return authMode === "proxy" ? `proxy\u0000${principal.id}` : "owner";
}
+// A record keeps who made it, not the auth mode it was made under.
+const EVERY_AUTH_MODE: Record = { password: true, tailscale: true, proxy: true, none: true };
+
+/**
+ * Whether `principal` is the same account as the principal a record is bound
+ * to (#3952): a chat's safety history, for one, belongs to the account, so
+ * another device's login continues it. A principal id always matches itself.
+ * Two different ids match only when both resolve to principals that
+ * `accountScope` puts in the same partition in every auth mode, which today
+ * means two owner logins: the one owner mints a principal at every sign-in.
+ * An ambient principal shares the owner's partition only in some modes, and
+ * an agent or system principal holds none, so each matches only itself. A
+ * missing or unresolvable principal is unknown and matches no other id.
+ */
+export function sameAccount(db: Database, bound: string | null | undefined, principal: string | null | undefined): boolean {
+ if (!bound || !principal) return false;
+ if (bound === principal) return true;
+ const a = resolvePrincipal(db, bound), b = resolvePrincipal(db, principal);
+ if (!a || !b) return false;
+ return (Object.keys(EVERY_AUTH_MODE) as AuthMode[]).every(mode => {
+ const scope = accountScope(a, mode);
+ return scope !== null && scope === accountScope(b, mode);
+ });
+}
+
export function deriveAccountPartitionKey(seed: string, root: string, scope: string): string {
return createHash("sha256")
.update("brain-ui:account-partition:v1\u0000")
diff --git a/packages/ui-server/tests/owner-safety-review.test.ts b/packages/ui-server/tests/owner-safety-review.test.ts
index f6dfa874ff..63f317d9ea 100644
--- a/packages/ui-server/tests/owner-safety-review.test.ts
+++ b/packages/ui-server/tests/owner-safety-review.test.ts
@@ -93,16 +93,23 @@ test("owner mutation requires a present matching Origin and bounded exact JSON",
} finally { await f.close(); }
});
-test("signed delegated and foreign-owner cookies cannot mutate another history", async () => {
+test("signed delegated cookies and owner cookies on another account's history cannot mutate it", 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});
+ const otherLogin = createPrincipal(f.db,{authMethod:"password",label:"Odysseus at Ithaca",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});
+ // Every password login is the one owner: another device's login reviews the chat (#3952).
+ expect((await post(f,"/prepare",body,{cookie:await f.cookieFor(otherLogin)})).status,"OWNER_REVIEW_ANOTHER_LOGIN_IS_THE_SAME_ACCOUNT").toBe(200);
+ // A history bound to another account stays unavailable to every owner login.
+ f.db.query("UPDATE safety_sessions SET principal_id=? WHERE session_id='ithaca'").run(agent.id);
+ for (const cookie of [f.cookie, await f.cookieFor(otherLogin)]) {
+ const denied = await post(f,"/prepare",body,{cookie});
+ expect(denied.status,"OWNER_REVIEW_FOREIGN_ACCOUNT_HISTORY").toBe(404);
+ expect(await denied.json()).toEqual({code:"unavailable",reason:"unavailable",retryable:false});
+ }
+ f.db.query("UPDATE safety_sessions SET principal_id=? WHERE session_id='ithaca'").run(f.principal.id);
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);
diff --git a/packages/ui-server/tests/safety-account-partition.test.ts b/packages/ui-server/tests/safety-account-partition.test.ts
new file mode 100644
index 0000000000..fad38c4690
--- /dev/null
+++ b/packages/ui-server/tests/safety-account-partition.test.ts
@@ -0,0 +1,228 @@
+/** A chat's safety history binds to the account, not the exact login (#3952). */
+import { expect, test } from "bun:test";
+import { mkdtempSync, rmSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { createUiDb } from "../src/db/client";
+import { createPrincipal, resolveAmbientPrincipal, resolveSystemPrincipal } from "../src/db/principals";
+import { openSqliteWriter } from "../src/db/write-worker";
+import { createGovernanceWrites } from "../src/governance/event-writes";
+import { createSafetyCollector } from "../src/governance/safety-collector";
+import { SafetyHistory } from "../src/governance/safety-history";
+import { safetyCatalogCreated, safetyRecords } from "../src/governance/safety-store";
+import { safetyReviewTarget, type SafetyReviewBody, type SafetyReviewer } from "../src/governance/safety-reviews";
+import { sameAccount } from "../src/middleware/account-partition";
+import { openDialogue } from "../src/ws/dialogue-storage";
+import { rejection } from "./helpers/expect-rejection";
+
+async function fixture() {
+ const root = mkdtempSync(join(tmpdir(), "odysseus-safety-account-")), path = join(root, "ui.db");
+ const db = createUiDb(path), writer = openSqliteWriter(db), writes = createGovernanceWrites(db, writer);
+ // Every sign-in mints its own owner principal: one on the ship, one at home.
+ const ship = createPrincipal(db, { authMethod: "password", label: "Odysseus on the ship", ttlSeconds: 3600 });
+ const home = createPrincipal(db, { authMethod: "password", label: "Odysseus at Ithaca", ttlSeconds: 3600 });
+ const agent = createPrincipal(db, { authMethod: "delegated", label: "Mentor", createdBy: ship.id, ttlSeconds: 3600 });
+ const penelope = resolveAmbientPrincipal(db, "proxy", "penelope", "Penelope");
+ const telemachus = resolveAmbientPrincipal(db, "proxy", "telemachus", "Telemachus");
+ const system = resolveSystemPrincipal(db, { identity: "harbour-watch", label: "Harbour watch" });
+ const triggers = () => safetyRecords(db, "ithaca").filter(r => r.kind === "occurrence");
+ const collector = (turnId: string, bindingId: string) => createSafetyCollector(db, writes, { turnId, bindingId, sessionId: () => "ithaca",
+ backendId: "claude", signal: new AbortController().signal, shellProxied: () => true, brainPath: root });
+ /** One finalized occurrence in a turn already bound to the chat. */
+ const taint = async (turnId: string, bindingId: string, call: string) => {
+ const c = collector(turnId, bindingId); await c.ready("claude", 1);
+ await c.begin(call, "WebFetch", { url: "https://ithaca.invalid/suitors" });
+ await c.result(call, "WebFetch", "The suitors are in the hall.", true);
+ return triggers().at(-1)!.id;
+ };
+ /** The chat `ithaca`, started on the ship, with one occurrence. */
+ const start = async (principalId = ship.id) => {
+ const bindingId = crypto.randomUUID();
+ await writes.safetyBegin({ turnId: "voyage", bindingId, sessionId: null, principalId, backendId: "claude", at: 0 });
+ 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(principalId);
+ safetyCatalogCreated(db, "ithaca", principalId, "voyage"); await writes.bind("voyage", "ithaca");
+ const first = await taint("voyage", bindingId, "A");
+ await writes.safetyEnd("voyage");
+ return { bindingId, first };
+ };
+ /** A later turn in `ithaca`, by whoever signed in. */
+ const resume = (turnId: string, principalId: string | null, bindingId = crypto.randomUUID()) =>
+ writes.safetyBegin({ turnId, bindingId, sessionId: "ithaca", principalId, backendId: "claude", at: 1 }).then(() => bindingId);
+ const collections = () => db.query("SELECT turn_id,principal_id,session_id,history_owner_id FROM safety_collections WHERE session_id='ithaca' ORDER BY turn_id")
+ .all() as { turn_id: string; principal_id: string | null; session_id: string; history_owner_id: string }[];
+ const session = () => db.query("SELECT principal_id,history_owner_id,generation FROM safety_sessions WHERE session_id='ithaca'").get() as
+ { principal_id: string | null; history_owner_id: string; generation: string };
+ return { root, db, writer, writes, ship, home, agent, penelope, telemachus, system, triggers, taint, start, resume, collections, session,
+ async close() { await writer.close(); db.close(); rmSync(root, { recursive: true, force: true }); } };
+}
+type Fixture = Awaited>;
+/** Which check refused a begin: the write worker's own message, under the retryable refusal. */
+async function refusedBy(promise: Promise): Promise {
+ const error = await rejection(promise) as Error & { cause?: Error };
+ return error.cause?.message ?? error.message;
+}
+/** Every principal that is not the ship's owner account. */
+function foreign(f: Fixture) {
+ return [["agent", f.agent.id], ["proxy-user", f.penelope.id], ["system", f.system.id], ["unknown-login", "pruned-login"], ["no-principal", null]] as const;
+}
+
+test("another owner login continues a chat, and its turn joins the chat's safety history and taint", async () => {
+ const f = await fixture(); try {
+ const { first } = await f.start();
+ expect(f.writes.safety(null, "ithaca").unresolvedCount).toBe(1);
+ const bindingId = await f.resume("homecoming", f.home.id);
+ expect(f.collections().find(c => c.turn_id === "homecoming"), "SAFETY_SECOND_OWNER_JOINS_THE_CHAT")
+ .toEqual({ turn_id: "homecoming", principal_id: f.home.id, session_id: "ithaca", history_owner_id: f.session().history_owner_id });
+ // The earlier taint restricts the turn on the other device too.
+ const turn = f.writes.safety("homecoming", "ithaca");
+ expect(turn.unresolvedCount, "SAFETY_SECOND_OWNER_INHERITS_THE_TAINT").toBe(1);
+ expect(turn.earliestUnresolvedId).toBe(first);
+ expect(turn.restriction).toBe("restricted");
+ const second = await f.taint("homecoming", bindingId, "B");
+ expect(f.triggers().map(r => r.id), "SAFETY_SECOND_OWNER_EXTENDS_THE_SAME_HISTORY").toEqual([first, second]);
+ expect(f.writes.safety(null, "ithaca").unresolvedCount).toBe(2);
+ } finally { await f.close(); }
+});
+
+test("another owner login continues a chat whose history already has a dialogue owner", async () => {
+ const f = await fixture(); try {
+ await f.start();
+ // A voice conversation on the ship gave the chat its dialogue owner.
+ const owner = openDialogue(f.db, { conversationId: "argos-voice", principalId: f.ship.id, epoch: 1, providerId: "voice", sessionId: "ithaca" });
+ expect(owner.id).toBe(f.session().history_owner_id);
+ await f.resume("homecoming", f.home.id);
+ expect(f.collections().find(c => c.turn_id === "homecoming")?.history_owner_id, "SAFETY_SECOND_OWNER_KEEPS_THE_DIALOGUE_OWNER").toBe(owner.id);
+ expect(f.writes.safety("homecoming", "ithaca").unresolvedCount).toBe(1);
+ } finally { await f.close(); }
+});
+
+test("a principal of another account is still refused, whichever record names the chat's owner", async () => {
+ const f = await fixture(); try {
+ await f.start();
+ for (const [name, principalId] of foreign(f))
+ expect(await refusedBy(f.resume(`intruder-${name}`, principalId)), `SAFETY_FOREIGN_PRINCIPAL_REFUSED: ${name}`).toBe("Safety principal mismatch");
+ openDialogue(f.db, { conversationId: "argos-voice", principalId: f.ship.id, epoch: 1, providerId: "voice", sessionId: "ithaca" });
+ for (const [name, principalId] of foreign(f))
+ expect(await refusedBy(f.resume(`listener-${name}`, principalId)), `SAFETY_FOREIGN_DIALOGUE_PRINCIPAL_REFUSED: ${name}`).toBe("Safety history ownership mismatch");
+ // A refused turn never read or extended the chat's history.
+ expect(f.collections().map(c => c.turn_id)).toEqual(["voyage"]);
+ } finally { await f.close(); }
+});
+
+test("an owner login never takes over a chat bound to an agent or to another proxy user", async () => {
+ for (const [name, starter, other] of [["agent", "agent", "ship"], ["proxy user", "penelope", "telemachus"]] as const) {
+ const f = await fixture(); try {
+ await f.start(f[starter].id);
+ expect(await refusedBy(f.resume("takeover", f[other].id)), `SAFETY_ACCOUNT_STAYS_BOUND: ${name}`).toBe("Safety principal mismatch");
+ await f.resume("same-principal", f[starter].id);
+ expect(f.collections().map(c => c.principal_id), `SAFETY_EXACT_PRINCIPAL_CONTINUES: ${name}`).toEqual([f[starter].id, f[starter].id]);
+ } finally { await f.close(); }
+ }
+});
+
+test("a chat's rows keep the principal that wrote them, and an owner login whose row is gone is unknown", async () => {
+ const f = await fixture(); try {
+ await f.start();
+ const before = { session: f.session(), records: safetyRecords(f.db, "ithaca") };
+ await f.resume("homecoming", f.home.id);
+ // No rewrite: the chat stays bound to the ship's principal.
+ expect(f.session(), "SAFETY_CONTINUATION_REWRITES_NO_BINDING").toEqual(before.session);
+ expect(safetyRecords(f.db, "ithaca").slice(0, before.records.length), "SAFETY_CONTINUATION_REWRITES_NO_HISTORY").toEqual(before.records);
+ // The login that started the chat still continues it.
+ await f.resume("return-to-the-ship", f.ship.id);
+ expect(f.collections().map(c => [c.turn_id, c.principal_id])).toEqual([["homecoming", f.home.id], ["return-to-the-ship", f.ship.id], ["voyage", f.ship.id]]);
+ // A pruned principal row leaves only an id nobody can vouch for.
+ f.db.query("DELETE FROM principals WHERE id=?").run(f.ship.id);
+ expect(await refusedBy(f.resume("after-pruning", f.home.id)), "SAFETY_PRUNED_OWNER_IS_UNKNOWN").toBe("Safety principal mismatch");
+ } finally { await f.close(); }
+});
+
+test("another owner login forks a chat; another account's principal cannot", async () => {
+ const f = await fixture(); try {
+ await f.start();
+ const fork = (turnId: string, principalId: string | null) => f.writes.safetyBegin({ turnId, bindingId: crypto.randomUUID(), sessionId: null, principalId,
+ backendId: "claude", sourceSessionId: "ithaca", at: 2 });
+ await fork("telemachy", f.home.id);
+ expect(f.writes.safety("telemachy", null).unresolvedCount, "SAFETY_SECOND_OWNER_FORK_INHERITS_TAINT").toBe(1);
+ for (const [name, principalId] of foreign(f))
+ expect(await refusedBy(fork(`stolen-${name}`, principalId)), `SAFETY_FOREIGN_FORK_REFUSED: ${name}`).toBe("Safety fork history ownership mismatch");
+ } finally { await f.close(); }
+});
+
+test("another owner login reads the chat's safety history; another account's principal cannot", async () => {
+ const f = await fixture(); try {
+ const { bindingId } = await f.start();
+ const history = new SafetyHistory(f.db, () => true, async () => {});
+ const page = await history.read(f.home, { sessionId: "ithaca" });
+ expect(page.identity, "SAFETY_SECOND_OWNER_READS_THE_CHAT").toEqual({ sessionId: "ithaca", historyOwnerId: f.session().history_owner_id, historyGeneration: "1" });
+ expect(page.records.filter(r => r.kind === "occurrence")).toHaveLength(1);
+ expect((await history.read(f.home, { turnId: "voyage", bindingId })).identity, "SAFETY_SECOND_OWNER_READS_A_TURN").toEqual(page.identity);
+ openDialogue(f.db, { conversationId: "argos-voice", principalId: f.ship.id, epoch: 1, providerId: "voice", sessionId: "ithaca" });
+ expect((await history.read(f.home, { sessionId: "ithaca" })).identity, "SAFETY_SECOND_OWNER_READS_PAST_THE_DIALOGUE_OWNER").toEqual(page.identity);
+ for (const principal of [f.agent, f.penelope, f.system]) {
+ expect(await rejection(history.read(principal, { sessionId: "ithaca" })), `SAFETY_FOREIGN_READ_REFUSED: ${principal.label}`).toHaveProperty("reason", "unavailable");
+ expect(await rejection(history.read(principal, { turnId: "voyage", bindingId })), `SAFETY_FOREIGN_TURN_READ_REFUSED: ${principal.label}`).toHaveProperty("reason", "unavailable");
+ }
+ history.close();
+ } finally { await f.close(); }
+});
+
+test("another owner login reviews an occurrence from the first login's turn; another account's principal cannot", async () => {
+ const f = await fixture(); try {
+ const { first } = await f.start();
+ // The ship's voice conversation gave the chat a dialogue owner too.
+ openDialogue(f.db, { conversationId: "argos-voice", principalId: f.ship.id, epoch: 1, providerId: "voice", sessionId: "ithaca" });
+ const body = (): SafetyReviewBody => {
+ const state = f.writes.safety(null, "ithaca");
+ return { version: 1, session: state.session!, occurrenceId: first, expectedEvidenceRevision: state.evidenceRevision, verdict: "safe" };
+ };
+ for (const principal of [f.agent, f.penelope, f.system]) {
+ const actor: SafetyReviewer = { principalId: principal.id, channel: "owner_history" };
+ expect(safetyReviewTarget(f.db, body(), principal.id), `SAFETY_FOREIGN_REVIEW_TARGET_REFUSED: ${principal.label}`).toBe("unavailable");
+ expect((await f.writes.safetyPrepareReview(body(), actor)).reason, `SAFETY_FOREIGN_REVIEW_REFUSED: ${principal.label}`).toBe("unavailable");
+ }
+ const actor: SafetyReviewer = { principalId: f.home.id, channel: "owner_history" };
+ expect(safetyReviewTarget(f.db, body(), f.home.id), "SAFETY_SECOND_OWNER_REVIEW_TARGET").toBeNull();
+ const prepared = await f.writes.safetyPrepareReview(body(), actor);
+ expect(prepared.stage, "SAFETY_SECOND_OWNER_PREPARES_A_REVIEW").toBe("prepared");
+ const committed = await f.writes.safetyCommitReview(prepared.requestId!, body(), actor);
+ expect(committed.stage, "SAFETY_SECOND_OWNER_COMMITS_A_REVIEW").toBe("verdict_committed");
+ expect(f.db.query("SELECT principal_id FROM safety_decisions").all(), "SAFETY_VERDICT_NAMES_ITS_REVIEWER").toEqual([{ principal_id: f.home.id }]);
+ expect(f.writes.safety(null, "ithaca").restriction).toBe("normal");
+ } finally { await f.close(); }
+});
+
+test("the decision trigger refuses another account's verdict on each record that names the chat's owner", async () => {
+ for (const record of ["session", "collection", "dialogue owner"] as const) {
+ const f = await fixture(); try {
+ const { first } = await f.start();
+ if (record === "dialogue owner") openDialogue(f.db, { conversationId: "argos-voice", principalId: f.ship.id, epoch: 1, providerId: "voice", sessionId: "ithaca" });
+ const { history_owner_id: owner } = f.session();
+ // Only the named record still names the ship's login; the others name the agent.
+ if (record !== "session") f.db.query("UPDATE safety_sessions SET principal_id=? WHERE session_id='ithaca'").run(f.agent.id);
+ if (record !== "collection") f.db.query("UPDATE safety_collections SET principal_id=? WHERE turn_id='voyage'").run(f.agent.id);
+ let sequence = 999000;
+ const decide = () => f.db.query("INSERT INTO safety_decisions VALUES(?,?,?,?,?,?,?,?,?,?,?)").run(crypto.randomUUID(), first, "ithaca",
+ owner, "1", String(sequence++), f.agent.id, crypto.randomUUID(), 1, "safe", "owner_history");
+ expect(decide, `SAFETY_DECISION_TRIGGER_CHECKS_THE_${record.toUpperCase()}`).toThrow("safety decision identity or exposure mismatch");
+ // Control: with that record the agent's too, the same verdict is admitted.
+ if (record === "session") f.db.query("UPDATE safety_sessions SET principal_id=? WHERE session_id='ithaca'").run(f.agent.id);
+ if (record === "collection") f.db.query("UPDATE safety_collections SET principal_id=? WHERE turn_id='voyage'").run(f.agent.id);
+ if (record === "dialogue owner") f.db.query("UPDATE dialogue_owners SET principal_id=? WHERE id=?").run(f.agent.id, owner);
+ decide();
+ } finally { await f.close(); }
+ }
+});
+
+test("only the same principal or two owner logins are one account", async () => {
+ const f = await fixture(); try {
+ const pairs: [string | null, string | null, boolean][] = [
+ [f.ship.id, f.ship.id, true], [f.ship.id, f.home.id, true], [f.home.id, f.ship.id, true],
+ [f.agent.id, f.agent.id, true], [f.ship.id, f.agent.id, false], [f.agent.id, f.ship.id, false],
+ [f.penelope.id, f.telemachus.id, false], [f.ship.id, f.penelope.id, false], [f.ship.id, f.system.id, false],
+ [f.ship.id, "pruned-login", false], ["pruned-login", f.ship.id, false], [f.ship.id, null, false], [null, null, false],
+ ];
+ for (const [bound, principal, same] of pairs) expect(sameAccount(f.db, bound, principal), `${bound} / ${principal}`).toBe(same);
+ } finally { await f.close(); }
+});
diff --git a/packages/ui-server/tests/safety-history.test.ts b/packages/ui-server/tests/safety-history.test.ts
index 2026c575bb..9ea71814b4 100644
--- a/packages/ui-server/tests/safety-history.test.ts
+++ b/packages/ui-server/tests/safety-history.test.ts
@@ -65,8 +65,12 @@ test("first-turn provisional binding retains exact occurrence identity without d
test("cursor scope, expiry after wait, principal revocation and retirement fence late authenticated reads",async()=>{
const f=await safetyHistoryFixture();try{
await f.add("A");await f.add("B");const first=await page(await f.get("?limit=1"));
- const foreign=createPrincipal(f.db,{authMethod:"password",label:"Penelope",ttlSeconds:3600}),cookie=await f.cookieFor(foreign);
- expect((await f.get(`?cursor=${first.nextCursor}`,cookie)).status).toBe(404);
+ // Another owner login reads the chat (#3952), but a cursor stays its own login's.
+ const otherLogin=createPrincipal(f.db,{authMethod:"password",label:"Odysseus at Ithaca",ttlSeconds:3600});
+ expect((await f.get(`?cursor=${first.nextCursor}`,await f.cookieFor(otherLogin))).status,"CURSOR_SCOPE_IS_ONE_LOGIN").toBe(409);
+ // Another account's principal sees nothing of the chat.
+ const agent=createPrincipal(f.db,{authMethod:"delegated",createdBy:f.principal.id,label:"Mentor",ttlSeconds:3600});
+ expect((await f.get(`?cursor=${first.nextCursor}`,await f.cookieFor(agent))).status,"CURSOR_SCOPE_FOREIGN_ACCOUNT").toBe(404);
const held=f.hold(),pending=f.get(`?cursor=${first.nextCursor}`);await held.arrived;f.advance(300001);held.release();
expect((await pending).status,"CURSOR_DELIVERY_CLOCK").toBe(409);
const revoked=f.hold(),late=f.get();await revoked.arrived;revokePrincipal(f.db,f.principal.id,Date.now());revoked.release();