@sema-agent/core
Version:
Stateless, task-oriented AI agent core
1,369 lines • 67.3 kB
JavaScript
import { randomBytes } from "node:crypto";
import { types } from "node:util";
import { isNameableToolName } from "@sema-agent/primitives";
import { canonicalize, textContentHashOf } from "./canonical-json.js";
import { PATH_RULE_FACES, escapeForDisclosure, formatRuleText, isRuleBehavior, isRuleLive, parseRuleText } from "./permission-rule-model.js";
import { readRuleOwner } from "./rule-owner.js";
import { callGrantRowFault } from "./session-call-grant.js";
import { PRINCIPAL_NAME_SPELLING } from "./principal-name.js";
import { thrownText } from "./thrown-value.js";
import { validatePath } from "./effective-path-target.js";
export const PERMISSION_RULES_LATER_GRAMMAR_CODE = "permission_rules.later_grammar";
export const PERMISSION_RULES_DAMAGED_BUCKET_CODE = "permission_rules.bucket_damaged";
export const PERMISSION_RULES_UNREADABLE_BUCKET_CODE = "permission_rules.bucket_unreadable";
export function isRuleRevision(rev) {
return typeof rev === "number" && Number.isSafeInteger(rev) && rev >= 0;
}
function outcomeWord(value) {
if (value === undefined)
return "no revision at all";
if (value === null)
return "a null revision";
if (typeof value === "number")
return `the number ${String(value)}, which is not a revision`;
return `a ${typeof value} where a revision belongs`;
}
function isReadableDrop(drop) {
if (drop === null || typeof drop !== "object")
return false;
const dot = drop.dot;
if (dot === null || typeof dot !== "object")
return false;
return typeof dot.actor === "string" && typeof dot.counter === "number" && typeof drop.reason === "string";
}
function readSyncReport(sync) {
if (sync === undefined)
return {};
if (sync === null || typeof sync !== "object")
return { unreadable: `the landing carried a ${sync === null ? "null" : typeof sync} where its sync report belongs` };
for (const member of ["droppedInbound", "quarantined"]) {
const value = sync[member];
if (value === undefined)
continue;
if (!Array.isArray(value))
return { unreadable: `the landing's sync report carried a ${typeof value} as \`${member}\`, which a reader cannot walk` };
const bad = value.findIndex((row) => !isReadableDrop(row));
if (bad !== -1)
return { unreadable: `the landing's sync report carried a \`${member}\` entry (#${String(bad)}) that is not a drop record, so what was dropped cannot be read` };
}
return { report: sync };
}
export function readRuleWriteOutcome(res) {
if (res === null || typeof res !== "object") {
return { kind: "unreadable", why: `the store answered ${res === null ? "null" : `a ${typeof res}`} where a write outcome belongs` };
}
const tagged = res;
const refusal = tagged.refused;
const conflict = tagged.conflict;
if (refusal !== undefined && conflict !== undefined) {
return { kind: "unreadable", why: "the store answered a refusal and a decline at once, and an answer that is two arms is not an answer about either" };
}
if (refusal !== undefined) {
return typeof refusal === "string" && refusal !== ""
? { kind: "refused", refused: refusal }
: { kind: "unreadable", why: `the store tagged its answer as a refusal and named it with a ${refusal === null ? "null" : typeof refusal}, so which refusal it is cannot be read` };
}
if (conflict !== undefined) {
if (conflict !== true)
return { kind: "unreadable", why: `the store tagged its answer as a decline with \`${String(conflict)}\`, which does not say a compare-and-set lost` };
return isRuleRevision(tagged.rev)
? { kind: "conflict", rev: tagged.rev }
: { kind: "unreadable", why: `the store declined the write with ${outcomeWord(tagged.rev)}, so the revision to re-anchor the next attempt to is unknown` };
}
if (!isRuleRevision(tagged.rev)) {
return { kind: "unreadable", why: `the store answered neither a conflict nor a refusal, and carried ${outcomeWord(tagged.rev)} — a landing reports the revision it committed at, so this answer cannot say whether the write landed` };
}
const { report, unreadable } = readSyncReport(tagged.sync);
return { kind: "landed", rev: tagged.rev, ...(report !== undefined ? { sync: report } : {}), ...(unreadable !== undefined ? { reportUnreadable: unreadable } : {}) };
}
export function unknownRuleWriteDeltaError(delta) {
const kind = delta?.kind;
return new Error(`the permission-rule store cannot apply a write delta of kind ${escapeForDisclosure(typeof kind === "string" ? kind : String(kind))} — the write face folds exactly four named arms (redemption-add, tighten-add, tighten-delete, sync-join), and an unnamed one is refused rather than read as any of them`);
}
export const PERMISSION_RULE_WRITER = "__semaPermissionRuleWriter";
export function writerOf(store) {
const w = store[PERMISSION_RULE_WRITER];
return w !== undefined && typeof w.apply === "function" && typeof w.nextDot === "function" ? w : undefined;
}
export function holdsRuleWriter(store) {
for (let o = store; o !== null; o = Object.getPrototypeOf(o)) {
const d = Object.getOwnPropertyDescriptor(o, PERMISSION_RULE_WRITER);
if (d === undefined)
continue;
if (d.get !== undefined) {
const held = store.writerHeld;
return typeof held === "function" && held.call(store) === true;
}
const w = d.value;
return w !== null && typeof w === "object" && typeof w.apply === "function" && typeof w.nextDot === "function";
}
return false;
}
export function sameScope(a, b) {
if (a.kind === "global")
return b.kind === "global";
if (a.kind === "session")
return b.kind === "session" && a.sessionId === b.sessionId;
return b.kind === "project" && a.root === b.root;
}
function sameDot(a, b) {
return a.actor === b.actor && (a.counter === b.counter || Object.is(a.counter, b.counter));
}
export const UNREADABLE_RULE_TEXT = "(unreadable)";
export function storedRuleTextOf(read) {
const { tool, match } = read;
const command = match === "tool" ? "" : read.command;
if (typeof tool !== "string" || typeof match !== "string" || typeof command !== "string")
return UNREADABLE_RULE_TEXT;
try {
const rule = formatRuleText(command, match, tool);
return "reject" in normalizePersistedRule({ ...read, command, rule }) ? UNREADABLE_RULE_TEXT : rule;
}
catch {
return UNREADABLE_RULE_TEXT;
}
}
const GLOBAL_SCOPE = Object.freeze({ kind: "global" });
function scopeReads(scope) {
if (scope === null || typeof scope !== "object")
return false;
const primitive = (k) => {
try {
const v = Reflect.get(scope, k);
return v === null || (typeof v !== "object" && typeof v !== "function");
}
catch {
return false;
}
};
if (!primitive("kind"))
return false;
const kind = scope.kind;
return kind === "project" ? primitive("root") : kind === "session" ? primitive("sessionId") : true;
}
export function storedRuleIdentityOf(row) {
if (row === null || typeof row !== "object")
return { behavior: "ask", rule: UNREADABLE_RULE_TEXT, scope: GLOBAL_SCOPE };
const read = (k) => {
try {
return Reflect.get(row, k);
}
catch {
return undefined;
}
};
const behavior = read("behavior");
const rule = read("rule");
const scope = read("scope");
if (!isRuleBehavior(behavior)) {
return {
behavior: "ask",
rule: typeof rule === "string" ? rule : UNREADABLE_RULE_TEXT,
scope: isValidDurableScope(scope) ? scope : GLOBAL_SCOPE,
};
}
return {
behavior,
rule: typeof rule === "string" ? rule : storedRuleTextOf({ behavior, tool: read("tool"), match: read("match"), command: read("command"), scope }),
scope: scopeReads(scope) ? scope : GLOBAL_SCOPE,
};
}
function storedExactIdentityOf(row) {
if (row === null || typeof row !== "object")
return undefined;
const read = (k) => {
try {
return Reflect.get(row, k);
}
catch {
return undefined;
}
};
const behavior = read("behavior");
const rule = read("rule");
const scope = read("scope");
return isRuleBehavior(behavior) && typeof rule === "string" && scopeReads(scope) ? { behavior, rule, scope } : undefined;
}
function sameDisplayedIdentity(row, identity) {
const x = storedRuleIdentityOf(row);
return x.behavior === identity.behavior && x.rule === identity.rule && sameScope(x.scope, identity.scope);
}
export function sameRuleIdentity(a, b) {
const x = storedExactIdentityOf(a);
const y = storedExactIdentityOf(b);
return x !== undefined && y !== undefined && x.behavior === y.behavior && x.rule === y.rule && sameScope(x.scope, y.scope);
}
function heldAddsOf(row) {
if (row === null || typeof row !== "object")
return undefined;
try {
const adds = Reflect.get(row, "adds");
return Array.isArray(adds) ? adds : undefined;
}
catch {
return undefined;
}
}
const DOT_SHAPE = { members: { actor: "primitive", counter: "primitive" } };
const SCOPE_SHAPE = { members: { kind: "primitive" }, byKind: { project: { root: "primitive" }, session: { sessionId: "primitive" } }, held: true };
const ADD_DOT_SHAPE = { members: { actor: "value", counter: "value" }, held: true };
const ADD_SHAPE = { members: { dot: ADD_DOT_SHAPE, origin: "primitive", createdAt: "time", peerFingerprint: "primitive" }, own: ["peerFingerprint"], held: true };
const RULE_ROW_MEMBERS = { behavior: "text", rule: "text", tool: "text", match: "text", command: "text", scope: SCOPE_SHAPE, adds: { listOf: ADD_SHAPE, held: true } };
export const TOMBSTONE_ROW_MEMBERS = { behavior: "primitive", rule: "primitive", scope: SCOPE_SHAPE, removedDots: { listOf: DOT_SHAPE }, deletedBy: DOT_SHAPE };
const TIME_OF_DATE = Date.prototype.getTime;
const ISO_OF_DATE = Date.prototype.toISOString;
const unreadValue = (why, kept) => ({ ok: false, why, ...(kept !== undefined ? { kept } : {}) });
export function servedValueOf(v, shape) {
const held = heldKindOf(shape);
if (v === null || (typeof v !== "object" && typeof v !== "function")) {
if (held === undefined || (held === "a text" && typeof v === "string") || (held === "a value" && v !== null && v !== undefined))
return { ok: true, v };
return unreadValue(`${v === null || v === undefined ? String(v) : `a ${typeof v}`} where ${held} belongs`);
}
if (shape === "time" && typeof v === "object" && !types.isProxy(v) && types.isDate(v) && Number.isFinite(TIME_OF_DATE.call(v)))
return { ok: true, v: ISO_OF_DATE.call(v) };
if (typeof shape === "string" || typeof v === "function")
return unreadValue(`${typeof v === "function" ? "a function" : shape === "time" ? "an object that is no valid date" : "an object"} where a ${typeof shape === "string" ? shape : "primitive"} belongs`);
if ("listOf" in shape) {
const length = servedLengthOf(v);
if ("why" in length)
return unreadValue(length.why);
const out = new Array(length.n);
const kept = [];
let why;
for (let i = 0; i < length.n; i++) {
const el = memberOf(v, i);
const got = "why" in el ? el : el.held ? servedValueOf(el.v, shape.listOf) : heldKindOf(shape.listOf) !== undefined ? unreadValue(`a hole where ${heldKindOf(shape.listOf)} belongs`) : undefined;
if (got === undefined)
continue;
if ("why" in got)
why ??= `element #${i}: ${got.why}`;
else
kept.push((out[i] = got.v));
}
return why === undefined ? { ok: true, v: out } : unreadValue(why, kept);
}
const out = {};
const readMembers = (members) => {
for (const [k, member] of Object.entries(members)) {
const got = memberOf(v, k);
if ("why" in got)
return unreadValue(got.why);
if (!got.held) {
if (heldKindOf(member) !== undefined)
return unreadValue(`nothing where ${heldKindOf(member)} belongs`);
continue;
}
if (got.v !== undefined && got.v !== null && "members" in shape && shape.own?.includes(k) === true && !ownMemberOf(v, k))
return unreadValue(`${k}: a value its prototype supplies, not the object's own`);
const value = servedValueOf(got.v, member);
if (!value.ok)
return unreadValue(value.why);
out[k] = value.v;
}
return undefined;
};
const failed = readMembers(shape.members);
if (failed !== undefined)
return failed;
const kind = out.kind;
const byKind = shape.byKind !== undefined && typeof kind === "string" && Object.hasOwn(shape.byKind, kind) ? readMembers(shape.byKind[kind]) : undefined;
return byKind ?? { ok: true, v: out };
}
function memberOf(o, k) {
try {
const v = Reflect.get(o, k);
return v === undefined && !(k in o) ? { held: false } : { held: true, v };
}
catch (e) {
return { why: errText(e), thrown: e };
}
}
function ownMemberOf(o, k) {
try {
return Object.hasOwn(o, k);
}
catch {
return false;
}
}
export function memberValueOf(o, k) {
const got = memberOf(o, k);
return "why" in got ? { ok: false, why: got.why, thrown: got.thrown } : { ok: true, v: got.held ? got.v : undefined };
}
const MAX_LIST_LENGTH = 2 ** 32 - 1;
export function servedLengthOf(v) {
let isList;
try {
isList = Array.isArray(v);
}
catch (e) {
return { why: errText(e), thrown: e };
}
if (!isList)
return { why: "an object where a list belongs" };
const got = memberValueOf(v, "length");
if (!got.ok)
return { why: got.why, ...("thrown" in got ? { thrown: got.thrown } : {}) };
const n = got.v;
return typeof n === "number" && Number.isInteger(n) && n >= 0 && n <= MAX_LIST_LENGTH ? { n } : { why: "a list whose length is no count" };
}
function heldKindOf(shape) {
if (shape === "text")
return "a text";
if (shape === "value")
return "a value";
if (typeof shape !== "object" || shape.held !== true)
return undefined;
return "listOf" in shape ? "a list" : "an object";
}
export function servedRowOf(row, members) {
if (row === null || typeof row !== "object") {
const why = `${row === null ? "null" : row === undefined ? "nothing" : `a ${typeof row}`} where a row belongs`;
return { failed: Object.keys(members).map((member) => ({ member, why })), read: {}, notObject: why };
}
const read = {};
const failed = [];
for (const [k, shape] of Object.entries(members)) {
const got = servedMemberOf(row, k, shape);
if ("why" in got)
failed.push({ member: k, why: got.why, ...("thrown" in got ? { threw: true } : {}), ...("kept" in got && got.kept !== undefined ? { kept: got.kept } : {}) });
else if (got.held)
read[k] = got.v;
}
return failed.length > 0 ? { failed: failed, read } : { row: read };
}
function servedMemberOf(row, k, shape) {
const got = memberOf(row, k);
if ("why" in got)
return got;
if (!got.held)
return heldKindOf(shape) !== undefined ? { why: `nothing where ${heldKindOf(shape)} belongs` } : got;
const value = servedValueOf(got.v, shape);
return value.ok ? { held: true, v: value.v } : { why: value.why, ...(value.kept !== undefined ? { kept: value.kept } : {}) };
}
function behaviorJudged(r) {
const read = ("row" in r ? r.row : r.read);
if (!Object.hasOwn(read, "behavior") || isRuleBehavior(read.behavior))
return r;
const { behavior, ...rest } = read;
const fault = { member: "behavior", why: `a word outside deny/ask/allow (${JSON.stringify(escapeForDisclosure(behavior))})` };
return { failed: [fault, ...("failed" in r ? r.failed : [])], read: rest };
}
function commandIsIdentity(match) {
return match !== "tool";
}
const UNNAMED_ADD = Object.freeze({ dot: Object.freeze({ actor: "", counter: 0 }), origin: "user", createdAt: "" });
function identityOf(read, failed) {
if (!failed.has("tool") && !failed.has("match") && !(failed.has("command") && commandIsIdentity(read.match)))
return {};
const parsed = failed.has("rule") || typeof read.rule !== "string" ? undefined : parseRuleText(read.rule, read.behavior);
return parsed === undefined || "reject" in parsed ? undefined : { tool: parsed.rule.tool, match: parsed.rule.match, command: parsed.rule.command };
}
function standingRowOf(read, failed, seat) {
const adds = failed.find((f) => f.member === "adds");
const stood = {
...read,
...(failed.some((f) => f.member === "scope") ? { scope: widestScopeOf(seat) } : {}),
...(read.match === "tool" && typeof read.command !== "string" ? { command: "" } : {}),
...(adds !== undefined ? { adds: adds.kept !== undefined && adds.kept.length > 0 ? [...adds.kept] : [UNNAMED_ADD] } : {}),
};
return failed.some((f) => f.member === "rule") ? { ...stood, rule: storedRuleTextOf(stood) } : stood;
}
function unreadableRowOf(read, failed, first, seat) {
const behavior = !failed.has("behavior") && (read.behavior === "deny" || read.behavior === "ask") ? read.behavior : "ask";
const tool = failed.has("tool") ? undefined : read.tool;
const pathDeny = (behavior === "deny" || failed.has("behavior")) && typeof tool === "string" && Object.hasOwn(PATH_RULE_FACES, tool) && PATH_RULE_FACES[tool]?.deny !== undefined;
return {
reason: failed.has("rule") ? "invalid_rule_text" : "metadata_mismatch",
rule: failed.has("rule") ? storedRuleTextOf(read) : String(read.rule),
behavior,
member: first,
reach: typeof tool === "string" && isNameableToolName(tool) && !pathDeny ? { tool } : "every",
...namedScopeOf(failed.has("scope") ? undefined : read.scope, seat),
};
}
export const DURABLE_SEAT = {};
function widestScopeOf(seat) {
return seat.session !== undefined ? { kind: "session", sessionId: seat.session } : { kind: "global" };
}
function namedScopeOf(scope, seat) {
if (seat.session === undefined)
return isValidDurableScope(scope) ? { scope: scope } : {};
if (scope === undefined)
return { scope: widestScopeOf(seat) };
const session = typeof scope === "object" && scope !== null && scope.kind === "session" && typeof scope.sessionId === "string";
return session ? { scope: scope } : {};
}
export function unreadableRowsLine(partition, rows) {
return (`the ${partition} rule partition served ${rows.length} deny or ask row(s) a member of which could not be read as the type it holds — one whose tool, match and command read, or whose text says the ones that did not, stands as written (its text, when that is the member, spelled from them; its scope, when that is the member, ${partition === "session" ? "the session's" : "everywhere"}); one whose neither do stands at its strictest reading over the calls it may reach (no allow clears them; a readable deny still refuses, a readable ask still asks); every other row stands: ` +
rows
.slice(0, 3)
.map(({ row, why }) => `${escapeForDisclosure(row.rule)} (${escapeForDisclosure(why)}; ${row.reach === "as_read" ? "as written" : row.reach === "every" ? "every call" : `the ${escapeForDisclosure(row.reach.tool)} calls`})`)
.join(", "));
}
export function ruleRowReadOf(served, seat) {
const r = behaviorJudged(servedRowOf(served, RULE_ROW_MEMBERS));
if ("row" in r)
return { row: r.row };
const failed = new Set(r.failed.map((f) => f.member));
const [first] = r.failed;
const why = `${first.member}: ${first.why}`;
const reason = failed.has("rule") ? "invalid_rule_text" : "metadata_mismatch";
const rule = failed.has("rule") ? storedRuleTextOf(r.read) : String(r.read.rule);
const scope = failed.has("scope") ? widestScopeOf(seat) : r.read.scope;
const dead = !failed.has("adds") && Array.isArray(r.read.adds) && r.read.adds.length === 0;
if (dead)
return { dead };
if (failed.has("behavior"))
return { named: { row: unreadableRowOf(r.read, failed, first.member, seat), why: r.notObject ?? `behavior: ${first.threw === true ? "a read that threw" : first.why}` }, scope };
if (r.read.behavior === "allow")
return { left: { reason, rule, member: first.member }, scope };
const identity = identityOf(r.read, failed);
if (identity === undefined)
return { named: { row: unreadableRowOf(r.read, failed, first.member, seat), why } };
const stood = standingRowOf({ ...r.read, ...identity }, r.failed, seat);
return { row: stood, named: { row: { reason, rule, behavior: r.read.behavior, member: first.member, reach: "as_read", ...namedScopeOf(failed.has("scope") ? undefined : r.read.scope, seat) }, why, stood } };
}
function scopeRootAsServed(root) {
return typeof root === "string" ? root : `(${root === null ? "null" : typeof root})`;
}
export function droppedRowOf(r) {
if (!isValidDurableScope(r.scope))
return { reason: "scope_root_not_absolute", rule: String(r.rule), scopeRoot: scopeRootAsServed(r.scope.root) };
if (r.behavior !== "allow")
return undefined;
const shape = normalizePersistedRule(r);
return "reject" in shape ? { reason: shape.reject, rule: r.rule } : undefined;
}
export function readDurableRuleRow(served) {
const r = ruleRowReadOf(served, DURABLE_SEAT);
if (r.dead === true)
return { kind: "inert", dead: true };
if (r.left !== undefined)
return { kind: "inert", dropped: r.left, unread: true };
if ("row" in r) {
const row = r.row;
const dropped = droppedRowOf(row);
if (dropped !== undefined)
return { kind: "inert", row, dropped };
if (!Array.isArray(row.adds) || row.adds.length === 0)
return { kind: "inert", row, dead: true };
return r.named !== undefined ? { kind: "acts", row, named: r.named } : { kind: "acts", row };
}
if (r.named !== undefined)
return { kind: "acts", named: r.named };
return { kind: "inert" };
}
function heldDotOf(add) {
if (add === null || typeof add !== "object")
return undefined;
const got = memberValueOf(add, "dot");
if (!got.ok)
return undefined;
const dot = servedValueOf(got.v, ADD_DOT_SHAPE);
return dot.ok ? dot.v : undefined;
}
function heldRowLive(row) {
return readDurableRuleRow(row).kind === "acts";
}
export function applyTombstones(rules, tombstones) {
return rules
.map((r) => {
const adds = heldAddsOf(r);
if (adds === undefined)
return r;
const removed = tombstones.filter((t) => sameRuleIdentity(t, r)).flatMap((t) => t.removedDots);
if (removed.length === 0)
return r;
return { ...r, adds: adds.filter((a) => { const dot = heldDotOf(a); return dot === undefined || !removed.some((d) => sameDot(d, dot)); }) };
})
.filter((r) => heldAddsOf(r)?.length !== 0);
}
export function foldDelta(rules, delta) {
const next = rules.map((r) => (heldAddsOf(r) !== undefined ? { ...r, adds: [...r.adds] } : r));
const existing = next.find((r) => heldAddsOf(r) !== undefined && sameRuleIdentity(r, delta));
if (existing === undefined) {
next.push({ behavior: delta.behavior, rule: delta.rule, tool: delta.tool, match: delta.match, command: delta.command, scope: delta.scope, adds: [delta.add] });
return next;
}
if (!holdsDot(existing, delta.add.dot))
existing.adds.push(delta.add);
return next;
}
export function addDotsOf(rules) {
return rules.flatMap((r) => r.adds.map((a) => a.dot));
}
const ADD_ONLY_KEYS = ["add", "redemption", "rule", "command", "match", "tool", "behavior"];
export function assertDeleteDeltaCarriesNoAdd(delta) {
const smuggled = ADD_ONLY_KEYS.filter((k) => Object.hasOwn(delta, k));
if (smuggled.length > 0) {
throw new Error(`a tighten-delete may not introduce a new add (it carried: ${smuggled.join(", ")})`);
}
if (!Array.isArray(delta.tombstone?.removedDots) || delta.tombstone.removedDots.length === 0) {
throw new Error("a tighten-delete must carry a tombstone naming at least one observed add dot");
}
}
export function assertWriteDeltaScopeDurable(delta) {
const scope = delta.kind === "tighten-delete" ? delta.tombstone?.scope : delta.scope;
if (scope?.kind === "session") {
const e = new Error(delta.kind === "tighten-delete"
? "a session-scope tombstone cannot enter the persisted store — session rows are not individually deletable and die with their session; refusing the tighten-delete (a tombstone here names a global scope or a project scope with a root)"
: `a session-scope rule cannot enter the persisted store — its home is the session's own overlay; refusing the ${delta.kind} (a session rule is written through a rule store provider with a writable durable partition and a session partition, createPermissionRuleStoreProvider({ durable, session }); persisting it instead takes a new consent for a global or absolute-root project rule)`);
e.code = "unsupported.session_scope_store";
throw e;
}
if (delta.kind === "tighten-delete") {
if (!namesAScopeIdentity(scope)) {
throw new Error("a tighten-delete must carry a tombstone whose scope names a global scope or a project scope with a root string — refusing the write");
}
return;
}
if (!isValidDurableScope(scope)) {
throw new Error(`a ${delta.kind} whose scope is not a well-formed durable scope cannot enter the persisted store (it holds a global scope or a project scope with a root) — refusing the write`);
}
}
function namesAScopeIdentity(scope) {
const sc = scope;
return sc?.kind === "global" || (sc?.kind === "project" && typeof sc.root === "string");
}
export function isValidConsentScope(scope) {
const sc = scope;
return (sc?.kind === "global" ||
(sc?.kind === "project" && isProjectScopeRoot(sc.root)) ||
(sc?.kind === "session" && typeof sc.sessionId === "string" && sc.sessionId !== ""));
}
export function isValidDurableScope(scope) {
const sc = scope;
return sc?.kind === "global" || (sc?.kind === "project" && isProjectScopeRoot(sc.root));
}
export function isProjectScopeRoot(root) {
return validatePath(root, { intent: "validate-coordinate" }) !== undefined;
}
function isValidDot(dot) {
const d = dot;
return typeof d?.actor === "string" && d.actor !== "" && typeof d.counter === "number" && Number.isFinite(d.counter);
}
function scopeKey(scope) {
return JSON.stringify(scope.kind === "global" ? ["g"] : scope.kind === "session" ? ["s", scope.sessionId] : ["p", scope.root]);
}
function dotKey(dot) {
return JSON.stringify([dot.actor, dot.counter]);
}
function ruleIdentityKey(behavior, rule, scope) {
return JSON.stringify([behavior, rule, scopeKey(scope)]);
}
function compareDots(a, b) {
return a.actor < b.actor ? -1 : a.actor > b.actor ? 1 : a.counter - b.counter;
}
export function dotAtOrBelowFrontier(dot, frontier) {
const cap = frontier[dot.actor];
return typeof cap === "number" && Number.isFinite(cap) && dot.counter <= cap;
}
export function ruleSyncVector(state) {
const out = {};
const feed = (dot) => {
const cur = out[dot.actor];
if (cur === undefined || dot.counter > cur)
out[dot.actor] = dot.counter;
};
for (const r of state.rules)
for (const a of r.adds)
feed(a.dot);
for (const t of state.tombstones) {
feed(t.deletedBy);
for (const d of t.removedDots)
feed(d);
}
return out;
}
export function joinFrontiers(a, b) {
const out = { ...a };
for (const [actor, counter] of Object.entries(b)) {
const cur = out[actor];
if (cur === undefined || counter > cur)
out[actor] = counter;
}
return out;
}
export function normalizePersistedRule(r) {
if (!isRuleBehavior(r.behavior))
return { reject: "invalid_rule_text" };
if (r.match === "call") {
const fault = callGrantRowFault(r);
return fault === undefined ? { rule: r } : { reject: fault };
}
const parsed = parseRuleText(r.rule, r.behavior);
if ("reject" in parsed)
return { reject: "invalid_rule_text" };
const p = parsed.rule;
if (p.rule !== r.rule)
return { reject: "invalid_rule_text" };
if (r.tool !== p.tool || r.match !== p.match || r.command !== p.command)
return { reject: "metadata_mismatch" };
return { rule: r };
}
export function screenRuleSyncState(state) {
const rejected = [];
const rules = [];
for (const r of state.rules) {
if (!Array.isArray(r.adds) || r.adds.length === 0)
continue;
if (r.scope?.kind === "session") {
for (const a of r.adds)
rejected.push({ behavior: r.behavior, rule: r.rule, scope: r.scope, dot: a.dot, reason: "session_scope_not_durable" });
continue;
}
const n = normalizePersistedRule(r);
if ("reject" in n) {
for (const a of r.adds)
rejected.push({ behavior: r.behavior, rule: r.rule, scope: r.scope, dot: a.dot, reason: n.reject });
continue;
}
rules.push(r);
}
const tombstones = [];
for (const t of state.tombstones) {
if (t?.scope?.kind === "session") {
rejected.push({ behavior: t.behavior, rule: t.rule, scope: t.scope, dot: t.deletedBy, reason: "session_scope_not_durable" });
continue;
}
if (!isRuleBehavior(t.behavior)) {
rejected.push({ behavior: t.behavior, rule: t.rule, scope: t.scope, dot: t.deletedBy, reason: "invalid_rule_text" });
continue;
}
tombstones.push(t);
}
return { state: { rules, tombstones }, rejected };
}
export function joinRuleStates(a, b) {
const sa = screenRuleSyncState(a).state;
const sb = screenRuleSyncState(b).state;
const ruleGroups = new Map();
for (const r of [...sa.rules, ...sb.rules]) {
const key = ruleIdentityKey(r.behavior, r.rule, r.scope);
const existing = ruleGroups.get(key);
if (existing === undefined) {
ruleGroups.set(key, { ...r, adds: [...r.adds] });
continue;
}
for (const add of r.adds) {
const i = existing.adds.findIndex((x) => sameDot(x.dot, add.dot));
if (i === -1)
existing.adds.push({ ...add });
else if (canonicalize(add) < canonicalize(existing.adds[i]))
existing.adds[i] = { ...add };
}
}
const rules = [...ruleGroups.values()]
.map((r) => ({ ...r, adds: [...r.adds].sort((x, y) => compareDots(x.dot, y.dot)) }))
.sort((x, y) => compareIdentity(x, y));
const tombGroups = new Map();
for (const t of [...sa.tombstones, ...sb.tombstones]) {
if (!Array.isArray(t.removedDots) || t.removedDots.length === 0)
continue;
const key = JSON.stringify([t.behavior, t.rule, scopeKey(t.scope), dotKey(t.deletedBy)]);
const existing = tombGroups.get(key);
if (existing === undefined) {
tombGroups.set(key, { ...t, removedDots: [...t.removedDots] });
continue;
}
for (const d of t.removedDots)
if (!existing.removedDots.some((x) => sameDot(x, d)))
existing.removedDots.push(d);
}
const tombstones = [...tombGroups.values()]
.map((t) => ({ ...t, removedDots: [...t.removedDots].sort(compareDots) }))
.sort((x, y) => compareIdentity(x, y) || compareDots(x.deletedBy, y.deletedBy));
return { rules, tombstones };
}
function compareIdentity(x, y) {
if (x.rule !== y.rule)
return x.rule < y.rule ? -1 : 1;
const sx = scopeKey(x.scope);
const sy = scopeKey(y.scope);
if (sx !== sy)
return sx < sy ? -1 : 1;
return x.behavior === y.behavior ? 0 : x.behavior < y.behavior ? -1 : 1;
}
export function collectBelowFrontier(state, frontier) {
const collectable = state.tombstones.filter((t) => dotAtOrBelowFrontier(t.deletedBy, frontier) && t.removedDots.every((d) => dotAtOrBelowFrontier(d, frontier)));
if (collectable.length === 0)
return { state, collectedTombstones: 0 };
const keep = state.tombstones.filter((t) => !collectable.includes(t));
const rules = state.rules
.map((r) => {
const covered = collectable.filter((t) => sameRuleIdentity(t, r)).flatMap((t) => t.removedDots);
return covered.length === 0 ? r : { ...r, adds: r.adds.filter((a) => !covered.some((d) => sameDot(d, a.dot))) };
})
.filter((r) => r.adds.length > 0);
return { state: { rules, tombstones: keep }, collectedTombstones: collectable.length };
}
export function unreadableLocalRuleIndices(rules) {
const out = [];
for (let i = 0; i < rules.length; i++) {
const r = rules[i];
const adds = heldAddsOf(r);
if (storedExactIdentityOf(r) === undefined || adds === undefined || adds.some((a) => { const d = heldDotOf(a); return d === undefined || !isValidDot(d); }))
out.push(i);
}
return out;
}
export function applySyncJoin(cur, delta, nowMs) {
if (delta.kind !== "sync-join" || delta.inbound === null || typeof delta.inbound !== "object" || !Array.isArray(delta.inbound.rules) || !Array.isArray(delta.inbound.tombstones)) {
throw new Error("a sync-join delta must carry an inbound state with rules and tombstones arrays");
}
const unreadableLocal = unreadableLocalRuleIndices(cur.rules);
if (unreadableLocal.length > 0) {
throw new Error(`local rule row (#${unreadableLocal[0]}) cannot be read as a stored rule row — refusing the sync-join rather than writing it away; repair or remove it in the store`);
}
for (const t of delta.inbound.tombstones) {
if (t?.scope?.kind === "session")
continue;
if (!Array.isArray(t?.removedDots) || t.removedDots.length === 0) {
throw new Error("an inbound tombstone must name at least one observed add dot — refusing the whole sync-join (the client's partitioning must withhold the round's adds alongside a malformed tombstone)");
}
if (!isValidDurableScope(t.scope) || !isValidDot(t.deletedBy) || !t.removedDots.every(isValidDot)) {
throw new Error("an inbound tombstone carries a malformed scope or dot — refusing the whole sync-join (a tombstone that cannot identity-match what it deletes would land its covered adds live)");
}
if (!isRuleBehavior(t.behavior)) {
throw new Error("an inbound tombstone carries a behavior word outside deny/ask/allow — refusing the whole sync-join (a tombstone that cannot identity-match what it deletes would land its covered adds live)");
}
const canonicalTomb = parseRuleText(t.rule, t.behavior);
if ("reject" in canonicalTomb || canonicalTomb.rule.rule !== t.rule) {
throw new Error(`an inbound tombstone names a non-canonical or invalid rule text ("${escapeForDisclosure(t.rule)}") — refusing the whole sync-join (the client's partitioning must withhold the round's adds alongside a malformed tombstone)`);
}
}
const droppedInbound = [];
const quarantinedNow = [];
const screened = screenRuleSyncState(delta.inbound);
droppedInbound.push(...screened.rejected);
const forgedDot = (dot) => dot.actor === cur.actor && dot.counter > cur.counter;
const dotIdentity = new Map();
for (const r of cur.rules)
for (const a of r.adds)
dotIdentity.set(dotKey(a.dot), ruleIdentityKey(r.behavior, r.rule, r.scope));
for (const q of cur.quarantined)
dotIdentity.set(dotKey(q.add.dot), ruleIdentityKey(q.behavior, q.rule, q.scope));
const inboundClaims = new Map();
for (const r of screened.state.rules) {
const identity = ruleIdentityKey(r.behavior, r.rule, r.scope);
for (const a of r.adds) {
const claims = inboundClaims.get(dotKey(a.dot)) ?? new Set();
claims.add(identity);
inboundClaims.set(dotKey(a.dot), claims);
}
}
const inboundTombstones = screened.state.tombstones.filter((t) => {
const forged = forgedDot(t.deletedBy) ? t.deletedBy : t.removedDots.find(forgedDot);
if (forged === undefined)
return true;
droppedInbound.push({ behavior: t.behavior, rule: t.rule, scope: t.scope, dot: forged, reason: "own_actor_forged" });
return false;
});
const tombstoneRejected = inboundTombstones.length !== screened.state.tombstones.length;
let withheldAdds = 0;
const inboundRules = [];
for (const r of screened.state.rules) {
if (tombstoneRejected) {
withheldAdds += r.adds.length;
continue;
}
if (!isValidDurableScope(r.scope)) {
for (const a of r.adds)
droppedInbound.push({ behavior: r.behavior, rule: r.rule, scope: r.scope, dot: a.dot, reason: "metadata_mismatch" });
continue;
}
const identity = ruleIdentityKey(r.behavior, r.rule, r.scope);
const kept = r.adds.filter((a) => {
if (!isValidDot(a.dot)) {
droppedInbound.push({ behavior: r.behavior, rule: r.rule, scope: r.scope, dot: a.dot, reason: "metadata_mismatch" });
return false;
}
if (forgedDot(a.dot)) {
droppedInbound.push({ behavior: r.behavior, rule: r.rule, scope: r.scope, dot: a.dot, reason: "own_actor_forged" });
return false;
}
const known = dotIdentity.get(dotKey(a.dot));
if ((known !== undefined && known !== identity) || (inboundClaims.get(dotKey(a.dot))?.size ?? 0) > 1) {
droppedInbound.push({ behavior: r.behavior, rule: r.rule, scope: r.scope, dot: a.dot, reason: "dot_identity_conflict" });
return false;
}
return true;
});
if (kept.length > 0)
inboundRules.push({ ...r, adds: kept });
}
const inbound = { rules: inboundRules, tombstones: inboundTombstones };
const localScreen = screenRuleSyncState({ rules: cur.rules, tombstones: cur.tombstones });
const quarantined = [...cur.quarantined];
const quarantineKey = (behavior, rule, scope, dot) => JSON.stringify([behavior, rule, scopeKey(scope), dotKey(dot)]);
const pushQuarantine = (behavior, rule, scope, add, reason) => {
if (quarantined.some((q) => sameRuleIdentity(q, { behavior, rule, scope }) && sameDot(q.add.dot, add.dot)))
return;
quarantined.push({ behavior, rule, scope, add, reason, atMs: nowMs });
quarantinedNow.push({ behavior, rule, scope, dot: add.dot, reason });
};
for (const rej of localScreen.rejected) {
const row = cur.rules.find((r) => sameRuleIdentity(r, rej));
const add = row?.adds.find((a) => sameDot(a.dot, rej.dot));
if (add !== undefined && (rej.reason === "invalid_rule_text" || rej.reason === "metadata_mismatch")) {
pushQuarantine(rej.behavior, rej.rule, rej.scope, add, rej.reason);
}
}
let joined = joinRuleStates(localScreen.state, inbound);
let collectedTombstones = 0;
if (delta.gcFrontier !== undefined) {
const collected = collectBelowFrontier(joined, delta.gcFrontier);
joined = collected.state;
collectedTombstones = collected.collectedTombstones;
const inboundDots = new Set(inbound.rules.flatMap((r) => r.adds.map((a) => dotKey(a.dot))));
const live = applyTombstones(joined.rules, joined.tombstones);
for (const r of live) {
for (const a of r.adds) {
if (dotAtOrBelowFrontier(a.dot, delta.gcFrontier) && !inboundDots.has(dotKey(a.dot))) {
pushQuarantine(r.behavior, r.rule, r.scope, a, "below_gc_frontier");
}
}
}
}
for (const q of delta.quarantine ?? []) {
if (q.scope?.kind === "session") {
const e = new Error("a quarantine instruction names a session scope — the persisted store never holds a session row, so there is nothing of it to quarantine here; refusing the instruction");
e.code = "unsupported.session_scope_store";
throw e;
}
for (const dot of q.dots) {
if (joined.tombstones.some((t) => sameDot(t.deletedBy, dot))) {
throw new Error("a quarantine instruction may not touch a tombstone — it moves adds only");
}
const row = joined.rules.find((r) => sameRuleIdentity(r, q));
const add = row?.adds.find((a) => sameDot(a.dot, dot));
if (add === undefined)
continue;
pushQuarantine(q.behavior, q.rule, q.scope, add, q.reason);
}
}
const quarantinedRows = new Set(quarantined.map((q) => quarantineKey(q.behavior, q.rule, q.scope, q.add.dot)));
const rules = joined.rules
.map((r) => ({ ...r, adds: r.adds.filter((a) => !quarantinedRows.has(quarantineKey(r.behavior, r.rule, r.scope, a.dot))) }))
.filter((r) => r.adds.length > 0);
return {
next: {
actor: cur.actor,
counter: cur.counter,
rules,
tombstones: joined.tombstones,
quarantined,
observedVector: delta.observedVector !== undefined ? joinFrontiers(cur.observedVector ?? {}, delta.observedVector) : cur.observedVector,
},
report: structuredClone({ droppedInbound, quarantined: quarantinedNow, collectedTombstones, withheldAdds }),
};
}
export function assertRedemptionNotQuarantined(quarantined, delta) {
const hit = quarantined.find((q) => sameDot(q.add.dot, delta.add.dot));
if (hit !== undefined) {
throw new Error(`this approval's add (dot ${delta.add.dot.actor}#${delta.add.dot.counter}) was quarantined (${hit.reason}) — replaying the old record cannot revive it; a new consent (a new ask, a new record, a new dot) is required`);
}
}
export async function ruleStoreChecksum(payload) {
return textContentHashOf(canonicalize(payload));
}
export const REMOVAL_LIVENESS_WORDS = Object.freeze(["yes", "no", "unknown"]);
export const RULE_WRITE_COMMITTED_WORDS = Object.freeze(["no", "unknown"]);
export const RULE_REFUSAL_CODES = Object.freeze([
"unsupported.layer_root",
"ticket_invalid",
"record_missing",
"wrong_principal",
"record_schema_stale",
"not_confirmed",
"record_malformed",
"not_chosen",
"parse_rejected",
"store_unavailable",
"record_changed",
"withheld",
"store_read",
"store_write",
"session_ended",
"occ",
"dot_removed",
]);
function resolveRuleWriter(store) {
let w;
try {
w = writerOf(store);
}
catch (err) {
return { unavailable: `the permission-rule store's write face could not be acquired (${errText(err)})`, committed: "unknown", code: "store_unavailable" };
}
return w === undefined ? { unavailable: "the resolved permission-rule store has no write face", committed: "no", code: "store_unavailable" } : { writer: w };
}
function ruleIdentityStands(rules, identity) {
return rules.some((r) => (sameRuleIdentity(r, identity) || sameDisplayedIdentity(r, identity)) && heldRowLive(r));
}
function holdsDot(row, dot) {
return heldAddsOf(row)?.some((a) => { const d = heldDotOf(a); return d !== undefined && sameDot(d, dot); }) === true;
}
function rowsStand(raw, identity) {
return ruleIdentityStands(applyTombstones(raw.rules, raw.tombstones), identity);
}
async function witnessRuleAdd(store, writer, delta) {
const identity = { behavior: delta.behavior, rule: delta.rule, scope: delta.scope };
const dot = delta.add.dot;
try {
if (delta.scope.kind === "session") {
const view = await store.effective({ sessionId: delta.scope.sessionId });
if (view.unreadable !== undefined)
return { unreadable: view.unreadable };
return { seen: view.rules.some((r) => sameRuleIdentity(r, identity) && holdsDot(r, dot)), rev: view.rev };
}
const raw = await writer.readRaw();
const inRows = raw.rules.some((r) => sameRuleIdentity(r, identity) && holdsDot(r, dot));
const inQuarantine = (raw.quarantined ?? []).some((q) => sameDot(q.add.dot, dot));
return { seen: inRows || inQuarantine, rev: raw.rev };
}
catch (err) {
return { unreadable: errText(err) };
}
}
async function readRuleLiveness(writer, identity) {
try {
return rowsStand(await writer.readRaw(), identity) ? "yes" : "no";
}
catch {
return "unknown";
}
}
export function sessionRevokeArmOf(revoked, refused) {
if (typeof revoked === "number" && refused === undefined)
return "counted";
return refused === "session_ended" && revoked === undefined ? "ended" : undefined;
}
const REMOVE_MAX_ATTEMPTS = 8;
const NO_TARGET_OWNER = `the principal given is neither a principal name (${PRINCIPAL_NAME_SPELLING}) nor an owner (a principal owner names a principal name; the local owner is { kind: "local-owner" })`;
function persistedRuleTargetOwner(target) {
return readRuleOwner(typeof target === "string" ? { kind: "principal", principal: target } : target);
}
export async function removePersistedRule(opts) {
const behavior = opts.behavior;
const rule = opts.rule;
const scope = structuredClone(opts.scope);
const target = opts.principal;
if (!isRuleBehavior(behavior)) {
return { status: "failed", code: "target_invalid", error: `removePersistedRule: behavior ${escapeForDisclosure(behavior)} is not one of ${["deny", "ask", "allow"].join("/")} — refusing to name a rule identity nothing can carry`, committed: "no" };
}
const identity = { behavior, rule, scope };
const owner = persistedRuleTargetOwner(target);
if (owner === undefined)
return { status: "failed", code: "target_invalid", error: `removePersistedRule: ${NO_TARGET_OWNER} — refusing to remove from a bucket nobody can name`, committed: "no" };
const provider = opts.provider;
const resolve = (open) => {
try {
return { store: open() };
}
catch (err) {
return { failed: { status: "failed", code: "store_unavailable", error: `could not resolve the owner's rule store: ${errText(err)}`, committed: "no" } };
}
};
const ownerStore = () => owner.kind === "local-owner" && provider.forLocalOwner === undefined
?
{ failed: { status: "failed", code: "store_unavailable", error: "this provider has no local-owner bucket (forLocalOwner is not implemented) — a local-owner rule cannot be removed through it", committed: "no" } }
: resolve(() => (owner.kind === "local-owner" ? provider.forLocalOwner() : provider.forPrincipal(owner.principal)));
if (scope?.kind === "session") {
const sessionId = scope.sessionId;
if (!isValidConsentScope(scope))
return { status: "failed", code: "target_invalid", error: "removePersistedRule: a session scope names a session by a non-empty id — refusing to remove from a session nobody can name", committed: "no" };
let revoke;
try {
revoke = provider.revokeSessionRule;
}
catch (err) {
return { status: "failed", code: "store_unavailable", error: `could not read the provider's take-back entry: ${errText(err)}`, committed: "no" };
}
if (revoke === undefined) {
const why = provider.partitions.session
? "this deployment's session rule partition implements no revoke(sessionId, target) — its rows end only with their session"
: "this deployment configured no session rule partition (createPermissionRuleStoreProvider({ session })) — there is no session row to remove";
return { status: "failed", code: "store_unavailable", error: `unsupported.session_scope_store: ${why}`, committed: "no" };
}
let revoked;
let refused;
let live;
try {
const answered = await revoke.call(provider, owner, sessionId, { behavior, rule });
const a = answered !== null && typeof answered === "object" ? answered : {};
revoked = a.revoked;
refused = a.refused;
live = a.stillLive;
}
catch (err) {
return { status: "failed", code: "store_write", error: `the session rule partition's revoke threw: ${errText(err)}`, committed: "unknown" };
}
const arm = sessionRevokeArmOf(revoked, refused);
if (arm === undefined)
return { status: "failed", code: "store_write", error: "the session rule partition answered the revoke with neither of its two arms (revoked / refused) — whether the row is gone is unknown; reconcile by reading the session's rules", committed: "unknown" };
const stillLive = REMOVAL_LIVENESS_WORDS.some((w) => w === live) ? live : "unknown";
return arm === "counted" && revoked > 0 ? { status: "removed", rev: 0, stillLive } : { status: "no-op", rev: 0, stillLive };
}
const resolved = ownerStore();
if ("failed" in resolved)
return resolved.failed;
const store = resolved.store;
const face = resolveRuleWriter(store);
if ("unavailable" in face) {
return { status: "failed", code: face.code, error: `${face.unavailable} — rules cannot be removed through it`, committed: face.committed };
}
const writer = face.writer;
let snapshot;
let removedDots = [];
try {
snapshot = await writer.readRaw();
let unretireableInertError;
for (const r of applyTombstones(snapshot.rules, snapshot.tombstones)) {
const exact = sameRuleIdentity(r, identity);
if (!exact && !sameDisplayedIdentity(r, identity))
continue;
const inert = readDurableRuleRow(r).kind === "inert";
if (!exact) {
const msg = `removePersistedRule: a stored row displayed as ${behavior} ${escapeForDisclosure(rule)} is not stored whole, so no tombstone can name it — nothing was written; remove it in the store`;
if (inert) {
unretireableInertError ??= msg;
continue;
}
return { status: "failed", code: "row_unremovable", error: msg, committed: "no" };
}
const dots = heldAddsOf(r)?.map(heldDotOf);
if (dots === undefined || dots.some((d) => d === undefined)) {
const msg = `removePersistedRule: a stored ${behavior} row named ${escapeForDisclosure(rule)} holds a list of adds this engine cannot read, so no tombstone can name them — nothing was written; remove it in the store`;
if (inert) {
unretireableInertError ??= msg;
continue;
}
return { status: "failed", code: "row_unremovable", error: msg, committed: "no" };
}
removedDots.push(...dots);
}
if (removedDots.length === 0 && unretireableInertError !== undefined) {
return { status: "failed", code: "row_unremovable", error: unretireableInertError, committed: "no" };
}
}
catch (err) {
return { status: "failed", code: "store_read", error: `could not read the permission-rule store: ${errText(err)}`, committed: "no" };
}
if (removedDots.length === 0)
return { status: "no-op", rev: snapshot.rev, stillLive: await readRuleLiveness(writer, identity) };
let deletedBy;
try {
deletedBy = await writer.nextDot();
}
catch (err) {
return { status: "failed", code: "store_write", error: `could not mint the removal's delete dot: ${errText(err)}`, committed: "no" };
}
const tombstone = { behavior, rule, scope, removedDots, deletedBy };
let expectedRev = snapshot.rev;
let lastError = "";
let settlement = "no";
let cause = "occ";
for (let attempt = 0; attempt < REMOVE_MAX_ATTEMPTS; attempt++) {
try {
const reading = readRuleWriteOutcome(await writer.apply({ kind: "tighten-delete", tombstone }, { expectedRev }));
if (reading.kind === "refused") {
return { status: "failed", code: "store_refused", error: `the store refused the tombstone (${reading.refused}) — nothing was removed`, committed: "no" };
}
if (reading.kind === "unreadable") {
settlement = "unknown";
cause = "store_write";
lastError = `the permission-rule store answered the write unreadably: ${reading.why}`;
break;
}
if (reading.kind === "landed") {
return { status: "removed", rev: reading.rev, stillLive: await readRuleLiveness(writer, identity) };
}
expectedRev = reading.rev;
}
catch (err) {
settlement = "unknown";
cause = "store_write";
lastError = errText(err);
break;
}
}
const reason = settlement === "unknown"
? lastError !== ""
? lastError
: "the permission-rule store threw while applying the tombstone, with no message"
: `optimistic-concurrency retries exhausted after ${REMOVE_MAX_ATTEMPTS} attempts`;
const committed = settlement;
try {
const after = await writer.readRaw();
const landed = after.tombstones.some((t) => t.deletedBy.actor === tombstone.deletedBy.actor && t.deletedBy.counter === tombstone.deletedBy.counter);
if (landed) {
return { status: "removed", rev: after.rev, stillLive: rowsStand(after, identity) ? "yes" : "no" };
}
return {
status: "failed",
code: cause,
error: settlement === "unknown"
? `${reason}; the store retains no tombstone for this removal, which cannot tell a write that never landed from one whose evidence was collected — the outcome is indeterminate, reconcile with list()`
: `${reason} (read-back confirms no tombstone was written)`,
committed,
};
}
catch (err) {
return {
status: "failed",
code: cause,
error: settlement === "unknown"
? `${reason}; the read-back also failed (${errText(err)}) so this outcome is indeterminate — reconcile with list()`
: `${reason}; the read-back also failed (${errText(err)}), but every attempt was answered by the store, so nothing was written`,
committed,
};
}
}
const RULE_ADD_MAX_ATTEMPTS = 8;
function addReadFault(view) {
return view.unreadable ?? view.unreadableRev;
}
const SESSION_ENDED_REFUSAL = "the session this authorization targets has ended — a session rule dies with its session, and a late or replayed redemption cannot revive it (re-trigger the command in a live session for a fresh card)";
export async function landRuleAdd(args) {
switch (args.delta.kind) {
case "redemption-add":
case "tighten-add":
break;
default: {
const unreachable = args.delta;
throw new Error(`landRuleAdd: unhandled add delta ${JSON.stringify(unreachable)}`);
}
}
for (let attempt = 0; attempt < RULE_ADD_MAX_ATTEMPTS; attempt++) {
let rev;
try {
const snapshot = await args.store.effective();
const fault = addReadFault(snapshot);
if (fault !== undefined)
throw new Error(fault);
rev = snapshot.rev;
const refusal = await args.preflight?.(snapshot);
if (refusal !== undefined)
return { landed: false, reason: refusal, committed: "no", code: "withheld" };
}
catch (err) {
return { landed: false, reason: `could not read the permission-rule store: ${errText(err)}`, committed: "no", code: "store_read" };
}
let res;
try {
res = await args.writer.apply(args.delta, { expectedRev: rev });
}
catch (err) {
return { landed: false, reason: `the permission-rule store refused the write: ${errText(err)}`, committed: "unknown", code: "store_write" };
}
const reading = readRuleWriteOutcome(res);
if (reading.kind === "refused")
return { landed: false, reason: SESSION_ENDED_REFUSAL, committed: "no", code: "session_ended" };
if (reading.kind === "unreadable")
return { landed: false, reason: `the permission-rule store answered the write unreadably: ${reading.why}`, committed: "unknown", code: "store_write" };
if (reading.kind === "landed") {
const witness = await witnessRuleAdd(args.store, args.writer, args.delta);
if ("unreadable" in witness) {
return { landed: false, reason: `the permission-rule store reported a landing at revision ${String(reading.rev)}, and the read-back that would have witnessed it could not be taken (${witness.unreadable})`, committed: "unknown", code: "store_read" };
}
if (!witness.seen) {
return { landed: false, reason: `the permission-rule store reported a landing at revision ${String(reading.rev)}, and a read-back of this add's own dot finds no trace of it — a revision says the ANSWER was well formed, not that a row exists, so nothing here can say the write landed`, committed: "unknown", code: "store_write" };
}
return { landed: true, rev: reading.rev };
}
}
return { landed: false, reason: `optimistic-concurrency retries exhausted after ${RULE_ADD_MAX_ATTEMPTS} attempts`, committed: "no", code: "occ" };
}
export async function addPersistedRule(opts) {
const behavior = opts.behavior;
const ruleText = opts.rule;
const scope = structuredClone(opts.scope);
const target = opts.principal;
if (!isRuleBehavior(behavior)) {
return { status: "failed", error: `addPersistedRule: behavior ${escapeForDisclosure(behavior)} is not one of ${["deny", "ask", "allow"].join("/")} — refusing to name a rule identity nothing can carry`, committed: "no" };
}
if (behavior === "allow") {
return {
status: "failed",
error: "addPersistedRule: an allow cannot be written through this entry — a standing approval is a person's yes and takes a consent record (prepare → confirm → redeem); this entry writes the tightening direction (deny/ask) only",
committed: "no",
};
}
if (!isValidConsentScope(scope)) {
return { status: "failed", error: `addPersistedRule: ${escapeForDisclosure(JSON.stringify(scope))} is not a valid rule scope — refusing to write a row nothing can read back`, committed: "no" };
}
const parsed = parseRuleText(ruleText, behavior);
if ("reject" in parsed)
return { status: "failed", error: `addPersistedRule: ${parsed.reject.code}: ${parsed.reject.message}`, committed: "no" };
const identity = { behavior, rule: parsed.rule.rule, scope };
const owner = persistedRuleTargetOwner(target);
if (owner === undefined)
return { status: "failed", error: `addPersistedRule: ${NO_TARGET_OWNER} — refusing to write into a bucket nobody can name`, committed: "no" };
const provider = opts.provider;
if (owner.kind === "local-owner" && provider.forLocalOwner === undefined) {
return { status: "failed", error: "this provider has no local-owner bucket (forLocalOwner is not implemented) — a local-owner rule cannot be added through it", committed: "no" };
}
const store = owner.kind === "local-owner" ? provider.forLocalOwner() : provider.forPrincipal(owner.principal);
const face = resolveRuleWriter(store);
if ("unavailable" in face) {
return { status: "failed", error: `${face.unavailable} — rules cannot be added through it`, committed: face.committed };
}
const writer = face.writer;
const query = scope.kind === "session" ? { sessionId: scope.sessionId } : undefined;
let snapshot;
try {
snapshot = await store.effective(query);
}
catch (err) {
return { status: "failed", error: `could not read the permission-rule store: ${errText(err)}`, committed: "no" };
}
const fault = addReadFault(snapshot);
if (fault !== undefined)
return { status: "failed", error: `could not read the permission-rule store: ${fault}`, committed: "no" };
if (snapshot.rules.some((r) => sameRuleIdentity(r, identity) && isRuleLive(r)))
return { status: "no-op", rev: snapshot.rev };
let dot;
try {
dot = await writer.nextDot();
}
catch (err) {
return { status: "failed", error: `could not mint the add's dot: ${errText(err)}`, committed: "no" };
}
const landing = await landRuleAdd({
store,
writer,
delta: {
kind: "tighten-add",
behavior,
rule: parsed.rule.rule,
scope,
tool: parsed.rule.tool,
match: parsed.rule.match,
command: parsed.rule.command,
add: { dot, origin: "user", createdAt: new Date().toISOString() },
},
});
if (landing.landed)
return { status: "added", rev: landing.rev, dot };
if (landing.committed === "no")
return { status: "failed", error: landing.reason, committed: landing.committed };
try {
let rev;
let rows;
let quarantinedRows = [];
if (scope.kind === "session") {
const view = await store.effective(query);
if (view.unreadable !== undefined)
throw new Error(view.unreadable);
({ rev, rules: rows } = view);
}
else {
const raw = await writer.readRaw();
({ rev, rules: rows } = raw);
quarantinedRows = raw.quarantined ?? [];
}
const stood = rows.some((r) => sameRuleIdentity(r, identity) && holdsDot(r, dot)) ||
quarantinedRows.some((q) => sameDot(q.add.dot, dot));
return stood
? { status: "added", rev, dot }
: { status: "failed", error: `${landing.reason}; the store retains no trace of this add, which cannot tell a write that never landed from one whose evidence was collected — the outcome is indeterminate, reconcile with list()`, committed: landing.committed };
}
catch (err) {
return { status: "failed", error: `${landing.reason}; the read-back also failed (${errText(err)}) so this outcome is indeterminate — reconcile with list()`, committed: landing.committed };
}
}
export function errText(err) {
return thrownText(err);
}
export const EMPTY_DURABLE_RULE_PARTITION = {
list: async () => ({ rules: [], tombstones: [], rev: 0 }),
durability: "process-local",
};
export class InMemoryDurableRulePartition {
actor;
now;
durability = "process-local";
fidelity = "structured-clone";
rules = [];
tombstones = [];
quarantinedRows = [];
observedVector;
rev = 0;
counter = 0;
constructor(actor = `mem-${randomBytes(6).toString("base64url")}`, now = Date.now) {
this.actor = actor;
this.now = now;
}
async list() {
return {
rules: structuredClone(applyTombstones(this.rules, this.tombstones)),
tombstones: structuredClone(this.tombstones),
rev: this.rev,
};
}
async quarantined() {
return structuredClone(this.quarantinedRows);
}
[PERMISSION_RULE_WRITER] = {
nextDot: async () => ({ actor: this.actor, counter: ++this.counter }),
readRaw: async () => structuredClone({
actor: this.actor,
counter: this.counter,
rev: this.rev,
rules: this.rules,
tombstones: this.tombstones,
...(this.observedVector !== undefined ? { observedVector: this.observedVector } : {}),
quarantined: this.quarantinedRows,
}),
apply: async (delta, opts) => {
delta = structuredClone(delta);
if (opts.expectedRev !== this.rev)
return { conflict: true, rev: this.rev };
switch (delta.kind) {
case "redemption-add": {
assertWriteDeltaScopeDurable(delta);
assertRedemptionNotQuarantined(this.quarantinedRows, delta);
this.rules = foldDelta(this.rules, delta);
break;
}
case "tighten-add": {
assertWriteDeltaScopeDurable(delta);
this.rules = foldDelta(this.rules, delta);
break;
}
case "tighten-delete": {
assertWriteDeltaScopeDurable(delta);
assertDeleteDeltaCarriesNoAdd(delta);
this.tombstones = [...this.tombstones, delta.tombstone];
break;
}
case "sync-join": {
const { next, report } = applySyncJoin({
actor: this.actor,
counter: this.counter,
rules: this.rules,
tombstones: this.tombstones,
quarantined: this.quarantinedRows,
...(this.observedVector !== undefined ? { observedVector: this.observedVector } : {}),
}, delta, this.now());
this.rules = next.rules;
this.tombstones = next.tombstones;
this.quarantinedRows = next.quarantined;
this.observedVector = next.observedVector;
this.rev += 1;
return { rev: this.rev, sync: report };
}
default: {
const unhandled = delta;
throw unknownRuleWriteDeltaError(unhandled);
}
}
this.rev += 1;
return { rev: this.rev };
},
};
}