@runeditrun/rer 0.2.80 → 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 (57) hide show
  1. package/cli/deploy-needs.mjs +4 -2
  2. package/cli/export.mjs +1 -1
  3. package/cli/ledger-refusal.mjs +18 -0
  4. package/cli/portability-migrations.mjs +30 -11
  5. package/cli/portability-worker.mjs +3 -1
  6. package/cli/portability.mjs +2 -0
  7. package/cli/release.mjs +4 -4
  8. package/cli/site-hosting.mjs +90 -0
  9. package/cli/site-render.mjs +3 -2
  10. package/cli/site.mjs +5 -2
  11. package/edition-authoring/base-copies.mjs +9 -0
  12. package/edition-authoring/runtime-dependencies.mjs +108 -0
  13. package/global/CHANGELOG.md +12 -0
  14. package/modules/demo/README.md +8 -0
  15. package/modules/demo/navigation.mjs +131 -15
  16. package/modules/dependencies/auth.mjs +2 -2
  17. package/modules/deploy-kit/owner.mjs +8 -1
  18. package/modules/import-kit/src/d1/apply-effects.ts +33 -0
  19. package/modules/import-kit/src/d1/apply.ts +38 -10
  20. package/modules/import-kit/src/types.ts +3 -1
  21. package/modules/operator-auth/README.md +92 -3
  22. package/modules/operator-auth/accounts/admin.mjs +52 -20
  23. package/modules/operator-auth/accounts/audit.mjs +24 -0
  24. package/modules/operator-auth/accounts/business-team.mjs +91 -0
  25. package/modules/operator-auth/accounts/domain-audit.mjs +24 -0
  26. package/modules/operator-auth/accounts/native.mjs +3 -1
  27. package/modules/operator-auth/accounts/settings-page.mjs +15 -2
  28. package/modules/operator-auth/accounts/status.mjs +7 -2
  29. package/modules/operator-auth/accounts/store.mjs +32 -6
  30. package/modules/operator-auth/business-settings.mjs +40 -0
  31. package/modules/operator-auth/identity/email-link/index.mjs +1 -1
  32. package/modules/operator-auth/identity/oidc/admin-audit.mjs +31 -0
  33. package/modules/operator-auth/identity/oidc/index.mjs +12 -5
  34. package/modules/operator-auth/identity/oidc/store.mjs +2 -0
  35. package/modules/operator-auth/index.d.mts +40 -1
  36. package/modules/operator-auth/routes.mjs +11 -6
  37. package/modules/operator-auth/service.mjs +8 -3
  38. package/modules/operator-auth/signin/index.mjs +1 -1
  39. package/modules/portability/README.md +82 -1
  40. package/modules/portability/export.mjs +6 -4
  41. package/modules/portability/format.mjs +5 -0
  42. package/modules/portability/index.d.mts +10 -2
  43. package/modules/portability/index.mjs +3 -2
  44. package/modules/portability/ledgers.mjs +27 -4
  45. package/modules/release/README.md +74 -2
  46. package/modules/release/sign.mjs +4 -2
  47. package/modules/release/signature.mjs +14 -7
  48. package/modules/release/signing-cli.mjs +2 -1
  49. package/modules/release/statement.mjs +2 -2
  50. package/modules/release/vectors/generate.mjs +1 -0
  51. package/modules/release/vectors/publisher-projects.mjs +133 -0
  52. package/modules/release/vectors/release-signature-vectors.json +5195 -0
  53. package/modules/release/verify.mjs +5 -1
  54. package/onboarding/schema/SETUP.schema.json +43 -1
  55. package/onboarding/schema/business-field-inputs.mjs +0 -1
  56. package/onboarding/schema/setup-validation.mjs +3 -0
  57. package/package.json +1 -1
