@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,3 +1,4 @@
1
+ import { auditMutation, operatorWitness } from './audit.mjs';
1
2
  import { writeOperatorStatus } from './status.mjs';
2
3
  import { AuthError, deny } from '../errors.mjs';
3
4
  import { normalizeEmail, safeReturnTo } from '../policy.mjs';
@@ -6,7 +7,7 @@ import { operatorColumns } from './store.mjs';
6
7
  import { DEFAULT_ROLES, emailAllowed } from './roles.mjs';
7
8
  const DOMAIN = /^(?=.{1,253}$)(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z][a-z0-9-]{0,61}[a-z0-9]$/;
8
9
  export function administration(context) {
9
- const { config, store, clock, authorize, authenticate, newToken, sendLink, limit, requireFreshProof, providers } = context;
10
+ const { config, store, clock, authorize, authenticate, newToken, sendLink, limit, requireFreshProof, providers, audit } = context;
10
11
  async function actorFor(request, action, target, role, mutation = true) {
11
12
  if (mutation) requirePost(request, config);
12
13
  const actor = await authenticate(request);
@@ -22,27 +23,43 @@ export function administration(context) {
22
23
  && (role === 'owner' || target?.role === 'owner')) await requireFreshProof(actor);
23
24
  return actor;
24
25
  }
26
+ function providerAudit(actor) {
27
+ if (!audit) return undefined;
28
+ const now = clock();
29
+ return { audit, actorId: actor.operator.id, fence: store.actorFence(actor, now), now };
30
+ }
25
31
  async function targetFor(id) {
26
32
  const target = typeof id === 'string' ? await store.operator(id) : null;
27
33
  if (!target) deny('operator_not_found', 404);
28
34
  return target;
29
35
  }
30
- return {
31
- async invite(request, input) {
36
+ async function prepareInvitation(request, input, snapshot) {
32
37
  const role = input.role ?? 'member';
33
38
  if (!DEFAULT_ROLES.includes(role)) throw new AuthError('invalid_role');
34
39
  const actor = await actorFor(request, 'operators:invite', undefined, role);
35
40
  const email = normalizeEmail(input.email);
36
- await limit(request, email, 'invite');
41
+ // A trusted server batch supplies its read snapshot; browser requests
42
+ // retain the per-IP and mailbox invitation limits.
43
+ if (!snapshot) await limit(request, email, 'invite');
37
44
  if (!emailAllowed(email, config.allowList)) deny('email_not_allowed');
38
- const existing = await store.byEmail(email);
45
+ const existing = snapshot ? snapshot.operator : await store.byEmail(email);
39
46
  const reinviting = existing?.status === 'inactive' && !!await store.cancellation(existing.id);
40
47
  if (existing && (existing.role !== role || (!reinviting && existing.status !== 'invited'))) deny('invitation_conflict', 409);
41
48
  const now = clock();
42
49
  const token = await newToken('invite', safeReturnTo(input.returnTo));
43
- const created = await store.invite({ operatorId: existing?.id ?? crypto.randomUUID(), expectedVersion: existing?.version ?? 1, reinviting, email, displayName: displayName(input.displayName), role, token, now }, actor);
50
+ const mutation = { operatorId: existing?.id ?? crypto.randomUUID(), expectedVersion: existing?.version ?? 1, reinviting, email, displayName: displayName(input.displayName), role, token, now };
51
+ return { mutation, actor, ...await store.prepareInvitation(mutation, actor, audit), async afterCommit() {
52
+ const issued = await store.first('SELECT id FROM oa_tokens WHERE id=? AND revoked_at IS NULL AND consumed_at IS NULL', [token.id]);
53
+ if (issued) await sendLink(email, token);
54
+ } };
55
+ }
56
+ return {
57
+ prepareInvitation,
58
+ async invite(request, input) {
59
+ const plan = await prepareInvitation(request, input);
60
+ const created = await store.invite(plan.mutation, plan.actor, plan);
44
61
  if (!created) deny('invitation_conflict', 409);
45
- await sendLink(email, token);
62
+ await plan.afterCommit();
46
63
  return { status: 'accepted' };
47
64
  },
48
65
  async listOperators(request) {
@@ -55,16 +72,20 @@ export function administration(context) {
55
72
  const target = await targetFor(operatorId);
56
73
  const actor = await actorFor(request, 'operators:deactivate', target);
57
74
  if (target.status !== 'invited') deny('invitation_conflict', 409);
58
- const fence = store.actorFence(actor, clock());
75
+ const now = clock();
76
+ const fence = store.actorFence(actor, now);
59
77
  // The guarded write and version trigger are one transaction: cancellation
60
78
  // invalidates every outstanding link and cannot deactivate a raced join.
61
79
  // Read the ledger to fail closed if its migration is missing. A previous
62
80
  // cancellation remains guarded throughout reinvitation; cancelling again
63
81
  // refreshes that marker through the existing database trigger.
64
82
  await store.cancellation(target.id);
65
- const result = await store.run(`UPDATE oa_operators SET status='inactive' WHERE id=? AND status='invited' AND version=?
66
- AND ${fence.sql}`,
67
- [target.id, target.version, ...fence.args]);
83
+ const [result] = await auditMutation(store, { audit,
84
+ event: { action: 'operators.cancel-invite', actorId: actor.operator.id, subjectId: target.id, detail: 'inactive', now },
85
+ before: { sql: `${fence.sql} AND EXISTS(SELECT 1 FROM oa_operators WHERE id=? AND status='invited' AND version=?)`, args: [...fence.args, target.id, target.version] },
86
+ after: operatorWitness(target, 'status', 'inactive'),
87
+ statements: [[`UPDATE oa_operators SET status='inactive' WHERE id=? AND status='invited' AND version=? AND ${fence.sql}`, [target.id, target.version, ...fence.args]]],
88
+ });
68
89
  if (result.meta.changes < 1) deny('authority_changed', 409);
69
90
  return store.operator(target.id);
70
91
  },
@@ -73,15 +94,21 @@ export function administration(context) {
73
94
  const target = await targetFor(operatorId);
74
95
  const actor = await actorFor(request, status === 'active' ? 'operators:reactivate' : 'operators:deactivate', target);
75
96
  if (target.status === 'invited') deny('invitation_required', 409);
76
- return writeOperatorStatus(store, actor, target, status, clock());
97
+ return writeOperatorStatus(store, actor, target, status, clock(), undefined, audit);
77
98
  },
78
99
  async setRole(request, operatorId, role) {
79
100
  if (!DEFAULT_ROLES.includes(role)) throw new AuthError('invalid_role');
80
101
  const target = await targetFor(operatorId);
81
102
  const actor = await actorFor(request, 'operators:role', target, role);
82
- const fence = store.actorFence(actor, clock());
103
+ const now = clock();
104
+ const fence = store.actorFence(actor, now);
83
105
  try {
84
- const result = await store.run(`UPDATE oa_operators SET role=? WHERE id=? AND version=? AND ${fence.sql}`, [role, target.id, target.version, ...fence.args]);
106
+ const [result] = await auditMutation(store, { audit: target.role === role ? undefined : audit,
107
+ event: { action: 'operators.role', actorId: actor.operator.id, subjectId: target.id, detail: role, now },
108
+ before: { sql: `${fence.sql} AND EXISTS(SELECT 1 FROM oa_operators WHERE id=? AND version=?)`, args: [...fence.args, target.id, target.version] },
109
+ after: operatorWitness(target, 'role', role),
110
+ statements: [[`UPDATE oa_operators SET role=? WHERE id=? AND version=? AND ${fence.sql}`, [role, target.id, target.version, ...fence.args]]],
111
+ });
85
112
  if (result.meta.changes < 1) deny('authority_changed', 409);
86
113
  } catch (e) { if (String(e).includes('last_owner')) deny('last_owner', 409); throw e; }
87
114
  return store.operator(target.id);
@@ -99,13 +126,18 @@ export function administration(context) {
99
126
  return rows.results.map((r) => ({ ...r, active: !!r.active }));
100
127
  },
101
128
  async revokeSession(request, sessionId) {
102
- const row = await store.first('SELECT operator_id AS operatorId FROM oa_sessions WHERE id=?', [sessionId]);
129
+ const row = await store.first('SELECT operator_id AS operatorId,revoked_at AS revokedAt FROM oa_sessions WHERE id=?', [sessionId]);
103
130
  if (!row) deny('session_not_found', 404);
104
131
  const target = await targetFor(row.operatorId);
105
132
  const actor = await actorFor(request, 'sessions:revoke', target);
106
133
  const now = clock();
107
134
  const fence = store.actorFence(actor, now);
108
- const result = await store.run(`UPDATE oa_sessions SET revoked_at=COALESCE(revoked_at,?) WHERE id=? AND EXISTS(SELECT 1 FROM oa_operators WHERE id=? AND version=?) AND ${fence.sql}`, [now, sessionId, target.id, target.version, ...fence.args]);
135
+ const [result] = await auditMutation(store, { audit: row.revokedAt === null ? audit : undefined,
136
+ event: { action: 'sessions.revoke', actorId: actor.operator.id, subjectId: target.id, detail: null, now },
137
+ before: { sql: `${fence.sql} AND EXISTS(SELECT 1 FROM oa_sessions s JOIN oa_operators o ON o.id=s.operator_id WHERE s.id=? AND s.revoked_at IS NULL AND o.id=? AND o.version=?)`, args: [...fence.args, sessionId, target.id, target.version] },
138
+ after: { sql: 'EXISTS(SELECT 1 FROM oa_sessions WHERE id=? AND revoked_at=?)', args: [sessionId, now] },
139
+ statements: [[`UPDATE oa_sessions SET revoked_at=COALESCE(revoked_at,?) WHERE id=? AND EXISTS(SELECT 1 FROM oa_operators WHERE id=? AND version=?) AND ${fence.sql}${audit && row.revokedAt === null ? ' RETURNING id' : ''}`, [now, sessionId, target.id, target.version, ...fence.args]]],
140
+ });
109
141
  if (result.meta.changes < 1) deny('authority_changed', 409);
110
142
  },
111
143
  async listDomainRules(request) {
@@ -120,7 +152,7 @@ export function administration(context) {
120
152
  const providerId = input.provider ?? null;
121
153
  if (providerId !== null && !providers?.ids.includes(providerId)) throw new AuthError('unknown_provider');
122
154
  await requireFreshProof(actor);
123
- await store.setDomainRule({ domain, providerId, now: clock() }, actor);
155
+ await store.setDomainRule({ domain, providerId, now: clock() }, actor, audit);
124
156
  return store.domainRules();
125
157
  },
126
158
  async listProviders(request) {
@@ -131,16 +163,16 @@ export function administration(context) {
131
163
  const actor = await actorFor(request, 'providers:manage');
132
164
  if (!providers?.ids.includes(input?.provider)) throw new AuthError('unknown_provider');
133
165
  await requireFreshProof(actor);
134
- await providers.unlink(input.provider);
166
+ await providers.unlink(input.provider, providerAudit(actor));
135
167
  // A rule naming a provider that is gone would lock its domain out.
136
- await store.liftDomainRules(input.provider);
168
+ if (!audit) await store.liftDomainRules(input.provider);
137
169
  return providers.links();
138
170
  },
139
171
  async relinkProvider(request, input) {
140
172
  const actor = await actorFor(request, 'providers:manage');
141
173
  if (!providers?.ids.includes(input?.provider)) throw new AuthError('unknown_provider');
142
174
  await requireFreshProof(actor);
143
- await providers.relink(input.provider);
175
+ await providers.relink(input.provider, providerAudit(actor));
144
176
  return providers.links();
145
177
  },
146
178
  };
@@ -0,0 +1,24 @@
1
+ import { deny } from '../errors.mjs';
2
+
3
+ // D1 has no interactive transaction. A failed SQL assertion rolls the whole
4
+ // batch back, including arbitrary seed-owned hook statements. Check the old
5
+ // snapshot before the write as well as its result: old+1 alone could witness a
6
+ // different request that won the race. No table, trigger or changes() counter.
7
+ const assertion = ({ sql, args = [] }) => [
8
+ `SELECT CASE WHEN (${sql}) THEN 1 ELSE json_extract('[]', '$[oa_audit_refused') END`, args,
9
+ ];
10
+ export async function auditMutation(store, { audit, event, before, after, statements }) {
11
+ if (!audit) return store.batch(statements);
12
+ const extra = await audit(event);
13
+ try {
14
+ const results = await store.batch([assertion(before), ...statements, assertion(after), ...extra]);
15
+ return results.slice(1, statements.length + 1);
16
+ } catch (error) {
17
+ if (String(error).includes('oa_audit_refused')) deny('authority_changed', 409);
18
+ throw error;
19
+ }
20
+ }
21
+ export function operatorWitness(target, field, value) {
22
+ return { sql: `EXISTS(SELECT 1 FROM oa_operators WHERE id=? AND version=? AND ${field}=?)`,
23
+ args: [target.id, target.version + (target[field] === value ? 0 : 1), value] };
24
+ }
@@ -0,0 +1,91 @@
1
+ // Trusted server integration only. The caller verifies the Business document;
2
+ // its nonce guard and every account mutation share one D1 batch.
3
+ import { administration, displayName } from './admin.mjs';
4
+ import { bindPolicyActor } from '../scheduled/fence.mjs';
5
+ import { normalizeEmail } from '../policy.mjs';
6
+ import { emailAllowed } from './roles.mjs';
7
+ import { deny } from '../errors.mjs';
8
+
9
+ export function businessTeam(context) {
10
+ const { store, accounts, config, clock, authorize } = context;
11
+ return Object.freeze({
12
+ async ownerEmail() { return (await accounts.owner())?.email ?? null; },
13
+ async prepare({ members, managed, ownerEmail, roles, guard }) {
14
+ const owner = await accounts.owner();
15
+ if (!owner || owner.email !== normalizeEmail(ownerEmail)) deny('owner_required', 403);
16
+ const operator = await store.operator(owner.id);
17
+ if (!operator || operator.email !== owner.email || operator.role !== 'owner' || operator.status !== 'active' || !emailAllowed(operator.email, config.allowList)) deny('owner_required', 403);
18
+ if (!guard || typeof guard.sql !== 'string' || !Array.isArray(guard.args)) deny('invalid_business_guard', 503);
19
+ if (![roles?.admin, roles?.member].every(role => role === 'admin' || role === 'member')) deny('invalid_role', 400);
20
+ const actor = Object.freeze({ operator });
21
+ bindPolicyActor(actor, () => ({ sql: `(${guard.sql}) AND EXISTS(SELECT 1 FROM oa_operators bo
22
+ WHERE bo.id=? AND bo.email=? AND bo.version=? AND bo.status='active' AND bo.role='owner'
23
+ AND bo.id=(SELECT o.id FROM oa_operators o LEFT JOIN oa_bootstrap b ON b.claim_id=o.id
24
+ WHERE o.role='owner' AND o.status='active' ORDER BY b.claim_id IS NULL,o.created_at,o.id LIMIT 1))`,
25
+ args: [...guard.args, operator.id, operator.email, operator.version] }));
26
+ const fence = store.actorFence(actor, clock());
27
+ const pending = [], rows = [];
28
+ // Abort the whole caller transaction if ownership changed, even when this
29
+ // document contains only conflicts or unchanged members.
30
+ const statements = [[`INSERT INTO oa_auth_audit(id,actor_id,action,value,created_at)
31
+ SELECT ?,NULL,'business:authority_changed','{}',? WHERE NOT (${fence.sql})`,
32
+ [crypto.randomUUID(), clock(), ...fence.args]]];
33
+ const audit = (action, id, condition = 'changes()>0', args = []) => statements.push([
34
+ `INSERT INTO oa_auth_audit(id,actor_id,action,value,created_at) SELECT ?,CASE WHEN (${condition}) THEN ? ELSE NULL END,?,?,?`,
35
+ [crypto.randomUUID(), ...args, operator.id, action, JSON.stringify({ operatorId: id, via: `via Business by ${operator.email}` }), clock()],
36
+ ]);
37
+ const allow = async (action, target, role) => {
38
+ if (target?.role === 'owner' || !await authorize({ actor: operator, action, target, role })) deny('business_team_denied', 403);
39
+ };
40
+ const request = new Request(new URL('/auth/invite', config.origin), { method: 'POST', headers: { origin: config.origin, host: new URL(config.origin).host } });
41
+ const desired = new Map(members.map(member => [normalizeEmail(member.email), member]));
42
+ const previous = new Map(managed.filter(row => row.operatorId).map(row => [normalizeEmail(row.email), row]));
43
+ const update = async (target, changes, action) => {
44
+ await allow(action, target, changes.role);
45
+ const changed = changes.role !== target.role || changes.status !== target.status;
46
+ statements.push([`UPDATE oa_operators SET role=?,status=?,display_name=? WHERE id=? AND email=? AND version=? AND role!='owner' AND ${fence.sql}`,
47
+ [changes.role, changes.status, changes.displayName, target.id, target.email, target.version, ...fence.args]]);
48
+ audit(action, target.id);
49
+ return { ...target, ...changes, version: target.version + (changed ? 1 : 0) };
50
+ };
51
+ for (const email of new Set([...desired.keys(), ...previous.keys()])) {
52
+ const member = desired.get(email), prior = previous.get(email);
53
+ // The roster address is a durable Business key, not the operator's
54
+ // current sign-in address. Self-service email changes keep this ID.
55
+ let target = prior ? await store.operator(prior.operatorId) : await store.byEmail(email);
56
+ const oldRole = target?.role;
57
+ if (target?.role === 'owner' || !prior && (email === owner.email || target) || prior && !target) {
58
+ // Never adopt an unrelated account, or discard a recorded identity
59
+ // because its old address now belongs to another account.
60
+ if (member || prior) rows.push({ email, operatorId: prior?.operatorId ?? null, invite: member?.invite ?? prior.invite, state: 'conflict' });
61
+ continue;
62
+ }
63
+ if (!member) {
64
+ if (target.status !== 'inactive') target = await update(target, { ...target, status: 'inactive' }, 'operators:deactivate');
65
+ rows.push({ email, operatorId: target.id, invite: prior.invite, state: 'inactive' });
66
+ continue;
67
+ }
68
+ const role = roles[member.role];
69
+ if (role !== 'admin' && role !== 'member') deny('invalid_role', 400);
70
+ const name = displayName(member.name);
71
+ if (target && target.role !== role) target = await update(target, { ...target, role }, 'operators:role');
72
+ const cancelled = target?.status === 'inactive' && !!await store.cancellation(target.id);
73
+ if (target?.status === 'inactive' && !cancelled) target = await update(target, { ...target, status: 'active' }, 'operators:reactivate');
74
+ if (!target || cancelled || target.status === 'invited' && member.invite > (prior?.invite ?? -1) || target.status === 'invited' && target.role !== oldRole) {
75
+ // Preparation is shared with the public administration.invite path.
76
+ // A preceding role write is represented in the read snapshot only;
77
+ // the exact expected version is repeated in its invitation SQL.
78
+ const plan = await administration({ ...context, authenticate: async () => actor })
79
+ .prepareInvitation(request, { email: target?.email ?? email, displayName: name, role }, { operator: target });
80
+ statements.push(...plan.statements);
81
+ audit('operators:invite', plan.mutation.operatorId, 'EXISTS(SELECT 1 FROM oa_tokens WHERE id=?)', [plan.mutation.token.id]);
82
+ pending.push(plan.afterCommit);
83
+ target = { id: plan.mutation.operatorId, status: 'invited' };
84
+ } else if (target.displayName !== name) target = await update(target, { ...target, displayName: name }, 'operators:role');
85
+ rows.push({ email, operatorId: target.id, invite: member.invite, state: target.status });
86
+ }
87
+ return { statements: statements.map(([sql, args]) => store.statement(sql, args)), rows,
88
+ async afterCommit() { for (const send of pending) await send(); } };
89
+ },
90
+ });
91
+ }
@@ -0,0 +1,24 @@
1
+ import { auditMutation } from './audit.mjs';
2
+
3
+ export async function auditDomainRule(store, { domain, providerId, now }, actor, audit) {
4
+ const previous = await store.first('SELECT provider_id,created_by,created_at FROM oa_domain_rules WHERE domain=?', [domain]);
5
+ if (providerId === null && !previous) return 0;
6
+ const fence = store.actorFence(actor, now);
7
+ const snapshot = previous
8
+ ? { sql: 'EXISTS(SELECT 1 FROM oa_domain_rules WHERE domain=? AND provider_id=? AND created_by=? AND created_at=?)', args: [domain, previous.provider_id, previous.created_by, previous.created_at] }
9
+ : { sql: 'NOT EXISTS(SELECT 1 FROM oa_domain_rules WHERE domain=?)', args: [domain] };
10
+ // The existing timestamp doubles as the domain rule's monotonic revision.
11
+ const revision = previous ? Math.max(previous.created_at + 1, now) : now;
12
+ const [result] = await auditMutation(store, { audit,
13
+ event: { action: providerId === null ? 'domains.rule.lift' : 'domains.rule.set', actorId: actor.operator.id, subjectId: null, detail: domain, now },
14
+ before: { sql: `${fence.sql} AND ${snapshot.sql}`, args: [...fence.args, ...snapshot.args] },
15
+ after: providerId === null
16
+ ? { sql: 'NOT EXISTS(SELECT 1 FROM oa_domain_rules WHERE domain=?)', args: [domain] }
17
+ : { sql: 'EXISTS(SELECT 1 FROM oa_domain_rules WHERE domain=? AND provider_id=? AND created_by=? AND created_at=?)', args: [domain, providerId, actor.operator.id, revision] },
18
+ statements: [providerId === null
19
+ ? ['DELETE FROM oa_domain_rules WHERE domain=? RETURNING domain', [domain]]
20
+ : [`INSERT INTO oa_domain_rules(domain,provider_id,created_by,created_at) VALUES(?,?,?,?)
21
+ ON CONFLICT(domain) DO UPDATE SET provider_id=excluded.provider_id,created_by=excluded.created_by,created_at=excluded.created_at RETURNING domain`, [domain, providerId, actor.operator.id, revision]]],
22
+ });
23
+ return result.results.length;
24
+ }
@@ -1,3 +1,4 @@
1
+ import { businessSettingsControls } from '../business-settings.mjs';
1
2
  // Native composition never constructs an OA account/session store. The seed
2
3
  // selects its tenant in these adapters, before any request is handled.
3
4
  import { AuthError, deny } from '../errors.mjs';
@@ -24,7 +25,7 @@ function validate(value, required, optional = []) {
24
25
  if (!value || typeof value !== 'object' || required.some(k => typeof value[k] !== 'function') || optional.some(k => value[k] !== undefined && typeof value[k] !== 'function')) throw new AuthError('invalid_native_adapter', 503);
25
26
  }
26
27
 
27
- export function createNativeAuth({ accounts, proofs, db, config, clock, hooks, mailSender, clientIp, fetch, waitUntil }) {
28
+ export function createNativeAuth({ businessSettings, accounts, proofs, db, config, clock, hooks, mailSender, clientIp, fetch, waitUntil }) {
28
29
  accountsAdapter(accounts);
29
30
  validate(accounts, ACCOUNT_METHODS, OPTIONAL);
30
31
  validate(proofs, PROOF_METHODS);
@@ -108,6 +109,7 @@ export function createNativeAuth({ accounts, proofs, db, config, clock, hooks, m
108
109
  return session;
109
110
  }
110
111
  return Object.freeze({
112
+ ...businessSettingsControls({ businessSettings, config, accounts, authenticate, requireFreshProof: email.requireFreshProof, clock }),
111
113
  // Account administration belongs to the seed; unsupported operations are
112
114
  // explicit refusals, never apparently successful writes to an unused store.
113
115
  ...Object.fromEntries(['invite', 'listOperators', 'cancelInvitation', 'setOperatorStatus', 'setRole', 'listSessions', 'revokeSession',
@@ -2,9 +2,9 @@ import { pageResponse } from '../page.mjs';
2
2
  import { escapeHtml } from '../http.mjs';
3
3
 
4
4
  // The owner's sign-in settings, in the same frame (and seed theme) as sign-in.
5
- export function identitySettingsPage({ idpSignIn, providerSetup }, branding, { saved = false, error, status = 200, method = 'GET' } = {}) {
5
+ export function identitySettingsPage({ idpSignIn, providerSetup, business }, branding, { saved = false, error, status = 200, method = 'GET' } = {}) {
6
6
  const states = { linked: 'Linked', configured: 'Configured · connects on first sign-in', unlinked: 'Not linked', 'needs-relink': 'Link needs setup again' };
7
- const notice = error ? '<p class="notice" role="alert">Provider sign-in could not be enabled. Link or relink your identity provider, then try again.</p>'
7
+ const notice = error === 'step_up_required' ? '<p class="notice" role="alert">Confirm your identity below, then stop Business settings.</p>' : error ? '<p class="notice" role="alert">Provider sign-in could not be enabled. Link or relink your identity provider, then try again.</p>'
8
8
  : saved ? `<p class="notice" role="status">Settings saved. Provider sign-in is ${idpSignIn ? 'on' : 'off'}.</p>` : '';
9
9
  const setup = providerSetup.providers.length
10
10
  ? providerSetup.providers.map(provider => `<p>${escapeHtml(provider.label)}: ${states[provider.state]}</p>`).join('')
@@ -13,6 +13,19 @@ export function identitySettingsPage({ idpSignIn, providerSetup }, branding, { s
13
13
  + '<h2>Provider setup</h2>' + setup
14
14
  + (!providerSetup.canEnable ? '<p>Have the installation administrator link or relink a provider through the project’s identity setup, then return here to enable sign-in.</p>' : '')
15
15
  + `<form action="/auth/settings/identity" method="post"><input type="hidden" name="setting" value="identity"><label class="check"><input type="checkbox" name="idpSignIn" value="true"${idpSignIn ? ' checked' : ''}${!providerSetup.canEnable && !idpSignIn ? ' disabled' : ''}>Allow provider sign-in</label><button>Save settings</button></form>`
16
+ + businessSection(business)
16
17
  + '<p class="secondary-link"><a href="/app">Back to app</a></p>';
17
18
  return pageResponse({ branding, title: 'Sign-in settings', heading: 'Sign-in settings', content, status, method, referrer: 'strict-origin' });
18
19
  }
20
+
21
+ function businessSection(value) {
22
+ if (!value) return '';
23
+ const details = value.business
24
+ ? `<p>Source: Business ${escapeHtml(value.business)}<br>Revision: ${escapeHtml(String(value.rev))}<br>Applied: ${escapeHtml(value.appliedAt ?? 'Not yet applied')}</p>`
25
+ : '<p>No Business settings have been applied.</p>';
26
+ if (value.stopped) return '<h2>Business</h2>' + details + '<p>Business settings are stopped. The last applied settings and team are kept.</p>';
27
+ return '<h2>Business</h2>' + details
28
+ + '<p>The owner can stop receiving settings and team updates from Business. Confirm your identity first.</p>'
29
+ + '<div class="stack"><form method="post" action="/auth/step-up"><input type="hidden" name="action" value="business:stop"><input type="hidden" name="returnTo" value="/auth/settings/identity"><button class="secondary">Confirm identity</button></form>'
30
+ + '<form method="post" action="/auth/settings/business"><button class="secondary">Stop taking settings from Business</button></form></div>';
31
+ }
@@ -1,13 +1,18 @@
1
+ import { auditMutation, operatorWitness } from './audit.mjs';
1
2
  import { deny } from '../errors.mjs';
2
3
  // One persistence door for session and policy actors. The caller authorizes the
3
4
  // action; the actor fence repeats live authority in this atomic write/audit.
4
- export async function writeOperatorStatus(store, actor, target, status, now, audit) {
5
+ export async function writeOperatorStatus(store, actor, target, status, now, audit, adminAudit) {
5
6
  const fence = store.actorFence(actor, now);
6
7
  try {
7
8
  const statements = [[`UPDATE oa_operators SET status=? WHERE id=? AND version=? AND ${fence.sql} RETURNING id`, [status, target.id, target.version, ...fence.args]]];
8
9
  if (audit) statements.push([`INSERT INTO oa_auth_audit(id,actor_id,action,value,created_at)
9
10
  SELECT ?,?,?,?,? WHERE changes()>0`, [crypto.randomUUID(), audit.actor, audit.action, JSON.stringify(audit.value), now]]);
10
- const [result] = await store.batch(statements);
11
+ const [result] = await (adminAudit && target.status !== status ? auditMutation(store, { audit: adminAudit,
12
+ event: { action: status === 'active' ? 'operators.reactivate' : 'operators.deactivate', actorId: actor.operator.id, subjectId: target.id, detail: status, now },
13
+ before: { sql: `${fence.sql} AND EXISTS(SELECT 1 FROM oa_operators WHERE id=? AND version=?)`, args: [...fence.args, target.id, target.version] },
14
+ after: operatorWitness(target, 'status', status), statements,
15
+ }) : store.batch(statements));
11
16
  if (!result.results.some(row => row.id === target.id)) deny('authority_changed', 409);
12
17
  } catch (error) {
13
18
  if (String(error).includes('last_owner')) deny('last_owner', 409);
@@ -1,3 +1,5 @@
1
+ import { deny } from '../errors.mjs';
2
+ import { auditDomainRule } from './domain-audit.mjs';
1
3
  import { policyActorFence } from '../scheduled/fence.mjs';
2
4
  import { providerPinFence, recordProviderPin } from './provider-pin.mjs';
3
5
  // D1 batches are transactions. All decisions that grant a session or mutate
@@ -59,7 +61,7 @@ export class AuthStore {
59
61
  [input.id, input.hash, input.kind, input.returnTo, input.now, input.expiresAt, input.operatorId, ...fence.args]);
60
62
  return result?.id === input.id;
61
63
  }
62
- async invite({ operatorId, expectedVersion, reinviting = false, email, displayName, role, token, now }, actor) {
64
+ invitationStatements({ operatorId, expectedVersion, reinviting = false, email, displayName, role, token, now }, actor, audit) {
63
65
  const fence = this.actorFence(actor, now);
64
66
  // Only a witnessed cancellation may reopen an inactive identity. Keep its
65
67
  // durable admission guard until confirmation, including through pruning.
@@ -69,11 +71,11 @@ export class AuthStore {
69
71
  [displayName, operatorId, email, role, expectedVersion, operatorId, ...fence.args]]
70
72
  : [`INSERT INTO oa_operators(id,email,display_name,role,status,created_at)
71
73
  SELECT ?,?,?,?,'invited',? WHERE ${fence.sql} ON CONFLICT(email) DO NOTHING`, [operatorId, email, displayName, role, now, ...fence.args]];
72
- const results = await this.batch([
74
+ return [
73
75
  prepare,
74
76
  [`INSERT INTO oa_tokens(id,token_hash,kind,operator_id,operator_version,issuer_id,issuer_version,return_to,created_at,expires_at)
75
77
  SELECT ?,?,'invite',id,version,?,?,?,?,? FROM oa_operators WHERE id=? AND status='invited' AND role=? AND version=?
76
- ${reinviting ? 'AND changes()=1' : ''} AND ${fence.sql} RETURNING id`,
78
+ ${reinviting && !audit ? 'AND changes()=1' : ''} AND ${fence.sql} RETURNING id`,
77
79
  [token.id, token.hash, actor.operator.id, actor.operator.version, token.returnTo, now, token.expiresAt, operatorId, role, expectedVersion + (reinviting ? 1 : 0), ...fence.args]],
78
80
  // Bind revocation to this transaction's successful issuance, so a stale
79
81
  // reissue cannot invalidate the winner's link or send another credential.
@@ -82,8 +84,31 @@ export class AuthStore {
82
84
  // A link minted while using a dev session stays a dev credential.
83
85
  ...(actor.kind === 'dev' ? [[`INSERT INTO oa_dev_credentials(credential,id,created_at)
84
86
  SELECT 'oa_tokens',id,? FROM oa_tokens WHERE id=?`, [now, token.id]]] : []),
85
- ]);
86
- return results[1].results.some(row => row.id === token.id);
87
+ ];
88
+ }
89
+ async prepareInvitation(input, actor, audit) {
90
+ const statements = this.invitationStatements(input, actor, audit);
91
+ if (!audit) return { statements, mutationOffset: 0, mutationCount: statements.length };
92
+ const { operatorId, expectedVersion, reinviting = false, role, token, now } = input;
93
+ const fence = this.actorFence(actor, now);
94
+ const previousToken = await this.first('SELECT id FROM oa_tokens WHERE operator_id=? ORDER BY rowid DESC LIMIT 1', [operatorId]);
95
+ const extra = await audit({ action: 'operators.invite', actorId: actor.operator.id, subjectId: operatorId, detail: role, now });
96
+ const assertion = ({ sql, args }) => [
97
+ `SELECT CASE WHEN (${sql}) THEN 1 ELSE json_extract('[]', '$[oa_audit_refused') END`, args,
98
+ ];
99
+ const before = { sql: `${fence.sql} AND (NOT EXISTS(SELECT 1 FROM oa_operators WHERE id=?) OR EXISTS(SELECT 1 FROM oa_operators WHERE id=? AND version=?)) AND COALESCE((SELECT id FROM oa_tokens WHERE operator_id=? ORDER BY rowid DESC LIMIT 1),'')=?`, args: [...fence.args, operatorId, operatorId, expectedVersion, operatorId, previousToken?.id ?? ''] };
100
+ const after = { sql: 'EXISTS(SELECT 1 FROM oa_tokens WHERE id=? AND operator_id=? AND operator_version=?)', args: [token.id, operatorId, expectedVersion + (reinviting ? 1 : 0)] };
101
+ return { statements: [assertion(before), ...statements, assertion(after), ...extra], mutationOffset: 1, mutationCount: statements.length };
102
+ }
103
+ async invite(input, actor, prepared) {
104
+ const plan = prepared ?? await this.prepareInvitation(input, actor);
105
+ try {
106
+ const results = (await this.batch(plan.statements)).slice(plan.mutationOffset, plan.mutationOffset + plan.mutationCount);
107
+ return results[1].results.some(row => row.id === input.token.id);
108
+ } catch (error) {
109
+ if (String(error).includes('oa_audit_refused')) deny('authority_changed', 409);
110
+ throw error;
111
+ }
87
112
  }
88
113
  async preview(hash, now) {
89
114
  return this.first(`SELECT t.kind,t.expires_at AS expiresAt,t.return_to AS returnTo,o.email,o.role,t.issuer_id AS issuerId,t.issuer_version AS issuerVersion,
@@ -211,7 +236,8 @@ export class AuthStore {
211
236
  }
212
237
  domainRule(domain) { return this.first('SELECT domain,provider_id AS providerId FROM oa_domain_rules WHERE domain=?', [domain]); }
213
238
  async domainRules() { return (await this.statement('SELECT domain,provider_id AS providerId,created_at AS createdAt FROM oa_domain_rules ORDER BY domain').all()).results; }
214
- async setDomainRule({ domain, providerId, now }, actor) {
239
+ async setDomainRule({ domain, providerId, now }, actor, audit) {
240
+ if (audit) return auditDomainRule(this, { domain, providerId, now }, actor, audit);
215
241
  const fence = this.actorFence(actor, now);
216
242
  const result = providerId === null
217
243
  ? await this.run(`DELETE FROM oa_domain_rules WHERE domain=? AND ${fence.sql}`, [domain, ...fence.args])
@@ -0,0 +1,40 @@
1
+ import { deny } from './errors.mjs';
2
+ import { requirePost } from './http.mjs';
3
+
4
+ // The integration contains only public branding and owner-visible provenance.
5
+ // It never returns the signed document (which includes private team data).
6
+ export function businessSettingsControls({ businessSettings, config, accounts, authenticate, requireFreshProof, store, clock }) {
7
+ if (!businessSettings) return {};
8
+ async function owner(request, post = false) {
9
+ if (post) requirePost(request, config);
10
+ const actor = await authenticate(request), current = await accounts.owner();
11
+ if (!actor) deny('unauthenticated', 401);
12
+ if (!current || current.id !== actor.operator.id) deny('owner_required', 403);
13
+ return actor;
14
+ }
15
+ return {
16
+ businessSettings,
17
+ async publicPresentation() {
18
+ const brand = await businessSettings.publicBrand();
19
+ const logo = typeof brand.logo === 'string' && /^\/rer-business-logo\?v=[a-f0-9]{12,64}$/.test(brand.logo) ? brand.logo : undefined;
20
+ return { ...config.branding, ...(brand.displayName ? { productName: brand.displayName } : {}), ...(logo ? { mark: logo } : {}) };
21
+ },
22
+ async businessSettingsInfo(request) {
23
+ await owner(request);
24
+ const value = await businessSettings.read();
25
+ return { business: value.document?.business ?? null, rev: value.rev, appliedAt: value.appliedAt, stopped: value.stopped };
26
+ },
27
+ async stopBusinessSettings(request) {
28
+ const actor = await owner(request, true);
29
+ await requireFreshProof(actor);
30
+ const current = await owner(request);
31
+ if (current.operator.version !== actor.operator.version) deny('authority_changed', 409);
32
+ const sessionFence = store?.actorFence(actor, clock());
33
+ const guard = sessionFence ? { sql: `(${sessionFence.sql}) AND ?=(SELECT o.id FROM oa_operators o
34
+ LEFT JOIN oa_bootstrap b ON b.claim_id=o.id WHERE o.role='owner' AND o.status='active'
35
+ ORDER BY b.claim_id IS NULL,o.created_at,o.id LIMIT 1)`, args: [...sessionFence.args, actor.operator.id] } : undefined;
36
+ await businessSettings.stop(actor.operator.id, guard);
37
+ return { stopped: true };
38
+ },
39
+ };
40
+ }
@@ -8,7 +8,7 @@ import { isLocalCli } from '../../local-cli.mjs';
8
8
  import { linkMessage } from './message.mjs';
9
9
  import { completionHook } from '../after-confirm.mjs';
10
10
  import { demoEffectsEnabled } from '../../../demo/effects.mjs';
11
- export const STEP_UP_ACTIONS = Object.freeze(['providers:unlink', 'providers:relink', 'domains:change', 'owner:transfer', 'export', 'delete', 'credentials:mint', 'email:change']);
11
+ export const STEP_UP_ACTIONS = Object.freeze(['providers:unlink', 'providers:relink', 'domains:change', 'owner:transfer', 'export', 'delete', 'credentials:mint', 'email:change', 'business:stop']);
12
12
  export const STEP_UP_SECONDS = 600;
13
13
 
14
14
  // Persistence owns the atomic authority check, proof consumption and session
@@ -0,0 +1,31 @@
1
+ import { auditMutation } from '../../accounts/audit.mjs';
2
+
3
+ // Only the authorized OA administration door supplies this context. Provider
4
+ // discovery/first-use pinning and native account adapters retain their own paths.
5
+ export async function adminProviderChange(db, id, provider, metadata, previous, { audit, actorId, fence, now }) {
6
+ const store = { batch: statements => db.batch(statements.map(([sql, args]) => db.prepare(sql).bind(...args))) };
7
+ const snapshot = previous
8
+ ? { sql: 'EXISTS(SELECT 1 FROM oa_identity_providers WHERE provider_id=? AND linked_at=? AND status=?)', args: [id, previous.linkedAt, previous.status] }
9
+ : { sql: 'NOT EXISTS(SELECT 1 FROM oa_identity_providers WHERE provider_id=?)', args: [id] };
10
+ const revision = previous ? Math.max(previous.linkedAt + 1, now) : now;
11
+ const statements = [];
12
+ if (provider) {
13
+ const args = [provider.preset, metadata.issuer, provider.clientId, metadata.jwks, metadata.authorization, metadata.token, JSON.stringify(metadata.algorithms), provider.tokenAuthMethod, metadata.responseIssuer ? 1 : 0, metadata.interfaceVersion, revision, id];
14
+ statements.push(previous
15
+ ? [`UPDATE oa_identity_providers SET preset=?,status='linked',issuer=?,client_id=?,jwks_uri=?,authorization_endpoint=?,token_endpoint=?,algorithms=?,token_auth_method=?,response_iss=?,interface_version=?,linked_at=?,pending_issuer=NULL,pending_client_id=NULL,pending_preset=NULL,pending_at=NULL,jwks=NULL,jwks_fetched_at=NULL WHERE provider_id=? RETURNING provider_id`, args]
16
+ : [`INSERT INTO oa_identity_providers(preset,issuer,client_id,jwks_uri,authorization_endpoint,token_endpoint,algorithms,token_auth_method,response_iss,interface_version,linked_at,provider_id,status) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,'linked') RETURNING provider_id`, args]);
17
+ } else {
18
+ // Advance this pin's generation too: its old unlinked status cannot witness
19
+ // this request, and trigger side effects on other rows prove nothing here.
20
+ statements.push(["UPDATE oa_identity_providers SET status='unlinked',linked_at=? WHERE provider_id=? AND linked_at=? AND status='linked' RETURNING provider_id", [revision, id, previous.linkedAt]],
21
+ ['DELETE FROM oa_domain_rules WHERE provider_id=?', [id]]);
22
+ }
23
+ statements.push([`DELETE FROM oa_identity_provider_health WHERE provider_id LIKE ? AND provider_id NOT IN
24
+ (SELECT 'exchange:' || provider_id || ':' || linked_at FROM oa_identity_providers WHERE provider_id=? AND status='linked')`, [`exchange:${id}:%`, id]]);
25
+ return auditMutation(store, { audit,
26
+ event: { action: provider ? 'providers.relink' : 'providers.unlink', actorId, subjectId: null, detail: id, now },
27
+ before: { sql: `${fence.sql} AND ${snapshot.sql}`, args: [...fence.args, ...snapshot.args] },
28
+ after: { sql: 'EXISTS(SELECT 1 FROM oa_identity_providers WHERE provider_id=? AND linked_at=? AND status=?)', args: [id, revision, provider ? 'linked' : 'unlinked'] },
29
+ statements,
30
+ });
31
+ }
@@ -257,19 +257,26 @@ export function createOidcProviders({ admission, db, config: input, clientIp, fe
257
257
  return result;
258
258
  },
259
259
  /** Owner actions; the caller requires a fresh step-up proof first. */
260
- async relink(id) {
260
+ async relink(id, audit) {
261
261
  const provider = providers.get(id);
262
262
  check(provider, 'oidc_unknown_provider', 404);
263
+ const previous = audit ? await store.link(id) : undefined;
263
264
  const metadata = await observe(provider, () => discover(fetcher, provider, config));
264
- if (await store.link(id)) await store.relink(id, provider, metadata, clock());
265
+ if (audit) await store.adminChange(id, provider, metadata, previous, audit);
266
+ else if (await store.link(id)) await store.relink(id, provider, metadata, clock());
265
267
  else await store.pin(id, provider, metadata, clock());
266
268
  return store.link(id);
267
269
  },
268
- async unlink(id) {
270
+ async unlink(id, audit) {
269
271
  check(providers.has(id), 'oidc_unknown_provider', 404);
270
272
  // Only a pin can be ended; a provider never linked has nothing to unlink.
271
- check(await store.link(id), 'oidc_not_linked', 409);
272
- await store.unlink(id);
273
+ const previous = await store.link(id);
274
+ check(previous, 'oidc_not_linked', 409);
275
+ // Preserve the successful response for an ended pin, without an audit
276
+ // callback or another mutation. The unaudited path keeps its behavior.
277
+ if (audit && previous.status === 'unlinked') return;
278
+ if (audit) await store.adminChange(id, null, null, previous, audit);
279
+ else await store.unlink(id);
273
280
  },
274
281
  async links() {
275
282
  const [links, health] = await Promise.all([store.links(), store.health()]);
@@ -1,3 +1,4 @@
1
+ import { adminProviderChange } from './admin-audit.mjs';
1
2
  import { check, fail } from './errors.mjs';
2
3
 
3
4
  const linkColumns = `provider_id AS id, preset, status, issuer, client_id AS clientId, jwks_uri AS jwks, authorization_endpoint AS authorization, token_endpoint AS token,
@@ -14,6 +15,7 @@ export function storage(db) {
14
15
  (SELECT 'exchange:' || provider_id || ':' || linked_at FROM oa_identity_providers WHERE provider_id=? AND status='linked')`).bind(`exchange:${id}:%`, id);
15
16
  const guarded = async operation => { try { return await operation(); } catch { fail('oidc_storage_unavailable', 503); } };
16
17
  return {
18
+ adminChange: (...args) => adminProviderChange(db, ...args),
17
19
  async limit(bucket, expiresAt, maximum) {
18
20
  try {
19
21
  const row = await db.prepare('INSERT INTO oa_oidc_limits (bucket,count,expires_at) VALUES (?,1,?) ON CONFLICT(bucket) DO UPDATE SET count=count+1 RETURNING count').bind(bucket, expiresAt).first();