@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
@@ -9,11 +9,13 @@ import { AuthError } from '../errors.mjs';
9
9
  import { hashToken, opaqueToken } from '../crypto.mjs';
10
10
  import { readCookie, sessionCookie, isLoopbackHost } from '../http.mjs';
11
11
  import { safeReturnTo } from '../policy.mjs';
12
- import { isActiveOperator, defaultRolePolicy } from '../accounts/roles.mjs';
12
+ import { isActiveOperator, emailAllowed, defaultRolePolicy } from '../accounts/roles.mjs';
13
13
  import { devGate, devNotFound } from '../dev-gate.mjs';
14
14
  import { registerDevAdmission } from '../dev-admission.mjs';
15
15
  import { definePersonas } from './personas.mjs';
16
16
  import { cliSession } from './cli-session.mjs';
17
+ import { signInRefusal } from './refusal.mjs';
18
+ import { representation } from '../representation.mjs';
17
19
  import { decorateLabel } from '../../demo/label.mjs';
18
20
  import { oneClickPage } from '../signin/one-click.mjs';
19
21
 
@@ -68,7 +70,13 @@ export function withDevIdentity(worker, { bindings = env => env, config: authCon
68
70
  const response = path === '/auth/local/cli-session' ? await cliSession(request, context, headers) : path === '/__dev/personas' ? Response.json(await context.list(request), { headers }) : await enter(request, gate, context);
69
71
  return rejectedResponse(request, response);
70
72
  } catch (error) {
71
- if (error instanceof AuthError) return rejectedResponse(request, Response.json({ error: error.code }, { status: error.status, headers }));
73
+ if (error instanceof AuthError) {
74
+ if (path === '/auth/dev/enter' && representation(request) === 'html') return rejectedResponse(request, await signInRefusal(request, context.config.branding, {
75
+ status: error.status,
76
+ message: 'This account can no longer use this sign-in link. Choose an available account, or ask an owner or administrator to restore its access.',
77
+ }));
78
+ return rejectedResponse(request, Response.json({ error: error.code }, { status: error.status, headers }));
79
+ }
72
80
  throw error;
73
81
  }
74
82
  }
@@ -109,8 +117,15 @@ function identity(env, authConfig, declared) {
109
117
  return { ...actor, hash: await hash(readCookie(request, config)) };
110
118
  },
111
119
  async list(request) {
112
- const personas = (await everyone()).map(({ as, email, role }) => ({ as, email, ...(role ? { role } : {}) }));
113
120
  const people = await auth.oneClick.people(request);
121
+ const personas = (await Promise.all((await everyone()).map(async ({ as, email, role }) => {
122
+ // Existing identities keep their real admission state. A declaration
123
+ // must never bring back an inactive account or an expired invitation.
124
+ const operator = email && await store.byEmail(email);
125
+ const person = people?.find(person => person.email === email);
126
+ if (email && (!emailAllowed(email, config.allowList) || (operator && !person))) return null;
127
+ return { as, email, ...(role ? { role: person?.role ?? role } : {}) };
128
+ }))).filter(Boolean);
114
129
  return [...personas, ...(people ?? []).filter(person => !personas.some(p => p.email === person.email))
115
130
  .map(person => ({ as: person.email, email: person.email, role: person.role })), { as: 'signed-out' }];
116
131
  },