@@ -1,32 +1,148 @@
1
- // Runs after the app's initial hydration, then follows its client navigation.
2
- // Each exit belongs beside an existing marked product label, never in a bar.
1
+ // Runs after hydration and follows client navigation. Exits are out of flow:
2
+ // even a zero-width flex item would add a host gap and move its siblings.
3
3
  export const NAVIGATION_SCRIPT = `(() => {
4
4
  const settings = document.querySelector('style[data-rer-label]');
5
5
  if (!settings.dataset.rerRun) return;
6
+ const exits = new Map();
7
+ let pending = false;
8
+ const set = (element, values) => {
9
+ for (const [key, value] of Object.entries(values)) {
10
+ if (element.style[key] !== value) element.style[key] = value;
11
+ }
12
+ };
13
+ const place = (link, x, y) => {
14
+ const parent = link.offsetParent;
15
+ if (!parent || (parent === document.body && getComputedStyle(parent).position === 'static')) {
16
+ set(link, { left: x + scrollX + 'px', top: y + scrollY + 'px' });
17
+ return;
18
+ }
19
+ const box = parent.getBoundingClientRect();
20
+ const scaleX = box.width / parent.offsetWidth || 1;
21
+ const scaleY = box.height / parent.offsetHeight || 1;
22
+ set(link, {
23
+ left: ((x - box.left) / scaleX - parent.clientLeft + parent.scrollLeft) + 'px',
24
+ top: ((y - box.top) / scaleY - parent.clientTop + parent.scrollTop) + 'px'
25
+ });
26
+ };
27
+ const fit = (position, link) => {
28
+ if (link.matches(':popover-open')) return;
29
+ const box = position.getBoundingClientRect();
30
+ if (!position.getClientRects().length || !box.width || !box.height) {
31
+ set(link, { display: 'none' });
32
+ return;
33
+ }
34
+ set(link, { display: 'block' });
35
+ const parent = position.parentElement;
36
+ const layout = getComputedStyle(parent);
37
+ const bounds = parent.getBoundingClientRect();
38
+ const rtl = layout.direction === 'rtl';
39
+ const height = parseFloat(getComputedStyle(link).lineHeight);
40
+ let top = box.top + (box.height - height) / 2;
41
+ // Clip only our own allocation to the viewport and any clipping ancestors.
42
+ let left = Math.max(0, bounds.left + parseFloat(layout.paddingLeft));
43
+ let right = Math.min(document.documentElement.clientWidth, bounds.right - parseFloat(layout.paddingRight));
44
+ let bottom = bounds.bottom - parseFloat(layout.paddingBottom);
45
+ for (let ancestor = parent; ancestor; ancestor = ancestor.parentElement) {
46
+ const style = getComputedStyle(ancestor);
47
+ if (style.overflowX !== 'visible') {
48
+ const clip = ancestor.getBoundingClientRect();
49
+ left = Math.max(left, clip.left + ancestor.clientLeft);
50
+ right = Math.min(right, clip.left + ancestor.clientLeft + ancestor.clientWidth);
51
+ bottom = Math.min(bottom, clip.top + ancestor.clientTop + ancestor.clientHeight);
52
+ }
53
+ }
54
+ left = Math.min(document.documentElement.clientWidth, left);
55
+ right = Math.max(left, right);
56
+ const start = rtl ? box.left : box.right;
57
+ const siblings = [...parent.children].filter(sibling => sibling !== position && !sibling.hasAttribute('data-rer-demo-exit'));
58
+ const outerLeft = left, outerRight = right;
59
+ for (const sibling of siblings) {
60
+ const rect = sibling.getBoundingClientRect();
61
+ if (!rect.width || rect.bottom <= top || rect.top >= top + height) continue;
62
+ if (rtl && rect.left < start) left = Math.max(left, Math.min(start, rect.right));
63
+ if (!rtl && rect.right > start) right = Math.min(right, Math.max(start, rect.left));
64
+ }
65
+ const range = document.createRange();
66
+ range.selectNodeContents(link.firstElementChild);
67
+ const natural = range.getBoundingClientRect().width;
68
+ const gap = parseFloat(getComputedStyle(link).fontSize) / 2;
69
+ const room = Math.max(0, (rtl ? start - left : right - start) - 2 * gap);
70
+ let width = Math.min(natural, room);
71
+ let x = Math.max(left, Math.min(right, rtl ? start - gap - width : start + gap));
72
+ // A vertical rail may already have an empty row under the lockup. Use it
73
+ // only if the whole exit fits there without touching any existing item.
74
+ const below = box.bottom + gap;
75
+ const belowX = rtl ? box.right - gap - natural : box.left + gap;
76
+ if (width < natural && below + height <= bottom && belowX >= outerLeft && belowX + natural <= outerRight && siblings.every(sibling => {
77
+ const rect = sibling.getBoundingClientRect();
78
+ return !rect.width || rect.bottom <= below || rect.top >= below + height || rect.right <= belowX || rect.left >= belowX + natural;
79
+ })) { width = natural; x = belowX; top = below; }
80
+ // With no readable room, retain a keyboard stop, revealed in the top layer
81
+ // on focus. Neither its box nor its focus ring can extend the document.
82
+ const concealed = width < height;
83
+ set(link, { width: (concealed ? 0 : width) + 'px', height: height + 'px', clipPath: concealed ? 'inset(50%)' : 'none' });
84
+ place(link, x, top);
85
+ };
86
+ const schedule = () => {
87
+ if (pending) return;
88
+ pending = true;
89
+ requestAnimationFrame(() => { pending = false; update(); });
90
+ };
91
+ const sizes = new ResizeObserver(schedule);
6
92
  const update = () => {
93
+ for (const [position, link] of exits) {
94
+ if (!position.isConnected || link.previousElementSibling !== position) {
95
+ link.remove();
96
+ exits.delete(position);
97
+ }
98
+ }
7
99
  for (const label of document.querySelectorAll('[data-rer-name]')) {
8
100
  const position = label.closest('a,button') ?? label;
9
- if (position.nextElementSibling?.hasAttribute('data-rer-demo-exit')) continue;
101
+ if (exits.has(position)) continue;
10
102
  const link = document.createElement('a');
11
103
  link.setAttribute('data-rer-demo-exit', '');
104
+ link.setAttribute('popover', 'manual');
12
105
  link.href = settings.dataset.rerRun;
13
- link.textContent = 'Run ' + settings.dataset.rerProduct;
106
+ link.title = link.ariaLabel = 'Run ' + settings.dataset.rerProduct;
107
+ const text = document.createElement('span');
108
+ text.textContent = link.title;
109
+ link.append(text);
110
+ // Own only the exit's box, including when a host styles all nav anchors.
111
+ set(link, { position: 'absolute', display: 'block', boxSizing: 'border-box', margin: '0', padding: '0', border: '0', minWidth: '0', maxWidth: 'none', inset: 'auto', width: '0', overflow: 'visible', background: 'transparent' });
112
+ link.addEventListener('focus', () => {
113
+ if (!link.matches(':focus-visible')) return;
114
+ link.showPopover();
115
+ const box = position.getBoundingClientRect();
116
+ set(link, { position: 'fixed', clipPath: 'none', width: 'max-content', maxWidth: 'calc(100vw - 16px)', height: 'auto', padding: '6px', background: 'Canvas', color: 'CanvasText' });
117
+ const rect = link.getBoundingClientRect();
118
+ set(link, { left: Math.max(8, Math.min(box.left, innerWidth - rect.width - 8)) + 'px', top: Math.max(8, Math.min(box.bottom + 4, innerHeight - rect.height - 8)) + 'px' });
119
+ });
120
+ link.addEventListener('blur', () => {
121
+ if (!link.matches(':popover-open')) return;
122
+ link.hidePopover();
123
+ set(link, { position: 'absolute', maxWidth: 'none', padding: '0', background: 'transparent', color: '' });
124
+ schedule();
125
+ });
14
126
  position.after(link);
15
- const layout = getComputedStyle(position.parentElement);
16
- if (label.scrollWidth > label.clientWidth && layout.display.includes('flex') && layout.flexWrap === 'nowrap') {
17
- link.style.width = 'min-content';
18
- link.style.whiteSpace = 'normal';
19
- link.style.textAlign = 'center';
20
- link.style.marginInlineStart = '0';
21
- }
127
+ exits.set(position, link);
128
+ sizes.observe(position);
129
+ sizes.observe(position.parentElement);
130
+ for (const sibling of position.parentElement.children) if (sibling !== link) sizes.observe(sibling);
22
131
  }
132
+ for (const [position, link] of exits) fit(position, link);
23
133
  };
24
134
  const start = () => {
25
135
  update();
26
- new MutationObserver(update).observe(document.body, { childList: true, subtree: true });
136
+ new MutationObserver(records => {
137
+ if (records.some(record => !record.target.closest?.('[data-rer-demo-exit]'))) schedule();
138
+ }).observe(document.body, { childList: true, subtree: true, attributes: true, characterData: true });
139
+ addEventListener('resize', schedule);
140
+ addEventListener('scroll', schedule, true);
141
+ document.fonts.addEventListener('loadingdone', schedule);
27
142
  };
28
- const ready = () => window.requestAnimationFrame(() => window.requestAnimationFrame(start));
143
+ const ready = () => requestAnimationFrame(() => requestAnimationFrame(start));
29
144
  if (document.readyState === 'complete') ready();
30
- else window.addEventListener('load', ready, { once: true });
145
+ else addEventListener('load', ready, { once: true });
31
146
  })()`;
