@runeditrun/rer 0.2.79 → 0.2.81

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (147) hide show
  1. package/README.md +17 -3
  2. package/cli/README.md +25 -13
  3. package/cli/authoring.mjs +14 -0
  4. package/cli/contract.mjs +25 -5
  5. package/cli/demo-host.mjs +4 -2
  6. package/cli/deploy-needs.mjs +4 -2
  7. package/cli/dev-identity.mjs +2 -2
  8. package/cli/export.mjs +1 -1
  9. package/cli/inspect.mjs +38 -2
  10. package/cli/ledger-refusal.mjs +18 -0
  11. package/cli/main.mjs +8 -2
  12. package/cli/managed-server.mjs +1 -1
  13. package/cli/parse.mjs +7 -6
  14. package/cli/portability-migrations.mjs +30 -11
  15. package/cli/portability-worker.mjs +4 -1
  16. package/cli/portability.mjs +8 -2
  17. package/cli/production-auth.mjs +2 -1
  18. package/cli/production-mail.mjs +36 -9
  19. package/cli/project.mjs +5 -14
  20. package/cli/release.mjs +6 -5
  21. package/cli/site-hosting.mjs +90 -0
  22. package/cli/site-preview.mjs +4 -1
  23. package/cli/site-render.mjs +3 -2
  24. package/cli/site.mjs +8 -4
  25. package/edition-authoring/adopt.mjs +39 -0
  26. package/edition-authoring/base-acknowledgements.mjs +24 -0
  27. package/edition-authoring/base-copies.mjs +427 -0
  28. package/edition-authoring/cli.mjs +85 -0
  29. package/edition-authoring/copy-checkout.mjs +69 -0
  30. package/edition-authoring/files.mjs +15 -2
  31. package/edition-authoring/lock.mjs +48 -0
  32. package/edition-authoring/offline-git.mjs +28 -0
  33. package/edition-authoring/parent-comparison.mjs +77 -0
  34. package/edition-authoring/projection-lock.mjs +38 -0
  35. package/edition-authoring/release.mjs +48 -0
  36. package/edition-authoring/runtime-dependencies.mjs +108 -0
  37. package/edition-authoring/sources.mjs +114 -0
  38. package/edition-authoring/updates.mjs +105 -0
  39. package/global/CHANGELOG.md +24 -0
  40. package/global/README.md +17 -3
  41. package/global/cli/install.mjs +3 -1
  42. package/global/main.mjs +9 -12
  43. package/modules/container/build.mjs +1 -1
  44. package/modules/d1-transport/index.mjs +68 -21
  45. package/modules/demo/README.md +16 -2
  46. package/modules/demo/declaration.mjs +21 -0
  47. package/modules/demo/input-path.mjs +18 -0
  48. package/modules/demo/label.d.mts +1 -1
  49. package/modules/demo/label.mjs +10 -5
  50. package/modules/demo/navigation.mjs +148 -0
  51. package/modules/demo/run-url.mjs +9 -0
  52. package/modules/demo/vite.d.mts +7 -2
  53. package/modules/demo/vite.mjs +17 -2
  54. package/modules/demo-host/README.md +5 -3
  55. package/modules/demo-host/page-style.mjs +2 -2
  56. package/modules/demo-host/pages.mjs +3 -3
  57. package/modules/demo-host/plan.mjs +6 -4
  58. package/modules/demo-host/theme.mjs +5 -2
  59. package/modules/dependencies/auth.mjs +2 -2
  60. package/modules/deploy-kit/README.md +19 -15
  61. package/modules/deploy-kit/owner-cli.mjs +1 -1
  62. package/modules/deploy-kit/owner.mjs +8 -1
  63. package/modules/deploy-kit/readiness-window.mjs +3 -3
  64. package/modules/erasure/README.md +10 -5
  65. package/modules/import-kit/src/d1/README.md +15 -9
  66. package/modules/import-kit/src/d1/apply-effects.ts +33 -0
  67. package/modules/import-kit/src/d1/apply.ts +46 -14
  68. package/modules/import-kit/src/d1/atomic-prefix.ts +64 -0
  69. package/modules/import-kit/src/d1/budget.ts +48 -26
  70. package/modules/import-kit/src/d1/compressed-plan.ts +9 -2
  71. package/modules/import-kit/src/d1/database.ts +2 -1
  72. package/modules/import-kit/src/d1/jobs.ts +2 -1
  73. package/modules/import-kit/src/d1/plans.ts +4 -2
  74. package/modules/import-kit/src/d1/verified-plan.ts +63 -0
  75. package/modules/import-kit/src/types.ts +3 -1
  76. package/modules/integrations/core/README.md +2 -2
  77. package/modules/mail/README.md +4 -3
  78. package/modules/mail/pnpm-lock.yaml +16 -0
  79. package/modules/operator-auth/README.md +92 -3
  80. package/modules/operator-auth/accounts/admin.mjs +52 -20
  81. package/modules/operator-auth/accounts/audit.mjs +24 -0
  82. package/modules/operator-auth/accounts/business-team.mjs +91 -0
  83. package/modules/operator-auth/accounts/domain-audit.mjs +24 -0
  84. package/modules/operator-auth/accounts/native.mjs +6 -2
  85. package/modules/operator-auth/accounts/provider-control.mjs +7 -4
  86. package/modules/operator-auth/accounts/provider-setup.mjs +34 -0
  87. package/modules/operator-auth/accounts/settings-page.mjs +26 -4
  88. package/modules/operator-auth/accounts/status.mjs +7 -2
  89. package/modules/operator-auth/accounts/store.mjs +32 -6
  90. package/modules/operator-auth/business-settings.mjs +40 -0
  91. package/modules/operator-auth/conformance/README.md +1 -1
  92. package/modules/operator-auth/dev/index.mjs +22 -4
  93. package/modules/operator-auth/dev/refusal.mjs +19 -0
  94. package/modules/operator-auth/docs/README.md +6 -5
  95. package/modules/operator-auth/docs/tanstack-start.md +1 -1
  96. package/modules/operator-auth/docs/vite-spa.md +5 -6
  97. package/modules/operator-auth/identity/email-link/index.mjs +1 -1
  98. package/modules/operator-auth/identity/oidc/admin-audit.mjs +31 -0
  99. package/modules/operator-auth/identity/oidc/index.mjs +12 -5
  100. package/modules/operator-auth/identity/oidc/store.mjs +2 -0
  101. package/modules/operator-auth/index.d.mts +41 -2
  102. package/modules/operator-auth/page.mjs +14 -0
  103. package/modules/operator-auth/representation.mjs +83 -0
  104. package/modules/operator-auth/routes.mjs +31 -3
  105. package/modules/operator-auth/service.mjs +8 -3
  106. package/modules/operator-auth/signin/index.mjs +1 -1
  107. package/modules/portability/README.md +173 -15
  108. package/modules/portability/bookkeeping.mjs +3 -3
  109. package/modules/portability/bridge.mjs +5 -4
  110. package/modules/portability/catalogue.mjs +12 -8
  111. package/modules/portability/cli.mjs +5 -1
  112. package/modules/portability/export.mjs +10 -14
  113. package/modules/portability/format.mjs +12 -1
  114. package/modules/portability/http-errors.mjs +51 -0
  115. package/modules/portability/http.mjs +4 -1
  116. package/modules/portability/import-lease.mjs +13 -2
  117. package/modules/portability/import.mjs +10 -0
  118. package/modules/portability/index.d.mts +13 -2
  119. package/modules/portability/index.mjs +3 -2
  120. package/modules/portability/ledgers.mjs +27 -4
  121. package/modules/portability/references.mjs +20 -0
  122. package/modules/portability/schema-identity.mjs +13 -0
  123. package/modules/portability/schema-legacy.mjs +21 -0
  124. package/modules/portability/sqlite-tokens.mjs +121 -0
  125. package/modules/release/README.md +94 -11
  126. package/modules/release/github-verify.mjs +30 -9
  127. package/modules/release/sign.mjs +4 -2
  128. package/modules/release/signature.mjs +14 -7
  129. package/modules/release/signing-cli.mjs +2 -1
  130. package/modules/release/statement.mjs +2 -2
  131. package/modules/release/vectors/generate.mjs +1 -0
  132. package/modules/release/vectors/publisher-projects.mjs +133 -0
  133. package/modules/release/vectors/release-signature-vectors.json +5195 -0
  134. package/modules/release/verify.mjs +5 -1
  135. package/modules/site/docs-search/search.css +1 -1
  136. package/onboarding/README.md +16 -4
  137. package/onboarding/adapter.mjs +5 -1
  138. package/onboarding/schema/SETUP.schema.json +68 -1
  139. package/onboarding/schema/business-field-inputs.mjs +36 -0
  140. package/onboarding/schema/json-schema.mjs +6 -2
  141. package/onboarding/schema/setup-validation.mjs +23 -3
  142. package/onboarding/server.mjs +1 -1
  143. package/onboarding/setup-manifest.mjs +2 -0
  144. package/onboarding/start-origin-diagnostic.mjs +24 -0
  145. package/onboarding/ui/style.css +9 -9
  146. package/package.json +1 -1
  147. package/scripts/publish-check/README.md +1 -1
