@runeditrun/rer 0.2.79 → 0.2.80

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 (113) 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/dev-identity.mjs +2 -2
  7. package/cli/export.mjs +1 -1
  8. package/cli/inspect.mjs +38 -2
  9. package/cli/main.mjs +8 -2
  10. package/cli/managed-server.mjs +1 -1
  11. package/cli/parse.mjs +7 -6
  12. package/cli/portability-worker.mjs +2 -1
  13. package/cli/portability.mjs +6 -2
  14. package/cli/production-auth.mjs +2 -1
  15. package/cli/production-mail.mjs +36 -9
  16. package/cli/project.mjs +5 -14
  17. package/cli/release.mjs +2 -1
  18. package/cli/site-preview.mjs +4 -1
  19. package/cli/site.mjs +3 -2
  20. package/edition-authoring/adopt.mjs +39 -0
  21. package/edition-authoring/base-acknowledgements.mjs +24 -0
  22. package/edition-authoring/base-copies.mjs +418 -0
  23. package/edition-authoring/cli.mjs +85 -0
  24. package/edition-authoring/copy-checkout.mjs +69 -0
  25. package/edition-authoring/files.mjs +15 -2
  26. package/edition-authoring/lock.mjs +48 -0
  27. package/edition-authoring/offline-git.mjs +28 -0
  28. package/edition-authoring/parent-comparison.mjs +77 -0
  29. package/edition-authoring/projection-lock.mjs +38 -0
  30. package/edition-authoring/release.mjs +48 -0
  31. package/edition-authoring/sources.mjs +114 -0
  32. package/edition-authoring/updates.mjs +105 -0
  33. package/global/CHANGELOG.md +12 -0
  34. package/global/README.md +17 -3
  35. package/global/cli/install.mjs +3 -1
  36. package/global/main.mjs +9 -12
  37. package/modules/container/build.mjs +1 -1
  38. package/modules/d1-transport/index.mjs +68 -21
  39. package/modules/demo/README.md +8 -2
  40. package/modules/demo/declaration.mjs +21 -0
  41. package/modules/demo/input-path.mjs +18 -0
  42. package/modules/demo/label.d.mts +1 -1
  43. package/modules/demo/label.mjs +10 -5
  44. package/modules/demo/navigation.mjs +32 -0
  45. package/modules/demo/run-url.mjs +9 -0
  46. package/modules/demo/vite.d.mts +7 -2
  47. package/modules/demo/vite.mjs +17 -2
  48. package/modules/demo-host/README.md +5 -3
  49. package/modules/demo-host/page-style.mjs +2 -2
  50. package/modules/demo-host/pages.mjs +3 -3
  51. package/modules/demo-host/plan.mjs +6 -4
  52. package/modules/demo-host/theme.mjs +5 -2
  53. package/modules/deploy-kit/README.md +19 -15
  54. package/modules/deploy-kit/owner-cli.mjs +1 -1
  55. package/modules/deploy-kit/readiness-window.mjs +3 -3
  56. package/modules/erasure/README.md +10 -5
  57. package/modules/import-kit/src/d1/README.md +15 -9
  58. package/modules/import-kit/src/d1/apply.ts +10 -6
  59. package/modules/import-kit/src/d1/atomic-prefix.ts +64 -0
  60. package/modules/import-kit/src/d1/budget.ts +48 -26
  61. package/modules/import-kit/src/d1/compressed-plan.ts +9 -2
  62. package/modules/import-kit/src/d1/database.ts +2 -1
  63. package/modules/import-kit/src/d1/jobs.ts +2 -1
  64. package/modules/import-kit/src/d1/plans.ts +4 -2
  65. package/modules/import-kit/src/d1/verified-plan.ts +63 -0
  66. package/modules/integrations/core/README.md +2 -2
  67. package/modules/mail/README.md +4 -3
  68. package/modules/mail/pnpm-lock.yaml +16 -0
  69. package/modules/operator-auth/accounts/native.mjs +3 -1
  70. package/modules/operator-auth/accounts/provider-control.mjs +7 -4
  71. package/modules/operator-auth/accounts/provider-setup.mjs +34 -0
  72. package/modules/operator-auth/accounts/settings-page.mjs +13 -4
  73. package/modules/operator-auth/conformance/README.md +1 -1
  74. package/modules/operator-auth/dev/index.mjs +22 -4
  75. package/modules/operator-auth/dev/refusal.mjs +19 -0
  76. package/modules/operator-auth/docs/README.md +6 -5
  77. package/modules/operator-auth/docs/tanstack-start.md +1 -1
  78. package/modules/operator-auth/docs/vite-spa.md +5 -6
  79. package/modules/operator-auth/index.d.mts +1 -1
  80. package/modules/operator-auth/page.mjs +14 -0
  81. package/modules/operator-auth/representation.mjs +83 -0
  82. package/modules/operator-auth/routes.mjs +25 -2
  83. package/modules/portability/README.md +91 -14
  84. package/modules/portability/bookkeeping.mjs +3 -3
  85. package/modules/portability/bridge.mjs +5 -4
  86. package/modules/portability/catalogue.mjs +12 -8
  87. package/modules/portability/cli.mjs +5 -1
  88. package/modules/portability/export.mjs +5 -11
  89. package/modules/portability/format.mjs +7 -1
  90. package/modules/portability/http-errors.mjs +51 -0
  91. package/modules/portability/http.mjs +4 -1
  92. package/modules/portability/import-lease.mjs +13 -2
  93. package/modules/portability/import.mjs +10 -0
  94. package/modules/portability/index.d.mts +3 -0
  95. package/modules/portability/references.mjs +20 -0
  96. package/modules/portability/schema-identity.mjs +13 -0
  97. package/modules/portability/schema-legacy.mjs +21 -0
  98. package/modules/portability/sqlite-tokens.mjs +121 -0
  99. package/modules/release/README.md +20 -9
  100. package/modules/release/github-verify.mjs +30 -9
  101. package/modules/site/docs-search/search.css +1 -1
  102. package/onboarding/README.md +16 -4
  103. package/onboarding/adapter.mjs +5 -1
  104. package/onboarding/schema/SETUP.schema.json +26 -1
  105. package/onboarding/schema/business-field-inputs.mjs +37 -0
  106. package/onboarding/schema/json-schema.mjs +6 -2
  107. package/onboarding/schema/setup-validation.mjs +20 -3
  108. package/onboarding/server.mjs +1 -1
  109. package/onboarding/setup-manifest.mjs +2 -0
  110. package/onboarding/start-origin-diagnostic.mjs +24 -0
  111. package/onboarding/ui/style.css +9 -9
  112. package/package.json +1 -1
  113. package/scripts/publish-check/README.md +1 -1