32
- export const NAVIGATION_STYLE = '[data-rer-demo-exit]{display:inline-block;flex-shrink:0;margin-inline-start:.5em;color:var(--rer-link,inherit);font:inherit;font-size:13px;font-weight:400;line-height:1.5;white-space:nowrap;text-decoration:underline;text-underline-offset:3px}[data-rer-demo-exit]:focus-visible{outline:2px solid var(--rer-focus,currentColor);outline-offset:3px}';
147
+
148
+ export const NAVIGATION_STYLE = '[data-rer-demo-exit]{color:var(--rer-link,inherit);font:inherit;font-size:.8125rem;font-weight:400;line-height:1.5;white-space:nowrap;text-decoration:underline;text-underline-offset:3px}[data-rer-demo-exit]>span{display:block;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}[data-rer-demo-exit]:focus-visible{outline:2px solid var(--rer-focus,currentColor);outline-offset:-2px}';
@@ -35,7 +35,7 @@ export function linkedProviders(options) {
35
35
  async links(){const p=await current();const links=[...await staticProviders?.links()??[],...(p!==staticProviders?await p?.links()??[]:[])];return [...new Map(links.map(link=>[link.id,link])).values()];},
36
36
  // The Auth dependency is linked and unlinked through its own approval routes;
37
37
  // a static provider keeps its own pin controls.
38
- async relink(id){if(id==='auth')throw new Error('Use the dependency link with fresh local owner proof');return staticProviders.relink(id);},
39
- async unlink(id){if(id==='auth')throw new Error('Use the dependency unlink with fresh local owner proof');return staticProviders.unlink(id);},
38
+ async relink(id, audit){if(id==='auth')throw new Error('Use the dependency link with fresh local owner proof');return staticProviders.relink(id, audit);},
39
+ async unlink(id, audit){if(id==='auth')throw new Error('Use the dependency unlink with fresh local owner proof');return staticProviders.unlink(id, audit);},
40
40
  };