@@ -0,0 +1,64 @@
1
+ import type { ImportAction } from '../types.ts';
2
+ import type { D1ImportContext, D1Sql } from './types.ts';
3
+ import type { NativeStagingScope } from './native-staging-context.ts';
4
+ import { GuardPacking, valueBytes } from './budget.ts';
5
+ import { authority, finalAuthority, postConditions, sql } from './database.ts';
6
+
7
+ /** Unbounded publication has append-only SQL and final checks. Bounded native
8
+ * staging derives an ExpectedState from the complete transaction instead. */
9
+ export function atomicPrefix(context: D1ImportContext, action: ImportAction, statements: D1Sql[], scope: NativeStagingScope) {
10
+ if (context.maxBatchBytes !== undefined) return undefined;
11
+ type Part = { statements: D1Sql[]; unchanged: () => boolean; prior?: Part };
12
+ const observe = (statement: D1Sql): (() => boolean) => {
13
+ const text = statement.sql, params = [...statement.params ?? []], sizes = params.map(p => p instanceof ArrayBuffer || ArrayBuffer.isView(p) ? valueBytes(p) : undefined);
14
+ const checks = [...statement.finalChecks ?? []], unchanged = checks.map(observe);
15
+ return () => statement.sql === text && (statement.params?.length ?? 0) === params.length
16
+ && params.every((p, i) => p === statement.params![i] && (sizes[i] === undefined || sizes[i] === valueBytes(p)))
17
+ && (statement.finalChecks?.length ?? 0) === checks.length && checks.every((check, i) => check === statement.finalChecks![i] && unchanged[i]());
18
+ };
19
+ const part = (statements: D1Sql[], prior?: Part): Part => {
20
+ const checks = statements.map(observe);
21
+ return { statements: [...statements], prior, unchanged: () => checks.every(check => check()) };
22
+ };
23
+ const same = (a: D1Sql, b: D1Sql) => a.sql === b.sql && (a.params?.length ?? 0) === (b.params?.length ?? 0) && (a.params ?? []).every((p, i) => p === b.params![i]);
24
+ const collect = (part: Part): D1Sql[] => {
25
+ const parts: D1Sql[][] = [];
26
+ for (let current: Part | undefined = part; current; current = current.prior) parts.push(current.statements);
27
+ return parts.reverse().flat();
28
+ };
29
+ class Prefix {
30
+ private writes?: GuardPacking;
31
+ private first?: D1Sql;
32
+ private firstUnchanged?: () => boolean;
33
+ private part: Part;
34
+ private post: GuardPacking;
35
+ private postLength: number;
36
+ constructor(part: Part, post: GuardPacking, postLength: number, prior?: Prefix) {
37
+ this.part = part; this.post = post; this.postLength = postLength;
38
+ if (prior) { this.writes = prior.writes?.fork().append(part.statements); this.first = prior.first; this.firstUnchanged = prior.firstUnchanged; }
39
+ }
40
+ extend(added: D1Sql[]): Prefix {
41
+ const checks = added.flatMap(s => s.finalChecks ?? []);
42
+ return new Prefix(part(added, this.part), this.post.fork().append(checks), this.postLength + checks.length, this);
43
+ }
44
+ count(tail: D1Sql[], returnReads: number): number {
45
+ // Authority is evaluated afresh even when its SQL remains equivalent.
46
+ const first = authority(context, action);
47
+ let changed = false;
48
+ for (let current: Part | undefined = this.part; current; current = current.prior) changed ||= !current.unchanged();
49
+ if (changed) {
50
+ const post = postConditions(context, collect(this.part), scope, action);
51
+ this.post = new GuardPacking().append(post); this.postLength = post.length;
52
+ }
53
+ if (changed || !this.writes || !this.first || !same(first, this.first) || !this.firstUnchanged?.()) {
54
+ this.writes = new GuardPacking().append([first, ...collect(this.part)]); this.first = first; this.firstUnchanged = observe(first);
55
+ }
56
+ const writes = this.writes.count([...tail, authority(context, action), sql('DELETE FROM ik_d1_assertions')]);
57
+ const checks = tail.flatMap(s => s.finalChecks ?? []), post = this.post.count(checks);
58
+ if (this.postLength + checks.length) finalAuthority(context, action);
59
+ return writes + post + Number(this.postLength + checks.length > 0) + returnReads;
60
+ }
61
+ }
62
+ const post = postConditions(context, statements, scope, action);
63
+ return new Prefix(part(statements), new GuardPacking().append(post), post.length);
64
+ }
@@ -57,33 +57,55 @@ function conjunction(predicates: string[], start = 0, end = predicates.length):
57
57
  }
58
58
  /** Adjacent assertions can share one CHECK without changing transactional order.
59
59
  * Native statements remain between their original pre/postconditions. */