@@ -6,6 +6,7 @@ import type { D1PlanCodec } from './types.ts';
6
6
  import { planFingerprint } from '../plan/index.ts';
7
7
  import { canonicalHash, canonicalSize, canonicalChunks, cloneJson } from '../provenance/canonical-stream.ts';
8
8
  import { canonicalJson, sha256 } from '../provenance/identity.ts';
9
+ import { ownDecodedPlan, reusedExpansion, retainVerifiedExpansion, type PlanReadScope } from './verified-plan.ts';
9
10
 
10
11
  function validateRoundTrip(plan: ImportPlan, payload: Json, codec: D1PlanCodec): void {
11
12
  const roundtrip = codec.decode(cloneJson(payload));
@@ -25,7 +26,7 @@ export function expandCompressedPlan(body: string, codec?: D1PlanCodec): ImportP
25
26
  }
26
27
  /** Custody loading already parses the envelope to distinguish storage formats.
27
28
  * Reuse that object, still comparing its complete canonical bytes with body. */
28
- export function expandCompressedEnvelope(body: string, value: any, codec?: D1PlanCodec): ImportPlan {
29
+ export function expandCompressedEnvelope(body: string, value: any, codec?: D1PlanCodec, scope?: PlanReadScope): ImportPlan {
29
30
  if (!value || typeof value !== 'object' || Array.isArray(value)) throw new Error('STORED_PLAN_CHANGED');
30
31
  if (canonicalHash(value) !== sha256(body)) throw new Error('STORED_PLAN_CHANGED');
31
32
  if (![2,3].includes(value.d1Plan) || !Number.isSafeInteger(value.size) || value.size < 0) throw new Error('STORED_PLAN_CHANGED');
@@ -35,12 +36,18 @@ export function expandCompressedEnvelope(body: string, value: any, codec?: D1Pla
35
36
  if (value.compression !== undefined && value.compression !== 'brotli') throw new Error('STORED_PLAN_CHANGED');
36
37
  if (value.d1Plan === 3 && (!Number.isSafeInteger(value.expandedSize) || value.expandedSize < 0)) throw new Error('STORED_PLAN_CHANGED');
37
38
  if (value.d1Plan === 3 && value.dictionary === 2 && (!Number.isSafeInteger(value.payloadSize) || value.payloadSize < 0)) throw new Error('STORED_PLAN_CHANGED');
39
+ // loadPlans has freshly checked the complete manifest and chunk bytes. Only
40
+ // this exact request/body/codec can reuse its already verified expansion.
41
+ const prior = scope && reusedExpansion(scope, body, codec);
42
+ if (prior) return prior;
38
43
  const payload = decodePayload(value, codec);
39
44
  const payloadHash = value.d1Plan === 3 ? canonicalHash(payload) : undefined;
40
- const plan = (value.d1Plan === 3 ? codec!.decode(payload) : payload) as ImportPlan;
45
+ const decoded = (value.d1Plan === 3 ? codec!.decode(payload) : payload) as ImportPlan;
46
+ const plan = scope ? ownDecodedPlan(decoded) : decoded;
41
47
  if (value.d1Plan === 3 && canonicalHash(codec!.encode(plan)) !== payloadHash) throw new Error('STORED_PLAN_CHANGED');
42
48
  if (value.d1Plan === 3 && plan.fingerprint !== value.fingerprint) throw new Error('STORED_PLAN_CHANGED');
43
49
  if (value.d1Plan === 3 && canonicalSize(plan) !== value.expandedSize) throw new Error('STORED_PLAN_CHANGED');
50
+ if (scope) return retainVerifiedExpansion(scope, body, plan, codec);
44
51
  if (planFingerprint(plan) !== plan.fingerprint) throw new Error('STORED_PLAN_CHANGED');
45
52
  return plan;
46
53
  }
@@ -99,7 +99,7 @@ export async function atomic(context: D1ImportContext, action: ImportAction, sta
99
99
  }
100
100
  await context.storage.database.batch(packed.map(s => prepare(context.storage.database, s)));
101
101
  }
102
- function postConditions(context:Pick<D1ImportContext,'maxBatchBytes'>,statements:D1Sql[],scope?:NativeStagingScope,action:ImportAction='read'):D1Sql[]{
102
+ export function postConditions(context:Pick<D1ImportContext,'maxBatchBytes'>,statements:D1Sql[],scope?:NativeStagingScope,action:ImportAction='read'):D1Sql[]{
103
103
  const stream = scope ? [...jobLayoutGuards(scope.job), ...streamBoundary(scope.job.id, action)] : [];
104
104
  if(context.maxBatchBytes===undefined)return [...stream,...statements.flatMap(statement=>statement.finalChecks??[])];
105
105
  const readOnly=statements.every(s=>guardPredicate(s));
@@ -132,6 +132,7 @@ function atomicPreparation(context:Parameters<typeof authority>[0]&Pick<D1Import
132
132
  const packed=[...atomicStatements(context,action,statements),...readonlyChecks(post),...(post.length?[finalAuthority(context,action)]:[])];
133
133
  return {post,packed,count:packed.length+returnReads};
134
134
  }
135
+ export { atomicPrefix } from './atomic-prefix.ts';
135
136
  /** SELECT-only fence: inspect every packed scalar before publishing snapshots.
136
137
  * Mutations continue to use atomic() and SQL CHECK rollback, never this path. */
137
138
  export async function readAtomic(context: D1ImportContext, guards: D1Sql[], scope?: NativeStagingScope, action: ImportAction = 'read'): Promise<void> {
@@ -16,6 +16,7 @@ import { guardErasedSources } from './erasure-claims.ts';
16
16
  import { readOriginals } from './originals.ts';
17
17
  import { retiredError } from './retirement.ts';
18
18
  import { attachReversal, loadReversalState, reversalGuards, reversalState } from './undo-state.ts';
19
+ import { verifiedPlanFingerprint } from './verified-plan.ts';
19
20
 
20
21
  export function decode(row: any): ImportJob {
21
22
  return { id: row.id, fingerprint: row.fingerprint, destination: row.destination, namespace: row.namespace, mappingVersion: row.mapping_version, principalId: row.principal_id, state: row.state, checkpoint: row.checkpoint, total: row.total, fence: row.fence, error: row.error };
@@ -33,7 +34,7 @@ export async function stored(id: string, context: D1ImportContext, action: Impor
33
34
  planReads.set(job, planChunkReads(row.plan_json, fenced));
34
35
  if (job.destination !== context.destination || job.namespace !== context.namespace || job.mappingVersion !== context.mappingVersion || job.principalId !== context.authorization.principalId) throw new Error('JOB_BINDING_MISMATCH');
35
36
  if (context.reviewedFingerprint !== undefined && context.reviewedFingerprint !== job.fingerprint) throw new Error('REVIEW_FINGERPRINT_MISMATCH');
36
- if (planFingerprint(plan) !== job.fingerprint || plan.fingerprint !== job.fingerprint || plan.destination !== job.destination || plan.namespace !== job.namespace || plan.mappingVersion !== job.mappingVersion || plan.principalId !== job.principalId || plan.entries.length !== job.total) throw new Error('STORED_PLAN_CHANGED');
37
+ if ((verifiedPlanFingerprint(plan) ?? planFingerprint(plan)) !== job.fingerprint || plan.fingerprint !== job.fingerprint || plan.destination !== job.destination || plan.namespace !== job.namespace || plan.mappingVersion !== job.mappingVersion || plan.principalId !== job.principalId || plan.entries.length !== job.total) throw new Error('STORED_PLAN_CHANGED');
37
38
  job.erasedRecords = plan.entries.filter(entry => entry.erased).length;
38
39
  attachReversal(job, await loadReversalState(row, plan, context));
39
40
  await captureJobLayout(job, row, context, action);
@@ -2,6 +2,7 @@ import { retainedSql } from './retained-values.ts';
2
2
  import { changedLazy, putRow } from './expected-state.ts';
3
3
  import { compressedPlan, storedStreamPage } from './stream-plan.ts';
4
4
  import { expandCompressedEnvelope } from './compressed-plan.ts';
5
+ import { planReadScope } from './verified-plan.ts';
5
6
  import { Buffer } from 'node:buffer';
6
7
  import { createHash } from 'node:crypto';
7
8
  import type { ImportPlan } from '../types.ts';
@@ -79,6 +80,7 @@ export async function loadPlans(rows: any[], db: D1Database, codec?: D1PlanCodec
79
80
  }
80
81
  }
81
82
  for (const row of rows) {
83
+ const scope = planReadScope(db, row.id, row.plan_json, codec);
82
84
  const parsed = JSON.parse(row.plan_json), parts = chunks.filter(c => c.job_id === row.id);
83
85
  let plan: ImportPlan, compressed = false;
84
86
  if (parsed?.d1Plan === 1) {
@@ -86,11 +88,11 @@ export async function loadPlans(rows: any[], db: D1Database, codec?: D1PlanCodec
86
88
  const body = parts.map(c => c.body).join('');
87
89
  if (Buffer.byteLength(body) !== parsed.size || sha256(body) !== parsed.sha256) throw new Error('STORED_PLAN_CHANGED');
88
90
  const payload = JSON.parse(body);
89
- if ([2,3].includes(payload?.d1Plan)) { if (parsed.entries !== undefined) throw new Error('STORED_PLAN_CHANGED'); plan = expandCompressedEnvelope(body,payload,codec); compressed = true; }
91
+ if ([2,3].includes(payload?.d1Plan)) { if (parsed.entries !== undefined) throw new Error('STORED_PLAN_CHANGED'); plan = expandCompressedEnvelope(body,payload,codec,scope); compressed = true; }
90
92
  else { if (canonicalHash(payload) !== parsed.sha256) throw new Error('STORED_PLAN_CHANGED'); plan = payload; }
91
93
  // The entry locator a referenced read trusts must describe these exact chunks.
92
94
  if (parsed.entries !== undefined && canonicalJson(entryLocator(plan, parts)) !== canonicalJson(parsed.entries)) throw new Error('STORED_PLAN_CHANGED');
93
- } else plan = [2,3].includes(parsed?.d1Plan) ? expandCompressedEnvelope(row.plan_json,parsed,codec) : parsed;
95
+ } else plan = [2,3].includes(parsed?.d1Plan) ? expandCompressedEnvelope(row.plan_json,parsed,codec,scope) : parsed;
94
96
  const captured = fences.get(row.id);
95
97
  snapshots.set(plan, { body: row.plan_json, chunks: parts, ...(row.custody_revision === undefined ? {} : {revision: row.custody_revision}), ...(compressed ? {compressed} : {}), ...(captured === undefined ? {} : {fence: captured}) }); result.set(row.id, plan);
96
98
  }
@@ -0,0 +1,63 @@
1
+ import type { ImportPlan } from '../types.ts';
2
+ import { planFingerprint } from '../plan/index.ts';
3
+ import { cloneJson } from '../provenance/canonical-stream.ts';
4
+ import type { D1Database, D1PlanCodec } from './types.ts';
5
+
6
+ export interface PlanReadScope { database: D1Database; jobId: string; storedBody: string }
7
+ interface VerifiedExpansion {
8
+ jobId: string; storedBody: string; body: string; codecId?: string;
9
+ encode?: D1PlanCodec['encode']; decode?: D1PlanCodec['decode'];
10
+ plan: ImportPlan; fingerprint: string;
11
+ }
12
+ // One active child per request database bounds retention. This contains no job
13
+ // progress, custody fence or authority result; those are read on every load.
14
+ const expansions = new WeakMap<D1Database, VerifiedExpansion>();
15
+ const owned = new WeakSet<ImportPlan>();
16
+ const fingerprints = new WeakMap<ImportPlan, string>();
17
+
18
+ /** Visit ordinary plans too: changing away from compressed custody invalidates
19
+ * its previous receipt even if a later read returns to those old bytes. */
20
+ export function planReadScope(database: D1Database, jobId: string, storedBody: string, codec?: D1PlanCodec): PlanReadScope {
21
+ const prior = expansions.get(database);
22
+ if (prior && (prior.jobId !== jobId || prior.storedBody !== storedBody || prior.codecId !== codec?.id || prior.encode !== codec?.encode || prior.decode !== codec?.decode)) expansions.delete(database);
23
+ return { database, jobId, storedBody };
24
+ }
25
+
26
+ /** Codec callbacks may retain aliases. Own every container before protecting
27
+ * the graph whose verified fingerprint will survive awaited database reads. */
28
+ export function ownDecodedPlan(plan: ImportPlan): ImportPlan {
29
+ const result = cloneJson(plan);
30
+ const freeze = (value: unknown): void => {
31
+ if (value === null || typeof value !== 'object' || Object.isFrozen(value)) return;
32
+ for (const child of Object.values(value)) freeze(child);
33
+ Object.freeze(value);
34
+ };
35
+ freeze(result); owned.add(result);
36
+ return result;
37
+ }
38
+
39
+ /** A fresh root keeps plans.ts custody snapshots independent even when their
40
+ * immutable content is shared by overlapping reads of the same request. */
41
+ function readView(expansion: VerifiedExpansion): ImportPlan {
42
+ const plan = Object.freeze({ ...expansion.plan });
43
+ fingerprints.set(plan, expansion.fingerprint);
44
+ return plan;
45
+ }
46
+ export function reusedExpansion(scope: PlanReadScope, body: string, codec?: D1PlanCodec): ImportPlan | undefined {
47
+ const prior = expansions.get(scope.database);
48
+ if (prior?.jobId === scope.jobId && prior.storedBody === scope.storedBody && prior.body === body && prior.codecId === codec?.id && prior.encode === codec?.encode && prior.decode === codec?.decode) return readView(prior);
49
+ // A changed body, job or codec must never recover an earlier receipt later.
50
+ expansions.delete(scope.database);
51
+ return undefined;
52
+ }
53
+ export function retainVerifiedExpansion(scope: PlanReadScope, body: string, plan: ImportPlan, codec?: D1PlanCodec): ImportPlan {
54
+ if (!owned.has(plan)) throw new Error('IMPORT_PLAN_VERIFICATION_REQUIRED');
55
+ const fingerprint = planFingerprint(plan);
56
+ if (fingerprint !== plan.fingerprint) throw new Error('STORED_PLAN_CHANGED');
57
+ const expansion = { jobId: scope.jobId, storedBody: scope.storedBody, body, codecId: codec?.id, encode: codec?.encode, decode: codec?.decode, plan, fingerprint };
58
+ expansions.set(scope.database, expansion);
59
+ return readView(expansion);
60
+ }
61
+ /** Only owned immutable decoded graphs receive this receipt. Caller-owned
62
+ * creation plans and ordinary mutable decoded plans still need a full hash. */
63
+ export const verifiedPlanFingerprint = (plan: ImportPlan): string | undefined => fingerprints.get(plan);
@@ -4,10 +4,10 @@ Import portable delivery, signed webhook, token and D1 APIs from `./index.ts`.
4
4
  Import Node adapters explicitly from `./sqlite.ts` and `./node-transport.ts`.
5
5
  Node 26 is the tested runtime; no runtime npm dependency is needed.
6
6
 
7
- The [consumer guide](../README.md) contains fresh SQLite migration, enqueue and
7
+ The [consumer guide](https://github.com/runeditrun/base/blob/main/modules/integrations/README.md) contains fresh SQLite migration, enqueue and
8
8
  Worker scheduling examples. The [public contract](CONTRACT.md) defines exact
9
9
  HMAC framing, retry outcomes, durable replay and same-database token authority.
10
- The [receiver guide](../receiver.md) supplies executable Node and Fetch receiver
10
+ The [receiver guide](https://github.com/runeditrun/base/blob/main/modules/integrations/receiver.md) supplies executable Node and Fetch receiver
11
11
  boundaries that verify original bytes before claiming replay identities.
12
12
 
13
13
  Apply `schema.sql` once through the application's numbered migration ledger.
@@ -43,6 +43,7 @@ modules/mail/src/adapters/sendgrid/index.mjs
43
43
  modules/mail/src/adapters/sendgrid/serialize.mjs
44
44
  modules/mail/src/adapters/rer/contract.mjs
45
45
  modules/mail/src/adapters/rer/index.mjs
46
+ modules/mail/src/adapters/rer/list-headers.mjs
46
47
  modules/mail/src/adapters/messaging/contract.mjs
47
48
  modules/mail/src/adapters/messaging/event-schema.mjs
48
49
  modules/mail/src/adapters/messaging/index.mjs
@@ -118,14 +119,14 @@ These are for developing the module itself or documentation. A seed may keep any
118
119
  - `modules/mail/README.md` and every `README.md` under `modules/mail/src/`
119
120
 
120
121
  The provider is explicit: `sendgrid`, `resend`, `cloudflare`, `rer`, `messaging`, or `development`.
121
- `mode` is required (`production`, `development`, or `test`). Remote providers require `apiKey`; Cloudflare additionally requires a 32-hex `accountId`. A remote provider in test/development mode still makes a real provider request unless the caller explicitly supplies a test fetch. Missing credentials, validation errors, or provider failure never select another provider. Config and messages reject unknown fields so requested features cannot silently disappear.
122
+ `mode` is required (`production`, `development`, or `test`). SendGrid, Resend, Cloudflare and RER require `apiKey`; Cloudflare additionally requires a 32-hex `accountId`. Messaging instead requires its signed-link configuration (`serviceOrigin`, `installId`, `kid` and `signingKey`) and rejects `apiKey` and `accountId`. A remote provider in test/development mode still makes a real provider request unless the caller explicitly supplies a test fetch. Missing credentials, validation errors, or provider failure never select another provider. Config and messages reject unknown fields so requested features cannot silently disappear.
122
123
 
123
124
  `createMailSender(config, dependencies?)` returns `{send(message)}`. Dependencies are optional standard `fetch`, `clock: () => epochMilliseconds`, and `timeoutMilliseconds` (a positive safe integer bounding each remote attempt; the default is 15,000). Production normally uses global fetch. Direct provider endpoints are fixed; `rer` uses its assigned relay URL. No retry or automatic replay exists. The sender snapshots configuration at construction and the message at submission.
124
125
 
125
126
  ### Managed mail through RER
126
127
 
127
128
  Seeds opt into Managed mail with `mail: {providers: ["rer"]}` in their candidate
128
- deployment spec. The [delivery producer](../delivery-producer/README.md#managed-mail)
129
+ deployment spec. The [delivery producer](https://github.com/runeditrun/base/blob/main/modules/delivery-producer/README.md#managed-mail)
129
130
  can generate the matching setup fields. RER assigns public `MAIL_PROVIDER`,
130
131
  `MAIL_FROM`, `MAIL_RELAY_URL` and private `MAIL_API_KEY`; Managed owners do not
131
132
  enter them. Wire those settings into the shared sender:
@@ -202,7 +203,7 @@ adapter makes no retries and never reads or logs provider error bodies.
202
203
 
203
204
  ## Message and results
204
205
 
205
- Required fields: `deliveryId` (nonempty, at most 512 characters), `from`, nonempty `to: string[]`, `subject: string` (SendGrid requires nonempty; other providers allow empty), and at least one nonempty `text` or `html`. Addresses accept a mailbox or `Display Name <mailbox>`; the conservative mailbox grammar rejects controls, multiple addresses inside one string and malformed domains. Use arrays for recipients.
206
+ Required fields: `deliveryId` (nonempty, at most 512 characters), `from`, nonempty `to: string[]`, `subject: string` (SendGrid requires nonempty; RER requires nonblank and at most 200 characters; other providers allow empty), and at least one nonempty `text` or `html`. Addresses accept a mailbox or `Display Name <mailbox>`; the conservative mailbox grammar rejects controls, multiple addresses inside one string and malformed domains. Use arrays for recipients.
206
207
 
207
208
  Optional `cc`, `bcc`, `replyTo`, and string-valued `headers` preserve envelope and threading. `In-Reply-To` and ordered `References` can be supplied as headers. SendGrid and Resend also accept `Message-ID`; Cloudflare generates it and rejects a caller-supplied value; `rer` rejects it and assigns one from an optional `messageKey`. CR/LF/control characters, duplicate header names ignoring case, reserved envelope/MIME/security headers and invalid header names fail before a request. Provider-specific header restrictions are also enforced.
208
209
 
@@ -91,89 +91,105 @@ packages:
91
91
  resolution: {integrity: sha512-Y3dgX/6lE2QhQb+Gxy0WZxfg9MEm/JBjamZpS2IklP7xIQoKN4hzAm7KcMVGtaVDt3neE9OKBC7vAfonA/Lr1A==}
92
92
  cpu: [arm64]
93
93
  os: [linux]
94
+ libc: [glibc]
94
95
 
95
96
  '@img/sharp-libvips-linux-arm@1.3.4':
96
97
  resolution: {integrity: sha512-LmRtTsOHuvM2+wlO2Db37dx5MiZhB0FvSunciw48YjdOkZz9KAiRbm8ujeMOA1INqmei5NapFxYEK1D1ZSidmw==}
97
98
  cpu: [arm]
98
99
  os: [linux]
100
+ libc: [glibc]
99
101
 
100
102
  '@img/sharp-libvips-linux-ppc64@1.3.4':
101
103
  resolution: {integrity: sha512-Le6boB8Tai0Nis+gIxIpKx68UDVVIqdR8Tin5Yf1z2LJJQLDJvCDRqRu+jC2qCoD+eIomonmOwB4smBRxfVpYQ==}
102
104
  cpu: [ppc64]
103
105
  os: [linux]
106
+ libc: [glibc]
104
107
 
105
108
  '@img/sharp-libvips-linux-riscv64@1.3.4':
106
109
  resolution: {integrity: sha512-aHkkIEHPRdQEegJN20MLmGtxYD9R2wQr3Cwpddnu5+YKMt6Uzax7S9h5gpZTo8wyrGuZSlfQ63OevL5mTyOC7Q==}
107
110
  cpu: [riscv64]
108
111
  os: [linux]
112
+ libc: [glibc]
109
113
 
110
114
  '@img/sharp-libvips-linux-s390x@1.3.4':
111
115
  resolution: {integrity: sha512-ra/mB6MikESDUO7Yg+Mi95bFBb9GsObURuhnOv3OqknjGe9sZrG8tCe9q0xSIGrtLgvgw0gKnFWcK4blSgQOuQ==}
112
116
  cpu: [s390x]
113
117
  os: [linux]
118
+ libc: [glibc]
114
119
 
115
120
  '@img/sharp-libvips-linux-x64@1.3.4':
116
121
  resolution: {integrity: sha512-GJ//SSXbnwSDes02umB3nDJLFcQzw8a18V8fyhqr6tV515tOEMdImjjxj1AoafMRz56F3PHgftnj1QEKSU1zkw==}
117
122
  cpu: [x64]
118
123
  os: [linux]
124
+ libc: [glibc]
119
125
 
120
126
  '@img/sharp-libvips-linuxmusl-arm64@1.3.4':
121
127
  resolution: {integrity: sha512-hvulFwtjUcagsis6BBxHwGFwWoNZjgYmULGVrZcyfNbjA8hKILbRxGg15/7w5HDyXHXUos/j6baAWqnCyQ2DWA==}
122
128
  cpu: [arm64]
123
129
  os: [linux]
130
+ libc: [musl]
124
131
 
125
132
  '@img/sharp-libvips-linuxmusl-x64@1.3.4':
126
133
  resolution: {integrity: sha512-6zXKeE/p39I1AmA3cJG35eyBGNqNddLnUXjhwBnsGjFPWqf5VKkDBEqaEkPDoTEtkxwi2vv8Tcr2mDyP4So7Fg==}
127
134
  cpu: [x64]
128
135
  os: [linux]
136
+ libc: [musl]
129
137
 
130
138
  '@img/sharp-linux-arm64@0.35.5':
131
139
  resolution: {integrity: sha512-LYVx5JTsOM2CBzmxreh+nl64/3H6Xb09iSLknqH47z2T2DFFxDeFLP5y4dJwe6H7uGQlHPyEEtIqyo3DYsRwdQ==}
132
140
  engines: {node: '>=20.9.0'}
133
141
  cpu: [arm64]
134
142
  os: [linux]
143
+ libc: [glibc]
135
144
 
136
145
  '@img/sharp-linux-arm@0.35.5':
137
146
  resolution: {integrity: sha512-LEaXK2WdXVK5ykcw0buWyPMsmLLL2vpHLD6yrNSW+JGEL3BZPA4tpKN6iaMc4AxTTAoaX/sU1rOL51lcIz48ZQ==}
138
147
  engines: {node: '>=20.9.0'}
139
148
  cpu: [arm]
140
149
  os: [linux]
150
+ libc: [glibc]
141
151
 
142
152
  '@img/sharp-linux-ppc64@0.35.5':
143
153
  resolution: {integrity: sha512-QVxAAq8evVRI9ia2vqgwrmWucn5Dfv+JdWzj75pD8omHLPSP7f8p20O8jxzjCcuCEQEOtYOZUmX1hkiZ0kdevA==}
144
154
  engines: {node: '>=20.9.0'}
145
155
  cpu: [ppc64]
146
156
  os: [linux]
157
+ libc: [glibc]
147
158
 
148
159
  '@img/sharp-linux-riscv64@0.35.5':
149
160
  resolution: {integrity: sha512-LtdreXguaavKODPIfzJ4kffx7UNt1omwtK0rch4EBbbSTXPnxWmYSayXdLJw0fJzQ97kHt1gL/yh4tvU+nCyRQ==}
150
161
  engines: {node: '>=20.9.0'}
151
162
  cpu: [riscv64]
152
163
  os: [linux]
164
+ libc: [glibc]
153
165
 
154
166
  '@img/sharp-linux-s390x@0.35.5':
155
167
  resolution: {integrity: sha512-UZasTOFiYzotTsGOCu42BfUzP6Tu6Do/947iRm1RsLKvlllxwGcn4RN27LibGWceix4Y+Pmw3jsnTcCQIgWjqA==}
156
168
  engines: {node: '>=20.9.0'}
157
169
  cpu: [s390x]
158
170
  os: [linux]
171
+ libc: [glibc]
159
172
 
160
173
  '@img/sharp-linux-x64@0.35.5':
161
174
  resolution: {integrity: sha512-SxFtLTeJInhAA9Q836kux2vZNeOBQEx658qvbboZScr0wIARym3IcGmW7KpVD5sbVg0Ojy+udFQdayYIZyoNog==}
162
175
  engines: {node: '>=20.9.0'}
163
176
  cpu: [x64]
164
177
  os: [linux]
178
+ libc: [glibc]
165
179
 
166
180
  '@img/sharp-linuxmusl-arm64@0.35.5':
167
181
  resolution: {integrity: sha512-9HbMclmI1zlNkFRs3z9/eBtDjfD0sGlrX1z6b1qwmiFY5ElDLh4BC0LPBdVp7z1DXFiKlIcznf+ZlsuZzLxQqg==}
168
182
  engines: {node: '>=20.9.0'}
169
183
  cpu: [arm64]
170
184
  os: [linux]
185
+ libc: [musl]
171
186
 
172
187
  '@img/sharp-linuxmusl-x64@0.35.5':
173
188
  resolution: {integrity: sha512-4KOphqB035HrVdqLZfCgMzzERrQkkzOwRhl4OAkRO1YCldbaFjySXMaK534Mo0V+LndnlJk+sbUyLeU0ULyD1A==}
174
189
  engines: {node: '>=20.9.0'}
175
190
  cpu: [x64]
176
191
  os: [linux]
192
+ libc: [musl]
177
193
 
178
194
  '@img/sharp-wasm32@0.35.5':
179
195
  resolution: {integrity: sha512-Ptsga1su4tQx+LLF1ECS9U6nz5kmrXKo6XVbtR48Ke3ZRxxgaWBu7IDtEe1quo8hiupwm6WFqxVlXaSf7IINGQ==}
@@ -14,6 +14,7 @@ import { createOidcProviders } from '../identity/oidc/index.mjs';
14
14
  import { isLocalCli } from '../local-cli.mjs';
15
15
  import { nativeDependencyAuthority } from '../../dependencies/native.mjs';
16
16
  import { linkedProviders } from '../../dependencies/auth.mjs';
17
+ import { providerSetup } from './provider-setup.mjs';
17
18
 
18
19
  const ACCOUNT_METHODS = ['findById', 'getSession', 'signOut', 'policyVersion', 'identityEnabled', 'requiredProvider', 'bindAndIssueSession'];
19
20
  const PROOF_METHODS = ['limits', 'token', 'preview', 'consumeLink', 'revokeLink', 'stepUpPreview', 'stepUpChallenge', 'consumeStepUp', 'revokeStepUp', 'steppedUp'];
@@ -146,11 +147,12 @@ export function createNativeAuth({ accounts, proofs, db, config, clock, hooks, m
146
147
  async admitVerifiedPassword(request, id, { returnTo } = {}) {
147
148
  requirePost(request, config); return localSession(request, id, 'password', returnTo);
148
149
  },
149
- async identitySettings(request) { await owner(request); return { idpSignIn: await enabled() }; },
150
+ async identitySettings(request) { await owner(request); return { idpSignIn: await enabled(), providerSetup: await providerSetup(db, config) }; },
150
151
  async setIdentitySettings(request, { idpSignIn }) {
151
152
  const actor = await owner(request, true);
152
153
  if (typeof idpSignIn !== 'boolean') deny('invalid_input', 400);
153
154
  if (!accounts.setIdentitySettings) unavailable();
155
+ if (idpSignIn && !(await providerSetup(db, config)).canEnable) deny('provider_unlinked', 409);
154
156
  if (!await accounts.setIdentitySettings({ actor, idpSignIn, now: clock() })) deny('authority_changed', 409);
155
157
  return { idpSignIn };
156
158
  },
@@ -1,6 +1,7 @@
1
1
  import { devAdmitted } from '../dev-admission.mjs';
2
2
  import { deny } from '../errors.mjs';
3
3
  import { requirePost } from '../http.mjs';
4
+ import { providerEnableFence, providerSetup } from './provider-setup.mjs';
4
5
 
5
6
  export function providerControl({ store, accounts, authenticate, config, clock }) {
6
7
  async function owner(request, post = false) {
@@ -11,17 +12,19 @@ export function providerControl({ store, accounts, authenticate, config, clock }
11
12
  return actor;
12
13
  }
13
14
  return {
14
- async identitySettings(request) { await owner(request); return { idpSignIn: await accounts.identityEnabled() }; },
15
+ async identitySettings(request) { await owner(request); return { idpSignIn: await accounts.identityEnabled(), providerSetup: await providerSetup(store.db, config) }; },
15
16
  async setIdentitySettings(request, { idpSignIn }) {
16
17
  const actor = await owner(request, true);
17
18
  if (typeof idpSignIn !== 'boolean') deny('invalid_input', 400);
19
+ const readiness = idpSignIn ? providerEnableFence(config) : { sql: '1', args: [] };
20
+ if (idpSignIn && !(await providerSetup(store.db, config)).canEnable) deny('provider_unlinked', 409);
18
21
  const fence = store.actorFence(actor, clock());
19
22
  const currentOwner = `?=(SELECT o.id FROM oa_operators o LEFT JOIN oa_bootstrap b ON b.claim_id=o.id WHERE o.role='owner' AND o.status='active' ORDER BY b.claim_id IS NULL,o.created_at,o.id LIMIT 1)`;
20
23
  const auditId=crypto.randomUUID();
21
24
  const results = await store.batch([
22
- [`INSERT INTO oa_auth_settings(singleton,idp_sign_in,generation,first_setup) SELECT 1,0,0,0 WHERE ${fence.sql} AND ${currentOwner} ON CONFLICT(singleton) DO UPDATE SET first_setup=0 RETURNING singleton`, [...fence.args, actor.operator.id]],
23
- [`INSERT INTO oa_auth_settings(singleton,idp_sign_in,generation) SELECT 1,?,1 WHERE ${fence.sql} AND ${currentOwner} AND NOT EXISTS(SELECT 1 FROM oa_auth_settings WHERE singleton=1 AND idp_sign_in=?)
24
- ON CONFLICT(singleton) DO UPDATE SET idp_sign_in=excluded.idp_sign_in,generation=oa_auth_settings.generation+1,first_setup=0 RETURNING singleton`, [idpSignIn ? 1 : 0, ...fence.args, actor.operator.id, idpSignIn ? 1 : 0]],
25
+ [`INSERT INTO oa_auth_settings(singleton,idp_sign_in,generation,first_setup) SELECT 1,0,0,0 WHERE ${fence.sql} AND ${currentOwner} AND (${readiness.sql}) ON CONFLICT(singleton) DO UPDATE SET first_setup=0 RETURNING singleton`, [...fence.args, actor.operator.id, ...readiness.args]],
26
+ [`INSERT INTO oa_auth_settings(singleton,idp_sign_in,generation) SELECT 1,?,1 WHERE ${fence.sql} AND ${currentOwner} AND (${readiness.sql}) AND NOT EXISTS(SELECT 1 FROM oa_auth_settings WHERE singleton=1 AND idp_sign_in=?)
27
+ ON CONFLICT(singleton) DO UPDATE SET idp_sign_in=excluded.idp_sign_in,generation=oa_auth_settings.generation+1,first_setup=0 RETURNING singleton`, [idpSignIn ? 1 : 0, ...fence.args, actor.operator.id, ...readiness.args, idpSignIn ? 1 : 0]],
25
28
  [`INSERT INTO oa_auth_audit(id,actor_id,action,value,created_at) SELECT ?,?,'idpSignIn',?,? WHERE changes()=1`, [auditId, actor.operator.id, String(idpSignIn), clock()]],
26
29
  [`UPDATE oa_sessions SET revoked_at=COALESCE(revoked_at,?) WHERE kind='oidc' AND EXISTS(SELECT 1 FROM oa_auth_audit WHERE id=? AND value='false')`, [clock(), auditId]],
27
30
  ]);
@@ -0,0 +1,34 @@
1
+ // Registration state, independent of the sign-in switch and network health.
2
+ // Static providers pin on first use; an explicit unlink still requires relinking.
3
+ export function providerEnableFence(config) {
4
+ if (config.externalIssuers.length) return { sql: '1', args: [] };
5
+ const clauses = [], args = [];
6
+ for (const provider of config.providers) {
7
+ clauses.push("NOT EXISTS(SELECT 1 FROM oa_identity_providers WHERE provider_id=? AND status='unlinked')");
8
+ args.push(provider.id);
9
+ }
10
+ if (config.dependencies) clauses.push(`EXISTS(SELECT 1 FROM rer_dependency_link l JOIN rer_dependency_keys k ON k.interface=l.interface
11
+ WHERE l.interface='oidc-provider@1' AND l.needs_relink=0)
12
+ AND NOT EXISTS(SELECT 1 FROM oa_identity_providers WHERE provider_id='auth' AND status='unlinked')`);
13
+ return { sql: clauses.length ? clauses.map(sql => `(${sql})`).join(' OR ') : '0', args };
14
+ }
15
+
16
+ export async function providerSetup(db, config) {
17
+ const providers = [];
18
+ if (config.externalIssuers.length) providers.push({ id: 'external', label: 'Verified identity provider', state: 'configured' });
19
+ if (config.providers.length || config.dependencies) {
20
+ let pins = config.providers.length ? (await db.prepare('SELECT provider_id,status FROM oa_identity_providers').all()).results : [];
21
+ for (const provider of config.providers) {
22
+ const pin = pins.find(pin => pin.provider_id === provider.id);
23
+ providers.push({ id: provider.id, label: provider.label ?? provider.id, state: pin?.status ?? 'configured' });
24
+ }
25
+ if (config.dependencies) {
26
+ const link = await db.prepare(`SELECT l.needs_relink,EXISTS(SELECT 1 FROM rer_dependency_keys k WHERE k.interface=l.interface) AS has_key
27
+ FROM rer_dependency_link l WHERE l.interface='oidc-provider@1'`).first();
28
+ if (link && !config.providers.length) pins = (await db.prepare('SELECT provider_id,status FROM oa_identity_providers').all()).results;
29
+ const unlinked = pins.some(pin => pin.provider_id === 'auth' && pin.status === 'unlinked');
30
+ providers.push({ id: 'auth', label: 'Auth', state: !link || unlinked ? 'unlinked' : link.needs_relink || !link.has_key ? 'needs-relink' : 'linked' });
31
+ }
32
+ }
33
+ return { canEnable: providers.some(provider => ['linked', 'configured'].includes(provider.state)), providers };
34
+ }
@@ -1,9 +1,18 @@
1
1
  import { pageResponse } from '../page.mjs';
2
+ import { escapeHtml } from '../http.mjs';
2
3
 
3
4
  // The owner's sign-in settings, in the same frame (and seed theme) as sign-in.
4
- export function identitySettingsPage({ idpSignIn }, branding) {
5
- const content = '<p>Allow invited people to sign in through your linked identity provider. Email links remain available to the owner.</p>'
6
- + `<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' : ''}>Allow provider sign-in</label><button>Save settings</button></form>`
5
+ export function identitySettingsPage({ idpSignIn, providerSetup }, branding, { saved = false, error, status = 200, method = 'GET' } = {}) {
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>'
8
+ : saved ? `<p class="notice" role="status">Settings saved. Provider sign-in is ${idpSignIn ? 'on' : 'off'}.</p>` : '';
9
+ const setup = providerSetup.providers.length
10
+ ? providerSetup.providers.map(provider => `<p>${escapeHtml(provider.label)}: ${states[provider.state]}</p>`).join('')
11
+ : '<p>No identity provider is configured.</p>';
12
+ const content = notice + '<p>Allow invited people to sign in through your linked identity provider. Email links remain available to the owner.</p>'
13
+ + '<h2>Provider setup</h2>' + setup
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
+ + `<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>`
7
16
  + '<p class="secondary-link"><a href="/app">Back to app</a></p>';
8
- return pageResponse({ branding, title: 'Sign-in settings', heading: 'Sign-in settings', content, referrer: 'strict-origin' });
17
+ return pageResponse({ branding, title: 'Sign-in settings', heading: 'Sign-in settings', content, status, method, referrer: 'strict-origin' });
9
18
  }
@@ -35,7 +35,7 @@ without a theme its CSP adds only `img-src 'self'`. Every other resource rule
35
35
  above still applies, and mail stays image-free.
36
36
 
37
37
  The Base conformance registration is executable at
38
- [`../tests/conformance.test.ts`](../tests/conformance.test.ts), and its D1/Worker
38
+ [`../tests/conformance.test.ts`](https://github.com/runeditrun/base/blob/main/modules/operator-auth/tests/conformance.test.ts), and its D1/Worker
39
39
  adapter lives in this directory's `tests/worker.mjs` and `tests/runtime.mjs`.
40
40
  An adopting seed should map these methods to its actual Hono/Worker dispatcher
41
41
  and native private API, then import and call the exported registration from its
@@ -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
@@ -155,7 +155,7 @@ export interface OperatorAuth<R extends string = Role> {
155
155
  authenticateCredential(request:Request):Promise<{id:string;personId:string;fence:number;kind:SessionKind}|null>;
156
156
  authorizeDependencySetup(request: Request, input: { token?: string }): Promise<boolean>;
157
157
  completeLocalSetup(request:Request):Promise<{complete:boolean}>;
158
- identitySettings(request:Request):Promise<{idpSignIn:boolean}>;
158
+ identitySettings(request:Request):Promise<{idpSignIn:boolean;providerSetup:{canEnable:boolean;providers:Array<{id:string;label:string;state:'linked'|'configured'|'unlinked'|'needs-relink'}>}}>;
159
159
  setIdentitySettings(request:Request,input:{idpSignIn:boolean}):Promise<{idpSignIn:boolean}>;
160
160
  requireEditorOwner(request:Request):Promise<Session<R>>;
161
161
  credentialFence(request:Request):Promise<{personId:string;fence:number;kind:SessionKind}>;