@@ -159,7 +174,10 @@ async function enter(request, gate, { config, store, hash, current, everyone, ow
159
174
  operator = await store.byEmail(persona.email);
160
175
  }
161
176
  if (!operator) return text(409, 'The owner that rer setup claimed is not in this database. Run rer setup.');
162
- if (!isActiveOperator(operator, config.allowList)) return text(403, `${as} is not an active operator in this app.`);
177
+ if (!isActiveOperator(operator, config.allowList)) return signInRefusal(request, config.branding, {
178
+ status: 403,
179
+ message: 'This account is inactive or no longer allowed to sign in to this app. Choose another account, or ask an owner or administrator to restore its access.',
180
+ });
163
181
  const domain = operator.email.slice(operator.email.lastIndexOf('@') + 1);
164
182
  if (operator.role !== 'owner' && await store.domainRule(domain)) return text(403, 'Sign-in refused');
165
183
  if (existing?.kind !== 'dev' || existing.operator.id !== operator.id) {
@@ -0,0 +1,19 @@
1
+ import { escapeHtml, securityHeaders } from '../http.mjs';
2
+ import { pageResponse } from '../page.mjs';
3
+ import { safeReturnTo } from '../policy.mjs';
4
+ import { representation } from '../representation.mjs';
5
+
6
+ // Stale local persona links can outlive the account's access. Browser visits
7
+ // receive the same frame as sign-in, with a path back to the current choices.
8
+ export async function signInRefusal(request, branding, { status, message }) {
9
+ const chosen = representation(request, 'text');
10
+ if (chosen === 'json') return Response.json({ error: 'sign_in_refused' }, { status, headers: securityHeaders() });
11
+ if (chosen === 'text') return new Response(message, {
12
+ status, headers: { ...securityHeaders(), 'content-type': 'text/plain; charset=utf-8' },
13
+ });
14
+ const next = new URL(branding.signInPath, request.url);
15
+ next.searchParams.set('returnTo', safeReturnTo(new URL(request.url).searchParams.get('returnTo')));
16
+ return pageResponse({ branding, status, heading: 'This account cannot sign in',
17
+ content: `<p>${escapeHtml(message)}</p><a class="action" href="${escapeHtml(next.pathname + next.search)}">Choose another account</a>`,
18
+ });
19
+ }
@@ -13,8 +13,8 @@ credential cleanup data. See the [migration and cancellation contract](../README
13
13
 
14
14
  Use the standard Worker secrets `OWNER_EMAIL`, `SESSION_SECRET`, and
15
15
  `SETUP_TOKEN`. Generate independent random values of at least 32 bytes for the
16
- two secrets; retain only `OWNER_EMAIL` after first-owner setup and remove
17
- `SETUP_TOKEN` after bootstrap. `SESSION_SECRET` must remain stable for sessions.
16
+ two secrets; retain `OWNER_EMAIL` and the stable `SESSION_SECRET` after
17
+ first-owner setup, and remove `SETUP_TOKEN` after bootstrap.
18
18
  They belong in server bindings, never `VITE_*`, rendered HTML, loaders, browser
19
19
  storage, logs or responses. Bootstrap creates only the configured owner and its
20
20
  session. It runs without mail and does not populate product tables. Invoke the
@@ -36,9 +36,10 @@ attempt; the auth core does not retry it.
36
36
 
37
37
  `OWNER_EMAIL` is the first owner. The default roles are `owner`, `admin`, and
38
38
  `member`. Configure `allowList` only as an additional admission restriction; it
39
- does not grant access. Use the exported `rolePolicy` for deterministic product
40
- policy variations while preserving the module's active-session, allow-list,
41
- version-fence and last-owner checks.
39
+ does not grant access. Pass a deterministic `rolePolicy` option to
40
+ `createOperatorAuth` for product policy variations; `defaultRolePolicy` is the
41
+ exported default. Preserve the module's active-session, allow-list, version-fence
42
+ and last-owner checks.
42
43
 
43
44
  Follow one of these integration recipes:
44
45
 
@@ -3,7 +3,7 @@
3
3
  Keep auth, D1, mail construction and Worker bindings in server-owned modules.
4
4
  The client-importable server-function wrapper may be a normal `.ts` file, but
5
5
  load true server modules dynamically inside each handler, following
6
- [`TANSTACK-START-MIGRATION.md`](../../../TANSTACK-START-MIGRATION.md). A route's
6
+ [`TANSTACK-START-MIGRATION.md`](https://github.com/runeditrun/base/blob/main/TANSTACK-START-MIGRATION.md). A route's
7
7
  parent session check protects its document; every child server function that
8
8
  reads or changes private data must check the session again before its first
9
9
  private operation.
@@ -129,12 +129,11 @@ Pass the actual `createMailSender` result directly to the auth core. An
129
129
  `503 mail_unavailable`; there is no fallback or automatic retry. Resolve an
130
130
  uncertain attempt before requesting another link.
131
131
 
132
- Optional OIDC remains server-side: configure one exact HTTPS issuer, use the
133
- same `auth` and D1 for `createOidcClient`, dispatch its handler before
134
- `createAuthHandler`, and forward every Set-Cookie header. The client constructs
135
- its trusted admission closure from `auth.createIdentityAdmission({ issuer,
136
- subjectEmails })`; custom auth adapters must implement the same server-only
137
- contract. An existing issuer/subject binding may sign in again, while a
132
+ Optional OIDC remains server-side: configure `config.providers` and an
133
+ independent `OIDC_TRANSACTION_SECRET` on `createOperatorAuth`;
134
+ `createAuthHandler` serves the provider routes. Preserve every `Set-Cookie`
135
+ header individually. See the [OIDC guide](../identity/oidc/README.md) for provider
136
+ configuration and trusted `subjectEmails` mappings. An existing issuer/subject binding may sign in again, while a
138
137
  different principal cannot join an already-bound operator by presenting the same
139
138
  verified email. Configure any subject-to-existing-email association from trusted
140
139
  server configuration, never callback or browser input. Do not expose its
@@ -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();
@@ -10,7 +10,7 @@ export interface AuthPresentation { readonly productName: string; readonly accen
10
10
  export interface LinkPreview { kind: 'magic' | 'invite' | 'step_up' | 'owner'; expiresInMinutes: number }
11
11
  /** A step-up confirmation proves the session's operator again; it issues no new session. */
12
12
  export interface StepUpConfirmed { stepUp: StepUpAction; returnTo: string; cookie?: undefined }
13
- export type StepUpAction = 'providers:unlink' | 'providers:relink' | 'domains:change' | 'owner:transfer' | 'export' | 'delete' | 'credentials:mint' | 'email:change';
13
+ export type StepUpAction = 'providers:unlink' | 'providers:relink' | 'domains:change' | 'owner:transfer' | 'export' | 'delete' | 'credentials:mint' | 'email:change' | 'business:stop';
14
14
  export const STEP_UP_ACTIONS: readonly StepUpAction[];
15
15
  export type ProviderPreset = 'auth' | 'google' | 'microsoft' | 'okta' | 'legacy-rs256';
16
16
  /** One identity provider. Secrets and the private key are server bindings, never source text. */
@@ -84,14 +84,47 @@ export interface VerifiedIdentity extends VerifiedPrincipal { email: string; ema
84
84
  /** Deployment-owned association, never populated from token claims or HTTP input. */
85
85
  export interface IdentityAdmissionConfig { issuer: string; subjectEmails?: Record<string, string> }
86
86
  export type IdentityAdmission<R extends string = Role> = (request: Request, identity: VerifiedPrincipal, input?: { returnTo?: string }) => Promise<CompletedSession<R>>;
87
+ export type AuthAuditAction = 'operators.invite' | 'operators.cancel-invite' | 'operators.deactivate' | 'operators.reactivate' | 'operators.role' | 'sessions.revoke' | 'domains.rule.set' | 'domains.rule.lift' | 'providers.unlink' | 'providers.relink';
88
+ /** OA administrative mutation metadata only; no private identity, record or file data. */
89
+ export interface AuthAuditEvent {
90
+ action: AuthAuditAction;
91
+ /** Opaque oa_operators.id of the authenticated actor. */
92
+ actorId: string;
93
+ /** Target oa_operators.id; null for domain and provider actions. */
94
+ subjectId: string | null;
95
+ /** New role/status, normalized domain, provider id, or null for session revocation. */
96
+ detail: string | null;
97
+ /** Action clock time in milliseconds since the Unix epoch. */
98
+ now: number;
99
+ }
100
+ export type AuthAuditStatement = [sql: string, args: unknown[]];
87
101
  export interface AuthHooks<R extends string = Role> {
88
102
  /** Before an email link is sent to an active operator. Return false to send nothing; the public answer is unchanged. */
89
103
  beforeMagicLink?(input: { request: Request; email: string; operator: Operator<R> }): boolean | void | Promise<boolean | void>;
90
104
  /** After an email-link or provider sign-in completes. Return a returnTo to redirect; throw to refuse (the new session is revoked). */
91
105
  afterConfirm?(input: { request: Request; operator: Operator<R>; session: CompletedSession<R>['session']; method: 'email' | 'oidc'; returnTo: string }): void | { returnTo?: string } | Promise<void | { returnTo?: string }>;
106
+ /** OA administration only: pure SQL generation for the same mutation batch. Failure refuses the action; no external writes. */
107
+ audit?(input: AuthAuditEvent): AuthAuditStatement[] | Promise<AuthAuditStatement[]>;
92
108
  }
93
109
  export type { ScheduledPolicy, ScheduledPolicyDoor, PolicyApproval, PolicyRun } from './scheduled/index.mjs';
110
+ export interface BusinessSettingsIntegration {
111
+ publicBrand(): Promise<{ displayName?: string; logo?: string }>;
112
+ read(): Promise<{ document: { business: string } | null; rev: number; appliedAt: string | null; stopped: boolean }>;
113
+ /** The OA actor fence is supplied for an atomic owner-authority check. */
114
+ stop(actor: string, guard?: { sql: string; args: unknown[] }): Promise<void>;
115
+ }
116
+ export interface BusinessTeamRow { email: string; operatorId: string | null; invite: number; state: 'invited' | 'active' | 'inactive' | 'conflict' }
117
+ export interface BusinessTeamAdapter {
118
+ ownerEmail(): Promise<string | null>;
119
+ prepare(input: {
120
+ members: Array<{ email: string; name: string; role: 'admin' | 'member'; invite: number }>;
121
+ managed: BusinessTeamRow[]; ownerEmail: string; roles: { admin: string; member: string };
122
+ /** Evaluated after the Business revision/nonce CAS in the same D1 batch. */
123
+ guard: { sql: string; args: unknown[] };
124
+ }): Promise<{ statements: Statement[]; rows: BusinessTeamRow[]; afterCommit(): Promise<void> }>;
125
+ }
94
126
  export interface AuthOptions<R extends string = Role> {
127
+ businessSettings?: BusinessSettingsIntegration;
95
128
  /** OA store only: trusted source, re-read at approval/run/action time. */
96
129
  scheduledPolicies?: () => import('./scheduled/index.mjs').ScheduledPolicy[];
97
130
  db: Database; config: AuthConfig; mailSender?: MailSender; clientIp: (request: Request) => string | Promise<string>; rolePolicy?: RolePolicy; clock?: () => number;
@@ -145,6 +178,12 @@ export interface IdentityProviders {
145
178
  }
146
179
  export interface DomainRule { domain: string; providerId: string; createdAt: number }
147
180
  export interface OperatorAuth<R extends string = Role> {
181
+ /** OA accounts only. Signed Business documents must be verified before calling. */
182
+ readonly businessTeam?: BusinessTeamAdapter;
183
+ readonly businessSettings?: BusinessSettingsIntegration;
184
+ publicPresentation?(): Promise<AuthPresentation>;
185
+ businessSettingsInfo?(request: Request): Promise<{ business: string | null; rev: number; appliedAt: string | null; stopped: boolean }>;
186
+ stopBusinessSettings?(request: Request): Promise<{ stopped: true }>;
148
187
  readonly scheduledPolicies?: import('./scheduled/index.mjs').ScheduledPolicyDoor;
149
188
  /** Key-gated local development or an isolated hosted demo; unavailable in production. */
150
189
  readonly oneClick?: {
@@ -155,7 +194,7 @@ export interface OperatorAuth<R extends string = Role> {
155
194
  authenticateCredential(request:Request):Promise<{id:string;personId:string;fence:number;kind:SessionKind}|null>;
156
195
  authorizeDependencySetup(request: Request, input: { token?: string }): Promise<boolean>;
157
196
  completeLocalSetup(request:Request):Promise<{complete:boolean}>;
158
- identitySettings(request:Request):Promise<{idpSignIn:boolean}>;
197
+ identitySettings(request:Request):Promise<{idpSignIn:boolean;providerSetup:{canEnable:boolean;providers:Array<{id:string;label:string;state:'linked'|'configured'|'unlinked'|'needs-relink'}>}}>;
159
198
  setIdentitySettings(request:Request,input:{idpSignIn:boolean}):Promise<{idpSignIn:boolean}>;
160
199
  requireEditorOwner(request:Request):Promise<Session<R>>;
161
200
  credentialFence(request:Request):Promise<{personId:string;fence:number;kind:SessionKind}>;
@@ -36,3 +36,17 @@ export async function pageResponse({ branding, title, heading, content, status =
36
36
  if (referrer) headers['Referrer-Policy'] = referrer;
37
37
  return new Response(method === 'HEAD' ? null : html, { status, headers });
38
38
  }
39
+
40
+ // Refusals on private document routes use the same frame as sign-in. The API
41
+ // adapter keeps its typed JSON response for callers that did not ask for HTML.
42
+ export function settingsRefusalPage(request, branding, code, status) {
43
+ const ownerOnly = code === 'owner_required';
44
+ const unauthenticated = code === 'unauthenticated';
45
+ const heading = ownerOnly ? 'Only the owner can change sign-in settings' : unauthenticated ? 'Sign in to view these settings' : 'Settings could not be changed';
46
+ const message = ownerOnly ? 'Your account can use the app. Ask the installation owner to manage identity providers.'
47
+ : unauthenticated ? 'Your session has ended or you are signed out. Sign in, then open settings again.'
48
+ : 'The request was refused and no settings were saved. Return to the app, reload settings and try again.';
49
+ const href = unauthenticated ? branding.signInPath : '/app';
50
+ return pageResponse({ branding, heading, status, method: request.method,
51
+ content: `<p>${message}</p><a class="action" href="${escapeHtml(href)}">${unauthenticated ? 'Sign in' : 'Back to app'}</a>` });
52
+ }
@@ -0,0 +1,83 @@
1
+ const token = /^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/;
2
+ const quality = /^(?:0(?:\.[0-9]{0,3})?|1(?:\.0{0,3})?)$/;
3
+
4
+ // Commas and semicolons inside quoted parameter values are not separators.
5
+ function split(value, separator) {
6
+ const parts = [];
7
+ let start = 0, quoted = false, escaped = false;
8
+ for (let i = 0; i < value.length; i++) {
9
+ const char = value[i];
10
+ if (escaped) escaped = false;
11
+ else if (quoted && char === '\\') escaped = true;
12
+ else if (char === '"') quoted = !quoted;
13
+ else if (!quoted && char === separator) { parts.push(value.slice(start, i)); start = i + 1; }
14
+ }
15
+ return quoted || escaped ? null : [...parts, value.slice(start)];
16
+ }
17
+
18
+ function ranges(value) {
19
+ if (/[\u0000-\u0008\u000a-\u001f\u007f]/.test(value)) return null;
20
+ const members = split(value, ',');
21
+ if (!members) return null;
22
+ const result = [];
23
+ for (const member of members) {
24
+ if (!member.trim()) continue; // RFC 9110 list syntax permits empty members.
25
+ const parts = split(member, ';');
26
+ if (!parts) return null;
27
+ const media = parts.shift().trim().toLowerCase().split('/');
28
+ if (media.length !== 2 || !media.every(part => token.test(part)) || (media[0] === '*' && media[1] !== '*')) return null;
29
+ const parameters = new Map();
30
+ let q = 1, weighted = false;
31
+ for (const part of parts) {
32
+ if (!part.trim()) continue;
33
+ const at = part.indexOf('='), name = part.slice(0, at).trim().toLowerCase(), raw = part.slice(at + 1).trim();
34
+ if (at < 0 || !token.test(name)) return null;
35
+ if (name === 'q') {
36
+ if (weighted || !quality.test(raw)) return null;
37
+ q = Number(raw); weighted = true;
38
+ } else {
39
+ if (parameters.has(name)) return null;
40
+ const quoted = /^"(?:[\t !#-\[\]-~\u0080-\u00ff]|\\[\t\x20-\x7e\u0080-\u00ff])*"$/.test(raw);
41
+ if (!token.test(raw) && !quoted) return null;
42
+ parameters.set(name, quoted ? raw.slice(1, -1).replace(/\\(.)/g, '$1') : raw);
43
+ }
44
+ }
45
+ result.push({ media, parameters, q, order: result.length });
46
+ }
47
+ return result;
48
+ }
49
+
50
+ function preference(accepted, type, subtype) {
51
+ let best = { q: 0, specificity: -1, parameters: -1, order: Infinity };
52
+ for (const range of accepted) {
53
+ if ((range.media[0] !== '*' && range.media[0] !== type) || (range.media[1] !== '*' && range.media[1] !== subtype)) continue;
54
+ // Both responses are UTF-8; other media parameters are not supplied.
55
+ if ([...range.parameters].some(([name, value]) => name !== 'charset' || value.toLowerCase() !== 'utf-8')) continue;
56
+ const specificity = range.media[0] === '*' ? 0 : range.media[1] === '*' ? 1 : 2;
57
+ const parameters = range.parameters.size;
58
+ // Most specific matching range sets quality, including an explicit q=0.
59
+ // Equally specific duplicate ranges use the first occurrence.
60
+ if (specificity > best.specificity || (specificity === best.specificity && parameters > best.parameters)) {
61
+ best = { q: range.q, specificity, parameters, order: range.order };
62
+ }
63
+ }
64
+ return best;
65
+ }
66
+
67
+ /**
68
+ * RFC 9110 Accept negotiation for the auth HTML/JSON surfaces. Equal quality
69
+ * prefers specificity, then header order. No preference (absent or wildcard),
70
+ * malformed fields, or no acceptable representation retain the non-HTML route
71
+ * default. Request Content-Type never overrides the response preference.
72
+ */
73
+ export function representation(request, routeDefault = 'json') {
74
+ const accepted = ranges(request.headers.get('accept') ?? '');
75
+ if (!accepted?.length) return routeDefault;
76
+ const html = preference(accepted, 'text', 'html');
77
+ const json = preference(accepted, 'application', 'json');
78
+ if (!html.q) return html.specificity >= 0 || json.q ? 'json' : routeDefault;
79
+ if (html.q !== json.q) return html.q > json.q ? 'html' : 'json';
80
+ if (html.specificity !== json.specificity) return html.specificity > json.specificity ? 'html' : 'json';
81
+ if (html.parameters !== json.parameters) return html.parameters > json.parameters ? 'html' : 'json';
82
+ return html.order === json.order ? routeDefault : html.order < json.order ? 'html' : 'json';
83
+ }
@@ -1,5 +1,7 @@
1
1
  import { rejectedResponse } from './rejected-response.mjs';
2
2
  import { identitySettingsPage } from './accounts/settings-page.mjs';
3
+ import { settingsRefusalPage } from './page.mjs';
4
+ import { representation } from './representation.mjs';
3
5
  import { confirmationResponse } from './identity/email-link/confirmation.mjs';
4
6
  import { createOidcHandler } from './identity/oidc/index.mjs';
5
7
  import { AuthError } from './errors.mjs';
@@ -64,10 +66,15 @@ export function createAuthHandler(auth) {
64
66
  if (auth.scheduledPolicies && path === '/auth/policy-runs' && request.method === 'GET') return json(await auth.scheduledPolicies.runs(request));
65
67
  if (path === '/auth/sessions' && request.method === 'GET') return json(await auth.listSessions(request, readParameters(url.searchParams).operatorId));
66
68
  if (path === '/auth/domain-rules' && request.method === 'GET') return json(await auth.listDomainRules(request));
67
- if (path === '/auth/settings/identity' && request.method === 'GET') {const value=await auth.identitySettings(request);return /text\/html/.test(request.headers.get('accept')??'')?await identitySettingsPage(value,auth.presentation):json(value);}
69
+ if (path === '/auth/settings/identity' && ['GET', 'HEAD'].includes(request.method)) {
70
+ const value = { ...await auth.identitySettings(request), ...(auth.businessSettingsInfo ? { business: await auth.businessSettingsInfo(request) } : {}) };
71
+ return representation(request) === 'html'
72
+ ? await identitySettingsPage(value, auth.publicPresentation ? await auth.publicPresentation() : auth.presentation, { saved: url.searchParams.get('saved') === '1', method: request.method })
73
+ : request.method === 'HEAD' ? new Response(null, { headers: { ...securityHeaders(), 'content-type': 'application/json' } }) : json(value);
74
+ }
68
75
  if (path === '/auth/providers' && request.method === 'GET') return json(await auth.listProviders(request));
69
76
  const posts = new Set(['/auth/bootstrap', '/auth/magic-link', '/auth/confirm', '/auth/signout', '/auth/invite', '/auth/invite/cancel', '/auth/review-session',
70
- '/auth/policy/approve', '/auth/policy/revoke', '/auth/operator/status', '/auth/operator/role', '/auth/session/revoke', '/auth/step-up', '/auth/domain-rules', '/auth/providers/unlink', '/auth/providers/relink', '/auth/settings/identity', '/auth/setup-complete', OWNER_SIGNIN_PATH, '/auth/email', '/auth/display-name']);
77
+ '/auth/policy/approve', '/auth/policy/revoke', '/auth/operator/status', '/auth/operator/role', '/auth/session/revoke', '/auth/step-up', '/auth/domain-rules', '/auth/providers/unlink', '/auth/providers/relink', '/auth/settings/identity', '/auth/settings/business', '/auth/setup-complete', OWNER_SIGNIN_PATH, '/auth/email', '/auth/display-name']);
71
78
  if (!posts.has(path)) return json({ error: 'not_found' }, 404);
72
79
  if (request.method !== 'POST') return json({ error: 'method_not_allowed' }, 405);
73
80
  const query = readParameters(url.searchParams);
@@ -80,7 +87,15 @@ export function createAuthHandler(auth) {
80
87
  switch (path) {
81
88
  case '/auth/policy/approve': return json(await auth.scheduledPolicies.approve(request, input));
82
89
  case '/auth/policy/revoke': await auth.scheduledPolicies.revoke(request, input); return json({ revoked: true });
83
- case '/auth/settings/identity': {const value=await auth.setIdentitySettings(request,formPost(request)?{idpSignIn:input.idpSignIn==='true'}:input);return formPost(request)?seeOther('/auth/settings/identity'):json(value);}
90
+ case '/auth/settings/identity': {
91
+ const value = await auth.setIdentitySettings(request, formPost(request) ? { idpSignIn: input.idpSignIn === 'true' } : input);
92
+ return formPost(request) ? seeOther('/auth/settings/identity?saved=1') : json(value);
93
+ }
94
+ case '/auth/settings/business': {
95
+ if (!auth.stopBusinessSettings) return json({ error: 'not_found' }, 404);
96
+ const value = await auth.stopBusinessSettings(request);
97
+ return formPost(request) ? seeOther('/auth/settings/identity') : json(value);
98
+ }
84
99
  case '/auth/setup-complete': return json(await auth.completeLocalSetup(request));
85
100
  case '/auth/bootstrap': { const value = await auth.bootstrap(request, input); return seeOther(value.returnTo, value.cookie); }
86
101
  case '/auth/magic-link': {
@@ -118,6 +133,15 @@ export function createAuthHandler(auth) {
118
133
  case '/auth/providers/relink': return json(await auth.relinkProvider(request, input));
119
134
  }
120
135
  } catch (error) {
136
+ if (['/auth/settings/identity', '/auth/settings/business'].includes(path) && representation(request) === 'html') {
137
+ const code = error instanceof AuthError ? error.code : 'auth_unavailable';
138
+ const status = error instanceof AuthError ? error.status : 503;
139
+ if (code === 'provider_unlinked' || code === 'step_up_required') {
140
+ try { return await identitySettingsPage({ ...await auth.identitySettings(request), ...(auth.businessSettingsInfo ? { business: await auth.businessSettingsInfo(request) } : {}) }, auth.publicPresentation ? await auth.publicPresentation() : auth.presentation, { error: code, status, method: request.method }); }
141
+ catch { return settingsRefusalPage(request, auth.presentation, 'auth_unavailable', 503); }
142
+ }
143
+ return settingsRefusalPage(request, auth.presentation, code, status);
144
+ }
121
145
  if (form) return seeOther(notice(auth, error instanceof AuthError ? error.code : 'auth_unavailable'));
122
146
  if (error instanceof AuthError) return json({ error: error.code }, error.status);
123
147
  // Do not put SQL, email addresses, setup tokens or provider exceptions on the wire.
@@ -126,6 +150,10 @@ export function createAuthHandler(auth) {
126
150
  };
127
151
  return async function(request) {
128
152
  const response = await handleAuth(request);
153
+ if (response && request.method === 'HEAD' && new URL(request.url).pathname === '/auth/settings/identity') {
154
+ void response.body?.cancel();
155
+ return rejectedResponse(request, new Response(null, { status: response.status, headers: response.headers }));
156
+ }
129
157
  return response ? rejectedResponse(request, response) : response;
130
158
  };
131
159
  }
@@ -1,5 +1,7 @@
1
1
  // Composed identity over Base's OA accounts, or an explicitly paired native
2
2
  // accounts/proof adapter. Native composition never constructs the OA store.
3
+ import { businessSettingsControls } from './business-settings.mjs';
4
+ import { businessTeam } from './accounts/business-team.mjs';
3
5
  import { scheduledPolicies } from './scheduled/index.mjs';
4
6
  import { fencedCredentials } from './accounts/credentials.mjs';
5
7
  import { providerControl } from './accounts/provider-control.mjs';
@@ -29,8 +31,8 @@ export function createOperatorAuth(options) {
29
31
  const { db, config: input, mailSender, clientIp, rolePolicy = defaultRolePolicy, clock = Date.now, hooks = {}, fetch, waitUntil, accounts: nativeAccounts, proofs } = options;
30
32
  const config = configure(input);
31
33
  if (typeof clientIp !== 'function') throw new AuthError('client_ip_required', 503);
32
- if (!hooks || typeof hooks !== 'object' || ['beforeMagicLink', 'afterConfirm'].some(name => hooks[name] !== undefined && typeof hooks[name] !== 'function')) throw new AuthError('invalid_configuration', 503);
33
- if (Object.hasOwn(options, 'accounts') || Object.hasOwn(options, 'proofs')) return createNativeAuth({ db, config, accounts: nativeAccounts, proofs, mailSender, clientIp, clock, hooks, fetch, waitUntil });
34
+ if (!hooks || typeof hooks !== 'object' || ['beforeMagicLink', 'afterConfirm', 'audit'].some(name => hooks[name] !== undefined && typeof hooks[name] !== 'function')) throw new AuthError('invalid_configuration', 503);
35
+ if (Object.hasOwn(options, 'accounts') || Object.hasOwn(options, 'proofs')) return createNativeAuth({ db, config, accounts: nativeAccounts, proofs, mailSender, clientIp, clock, hooks, fetch, waitUntil, businessSettings: options.businessSettings });
34
36
  const store = new AuthStore(db);
35
37
  const sessions = oaSessions({ config, store, clock });
36
38
  const { hash, newSession, completed, authenticate } = sessions;
@@ -73,10 +75,13 @@ export function createOperatorAuth(options) {
73
75
  },
74
76
  } });
75
77
  const { limit, newToken, sendLink, requireFreshProof } = email;
76
- const admin = administration({ config, store, clock, authorize: rolePolicy, authenticate, newToken, sendLink, limit, requireFreshProof, providers });
78
+ const adminContext = { config, store, clock, authorize: rolePolicy, authenticate, newToken, sendLink, limit, requireFreshProof, providers, accounts, audit: hooks.audit };
79
+ const { prepareInvitation: _prepareInvitation, ...admin } = administration(adminContext);
77
80
  const external = legacyAdmission({ admission, config });
78
81
  return Object.freeze({
79
82
  ...admin,
83
+ businessTeam: businessTeam(adminContext),
84
+ ...businessSettingsControls({ businessSettings: options.businessSettings, config, accounts, authenticate, requireFreshProof, store, clock }),
80
85
  ...(options.scheduledPolicies ? { scheduledPolicies: scheduledPolicies({ definitions: options.scheduledPolicies, store, config, clock, authenticate, requireFreshProof, rolePolicy }) } : {}),
81
86
  ...providerControl({ store, accounts, authenticate, config, clock }),
82
87
  ...fencedCredentials({store,authenticate,requireFreshProof,config,clock,hash}),
@@ -48,7 +48,7 @@ export function createSignInHandler(auth, { setup, links, defaultReturnTo = '/ap
48
48
  return async function signIn(request) {
49
49
  const url = new URL(request.url);
50
50
  if (url.pathname !== path || !['GET', 'HEAD'].includes(request.method)) return null;
51
- const branding = auth.presentation;
51
+ const branding = auth.publicPresentation ? await auth.publicPresentation() : auth.presentation;
52
52
  const returnTo = safeReturnTo(url.searchParams.get('returnTo'), defaultReturnTo);
53
53
  const hint = emailHint(url.searchParams.get('login_hint'));
54
54
  const providers = auth.providers ? (await auth.providers.list()).filter(p => p.visible) : [];