41
41
  }
@@ -28,6 +28,13 @@ const ENTRY_KEYS = {d1:['binding'],r2:['binding','locationHint'],kv:['binding'],
28
28
 
29
29
  export function refuse(code, kind, name) { const error = new Error(code); error.resource = `${kind}:${name}`; return error; }
30
30
 
31
+ /** Where a declaration deploys: `platforms` when it lists them, else Workers alone. */
32
+ export function ownerPlatforms(declaration) {
33
+ const platforms = declaration.platforms ?? ['workers'];
34
+ assert(Array.isArray(platforms) && platforms.length > 0 && new Set(platforms).size === platforms.length && platforms.every(item => ['workers','container'].includes(item)), 'invalid-platforms');
35
+ return platforms;
36
+ }
37
+
31
38
  export function ownerWorkerName(project, environment) {
32
39
  assert(typeof project === 'string' && /^(?:[a-z0-9][a-z0-9-]*\/)?[a-z0-9-]+$/.test(project) && segment.test(project.split('/').at(-1)), 'invalid-owner-project');
33
40
  assert(typeof environment === 'string' && environment.length <= 32 && segment.test(environment), 'invalid-owner-environment');
@@ -116,7 +123,7 @@ export function localOnlyBinding(declaration, localOnlyKeys = []) {
116
123
  export function ownerPlan(target, declaration, artifact, { localOnlyKeys = [], env = {} } = {}) {
117
124
  assert(declaration?.version === 1 && typeof declaration === 'object' && Object.keys(declaration).every(key => DECLARATION_KEYS.includes(key)), 'invalid-owner-declaration');
118
125
  assert(declaration.publicSettings === undefined || Array.isArray(declaration.publicSettings) && new Set(declaration.publicSettings).size === declaration.publicSettings.length && declaration.publicSettings.every(name => typeof name === 'string' && /^[A-Z][A-Z0-9_]*$/.test(name)), 'invalid-public-settings');
119
- if (declaration.platforms !== undefined) assert(Array.isArray(declaration.platforms) && declaration.platforms.length > 0 && new Set(declaration.platforms).size === declaration.platforms.length && declaration.platforms.every(item => ['workers','container'].includes(item)), 'invalid-platforms');
126
+ ownerPlatforms(declaration);
120
127
  if (declaration.container !== undefined) {
121
128
  const config=declaration.container;
122
129
  assert(config&&typeof config==='object'&&!Array.isArray(config)&&Object.keys(config).every(key=>['engine','cacheContract','runner','hostVariables','ingress'].includes(key))&&['node','workerd'].includes(config.engine),'invalid-container');
@@ -0,0 +1,33 @@
1
+ import type { ImportJob, PlanEntry, ProvenanceRow, TargetRow } from '../types.ts';
2
+ import type { D1ImportContext } from './types.ts';
3
+ import type { D1UndoEffect } from './undo-types.ts';
4
+ import { canonicalJson, sha256, attachmentHash } from '../provenance/identity.ts';
5
+ import { effectIdentity } from '../storage/provenance.ts';
6
+ import { remaining } from './budget.ts';
7
+
8
+ /** The exact prospective publication shape, shared by apply and admission. */
9
+ export function prospectiveEffect(id: string, entry: PlanEntry, index: number, before: TargetRow | undefined, destination: string): D1UndoEffect {
10
+ const effect = entry.effects[index], appliedRevision = sha256(canonicalJson([id, entry.identity, index, 'applied']));
11
+ const expected: TargetRow = { destination, targetKind: effect.targetKind, targetId: effect.targetId, value: effect.value, revision: appliedRevision, ...(effect.attachment ? { attachment: effect.attachment } : {}) };
12
+ const provenance: ProvenanceRow = { id: effectIdentity(id, entry.identity, index), jobId: id, sourceIdentity: entry.identity, sourceKind: entry.source.kind, sourceId: entry.source.sourceId, sourceHash: entry.source.payloadHash, artifactHash: entry.source.artifactHash, location: entry.source.location, destination, targetKind: effect.targetKind, targetId: effect.targetId, valueHash: sha256(canonicalJson(effect.value)), attachmentHash: attachmentHash(effect.attachment), appliedRevision, before: before ?? null, reversed: false };
13
+ return { provenance, expected, retained: false };
14
+ }
15
+
16
+ /** Small-batch callers can admit consecutive pending effects together, before
17
+ * any of them publish. This avoids repeatedly listing the growing native set
18
+ * for each one-record publication. Admission never survives a public request. */
19
+ export async function admissionWindow(job: ImportJob, entries: PlanEntry[], effects: D1UndoEffect[], plan: { entries: PlanEntry[] }, context: D1ImportContext, batches: number, batchSize: number, publicationCost: number): Promise<void> {
20
+ let end = job.checkpoint + entries.length;
21
+ const limit = Math.min(job.total, job.checkpoint + batchSize * Math.min(batches, Math.ceil(20 / batchSize)));
22
+ for (const entry of plan.entries.slice(end, limit)) {
23
+ if (effects.length + entry.effects.length > 1000 || remaining(context) - publicationCost < 40 + entry.effects.length * 16) break;
24
+ const { database, targets } = context.storage;
25
+ if (!await database.prepare('SELECT 1 AS present FROM ik_sources WHERE identity=?').bind(entry.identity).first()) {
26
+ for (const [index, effect] of entry.effects.entries()) {
27
+ const before = await targets.read(database, context.destination, effect.targetKind, effect.targetId);
28
+ effects.push(prospectiveEffect(job.id, entry, index, before, context.destination));
29
+ }
30
+ }
31
+ end++;
32
+ }
33
+ }
@@ -2,12 +2,14 @@ import { retainedSql } from './retained-values.ts';
2
2
  import { nativeStagingScope, readStagedTarget, expectedStagedTarget, type NativeStagingScope } from './native-staging-context.ts';
3
3
  import { targetGuards } from './target-guards.ts';
4
4
  import { D1RequestLimitError, requestContext, remaining } from './budget.ts';
5
- import type { ImportJob, PlanEntry, ProvenanceRow, TargetRow } from '../types.ts';
5
+ import type { ImportJob, PlanEntry } from '../types.ts';
6
6
  import { canonicalJson, sha256, attachmentHash } from '../provenance/identity.ts';
7
7
  import { validateEffect } from '../plan/index.ts';
8
- import { effectIdentity } from '../storage/provenance.ts';
8
+ import { prospectiveEffect, admissionWindow } from './apply-effects.ts';
9
9
  import type { D1ImportContext, D1Sql } from './types.ts';
10
- import { atomic, atomicCount, atomicPrefix, authorize, guard, limits, sql, fitsBatch } from './database.ts';
10
+ import type { D1UndoEffect } from './undo-types.ts';
11
+ import { reversalState } from './undo-state.ts';
12
+ import { atomic, atomicCount, atomicPrefix, authorize, guard, limits, sql, fitsBatch, readAtomic } from './database.ts';
11
13
  import { stored, boundary, storedReads } from './jobs.ts';
12
14
  import { custodyGuards, validatedProvenance, inventoryGuards, reusedSourceGuards } from './integrity.ts';
13
15
  import { supersedeTarget } from './history.ts';
@@ -19,6 +21,8 @@ export async function applyD1ImportBatches(jobOrId: ImportJob | string, context:
19
21
  const id = typeof jobOrId === 'string' ? jobOrId : jobOrId.id, { batchSize, maxBatches } = limits(context);
20
22
  await authorize(context, 'apply');
21
23
  let current = await stored(id, context, 'apply'), published: ImportJob | undefined;
24
+ const admitted = new Map<string, string>();
25
+ let preparing = context.storage.targets.preparePreservedUndo;
22
26
  try {
23
27
  for (let count = 0; count < maxBatches; count++) {
24
28
  const { job, plan } = current;
@@ -27,6 +31,7 @@ export async function applyD1ImportBatches(jobOrId: ImportJob | string, context:
27
31
  if (job.state === 'completed') { await atomic(context, 'apply', [...boundary(job, plan, 'apply'), ...custodyGuards(plan, id), ...await inventoryGuards(job, plan, context)], 0, nativeStagingScope(job, plan)); return job; }
28
32
  if (!['queued', 'applying', 'failed'].includes(job.state)) throw new Error('IMPORT_ALREADY_REVERSING');
29
33
  const statements: D1Sql[] = [...boundary(job, plan, 'apply'), ...custodyGuards(plan, id), ...await inventoryGuards(job, plan, context)], entries: PlanEntry[] = [], returnReads = storedReads(job);
34
+ const undoEffects: D1UndoEffect[] | undefined = reversalState(job).policy === 'preserve-conflicts' ? [] : undefined;
30
35
  let effects = 0, scope = nativeStagingScope(job, plan);
31
36
  let prefix = atomicPrefix(context, 'apply', statements, scope);
32
37
  let planned = prefix ? prefix.count(progress(job, 0), returnReads) : cost(context, publication(job, 0, statements, scope), returnReads);
@@ -38,21 +43,44 @@ export async function applyD1ImportBatches(jobOrId: ImportJob | string, context:
38
43
  const reserve = 40 + entry.effects.length * 16;
39
44
  if (remaining(context) - planned < reserve) { if (!entries.length) { if (count > 0) return job; throw new D1RequestLimitError(); } break; }
40
45
  const candidate: D1Sql[] = [], nextScope = { ...scope, nativeGuards:[...scope.nativeGuards], postGuards:[...scope.postGuards], targets:[...scope.targets] };
41
- await publishEntry(id, entry, job.checkpoint + entries.length, context, candidate, nextScope);
46
+ const candidateUndo: D1UndoEffect[] | undefined = undoEffects && [];
47
+ await publishEntry(id, entry, job.checkpoint + entries.length, context, candidate, nextScope, candidateUndo);
42
48
  const nextPrefix = prefix?.extend(candidate);
43
49
  const next = nextPrefix ? undefined : publication(job, entries.length + 1, [...statements, ...candidate], nextScope);
44
50
  const spent = nextPrefix ? nextPrefix.count(progress(job, entries.length + 1), returnReads) : cost(context, next!, returnReads);
45
51
  if (spent > remaining(context)) { if (entries.length) break; if (count > 0) return job; throw new D1RequestLimitError(); }
46
52
  const fits = nextPrefix ? true : fitsBatch(context, 'apply', next!.statements, next!.scope);
47
53
  if (!fits && entries.length) break;
48
- statements.push(...candidate); prefix = nextPrefix;
54
+ statements.push(...candidate); undoEffects?.push(...candidateUndo!); prefix = nextPrefix;
49
55
  scope = nextScope; entries.push(entry); effects += entry.effects.length; planned = spent;
50
56
  if (!fits) break;
51
57
  }
58
+ // Check the preserving contract before every native publication, including
59
+ // batches resumed from a nonzero checkpoint.
60
+ // This read-only admission makes no undo decision and authorizes no
61
+ // effects. Apply still fences its own exact before-images atomically.
62
+ // Do not copy this potentially large native snapshot into staging's
63
+ // compact baseline, which must fit every private publication batch.
64
+ if (undoEffects && (!admitted.size || undoEffects.some(effect => admitted.get(effect.provenance.id) !== sha256(canonicalJson(effect))) || preparing !== context.storage.targets.preparePreservedUndo)) {
65
+ const { classifyUndo } = await import('./undo-snapshot.ts');
66
+ const { database, targets } = context.storage;
67
+ const prepare = targets.preparePreservedUndo;
68
+ if (typeof prepare !== 'function') throw new Error('IMPORT_PRESERVED_UNDO_ADAPTER_REQUIRED');
69
+ await admissionWindow(job, entries, undoEffects, plan, context, maxBatches - count, batchSize, planned);
70
+ const snapshot = await prepare.call(targets, database, context.destination, structuredClone(undoEffects));
71
+ const admission = classifyUndo(undoEffects, snapshot, context);
72
+ await readAtomic(context, admission.guards, nativeStagingScope(job, plan), 'apply');
73
+ admitted.clear();
74
+ for (const effect of undoEffects) admitted.set(effect.provenance.id, sha256(canonicalJson(effect)));
75
+ preparing = prepare;
76
+ }
77
+ if (undoEffects && preparing !== context.storage.targets.preparePreservedUndo) throw new Error('IMPORT_PRESERVED_UNDO_ADAPTER_REQUIRED');
52
78
  const request = publication(job, entries.length, statements, scope), done = job.checkpoint + entries.length === job.total;
53
79
  await atomic(context, 'apply', request.statements, returnReads, request.scope);
54
80
  current = await stored(id, context, 'apply'); published = current.job;
55
- if (done || remaining(context) < 200) return published;
81
+ // Preserving admission spends a variable number of reads; let the exact
82
+ // next-batch budget check decide whether more work fits.
83
+ if (done || (!undoEffects && remaining(context) < 200)) return published;
56
84
  }
57
85
  } catch (error) {
58
86
  // Later preflight has no native effects. Its measured budget exhaustion
@@ -62,7 +90,7 @@ export async function applyD1ImportBatches(jobOrId: ImportJob | string, context:
62
90
  }
63
91
  return current.job;
64
92
  }
65
- async function publishEntry(id: string, entry: PlanEntry, ordinal: number, context: D1ImportContext, statements: D1Sql[], scope: NativeStagingScope): Promise<void> {
93
+ async function publishEntry(id: string, entry: PlanEntry, ordinal: number, context: D1ImportContext, statements: D1Sql[], scope: NativeStagingScope, undoEffects?: D1UndoEffect[]): Promise<void> {
66
94
  const { database: db, targets } = context.storage, effectsHash = sha256(canonicalJson(entry.effects));
67
95
  const prior = await db.prepare('SELECT * FROM ik_sources WHERE identity=?').bind(entry.identity).first();
68
96
  if (prior) {
@@ -87,12 +115,12 @@ async function publishEntry(id: string, entry: PlanEntry, ordinal: number, conte
87
115
  validateEffect(effect);
88
116
  const before = await readStagedTarget(context, scope, effect.targetKind, effect.targetId);
89
117
  if (before ? effect.expectedRevision !== before.revision : effect.expectedRevision !== undefined) throw new Error('TARGET_REVISION_CONFLICT');
90
- const appliedRevision = sha256(canonicalJson([id, entry.identity, index, 'applied']));
91
- const row: TargetRow = { destination: context.destination, targetKind: effect.targetKind, targetId: effect.targetId, value: effect.value, revision: appliedRevision, ...(effect.attachment ? { attachment: effect.attachment } : {}) };
118
+ const prospective = prospectiveEffect(id, entry, index, before, context.destination);
119
+ const { expected: row, provenance: p } = prospective;
92
120
  expectedStagedTarget(scope,effect.targetKind,effect.targetId,true);
93
121
  const post = targetGuards(targets, row, context.destination, effect.targetKind, effect.targetId);
94
122
  scope.postGuards.push(...post);
95
- const p: ProvenanceRow = { id: effectIdentity(id, entry.identity, index), jobId: id, sourceIdentity: entry.identity, sourceKind: entry.source.kind, sourceId: entry.source.sourceId, sourceHash: entry.source.payloadHash, artifactHash: entry.source.artifactHash, location: entry.source.location, destination: context.destination, targetKind: effect.targetKind, targetId: effect.targetId, valueHash: sha256(canonicalJson(effect.value)), attachmentHash: attachmentHash(effect.attachment), appliedRevision, before: before ?? null, reversed: false };
123
+ undoEffects?.push(prospective);
96
124
  await supersedeTarget(p, before, context, statements);
97
125
  const record_json=canonicalJson(p);
98
126
  statements.push(...targetGuards(targets,before ?? null, context.destination, effect.targetKind, effect.targetId), ...targets.write(row), ...post, changed(retainedSql(['INSERT INTO ik_provenance(id,job_id,ordinal,effect_ordinal,source_identity,destination,target_kind,target_id,record_json) VALUES(', ',', ',', ',', ',', ',', ',', ',', ',', ')'], [p.id, id, ordinal, index, entry.identity, context.destination, effect.targetKind, effect.targetId, record_json], [8]),putRow('ik_provenance',{id:p.id,job_id:id,ordinal,effect_ordinal:index,source_identity:entry.identity,destination:context.destination,target_kind:effect.targetKind,target_id:effect.targetId,reversed:0,record_json})));
@@ -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'
@@ -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.