60
- export function packGuards(statements: D1Sql[], readOnly = false): D1Sql[] {
61
- const prefix = readOnly ? 'SELECT CASE WHEN (' : 'INSERT INTO ik_d1_assertions(ok) SELECT CASE WHEN (';
62
- const suffix = readOnly ? ') THEN 1 ELSE 0 END AS ok' : ') THEN 1 ELSE 0 END';
63
- const result: D1Sql[] = []; const seen = new Map<string, D1Sql[]>(); let predicates: string[] = [], params: any[] = [], bytes = 0;
64
- const flush = () => {
65
- if (predicates.length) {
66
- // A flat AND list becomes a left-deep SQLite expression tree. Keep the
67
- // added depth logarithmic without changing predicates or binding order.
68
- const text=conjunction(predicates),packed = readOnly ? { sql: `${prefix}${text}${suffix}`, params } : guard({sql:text,params});
69
- checkSql(packed); result.push(packed);
60
+ /** Append-only state for the exact same packing algorithm. Count-only forks
61
+ * retain the open guard run, never copy or rebuild the already packed prefix. */
62
+ export class GuardPacking {
63
+ private seen = new Map<string, D1Sql[]>();
64
+ private predicates: string[] = [];
65
+ private params: any[] = [];
66
+ private bytes = 0;
67
+ private values = 0;
68
+ private completed = 0;
69
+ private output: D1Sql[] | undefined;
70
+ private readOnly: boolean;
71
+ constructor(readOnly = false, collect = false) { this.readOnly = readOnly; if (collect) this.output = []; }
72
+ fork(): GuardPacking {
73
+ const next = new GuardPacking(this.readOnly);
74
+ next.seen = new Map([...this.seen].map(([key, value]) => [key, [...value]]));
75
+ next.predicates = [...this.predicates]; next.params = [...this.params];
76
+ next.bytes = this.bytes; next.values = this.values; next.completed = this.completed;
77
+ return next;
78
+ }
79
+ private flush(): void {
80
+ if (this.predicates.length) {
81
+ const text = conjunction(this.predicates), packed = this.readOnly
82
+ ? { sql: `SELECT CASE WHEN (${text}) THEN 1 ELSE 0 END AS ok`, params: this.params }
83
+ : guard({ sql: text, params: this.params });
84
+ checkSql(packed); this.output?.push(packed); this.completed++;
70
85
  }
71
- predicates = []; params = []; bytes = 0;
72
- };
73
- for (const statement of statements) {
74
- checkSql(statement);
75
- const predicate = guardPredicate(statement);
76
- if (!predicate) {
77
- if (readOnly) throw new Error('IMPORT_READ_GUARD_REQUIRED');
78
- flush(); seen.clear(); result.push(statement); continue;
86
+ this.predicates = []; this.params = []; this.bytes = this.values = 0;
87
+ }
88
+ append(statements: D1Sql[]): this {
89
+ for (const statement of statements) {
90
+ checkSql(statement);
91
+ const predicate = guardPredicate(statement);
92
+ if (!predicate) {
93
+ if (this.readOnly) throw new Error('IMPORT_READ_GUARD_REQUIRED');
94
+ this.flush(); this.seen.clear(); this.output?.push(statement); this.completed++; continue;
95
+ }
96
+ const prior = this.seen.get(statement.sql) ?? [];
97
+ if (prior.some(s => (s.params?.length ?? 0) === (statement.params?.length ?? 0) && (s.params ?? []).every((p, i) => p === statement.params![i]))) continue;
98
+ prior.push(statement); this.seen.set(statement.sql, prior);
99
+ const params = predicate.params ?? [], text = `(${predicate.sql})`;
100
+ const bytes = Buffer.byteLength(text), values = params.reduce((n, p) => n + valueBytes(p), 0);
101
+ if (this.predicates.length && (this.params.length + params.length > 100 || this.bytes + bytes > 90000 || this.values + values > 1500000 || this.predicates.length >= 50)) this.flush();
102
+ this.predicates.push(text); this.params.push(...params); this.bytes += bytes; this.values += values;
79
103
  }
80
- const prior = seen.get(statement.sql) ?? [];
81
- if (prior.some(s => (s.params?.length ?? 0) === (statement.params?.length ?? 0) && (s.params ?? []).every((p, i) => p === statement.params![i]))) continue;
82
- prior.push(statement); seen.set(statement.sql, prior);
83
- const p = predicate.params ?? [], text = `(${predicate.sql})`;
84
- const nextBytes = Buffer.byteLength(text);
85
- if (predicates.length && (params.length + p.length > 100 || bytes + nextBytes > 90000 || params.reduce((n, p) => n + valueBytes(p), 0) + p.reduce((n, p) => n + valueBytes(p), 0) > 1500000 || predicates.length >= 50)) flush();
86
- predicates.push(text); params.push(...p); bytes += nextBytes;
104
+ return this;
87
105
  }
88
- flush(); return result;
106
+ count(tail: D1Sql[] = []): number { const next = this.fork().append(tail); next.flush(); return next.completed; }
107
+ finish(): D1Sql[] { this.flush(); return this.output!; }
108
+ }
109
+ export function packGuards(statements: D1Sql[], readOnly = false): D1Sql[] {
110
+ return new GuardPacking(readOnly, true).append(statements).finish();
89
111
  }
@@ -6,6 +6,7 @@ import type { D1PlanCodec } from './types.ts';
6
6
  import { planFingerprint } from '../plan/index.ts';
7
7
  import { canonicalHash, canonicalSize, canonicalChunks, cloneJson } from '../provenance/canonical-stream.ts';
8
8
  import { canonicalJson, sha256 } from '../provenance/identity.ts';
9
+ import { ownDecodedPlan, reusedExpansion, retainVerifiedExpansion, type PlanReadScope } from './verified-plan.ts';
9
10
 
10
11
  function validateRoundTrip(plan: ImportPlan, payload: Json, codec: D1PlanCodec): void {
11
12
  const roundtrip = codec.decode(cloneJson(payload));
@@ -25,7 +26,7 @@ export function expandCompressedPlan(body: string, codec?: D1PlanCodec): ImportP
25
26
  }
26
27
  /** Custody loading already parses the envelope to distinguish storage formats.
27
28
  * Reuse that object, still comparing its complete canonical bytes with body. */
28
- export function expandCompressedEnvelope(body: string, value: any, codec?: D1PlanCodec): ImportPlan {
29
+ export function expandCompressedEnvelope(body: string, value: any, codec?: D1PlanCodec, scope?: PlanReadScope): ImportPlan {
29
30
  if (!value || typeof value !== 'object' || Array.isArray(value)) throw new Error('STORED_PLAN_CHANGED');
30
31
  if (canonicalHash(value) !== sha256(body)) throw new Error('STORED_PLAN_CHANGED');
31
32
  if (![2,3].includes(value.d1Plan) || !Number.isSafeInteger(value.size) || value.size < 0) throw new Error('STORED_PLAN_CHANGED');
@@ -35,12 +36,18 @@ export function expandCompressedEnvelope(body: string, value: any, codec?: D1Pla
35
36
  if (value.compression !== undefined && value.compression !== 'brotli') throw new Error('STORED_PLAN_CHANGED');
36
37
  if (value.d1Plan === 3 && (!Number.isSafeInteger(value.expandedSize) || value.expandedSize < 0)) throw new Error('STORED_PLAN_CHANGED');
37
38
  if (value.d1Plan === 3 && value.dictionary === 2 && (!Number.isSafeInteger(value.payloadSize) || value.payloadSize < 0)) throw new Error('STORED_PLAN_CHANGED');
39
+ // loadPlans has freshly checked the complete manifest and chunk bytes. Only
40
+ // this exact request/body/codec can reuse its already verified expansion.
41
+ const prior = scope && reusedExpansion(scope, body, codec);
42
+ if (prior) return prior;
38
43
  const payload = decodePayload(value, codec);
39
44
  const payloadHash = value.d1Plan === 3 ? canonicalHash(payload) : undefined;
40
- const plan = (value.d1Plan === 3 ? codec!.decode(payload) : payload) as ImportPlan;
45
+ const decoded = (value.d1Plan === 3 ? codec!.decode(payload) : payload) as ImportPlan;
46
+ const plan = scope ? ownDecodedPlan(decoded) : decoded;
41
47
  if (value.d1Plan === 3 && canonicalHash(codec!.encode(plan)) !== payloadHash) throw new Error('STORED_PLAN_CHANGED');
42
48
  if (value.d1Plan === 3 && plan.fingerprint !== value.fingerprint) throw new Error('STORED_PLAN_CHANGED');
43
49
  if (value.d1Plan === 3 && canonicalSize(plan) !== value.expandedSize) throw new Error('STORED_PLAN_CHANGED');
50
+ if (scope) return retainVerifiedExpansion(scope, body, plan, codec);
44
51
  if (planFingerprint(plan) !== plan.fingerprint) throw new Error('STORED_PLAN_CHANGED');
45
52
  return plan;
46
53
  }
@@ -99,7 +99,7 @@ export async function atomic(context: D1ImportContext, action: ImportAction, sta
99
99
  }
100
100
  await context.storage.database.batch(packed.map(s => prepare(context.storage.database, s)));
101
101
  }
102
- function postConditions(context:Pick<D1ImportContext,'maxBatchBytes'>,statements:D1Sql[],scope?:NativeStagingScope,action:ImportAction='read'):D1Sql[]{
102
+ export function postConditions(context:Pick<D1ImportContext,'maxBatchBytes'>,statements:D1Sql[],scope?:NativeStagingScope,action:ImportAction='read'):D1Sql[]{
103
103
  const stream = scope ? [...jobLayoutGuards(scope.job), ...streamBoundary(scope.job.id, action)] : [];
104
104
  if(context.maxBatchBytes===undefined)return [...stream,...statements.flatMap(statement=>statement.finalChecks??[])];
105
105
  const readOnly=statements.every(s=>guardPredicate(s));
@@ -132,6 +132,7 @@ function atomicPreparation(context:Parameters<typeof authority>[0]&Pick<D1Import
132
132
  const packed=[...atomicStatements(context,action,statements),...readonlyChecks(post),...(post.length?[finalAuthority(context,action)]:[])];
133
133
  return {post,packed,count:packed.length+returnReads};
134
134
  }
135
+ export { atomicPrefix } from './atomic-prefix.ts';
135
136
  /** SELECT-only fence: inspect every packed scalar before publishing snapshots.
136
137
  * Mutations continue to use atomic() and SQL CHECK rollback, never this path. */
137
138
  export async function readAtomic(context: D1ImportContext, guards: D1Sql[], scope?: NativeStagingScope, action: ImportAction = 'read'): Promise<void> {
@@ -16,6 +16,7 @@ import { guardErasedSources } from './erasure-claims.ts';
16
16
  import { readOriginals } from './originals.ts';
17
17
  import { retiredError } from './retirement.ts';
18
18
  import { attachReversal, loadReversalState, reversalGuards, reversalState } from './undo-state.ts';
19
+ import { verifiedPlanFingerprint } from './verified-plan.ts';
19
20
 
20
21
  export function decode(row: any): ImportJob {
21
22
  return { id: row.id, fingerprint: row.fingerprint, destination: row.destination, namespace: row.namespace, mappingVersion: row.mapping_version, principalId: row.principal_id, state: row.state, checkpoint: row.checkpoint, total: row.total, fence: row.fence, error: row.error };
@@ -33,7 +34,7 @@ export async function stored(id: string, context: D1ImportContext, action: Impor
33
34
  planReads.set(job, planChunkReads(row.plan_json, fenced));
34
35
  if (job.destination !== context.destination || job.namespace !== context.namespace || job.mappingVersion !== context.mappingVersion || job.principalId !== context.authorization.principalId) throw new Error('JOB_BINDING_MISMATCH');
35
36
  if (context.reviewedFingerprint !== undefined && context.reviewedFingerprint !== job.fingerprint) throw new Error('REVIEW_FINGERPRINT_MISMATCH');
36
- if (planFingerprint(plan) !== job.fingerprint || plan.fingerprint !== job.fingerprint || plan.destination !== job.destination || plan.namespace !== job.namespace || plan.mappingVersion !== job.mappingVersion || plan.principalId !== job.principalId || plan.entries.length !== job.total) throw new Error('STORED_PLAN_CHANGED');
37
+ if ((verifiedPlanFingerprint(plan) ?? planFingerprint(plan)) !== job.fingerprint || plan.fingerprint !== job.fingerprint || plan.destination !== job.destination || plan.namespace !== job.namespace || plan.mappingVersion !== job.mappingVersion || plan.principalId !== job.principalId || plan.entries.length !== job.total) throw new Error('STORED_PLAN_CHANGED');
37
38
  job.erasedRecords = plan.entries.filter(entry => entry.erased).length;
38
39
  attachReversal(job, await loadReversalState(row, plan, context));
39
40
  await captureJobLayout(job, row, context, action);
@@ -2,6 +2,7 @@ import { retainedSql } from './retained-values.ts';
2
2
  import { changedLazy, putRow } from './expected-state.ts';
3
3
  import { compressedPlan, storedStreamPage } from './stream-plan.ts';
4
4
  import { expandCompressedEnvelope } from './compressed-plan.ts';
5
+ import { planReadScope } from './verified-plan.ts';
5
6
  import { Buffer } from 'node:buffer';
6
7
  import { createHash } from 'node:crypto';
7
8
  import type { ImportPlan } from '../types.ts';
@@ -79,6 +80,7 @@ export async function loadPlans(rows: any[], db: D1Database, codec?: D1PlanCodec
79
80
  }
80
81
  }
81
82
  for (const row of rows) {
83
+ const scope = planReadScope(db, row.id, row.plan_json, codec);
82
84
  const parsed = JSON.parse(row.plan_json), parts = chunks.filter(c => c.job_id === row.id);
83
85
  let plan: ImportPlan, compressed = false;
84
86
  if (parsed?.d1Plan === 1) {
@@ -86,11 +88,11 @@ export async function loadPlans(rows: any[], db: D1Database, codec?: D1PlanCodec
86
88
  const body = parts.map(c => c.body).join('');
87
89
  if (Buffer.byteLength(body) !== parsed.size || sha256(body) !== parsed.sha256) throw new Error('STORED_PLAN_CHANGED');
88
90
  const payload = JSON.parse(body);
89
- if ([2,3].includes(payload?.d1Plan)) { if (parsed.entries !== undefined) throw new Error('STORED_PLAN_CHANGED'); plan = expandCompressedEnvelope(body,payload,codec); compressed = true; }
91
+ if ([2,3].includes(payload?.d1Plan)) { if (parsed.entries !== undefined) throw new Error('STORED_PLAN_CHANGED'); plan = expandCompressedEnvelope(body,payload,codec,scope); compressed = true; }
90
92
  else { if (canonicalHash(payload) !== parsed.sha256) throw new Error('STORED_PLAN_CHANGED'); plan = payload; }
91
93
  // The entry locator a referenced read trusts must describe these exact chunks.
92
94
  if (parsed.entries !== undefined && canonicalJson(entryLocator(plan, parts)) !== canonicalJson(parsed.entries)) throw new Error('STORED_PLAN_CHANGED');
93
- } else plan = [2,3].includes(parsed?.d1Plan) ? expandCompressedEnvelope(row.plan_json,parsed,codec) : parsed;
95
+ } else plan = [2,3].includes(parsed?.d1Plan) ? expandCompressedEnvelope(row.plan_json,parsed,codec,scope) : parsed;
94
96
  const captured = fences.get(row.id);
95
97
  snapshots.set(plan, { body: row.plan_json, chunks: parts, ...(row.custody_revision === undefined ? {} : {revision: row.custody_revision}), ...(compressed ? {compressed} : {}), ...(captured === undefined ? {} : {fence: captured}) }); result.set(row.id, plan);
96
98
  }
@@ -0,0 +1,63 @@
1
+ import type { ImportPlan } from '../types.ts';
2
+ import { planFingerprint } from '../plan/index.ts';
3
+ import { cloneJson } from '../provenance/canonical-stream.ts';
4
+ import type { D1Database, D1PlanCodec } from './types.ts';
5
+
6
+ export interface PlanReadScope { database: D1Database; jobId: string; storedBody: string }
7
+ interface VerifiedExpansion {
8
+ jobId: string; storedBody: string; body: string; codecId?: string;
9
+ encode?: D1PlanCodec['encode']; decode?: D1PlanCodec['decode'];
10
+ plan: ImportPlan; fingerprint: string;
11
+ }
12
+ // One active child per request database bounds retention. This contains no job
13
+ // progress, custody fence or authority result; those are read on every load.
14
+ const expansions = new WeakMap<D1Database, VerifiedExpansion>();
15
+ const owned = new WeakSet<ImportPlan>();
16
+ const fingerprints = new WeakMap<ImportPlan, string>();
17
+
18
+ /** Visit ordinary plans too: changing away from compressed custody invalidates
19
+ * its previous receipt even if a later read returns to those old bytes. */
20
+ export function planReadScope(database: D1Database, jobId: string, storedBody: string, codec?: D1PlanCodec): PlanReadScope {
21
+ const prior = expansions.get(database);
22
+ if (prior && (prior.jobId !== jobId || prior.storedBody !== storedBody || prior.codecId !== codec?.id || prior.encode !== codec?.encode || prior.decode !== codec?.decode)) expansions.delete(database);
23
+ return { database, jobId, storedBody };
24
+ }
25
+
26
+ /** Codec callbacks may retain aliases. Own every container before protecting
27
+ * the graph whose verified fingerprint will survive awaited database reads. */
28
+ export function ownDecodedPlan(plan: ImportPlan): ImportPlan {
29
+ const result = cloneJson(plan);
30
+ const freeze = (value: unknown): void => {
31
+ if (value === null || typeof value !== 'object' || Object.isFrozen(value)) return;
32
+ for (const child of Object.values(value)) freeze(child);
33
+ Object.freeze(value);
34
+ };
35
+ freeze(result); owned.add(result);
36
+ return result;
37
+ }
38
+
39
+ /** A fresh root keeps plans.ts custody snapshots independent even when their
40
+ * immutable content is shared by overlapping reads of the same request. */
41
+ function readView(expansion: VerifiedExpansion): ImportPlan {
42
+ const plan = Object.freeze({ ...expansion.plan });
43
+ fingerprints.set(plan, expansion.fingerprint);
44
+ return plan;
45
+ }
46
+ export function reusedExpansion(scope: PlanReadScope, body: string, codec?: D1PlanCodec): ImportPlan | undefined {
47
+ const prior = expansions.get(scope.database);
48
+ if (prior?.jobId === scope.jobId && prior.storedBody === scope.storedBody && prior.body === body && prior.codecId === codec?.id && prior.encode === codec?.encode && prior.decode === codec?.decode) return readView(prior);
49
+ // A changed body, job or codec must never recover an earlier receipt later.
50
+ expansions.delete(scope.database);
51
+ return undefined;
52
+ }
53
+ export function retainVerifiedExpansion(scope: PlanReadScope, body: string, plan: ImportPlan, codec?: D1PlanCodec): ImportPlan {
54
+ if (!owned.has(plan)) throw new Error('IMPORT_PLAN_VERIFICATION_REQUIRED');
55
+ const fingerprint = planFingerprint(plan);
56
+ if (fingerprint !== plan.fingerprint) throw new Error('STORED_PLAN_CHANGED');
57
+ const expansion = { jobId: scope.jobId, storedBody: scope.storedBody, body, codecId: codec?.id, encode: codec?.encode, decode: codec?.decode, plan, fingerprint };
58
+ expansions.set(scope.database, expansion);
59
+ return readView(expansion);
60
+ }
61
+ /** Only owned immutable decoded graphs receive this receipt. Caller-owned
62
+ * creation plans and ordinary mutable decoded plans still need a full hash. */
63
+ export const verifiedPlanFingerprint = (plan: ImportPlan): string | undefined => fingerprints.get(plan);
@@ -12,7 +12,9 @@ export interface SourceArtifact { name: string; sha256: string; size: number; or
12
12
  export interface RetainedOriginal { jobId: string; kind: 'artifact' | 'attachment'; key: string; name: string; sha256: string; size: number; original: { status: 'retained'; base64: string } | UnavailableOriginal }
13
13
  /** Exact noncredential pagination query key; strict credential policy when omitted. */
14
14
  export type PaginationCursorPolicy = 'page-token-v1';
15
- export interface SourceBundle { paginationCursorPolicy?: PaginationCursorPolicy; records: SourceRecord[]; artifacts: SourceArtifact[]; diagnostics: Diagnostic[] }
15
+ /** The door's sanitized form is the original custody, never the user's raw file. */
16
+ export interface IntakeCustody { sanitized: true; allowlistSha256: string; inputFormat: 'csv' | 'ndjson' | 'json'; custodyFormat: 'ndjson' }
17
+ export interface SourceBundle { intake?: IntakeCustody; paginationCursorPolicy?: PaginationCursorPolicy; records: SourceRecord[]; artifacts: SourceArtifact[]; diagnostics: Diagnostic[] }
16
18
  export interface ReaderLimits { maxBytes?: number; maxRecords?: number; maxRecordBytes?: number }
17
19
  export interface ParsedRecord { kind: string; sourceId: string; payload: Json; pointer?: string }
18
20
  /** 'refuse' (the default) rejects a source holding a credential value; 'remove'
@@ -4,10 +4,10 @@ Import portable delivery, signed webhook, token and D1 APIs from `./index.ts`.
4
4
  Import Node adapters explicitly from `./sqlite.ts` and `./node-transport.ts`.
5
5
  Node 26 is the tested runtime; no runtime npm dependency is needed.
6
6
 
7
- The [consumer guide](../README.md) contains fresh SQLite migration, enqueue and
7
+ The [consumer guide](https://github.com/runeditrun/base/blob/main/modules/integrations/README.md) contains fresh SQLite migration, enqueue and
8
8
  Worker scheduling examples. The [public contract](CONTRACT.md) defines exact
9
9
  HMAC framing, retry outcomes, durable replay and same-database token authority.
10
- The [receiver guide](../receiver.md) supplies executable Node and Fetch receiver
10
+ The [receiver guide](https://github.com/runeditrun/base/blob/main/modules/integrations/receiver.md) supplies executable Node and Fetch receiver
11
11
  boundaries that verify original bytes before claiming replay identities.
12
12
 
13
13
  Apply `schema.sql` once through the application's numbered migration ledger.
@@ -43,6 +43,7 @@ modules/mail/src/adapters/sendgrid/index.mjs
43
43
  modules/mail/src/adapters/sendgrid/serialize.mjs
44
44
  modules/mail/src/adapters/rer/contract.mjs
45
45
  modules/mail/src/adapters/rer/index.mjs
46
+ modules/mail/src/adapters/rer/list-headers.mjs
46
47
  modules/mail/src/adapters/messaging/contract.mjs
47
48
  modules/mail/src/adapters/messaging/event-schema.mjs
48
49
  modules/mail/src/adapters/messaging/index.mjs
@@ -118,14 +119,14 @@ These are for developing the module itself or documentation. A seed may keep any
118
119
  - `modules/mail/README.md` and every `README.md` under `modules/mail/src/`
119
120
 
120
121
  The provider is explicit: `sendgrid`, `resend`, `cloudflare`, `rer`, `messaging`, or `development`.
121
- `mode` is required (`production`, `development`, or `test`). Remote providers require `apiKey`; Cloudflare additionally requires a 32-hex `accountId`. A remote provider in test/development mode still makes a real provider request unless the caller explicitly supplies a test fetch. Missing credentials, validation errors, or provider failure never select another provider. Config and messages reject unknown fields so requested features cannot silently disappear.
122
+ `mode` is required (`production`, `development`, or `test`). SendGrid, Resend, Cloudflare and RER require `apiKey`; Cloudflare additionally requires a 32-hex `accountId`. Messaging instead requires its signed-link configuration (`serviceOrigin`, `installId`, `kid` and `signingKey`) and rejects `apiKey` and `accountId`. A remote provider in test/development mode still makes a real provider request unless the caller explicitly supplies a test fetch. Missing credentials, validation errors, or provider failure never select another provider. Config and messages reject unknown fields so requested features cannot silently disappear.
122
123
 
123
124
  `createMailSender(config, dependencies?)` returns `{send(message)}`. Dependencies are optional standard `fetch`, `clock: () => epochMilliseconds`, and `timeoutMilliseconds` (a positive safe integer bounding each remote attempt; the default is 15,000). Production normally uses global fetch. Direct provider endpoints are fixed; `rer` uses its assigned relay URL. No retry or automatic replay exists. The sender snapshots configuration at construction and the message at submission.
124
125
 
125
126
  ### Managed mail through RER
126
127
 
127
128
  Seeds opt into Managed mail with `mail: {providers: ["rer"]}` in their candidate
128
- deployment spec. The [delivery producer](../delivery-producer/README.md#managed-mail)
129
+ deployment spec. The [delivery producer](https://github.com/runeditrun/base/blob/main/modules/delivery-producer/README.md#managed-mail)
129
130
  can generate the matching setup fields. RER assigns public `MAIL_PROVIDER`,
130
131
  `MAIL_FROM`, `MAIL_RELAY_URL` and private `MAIL_API_KEY`; Managed owners do not
131
132
  enter them. Wire those settings into the shared sender:
@@ -202,7 +203,7 @@ adapter makes no retries and never reads or logs provider error bodies.
202
203
 
203
204
  ## Message and results
204
205
 
205
- Required fields: `deliveryId` (nonempty, at most 512 characters), `from`, nonempty `to: string[]`, `subject: string` (SendGrid requires nonempty; other providers allow empty), and at least one nonempty `text` or `html`. Addresses accept a mailbox or `Display Name <mailbox>`; the conservative mailbox grammar rejects controls, multiple addresses inside one string and malformed domains. Use arrays for recipients.
206
+ Required fields: `deliveryId` (nonempty, at most 512 characters), `from`, nonempty `to: string[]`, `subject: string` (SendGrid requires nonempty; RER requires nonblank and at most 200 characters; other providers allow empty), and at least one nonempty `text` or `html`. Addresses accept a mailbox or `Display Name <mailbox>`; the conservative mailbox grammar rejects controls, multiple addresses inside one string and malformed domains. Use arrays for recipients.
206
207
 
207
208
  Optional `cc`, `bcc`, `replyTo`, and string-valued `headers` preserve envelope and threading. `In-Reply-To` and ordered `References` can be supplied as headers. SendGrid and Resend also accept `Message-ID`; Cloudflare generates it and rejects a caller-supplied value; `rer` rejects it and assigns one from an optional `messageKey`. CR/LF/control characters, duplicate header names ignoring case, reserved envelope/MIME/security headers and invalid header names fail before a request. Provider-specific header restrictions are also enforced.
208
209
 
@@ -91,89 +91,105 @@ packages:
91
91
  resolution: {integrity: sha512-Y3dgX/6lE2QhQb+Gxy0WZxfg9MEm/JBjamZpS2IklP7xIQoKN4hzAm7KcMVGtaVDt3neE9OKBC7vAfonA/Lr1A==}
92
92
  cpu: [arm64]
93
93
  os: [linux]
94
+ libc: [glibc]
94
95
 
95
96
  '@img/sharp-libvips-linux-arm@1.3.4':
96
97
  resolution: {integrity: sha512-LmRtTsOHuvM2+wlO2Db37dx5MiZhB0FvSunciw48YjdOkZz9KAiRbm8ujeMOA1INqmei5NapFxYEK1D1ZSidmw==}
97
98
  cpu: [arm]
98
99
  os: [linux]
100
+ libc: [glibc]
99
101
 
100
102
  '@img/sharp-libvips-linux-ppc64@1.3.4':
101
103
  resolution: {integrity: sha512-Le6boB8Tai0Nis+gIxIpKx68UDVVIqdR8Tin5Yf1z2LJJQLDJvCDRqRu+jC2qCoD+eIomonmOwB4smBRxfVpYQ==}
102
104
  cpu: [ppc64]
103
105
  os: [linux]
106
+ libc: [glibc]
104
107
 
105
108
  '@img/sharp-libvips-linux-riscv64@1.3.4':
106
109
  resolution: {integrity: sha512-aHkkIEHPRdQEegJN20MLmGtxYD9R2wQr3Cwpddnu5+YKMt6Uzax7S9h5gpZTo8wyrGuZSlfQ63OevL5mTyOC7Q==}
107
110
  cpu: [riscv64]
108
111
  os: [linux]
112
+ libc: [glibc]
109
113
 
110
114
  '@img/sharp-libvips-linux-s390x@1.3.4':
111
115
  resolution: {integrity: sha512-ra/mB6MikESDUO7Yg+Mi95bFBb9GsObURuhnOv3OqknjGe9sZrG8tCe9q0xSIGrtLgvgw0gKnFWcK4blSgQOuQ==}
112
116
  cpu: [s390x]
113
117
  os: [linux]
118
+ libc: [glibc]
114
119
 
115
120
  '@img/sharp-libvips-linux-x64@1.3.4':
116
121
  resolution: {integrity: sha512-GJ//SSXbnwSDes02umB3nDJLFcQzw8a18V8fyhqr6tV515tOEMdImjjxj1AoafMRz56F3PHgftnj1QEKSU1zkw==}
117
122
  cpu: [x64]
118
123
  os: [linux]
124
+ libc: [glibc]
119
125
 
120
126
  '@img/sharp-libvips-linuxmusl-arm64@1.3.4':
121
127
  resolution: {integrity: sha512-hvulFwtjUcagsis6BBxHwGFwWoNZjgYmULGVrZcyfNbjA8hKILbRxGg15/7w5HDyXHXUos/j6baAWqnCyQ2DWA==}
122
128
  cpu: [arm64]
123
129
  os: [linux]
130
+ libc: [musl]
124
131
 
125
132
  '@img/sharp-libvips-linuxmusl-x64@1.3.4':
126
133
  resolution: {integrity: sha512-6zXKeE/p39I1AmA3cJG35eyBGNqNddLnUXjhwBnsGjFPWqf5VKkDBEqaEkPDoTEtkxwi2vv8Tcr2mDyP4So7Fg==}
127
134
  cpu: [x64]
128
135
  os: [linux]
136
+ libc: [musl]
129
137
 
130
138
  '@img/sharp-linux-arm64@0.35.5':
131
139
  resolution: {integrity: sha512-LYVx5JTsOM2CBzmxreh+nl64/3H6Xb09iSLknqH47z2T2DFFxDeFLP5y4dJwe6H7uGQlHPyEEtIqyo3DYsRwdQ==}
132
140
  engines: {node: '>=20.9.0'}
133
141
  cpu: [arm64]
134
142
  os: [linux]
143
+ libc: [glibc]
135
144
 
136
145
  '@img/sharp-linux-arm@0.35.5':
137
146
  resolution: {integrity: sha512-LEaXK2WdXVK5ykcw0buWyPMsmLLL2vpHLD6yrNSW+JGEL3BZPA4tpKN6iaMc4AxTTAoaX/sU1rOL51lcIz48ZQ==}
138
147
  engines: {node: '>=20.9.0'}
139
148
  cpu: [arm]
140
149
  os: [linux]
150
+ libc: [glibc]
141
151
 
142
152
  '@img/sharp-linux-ppc64@0.35.5':
143
153
  resolution: {integrity: sha512-QVxAAq8evVRI9ia2vqgwrmWucn5Dfv+JdWzj75pD8omHLPSP7f8p20O8jxzjCcuCEQEOtYOZUmX1hkiZ0kdevA==}
144
154
  engines: {node: '>=20.9.0'}
145
155
  cpu: [ppc64]
146
156
  os: [linux]
157
+ libc: [glibc]
147
158
 
148
159
  '@img/sharp-linux-riscv64@0.35.5':
149
160
  resolution: {integrity: sha512-LtdreXguaavKODPIfzJ4kffx7UNt1omwtK0rch4EBbbSTXPnxWmYSayXdLJw0fJzQ97kHt1gL/yh4tvU+nCyRQ==}
150
161
  engines: {node: '>=20.9.0'}
151
162
  cpu: [riscv64]
152
163
  os: [linux]
164
+ libc: [glibc]
153
165
 
154
166
  '@img/sharp-linux-s390x@0.35.5':
155
167
  resolution: {integrity: sha512-UZasTOFiYzotTsGOCu42BfUzP6Tu6Do/947iRm1RsLKvlllxwGcn4RN27LibGWceix4Y+Pmw3jsnTcCQIgWjqA==}
156
168
  engines: {node: '>=20.9.0'}
157
169
  cpu: [s390x]
158
170
  os: [linux]
171
+ libc: [glibc]
159
172
 
160
173
  '@img/sharp-linux-x64@0.35.5':
161
174
  resolution: {integrity: sha512-SxFtLTeJInhAA9Q836kux2vZNeOBQEx658qvbboZScr0wIARym3IcGmW7KpVD5sbVg0Ojy+udFQdayYIZyoNog==}
162
175
  engines: {node: '>=20.9.0'}
163
176
  cpu: [x64]
164
177
  os: [linux]
178
+ libc: [glibc]
165
179
 
166
180
  '@img/sharp-linuxmusl-arm64@0.35.5':
167
181
  resolution: {integrity: sha512-9HbMclmI1zlNkFRs3z9/eBtDjfD0sGlrX1z6b1qwmiFY5ElDLh4BC0LPBdVp7z1DXFiKlIcznf+ZlsuZzLxQqg==}
168
182
  engines: {node: '>=20.9.0'}
169
183
  cpu: [arm64]
170
184
  os: [linux]
185
+ libc: [musl]
171
186
 
172
187
  '@img/sharp-linuxmusl-x64@0.35.5':
173
188
  resolution: {integrity: sha512-4KOphqB035HrVdqLZfCgMzzERrQkkzOwRhl4OAkRO1YCldbaFjySXMaK534Mo0V+LndnlJk+sbUyLeU0ULyD1A==}
174
189
  engines: {node: '>=20.9.0'}
175
190
  cpu: [x64]
176
191
  os: [linux]
192
+ libc: [musl]
177
193
 
178
194
  '@img/sharp-wasm32@0.35.5':
179
195
  resolution: {integrity: sha512-Ptsga1su4tQx+LLF1ECS9U6nz5kmrXKo6XVbtR48Ke3ZRxxgaWBu7IDtEe1quo8hiupwm6WFqxVlXaSf7IINGQ==}
@@ -1,7 +1,7 @@
1
1
  # Operator auth (IF-055-CORE-v1)
2
2
 
3
3
  Portable server-only ESM: import `createOperatorAuth`, `createAuthHandler` and
4
- `createSignInHandler` from `modules/operator-auth/index.mjs`. TypeScript
4
+ `createSignInHandler` from `./modules/operator-auth/index.mjs`. TypeScript
5
5
  declarations are `index.d.mts`. No framework or mail transport is bundled. Apply
6
6
  `accounts/schema/operator-auth.sql` once for a fresh auth database (and
7
7
  `identity/oidc/schema/oidc.sql` when the app offers identity providers). Preserve applied migration history in an existing
@@ -418,6 +418,63 @@ Two hooks on `createOperatorAuth({hooks})` keep a seed's own sign-in work in pla
418
418
  (Pencil's audit mail), or throw an `AuthError` to refuse: the session it was
419
419
  about to get is revoked first (Cradle's forgery check).
420
420
 
421
+ ## Administrative audit hook
422
+
423
+ `createOperatorAuth({hooks: {audit}})` optionally accepts
424
+ `audit({action, actorId, subjectId, detail, now})`, returning `[sql, args][]` or a
425
+ Promise of those pairs. The callback must be pure: return SQL for the module to
426
+ append to the administrative mutation's own D1 batch, with no external writes. A raced
427
+ request may generate statements and then be refused by its transaction fence.
428
+ Authorization, actor/version fences, the mutation and audit statements retain
429
+ their transaction guards. A refused or rolled-back mutation leaves no audit row;
430
+ a thrown hook or failed audit SQL fails the action closed. With no hook,
431
+ administrative behavior is unchanged. This hook covers the OA-backed
432
+ administrative methods below; it does not cover native accounts adapters or
433
+ other write paths.
434
+
435
+ An already-unlinked provider remains a successful no-op (HTTP 200, as without
436
+ the hook) and produces no audit row. An audited unlink advances the pin's
437
+ generation in the same statement; the batch checks the old snapshot and that
438
+ new generation before inserting audit rows. A suppressed or stale mutation
439
+ returns 409 and rolls back the batch.
440
+
441
+ `actorId` is the authenticated actor's opaque `oa_operators.id`. `subjectId` is
442
+ the target operator's opaque id, including the operator owning a revoked
443
+ session; domain and provider actions use `null`. `now` is the action's clock
444
+ time in milliseconds since the Unix epoch. The event has only these fields:
445
+
446
+ | `action` | `subjectId` | `detail` |
447
+ | --- | --- | --- |
448
+ | `operators.invite` | Invited operator id | New role |
449
+ | `operators.cancel-invite` | Cancelled operator id | `inactive` |
450
+ | `operators.deactivate` | Target operator id | `inactive` |
451
+ | `operators.reactivate` | Target operator id | `active` |
452
+ | `operators.role` | Target operator id | New role |
453
+ | `sessions.revoke` | Session owner's operator id | `null` |
454
+ | `domains.rule.set` | `null` | Normalized domain |
455
+ | `domains.rule.lift` | `null` | Normalized domain |
456
+ | `providers.unlink` | `null` | Provider id |
457
+ | `providers.relink` | `null` | Provider id |
458
+
459
+ `detail` is a string or `null`. Never add names, email addresses, IdP issuers or
460
+ subjects, tokens, record data or file paths. The seed owns audit storage,
461
+ migrations, retention and erasure; Base creates no audit table. For example,
462
+ Cradle can return an insert into its `company_identity_audit` table after its
463
+ seed migration adds nullable `detail` and supports nullable `operator_id` for
464
+ domain/provider events:
465
+
466
+ ```js
467
+ hooks: {
468
+ audit: ({action, actorId, subjectId, detail, now}) => [[
469
+ 'INSERT INTO company_identity_audit(actor_id,operator_id,action,detail,created_at) VALUES(?,?,?,?,?)',
470
+ [actorId, subjectId, action, detail, now],
471
+ ]],
472
+ }
473
+ ```
474
+
475
+ Use the seed's actor and subject erasure rules for this table. `oa_auth_audit`
476
+ is not a substitute for seed-owned administrative audit storage.
477
+
421
478
  ## Domain rules and step-up
422
479
 
423
480
  An owner can require a provider for an email domain (`POST /auth/domain-rules`
@@ -594,7 +651,7 @@ an independently captured pre-update source snapshot containing the complete
594
651
  root. With the frozen workspace dependencies installed, run:
595
652
 
596
653
  ```sh
597
- OA_BASELINE_SOURCE=/path/to/snapshot node --test modules/operator-auth/tests/reinvitation-upgrade.mjs
654
+ OA_BASELINE_SOURCE=/path/to/snapshot node --test ./modules/operator-auth/tests/reinvitation-upgrade.mjs
598
655
  ```
599
656
 
600
657
  Runtime tests use the locked Wrangler Miniflare/esbuild dependencies and run the
@@ -608,7 +665,7 @@ deployment remain separate.
608
665
 
609
666
  ## Adopting this version
610
667
 
611
- Copy the **complete** `modules/operator-auth/` directory from one reviewed Base
668
+ Copy the **complete** `./modules/operator-auth/` directory from one reviewed Base
612
669
  revision into the seed's operator-auth source location. Keep its layers
613
670
  (`identity/`, `accounts/`, `dev/`), runtime files, declarations, schema,
614
671
  conformance files and tests from that same revision; `rer check` names any copied
@@ -707,3 +764,35 @@ OA accounts offer a bounded, hash-pinned scheduled policy door, separate from
707
764
  human sessions. Read [SCHEDULED-POLICY.md](SCHEDULED-POLICY.md) for the design,
708
765
  additive migration, declaration, owner approval/revocation flow and audit contract.
709
766
  The reference `/app/policies` screen and Worker scheduled handler show adoption.
767
+
768
+ ### Business settings and the default team adapter
769
+
770
+ An edition that adopts `./modules/business-settings` passes its runtime instance as
771
+ `createOperatorAuth({ ..., businessSettings })`. It supplies `publicBrand()`,
772
+ `read()` provenance and `stop(actorId, guard?)`. The optional guard is the OA
773
+ session's live SQL authority fence: include it in the stop transaction. The
774
+ owner-only sign-in settings page shows the source Business, revision and applied
775
+ time, with a `business:stop` step-up control. Public sign-in uses the runtime
776
+ name and versioned same-origin logo; no Business colour is applied there. For
777
+ Base's setup frame, pass the instance as `theme.businessSettings`.
778
+
779
+ OA compositions expose the server-only `auth.businessTeam` adapter. The Business
780
+ runtime calls `ownerEmail()` to bind trust to the current claimed owner, then
781
+ `prepare({ members, managed, ownerEmail, roles, guard })`. Here `members` is the
782
+ verified roster; `managed` contains only durable Business-owned rows
783
+ `{email,operatorId,invite,state}`; `roles` maps `admin` and `member` to the app's
784
+ non-owner OA roles; and `guard:{sql,args}` proves this document's accepted
785
+ revision and fresh nonce. Batch the returned `statements` with settings, logo
786
+ and managed-row writes on the same D1 binding, then call `afterCommit()` to send
787
+ invitations. Never call it before a successful batch.
788
+
789
+ The adapter preserves the configured role policy and repeats claimed-owner and
790
+ target versions in SQL. New and reissued invitations use the existing
791
+ administration invitation preparation, issuer authority, cancellation ledger
792
+ and app mail sender. Removal cancels pending invitations or deactivates an
793
+ accepted account, invalidating its sessions. Re-adding an unaccepted account
794
+ requires its invitation; accepted accounts reactivate. Existing unowned
795
+ operators return `conflict`, and owner operators are never changed or granted.
796
+ Audit rows retain the claimed owner as actor and record `via: "via Business by <owner email>"`. Native account compositions
797
+ supply their own team adapter and can use the same optional branding/settings
798
+ integration.