@runeditrun/rer 0.2.20 → 0.2.22

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 (51) hide show
  1. package/cli/README.md +7 -0
  2. package/cli/demo-host.mjs +9 -8
  3. package/cli/demo-removal-provider.mjs +24 -0
  4. package/cli/deploy-command.mjs +10 -7
  5. package/cli/deploy-hook.mjs +10 -14
  6. package/cli/deploy.mjs +3 -1
  7. package/cli/export.mjs +1 -1
  8. package/cli/managed-server.mjs +5 -2
  9. package/cli/production-auth.mjs +19 -5
  10. package/global/CHANGELOG.md +7 -1
  11. package/modules/container/README.md +10 -0
  12. package/modules/container/build.mjs +10 -12
  13. package/modules/container/host.mjs +3 -1
  14. package/modules/container/ingress.mjs +15 -4
  15. package/modules/container/migration-inventory.mjs +33 -0
  16. package/modules/container/migrations.mjs +16 -2
  17. package/modules/delivery-producer/migrations.mjs +61 -0
  18. package/modules/demo/effects.mjs +4 -0
  19. package/modules/demo-host/README.md +34 -15
  20. package/modules/demo-host/capacity.mjs +1 -1
  21. package/modules/demo-host/container.mjs +73 -39
  22. package/modules/demo-host/diagnostics.mjs +1 -0
  23. package/modules/demo-host/pages.mjs +1 -1
  24. package/modules/demo-host/placement.mjs +23 -0
  25. package/modules/demo-host/plan.mjs +20 -7
  26. package/modules/demo-host/remove.mjs +9 -7
  27. package/modules/demo-host/start-script.mjs +10 -1
  28. package/modules/demo-host/startup.mjs +4 -2
  29. package/modules/demo-host/worker.mjs +18 -1
  30. package/modules/dependencies/approval.mjs +3 -2
  31. package/modules/dependencies/index.mjs +2 -2
  32. package/modules/deploy-kit/README.md +16 -2
  33. package/modules/deploy-kit/diagnostics.mjs +9 -0
  34. package/modules/deploy-kit/health-request.mjs +7 -5
  35. package/modules/deploy-kit/provider-transport.mjs +56 -0
  36. package/modules/deploy-kit/provider.mjs +22 -20
  37. package/modules/operator-auth/README.md +4 -0
  38. package/modules/operator-auth/accounts/credentials.mjs +2 -2
  39. package/modules/operator-auth/accounts/email-change.mjs +2 -2
  40. package/modules/operator-auth/accounts/provider-control.mjs +3 -3
  41. package/modules/operator-auth/accounts/store.mjs +9 -8
  42. package/modules/operator-auth/dev/cli-session.mjs +5 -4
  43. package/modules/operator-auth/dev/index.mjs +5 -5
  44. package/modules/operator-auth/dev-gate.mjs +4 -2
  45. package/modules/operator-auth/identity/email-link/index.mjs +2 -1
  46. package/modules/operator-auth/signin/index.mjs +10 -2
  47. package/onboarding/adapter.mjs +11 -3
  48. package/onboarding/operator-installer.mjs +2 -2
  49. package/onboarding/operator-migrations.mjs +48 -0
  50. package/onboarding/process-table.mjs +45 -19
  51. package/package.json +1 -1
@@ -52,7 +52,7 @@ Cron reads require the documented `result: {schedules: [...]}` envelope, includi
52
52
 
53
53
  `workerConsumerScript(consumer)` (also exported from `index.mjs`) decodes Worker consumer identities from either documented `script_name` or the observed GET response string `script`. It returns the exact name using the plan's resource-name grammar, or `null` for missing, malformed, conflicting, or non-Worker identities. If both fields are present, each must be valid and both must agree; a malformed alias is never ignored. Reconciliation checks every consumer on queues with a requested consumer before any trigger write and rejects foreign or duplicate consumers. Writes continue to use the documented `script_name` request field. Read-only health and retained-receipt repeats accept either response variant without repairs.
54
54
 
55
- D1/Queue/DO account listings fully paginate with bounded page/request budgets. R2 follows provider cursors. Missing pagination evidence, duplicate names, permission errors, partial success, redirects and transport failures fail visibly. Requests go only to Cloudflare's exact account API. Every read has a 30-second timeout and bounded response size; no request is retried. Asset upload tokens are used only on the documented same-account assets endpoint.
55
+ D1/Queue/DO account listings fully paginate with bounded page/request budgets. R2 follows provider cursors. Missing pagination evidence, duplicate names, permission errors, partial success, redirects and transport failures fail visibly. Requests go only to Cloudflare's exact account API. Requests have a 30-second timeout and bounded response size. Before any HTTP status, GET/HEAD reads and writes that provably failed before connecting (DNS failure, connection refusal or connect timeout) may retry once, sharing the original timeout and request budget. The first read reserves half the timeout for a retry; caller deadlines and cancellation still apply. HTTP responses, failed response-body reads and ambiguous write failures are never replayed. Asset upload tokens are used only on the documented same-account assets endpoint.
56
56
 
57
57
  The first receipt binds source commit SHA and tree, artifact/config SHA-256, effective deployment fingerprint, account/Worker, actual resource IDs, migration hashes, secret names and active provider deployment/version/etag. It contains no secret value. The CLI creates it exclusively at mode 0600 before the first health request; it is an identity receipt, not a claim that health passed (health attempts are added afterwards, see below). A failed health request still exits nonzero, while the retained identity allows the next explicit invocation to authenticate state without another upload. For the second deployment use the **same artifact, run/attempt and receipt**. Current provider state must match the prior receipt. The kit performs no resource creation, Worker/asset upload, SQL mutation, Cron/consumer update, or secret rewrite when unchanged. Read-only D1 queries use the provider's POST query transport; a POST is not by itself a database mutation. The receipt remains byte-identical on a repeat. Missing resources, drift or stale state fail without repair during this repeat.
58
58
 
@@ -109,6 +109,8 @@ Ownership lives in a state file, by default `.rer/deploy/<environment>.json` und
109
109
  The CLI prints JSON: refusal codes and resource names only, never inputs, tokens or provider bodies.
110
110
  A refused provider call also carries `providerRefusal` on the thrown error: the call (`PUT /workers/scripts/<name>`) and Cloudflare's own codes and messages, with the account id and token removed and each message cut to 300 characters. `rer deploy` names it when a custom deploy hook fails on one.
111
111
 
112
+ A transport failure carries `providerTransport`: the operation, sanitized endpoint, attempt count, whether an HTTP status was received and a structural network reason. Both standard and custom-hook `rer deploy` failures name the call and retain the same-input recovery command. Endpoint details omit URL credentials, queries, account ids and R2 object keys; signed D1 import destinations are withheld.
113
+
112
114
  ### rer deploy: inputs, the hosted owner, secret changes and removal
113
115
 
114
116
  `rer deploy` runs these steps for a seed whose adapter uses `ownerDeploy` from `cli/deploy.mjs`.
@@ -261,7 +263,7 @@ without metadata fails closed. Present metadata must supply a valid positive
261
263
  Cursors are encoded, validated and checked for cycles. Any supplied count or
262
264
  total count must agree with returned rows and completion, and totals cannot
263
265
  change between pages. Request, page, row and response-size budgets still apply.
264
- No metadata is fabricated and no request is retried. Generic `pagination:'cursor'`
266
+ No metadata is fabricated; only the bounded pre-status transport retry above applies. Generic `pagination:'cursor'`
265
267
  retains its existing contract: omitted metadata fails, and its R2 null-metadata
266
268
  exception accepts only a short page. D1/Queue/DO page pagination is unchanged.
267
269
  The bounded strategy is covered with local provider fixtures; this change does
@@ -292,6 +294,18 @@ again, within 30 seconds. Library `verifyHealth`
292
294
  retains the existing window, retrying only 404, 503 and network failures for
293
295
  30 seconds by default.
294
296
 
297
+ Custom-hook `rer deploy` finalization gets a separate 90-second `/health` wait
298
+ after the hook returns, using the current recorded Worker version when available.
299
+ The hook can already have claimed the owner and retired its token, which creates
300
+ another version and can exhaust the original upload window. First hosted Slate
301
+ and Pencil deploys on 15 October 2026 failed this final gate even though health
302
+ named the right commit seconds later. Reusing the existing 90-second propagation
303
+ budget gives this final observation the same bounded allowance, without spending
304
+ it on the hook's earlier work. Transport failures and healthy identity mismatches wait;
305
+ permanent HTTP or malformed responses still fail. The deadline includes request
306
+ time and backoff; each request is capped at 30 seconds. Failure names the last
307
+ observed answer and the exact same-environment rerun.
308
+
295
309
  The returned receipt carries `health: {ok, versionId, attempts}`. Each attempt is
296
310
  `{offsetMs, status, cfRay, contentType, errorClass}`: `status` is null for
297
311
  a transport failure and `errorClass` is null for the passing attempt. The receipt
@@ -24,6 +24,15 @@ export function providerRefusal(error, redact = String) {
24
24
  const said = refusal.errors.map(item => [item?.code, typeof item?.message === 'string' ? redact(item.message).slice(0,300) : undefined].filter(part => part !== undefined && part !== '').join(' ')).filter(Boolean).slice(0,3);
25
25
  return `Cloudflare refused ${redact(refusal.operation).slice(0,200)}${said.length ? `: ${said.join('; ')}` : ''}`;
26
26
  }
27
+ /** Safe call identity travels with errors from independently vendored kits. */
28
+ export function providerTransport(error, redact = String) {
29
+ const detail = error?.providerTransport;
30
+ if (typeof detail?.operation !== 'string' || typeof detail.endpoint !== 'string') return undefined;
31
+ const clean = value => redact(value).replace(/[\x00-\x1f\x7f-\x9f]+/g,' ').replace(/\b[a-f0-9]{32}\b/gi,'[REDACTED]').slice(0,300);
32
+ const attempts = detail.attempts === 2 ? ' after 2 attempts' : '';
33
+ const status = Number.isInteger(detail.status) ? `while reading HTTP ${detail.status}` : 'before any HTTP status';
34
+ return `Cloudflare transport failed for ${clean(detail.operation)} at ${clean(detail.endpoint)} ${status}${attempts}${typeof detail.reason === 'string' ? `: ${clean(detail.reason)}` : ''}`;
35
+ }
27
36
  function operation(path, options = {}) {
28
37
  const write = options.method && options.method !== 'GET';
29
38
  if (/\/d1\/database\/[^/]+\/query/.test(path)) return 'migrate D1';
@@ -21,7 +21,7 @@ async function bodyPrefix(response) {
21
21
 
22
22
  /** One credential-free, bounded request. Retain only bounded response evidence. */
23
23
  /** `expected` holds the deploy identity fields the caller knows; each must match. */
24
- export async function healthRequest({origin, expected, request, timeoutMs, offsetMs}) {
24
+ export async function healthRequest({origin, expected, request, timeoutMs, offsetMs, retryIdentityMismatch = false}) {
25
25
  const attempt = {offsetMs,status:null,cfRay:null,contentType:null,body:'',errorClass:null};
26
26
  let response;
27
27
  try {
@@ -63,10 +63,12 @@ export async function healthRequest({origin, expected, request, timeoutMs, offse
63
63
  if (body?.ok !== true || Object.entries(expected).some(([key, value]) => body.deployment?.[key] !== value)) {
64
64
  attempt.errorClass = 'health-identity-mismatch';
65
65
  // Right after an upload the edge can still answer from another version: that
66
- // settles within the bound. The expected version answering wrongly does not.
66
+ // settles within the bound. Final source observation also waits out healthy
67
+ // identity mismatches; other callers reject a wrong identity from the
68
+ // expected version at once.
67
69
  const key = expected.versionId ? 'versionId' : 'sourceSha';
68
70
  const other = body?.ok === true && typeof body.deployment?.[key] === 'string' && body.deployment[key] !== expected[key];
69
- return {attempt,transient:other};
71
+ return {attempt,transient:other || retryIdentityMismatch && body?.ok === true};
70
72
  }
71
73
  return {attempt,transient:false};
72
74
  }
@@ -77,13 +79,13 @@ const MIN_DELAY_MS = 2000, MAX_DELAY_MS = 10000;
77
79
 
78
80
  /** The total bound includes requests, body reads and backoff; no request starts at the deadline.
79
81
  * Only a transient outcome is retried. Every attempt is recorded, in order, whatever the end. */
80
- export async function waitHealth({origin,receipt,versionId,expected={sourceSha:receipt.source.sha,fingerprint:receipt.fingerprint,versionId},request,timeoutMs=30000,totalMs=90000,clock=()=>performance.now(),sleep=ms=>new Promise(resolve=>setTimeout(resolve,ms)),onAttempt=()=>{},single=false,freshUpload=false,window}) {
82
+ export async function waitHealth({origin,receipt,versionId,expected={sourceSha:receipt.source.sha,fingerprint:receipt.fingerprint,versionId},request,timeoutMs=30000,totalMs=90000,clock=()=>performance.now(),sleep=ms=>new Promise(resolve=>setTimeout(resolve,ms)),onAttempt=()=>{},single=false,freshUpload=false,window,retryIdentityMismatch=false}) {
81
83
  assert(Number.isFinite(totalMs) && totalMs > 0 && totalMs <= 90000 && Number.isFinite(timeoutMs) && timeoutMs > 0,'invalid-health-bound');
82
84
  const start = clock(); const attempts = []; let delay = 1000;
83
85
  while (true) {
84
86
  const remaining = Math.min(totalMs - (clock()-start), window?.remaining() ?? Infinity);
85
87
  if (remaining <= 0) break;
86
- const result = await healthRequest({origin,expected,request,timeoutMs:Math.max(1,Math.ceil(Math.min(timeoutMs,remaining))),offsetMs:Math.round(clock()-start)});
88
+ const result = await healthRequest({origin,expected,request,timeoutMs:Math.max(1,Math.ceil(Math.min(timeoutMs,remaining))),offsetMs:Math.round(clock()-start),retryIdentityMismatch});
87
89
  attempts.push(result.attempt); await onAttempt(result.attempt,attempts);
88
90
  if (!result.attempt.errorClass) return {ok:true,versionId,attempts};
89
91
  // A newly uploaded workers.dev route can briefly disappear even after its
@@ -0,0 +1,56 @@
1
+ // A missing HTTP status does not prove that a write never reached Cloudflare.
2
+ // Only these connection-establishment failures make replaying a write safe.
3
+ const UNSENT = new Set(['ENOTFOUND', 'EAI_AGAIN', 'ECONNREFUSED', 'UND_ERR_CONNECT_TIMEOUT']);
4
+ function unsent(error, seen = new Set()) {
5
+ if (!error || seen.has(error) || seen.size >= 8) return false;
6
+ seen.add(error);
7
+ if (Array.isArray(error.errors)) return error.errors.length > 0 && error.errors.every(cause => unsent(cause, seen));
8
+ if (typeof error.code === 'string') return UNSENT.has(error.code);
9
+ return unsent(error.cause, seen);
10
+ }
11
+
12
+ /** Retry only before a response, once, sharing the original deadline and budget. */
13
+ export async function providerResponse({send, method, timeoutMs, callerSignal, reserveRetry, failure}) {
14
+ const timeout = AbortSignal.timeout(timeoutMs);
15
+ const signal = callerSignal ? AbortSignal.any([callerSignal, timeout]) : timeout;
16
+ const read = method === 'GET' || method === 'HEAD';
17
+ for (let attempt = 1; ; attempt++) {
18
+ // Leave time for a second read when the first one times out. Caller deadlines
19
+ // remain authoritative and are never reset by a retry.
20
+ const firstRead = read && attempt === 1 ? new AbortController() : undefined;
21
+ const timer = firstRead ? setTimeout(() => firstRead.abort(new DOMException('Provider read timed out','TimeoutError')), Math.max(1, Math.ceil(timeoutMs / 2))) : undefined;
22
+ timer?.unref();
23
+ const attemptSignal = firstRead ? AbortSignal.any([signal, firstRead.signal]) : signal;
24
+ try { return {response:await send(attemptSignal),attempts:attempt}; }
25
+ catch (cause) {
26
+ if (attempt === 1 && !signal.aborted && (read || unsent(cause)) && reserveRetry()) continue;
27
+ throw failure(cause, attempt);
28
+ }
29
+ // Headers end the retry window; body consumption keeps the total deadline.
30
+ finally { clearTimeout(timer); }
31
+ }
32
+ }
33
+
34
+ export function transportOutput(error) {
35
+ const lines = [], seen = new Set();
36
+ for (let cause = error; cause && !seen.has(cause) && seen.size < 4; cause = cause.cause) {
37
+ seen.add(cause);
38
+ lines.push([typeof cause.code === 'string' ? cause.code : '', typeof cause.message === 'string' ? cause.message : ''].filter(Boolean).join(': '));
39
+ }
40
+ // Network errors can echo signed URLs. Keep their destination, never URL
41
+ // credentials, query parameters or fragments, before later secret redaction.
42
+ return lines.filter(Boolean).join('\n').replace(/\bhttps?:\/\/[^\s<>"']+/gi, value => {
43
+ try { const url = new URL(value); url.username = ''; url.password = ''; url.search = ''; url.hash = ''; return url.href; }
44
+ catch { return '[URL omitted]'; }
45
+ });
46
+ }
47
+
48
+ export function transportReason(error) {
49
+ const seen = new Set();
50
+ for (let cause = error; cause && !seen.has(cause) && seen.size < 4; cause = cause.cause) {
51
+ seen.add(cause);
52
+ if (typeof cause.code === 'string' && /^[A-Z][A-Z0-9_]{1,63}$/.test(cause.code)) return cause.code;
53
+ if (cause.name === 'TimeoutError' || cause.name === 'AbortError') return cause.name;
54
+ }
55
+ return 'network error';
56
+ }
@@ -3,6 +3,7 @@ import { isR2ObjectDelete } from './r2-objects.mjs';
3
3
  import { recordDeployFailure } from './diagnostics.mjs';
4
4
  import { importD1, importUploadURL } from './d1-import.mjs';
5
5
  import { assert, hexId } from './validation.mjs';
6
+ import { providerResponse, transportOutput, transportReason } from './provider-transport.mjs';
6
7
 
7
8
  // A gateway/server error can arrive after a write. An explicit API refusal cannot.
8
9
  export const definiteProviderRefusal = error => error.status === 200 || error.status >= 400 && error.status < 500;
@@ -23,14 +24,6 @@ async function boundedText(response, limit = 4 * 1024 * 1024, onReadError) {
23
24
  export async function boundedJSON(response, limit) {
24
25
  try { return JSON.parse(await boundedText(response,limit)); } catch (error) { if (error instanceof SyntaxError) throw new Error('malformed-response'); throw error; }
25
26
  }
26
- function transportOutput(error) {
27
- const lines = []; const seen = new Set();
28
- for (let cause = error; cause && !seen.has(cause) && seen.size < 4; cause = cause.cause) {
29
- seen.add(cause);
30
- lines.push([typeof cause.code === 'string' ? cause.code : '', typeof cause.message === 'string' ? cause.message : ''].filter(Boolean).join(': '));
31
- }
32
- return lines.filter(Boolean).join('\n');
33
- }
34
27
  /** Only this fixed origin and the explicitly selected account ever receive the token. */
35
28
  export function cloudflare({ accountId, token, fetch: request = globalThis.fetch, objectDelete = deleteR2Object, timeoutMs = 30000, maxRequests = 500 }) {
36
29
  assert(hexId(accountId), 'invalid-cloudflare-account-id');
@@ -44,16 +37,24 @@ export function cloudflare({ accountId, token, fetch: request = globalThis.fetch
44
37
  assert(!assetToken || path === '/workers/assets/upload?base64=true', 'invalid-asset-auth-target');
45
38
  // Asset-session credentials are discovered at runtime, outside the CLI env.
46
39
  // Preserve complete text for the CLI's remaining redaction before truncation.
47
- const redactAuth = text => /\/r2\/buckets\/[^/]+\/objects(?:[/?]|$)/.test(path) ? '[R2 object details omitted]' : /\/d1\/database\/[^/]+\/import$/.test(path) ? '[D1 import details omitted]' : [accountId,token,assetToken].filter(Boolean).flatMap(value=>[value,encodeURIComponent(value),JSON.stringify(value).slice(1,-1)]).sort((a,b)=>b.length-a.length).reduce((value,secret)=>value.split(secret).join('[REDACTED]'),text);
48
- const transportFailure = cause => recordDeployFailure(new Error('provider-transport-failed'),{output:redactAuth(transportOutput(cause))});
49
- const timeout = AbortSignal.timeout(timeoutMs);
50
- const signal = callerSignal ? AbortSignal.any([callerSignal,timeout]) : timeout;
51
- let response;
52
- try { response = isR2ObjectDelete(path, method) ? await objectDelete(`/client/v4/accounts/${accountId}${path}`, {headers:{Authorization:`Bearer ${token}`},signal}) : await request(zone ? `https://api.cloudflare.com/client/v4${path}` : `https://api.cloudflare.com/client/v4/accounts/${accountId}${path}`, {
40
+ const redactCredentials = text => [accountId,token,assetToken].filter(Boolean).flatMap(value=>[value,encodeURIComponent(value),JSON.stringify(value).slice(1,-1)]).sort((a,b)=>b.length-a.length).reduce((value,secret)=>value.split(secret).join('[REDACTED]'),text);
41
+ const redactAuth = text => /\/r2\/buckets\/[^/]+\/objects(?:[/?]|$)/.test(path) ? '[R2 object details omitted]' : /\/d1\/database\/[^/]+\/import$/.test(path) ? '[D1 import details omitted]' : redactCredentials(text);
42
+ const operation = `${method} ${path.split('?')[0].replace(/(\/r2\/buckets\/[^/]+\/objects)\/.*/, '$1/[object]')}`;
43
+ const endpoint = redactCredentials(`https://api.cloudflare.com/client/v4${zone ? '' : '/accounts/[REDACTED]'}${operation.slice(method.length + 1)}`);
44
+ const transportFailure = (cause, attempts, status = null) => {
45
+ const error = new Error('provider-transport-failed');
46
+ // Portable across vendored kit copies used by custom deploy hooks. Raw
47
+ // network messages stay private until the CLI applies its redactor.
48
+ error.providerTransport = {operation:redactCredentials(operation),endpoint,attempts,status,reason:transportReason(cause)};
49
+ return recordDeployFailure(error,{output:redactAuth(transportOutput(cause))});
50
+ };
51
+ const {response,attempts} = await providerResponse({method,timeoutMs,callerSignal,
52
+ reserveRetry:() => requests < maxRequests && (++requests, true),failure:transportFailure,
53
+ send:signal => isR2ObjectDelete(path, method) ? objectDelete(`/client/v4/accounts/${accountId}${path}`, {headers:{Authorization:`Bearer ${token}`},signal}) : request(zone ? `https://api.cloudflare.com/client/v4${path}` : `https://api.cloudflare.com/client/v4/accounts/${accountId}${path}`, {
53
54
  method, redirect: 'error', signal, headers: { Authorization: `Bearer ${assetToken ?? token}`, ...(body && !(body instanceof FormData) ? { 'Content-Type':'application/json' } : {}) },
54
55
  ...(body === undefined ? {} : { body: body instanceof FormData ? body : JSON.stringify(body) }),
55
- }); } catch (cause) { throw transportFailure(cause); }
56
- const output = response.body ? await boundedText(response,undefined,transportFailure) : '';
56
+ })});
57
+ const output = response.body ? await boundedText(response,undefined,cause => transportFailure(cause,attempts,response.status)) : '';
57
58
  // A successful DELETE may have no response body (including HTTP 200).
58
59
  // Nonempty replies and all other methods still require the API envelope.
59
60
  if (method === 'DELETE' && response.ok && output === '') return { success: true, result: null };
@@ -156,10 +157,11 @@ export function cloudflare({ accountId, token, fetch: request = globalThis.fetch
156
157
  async function upload(url, bytes, etag) {
157
158
  const destination = importUploadURL(url);
158
159
  assert(++requests <= maxRequests, 'provider-request-budget');
159
- let response;
160
- try {
161
- response = await request(destination, { method:'PUT', redirect:'error', signal:AbortSignal.timeout(timeoutMs), headers:{'Content-Length':String(bytes.length)}, body:bytes });
162
- } catch { throw new Error('d1-import-upload-transport-failed'); }
160
+ const {response} = await providerResponse({method:'PUT',timeoutMs,
161
+ reserveRetry:() => requests < maxRequests && (++requests, true),
162
+ send:signal => request(destination, { method:'PUT', redirect:'error', signal, headers:{'Content-Length':String(bytes.length)}, body:bytes }),
163
+ failure:(cause,attempts) => Object.assign(new Error('d1-import-upload-transport-failed'), {providerTransport:{operation:'PUT D1 import upload',endpoint:'https://[REDACTED].r2.cloudflarestorage.com/[D1 import upload]',attempts,status:null,reason:transportReason(cause)}}),
164
+ });
163
165
  // Upload bodies and signed URLs are never diagnostics, including on failure.
164
166
  await response.body?.cancel().catch(() => {});
165
167
  assert(response.status === 200, 'd1-import-upload-failed');
@@ -566,6 +566,10 @@ file that differs from the pinned revision (`SC-05.auth-copy.*`); the runtime im
566
566
  server-only, reconcile the seed's route integration, and run that seed's real auth
567
567
  and browser checks.
568
568
 
569
+ The sign-in page fills in its email field from `?login_hint=<email>` (a complete
570
+ address; anything else is ignored; never submitted for the visitor), so a link
571
+ from the platform's Open app or a seed's own page can pass the claimed owner.
572
+
569
573
  Wire `config.branding` with the seed's `productName`, `accentColor` and
570
574
  `signInPath`; the defaults are `your workspace`, `#334155` and `/signin`. Keep
571
575
  `MAIL_FROM` in auth config and provide a real `mailSender` that implements
@@ -11,9 +11,9 @@ export function fencedCredentials({store,authenticate,requireFreshProof,config,c
11
11
  await requireFreshProof(actor);
12
12
  if(!Number.isSafeInteger(expiresInSeconds)||expiresInSeconds<1||expiresInSeconds>365*86400)deny('invalid_input');
13
13
  const token=opaqueToken(),id=crypto.randomUUID(),fence=store.actorFence(actor,clock());
14
- const inserted=await store.run(`INSERT INTO oa_credentials(id,token_hash,operator_id,operator_version,kind,expires_at) SELECT ?,?,?,?,?,? WHERE ${fence.sql}`,
14
+ const inserted=await store.first(`INSERT INTO oa_credentials(id,token_hash,operator_id,operator_version,kind,expires_at) SELECT ?,?,?,?,?,? WHERE ${fence.sql} RETURNING id`,
15
15
  [id,await hash('credential',token),actor.operator.id,actor.operator.version,actor.kind,clock()+expiresInSeconds*1000,...fence.args]);
16
- if(inserted.meta.changes!==1)deny('authority_changed',409);
16
+ if(inserted?.id!==id)deny('authority_changed',409);
17
17
  return {id,token,expiresAt:clock()+expiresInSeconds*1000};
18
18
  },
19
19
  async authenticateCredential(request) {
@@ -21,12 +21,12 @@ export function emailChange({ config, store, clock, authenticate, requireFreshPr
21
21
  let changed;
22
22
  try {
23
23
  [changed] = await store.batch([
24
- [`UPDATE oa_operators SET email=? WHERE id=? AND version=? AND ${fence.sql}`, [email, actor.operator.id, actor.operator.version, ...fence.args]],
24
+ [`UPDATE oa_operators SET email=? WHERE id=? AND version=? AND ${fence.sql} RETURNING id`, [email, actor.operator.id, actor.operator.version, ...fence.args]],
25
25
  ['UPDATE oa_tokens SET revoked_at=? WHERE operator_id=? AND consumed_at IS NULL AND revoked_at IS NULL AND EXISTS(SELECT 1 FROM oa_operators WHERE id=? AND email=?)',
26
26
  [now, actor.operator.id, actor.operator.id, email]],
27
27
  ]);
28
28
  } catch (error) { if (/UNIQUE/.test(String(error))) deny('email_in_use', 409); throw error; }
29
- if (changed.meta.changes !== 1) deny('authority_changed', 409);
29
+ if (!changed.results.some(row => row.id === actor.operator.id)) deny('authority_changed', 409);
30
30
  }
31
31
  return store.operator(actor.operator.id);
32
32
  },
@@ -19,13 +19,13 @@ export function providerControl({ store, accounts, authenticate, config, clock }
19
19
  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
20
  const auditId=crypto.randomUUID();
21
21
  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`, [...fence.args, actor.operator.id]],
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
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`, [idpSignIn ? 1 : 0, ...fence.args, actor.operator.id, idpSignIn ? 1 : 0]],
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
25
  [`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
26
  [`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
27
  ]);
28
- if (results[0].meta.changes !== 1 && results[1].meta.changes !== 1) deny('authority_changed', 409);
28
+ if (!results[0].results.some(row => row.singleton === 1) && !results[1].results.some(row => row.singleton === 1)) deny('authority_changed', 409);
29
29
  return { idpSignIn };
30
30
  },
31
31
  async requireEditorOwner(request) {
@@ -1,6 +1,7 @@
1
1
  import { providerPinFence, recordProviderPin } from './provider-pin.mjs';
2
2
  // D1 batches are transactions. All decisions that grant a session or mutate
3
3
  // operator authority are repeated inside the same database transaction.
4
+ // RETURNING keys witness each write; D1 meta.changes also counts trigger writes.
4
5
  export const operatorColumns = 'id, email, display_name AS displayName, role, status, version, created_at AS createdAt';
5
6
  export class AuthStore {
6
7
  constructor(db) { this.db = db; }
@@ -50,10 +51,10 @@ export class AuthStore {
50
51
  async token(input, actor) {
51
52
  let fence = { sql: '1', args: [] };
52
53
  if (actor) fence = this.actorFence(actor, input.now);
53
- const result = await this.run(`INSERT INTO oa_tokens(id,token_hash,kind,operator_id,operator_version,return_to,created_at,expires_at)
54
- SELECT ?,?,?,id,version,?,?,? FROM oa_operators WHERE id=? AND status='active' AND ${fence.sql}`,
54
+ const result = await this.first(`INSERT INTO oa_tokens(id,token_hash,kind,operator_id,operator_version,return_to,created_at,expires_at)
55
+ SELECT ?,?,?,id,version,?,?,? FROM oa_operators WHERE id=? AND status='active' AND ${fence.sql} RETURNING id`,
55
56
  [input.id, input.hash, input.kind, input.returnTo, input.now, input.expiresAt, input.operatorId, ...fence.args]);
56
- return result.meta.changes === 1;
57
+ return result?.id === input.id;
57
58
  }
58
59
  async invite({ operatorId, expectedVersion, reinviting = false, email, displayName, role, token, now }, actor) {
59
60
  const fence = this.actorFence(actor, now);
@@ -69,7 +70,7 @@ export class AuthStore {
69
70
  prepare,
70
71
  [`INSERT INTO oa_tokens(id,token_hash,kind,operator_id,operator_version,issuer_id,issuer_version,return_to,created_at,expires_at)
71
72
  SELECT ?,?,'invite',id,version,?,?,?,?,? FROM oa_operators WHERE id=? AND status='invited' AND role=? AND version=?
72
- ${reinviting ? 'AND changes()=1' : ''} AND ${fence.sql}`,
73
+ ${reinviting ? 'AND changes()=1' : ''} AND ${fence.sql} RETURNING id`,
73
74
  [token.id, token.hash, actor.operator.id, actor.operator.version, token.returnTo, now, token.expiresAt, operatorId, role, expectedVersion + (reinviting ? 1 : 0), ...fence.args]],
74
75
  // Bind revocation to this transaction's successful issuance, so a stale
75
76
  // reissue cannot invalidate the winner's link or send another credential.
@@ -79,7 +80,7 @@ export class AuthStore {
79
80
  ...(actor.kind === 'dev' ? [[`INSERT INTO oa_dev_credentials(credential,id,created_at)
80
81
  SELECT 'oa_tokens',id,? FROM oa_tokens WHERE id=?`, [now, token.id]]] : []),
81
82
  ]);
82
- return results[1].meta.changes === 1;
83
+ return results[1].results.some(row => row.id === token.id);
83
84
  }
84
85
  async preview(hash, now) {
85
86
  return this.first(`SELECT t.kind,t.expires_at AS expiresAt,t.return_to AS returnTo,o.email,o.role,t.issuer_id AS issuerId,t.issuer_version AS issuerVersion,
@@ -219,9 +220,9 @@ export class AuthStore {
219
220
  liftDomainRules(providerId) { return this.run('DELETE FROM oa_domain_rules WHERE provider_id=?', [providerId]); }
220
221
  async stepUpChallenge({ id, hash, action, returnTo, now, expiresAt }, actor) {
221
222
  const fence = this.actorFence(actor, now);
222
- const result = await this.run(`INSERT INTO oa_step_up_challenges(id,token_hash,session_id,operator_id,operator_version,action,return_to,created_at,expires_at)
223
- SELECT ?,?,?,?,?,?,?,?,? WHERE ${fence.sql}`, [id, hash, actor.id, actor.operator.id, actor.operator.version, action, returnTo, now, expiresAt, ...fence.args]);
224
- return result.meta.changes === 1;
223
+ const result = await this.first(`INSERT INTO oa_step_up_challenges(id,token_hash,session_id,operator_id,operator_version,action,return_to,created_at,expires_at)
224
+ SELECT ?,?,?,?,?,?,?,?,? WHERE ${fence.sql} RETURNING id`, [id, hash, actor.id, actor.operator.id, actor.operator.version, action, returnTo, now, expiresAt, ...fence.args]);
225
+ return result?.id === id;
225
226
  }
226
227
  stepUpPreview(hash, now) {
227
228
  return this.first(`SELECT c.session_id AS sessionId,c.action,c.expires_at AS expiresAt FROM oa_step_up_challenges c JOIN oa_operators o ON o.id=c.operator_id
@@ -23,10 +23,11 @@ export async function cliSession(request, { config, store, hash, everyone }, hea
23
23
  if (!record || record.operator.role !== 'owner') throw new AuthError('authority_changed', 409);
24
24
  // A local owner proof uses the existing durable, version-fenced proof ledger.
25
25
  // It can authorize setup linking without manufacturing an email credential.
26
- const inserted = await store.run(`INSERT INTO oa_step_up_challenges(id,token_hash,session_id,operator_id,operator_version,action,return_to,created_at,expires_at,consumed_at)
26
+ const proofId = crypto.randomUUID();
27
+ const inserted = await store.first(`INSERT INTO oa_step_up_challenges(id,token_hash,session_id,operator_id,operator_version,action,return_to,created_at,expires_at,consumed_at)
27
28
  SELECT ?,?,?,?,?,?,?,?,?,? WHERE EXISTS(SELECT 1 FROM oa_sessions s JOIN oa_operators o ON o.id=s.operator_id
28
- WHERE s.id=? AND s.revoked_at IS NULL AND o.role='owner' AND o.status='active' AND o.version=?)`,
29
- [crypto.randomUUID(), await hash(opaqueToken()), record.id, operator.id, operator.version, 'local-cli', '/', now, session.expiresAt, now, record.id, operator.version]);
30
- if (inserted.meta.changes !== 1) throw new AuthError('authority_changed', 409);
29
+ WHERE s.id=? AND s.revoked_at IS NULL AND o.role='owner' AND o.status='active' AND o.version=?) RETURNING id`,
30
+ [proofId, await hash(opaqueToken()), record.id, operator.id, operator.version, 'local-cli', '/', now, session.expiresAt, now, record.id, operator.version]);
31
+ if (inserted?.id !== proofId) throw new AuthError('authority_changed', 409);
31
32
  return new Response(null, { status: 303, headers: { ...headers, location: safeReturnTo(input.returnTo), 'set-cookie': sessionCookie(token, config) } });
32
33
  }
@@ -129,12 +129,12 @@ async function enter(request, gate, { config, store, hash, current, everyone, ow
129
129
  // Personas are real operators, created only here, in local dev.
130
130
  if (!operator && persona.role) {
131
131
  if (persona.role === 'owner') {
132
- const actor = await ownerProof(request), now = Date.now();
132
+ const actor = await ownerProof(request), now = Date.now(), id = crypto.randomUUID();
133
133
  const fence = store.actorFence(actor, now);
134
- const result = await store.run(`INSERT INTO oa_operators(id,email,display_name,role,status,created_at)
135
- SELECT ?,?,?,'owner','active',? WHERE ${fence.sql} ON CONFLICT(email) DO NOTHING`,
136
- [crypto.randomUUID(), persona.email, persona.displayName, now, ...fence.args]);
137
- if (result.meta.changes !== 1) throw new AuthError('authority_changed', 409);
134
+ const result = await store.first(`INSERT INTO oa_operators(id,email,display_name,role,status,created_at)
135
+ SELECT ?,?,?,'owner','active',? WHERE ${fence.sql} ON CONFLICT(email) DO NOTHING RETURNING id`,
136
+ [id, persona.email, persona.displayName, now, ...fence.args]);
137
+ if (result?.id !== id) throw new AuthError('authority_changed', 409);
138
138
  } else {
139
139
  await store.run(`INSERT INTO oa_operators(id,email,display_name,role,status,created_at) VALUES(?,?,?,?,'active',?) ON CONFLICT(email) DO NOTHING`,
140
140
  [crypto.randomUUID(), persona.email, persona.displayName, persona.role, Date.now()]);
@@ -27,8 +27,10 @@ async function cookieValue(key) {
27
27
 
28
28
  // Reads `#rer-dev=KEY` (with optional `as` or `next`), removes it from the
29
29
  // address bar first, then trades it through a same-origin POST. The fragment
30
- // never reaches a server; the key never appears in a query string.
31
- export const EXCHANGE_SCRIPT = "(()=>{const h=new URLSearchParams(location.hash.slice(1)),k=h.get('rer-dev');if(!k)return;history.replaceState(null,'',location.pathname+location.search);const a=h.get('as'),n=h.get('next')||(a?'/auth/dev/enter?as='+encodeURIComponent(a):location.pathname+location.search),to=n.startsWith('/')&&!n.startsWith('//')&&!n.includes('\\\\')?n:'/';fetch('" + DEV_KEY_PATH + "',{method:'POST',credentials:'same-origin',headers:{'content-type':'application/json'},body:JSON.stringify({key:k})}).then(r=>{if(r.ok)location.replace(to);else document.body.insertAdjacentHTML('beforeend','<p role=\"alert\">This link no longer opens the app. Run rer dev again for a fresh one.</p>')})})()";
30
+ // never reaches a server; the key never appears in a query string. Listen for
31
+ // fragment navigation too: an open gate page stays loaded when RER_OPEN points
32
+ // to the same path with a fresh key fragment.
33
+ export const EXCHANGE_SCRIPT = "(()=>{const exchange=()=>{const h=new URLSearchParams(location.hash.slice(1)),k=h.get('rer-dev');if(!k)return;history.replaceState(null,'',location.pathname+location.search);const a=h.get('as'),n=h.get('next')||(a?'/auth/dev/enter?as='+encodeURIComponent(a):location.pathname+location.search),to=n.startsWith('/')&&!n.startsWith('//')&&!n.includes('\\\\')?n:'/';fetch('" + DEV_KEY_PATH + "',{method:'POST',credentials:'same-origin',headers:{'content-type':'application/json'},body:JSON.stringify({key:k})}).then(r=>{if(r.ok)location.replace(to);else document.body.insertAdjacentHTML('beforeend','<p role=\"alert\">This link no longer opens the app. Run rer dev again for a fresh one.</p>')})};addEventListener('hashchange',exchange);exchange()})()";
32
34
  const PAGE_STYLE = 'body{margin:0;font:16px/1.5 system-ui,sans-serif;color:#17212e;background:#f5f7fa}main{max-width:36rem;margin:0 auto;padding:32px 16px}';
33
35
  let hashes;
34
36
  export async function exchangeHashes() {
@@ -7,6 +7,7 @@ import { isActiveOperator } from '../../accounts/roles.mjs';
7
7
  import { isLocalCli } from '../../local-cli.mjs';
8
8
  import { linkMessage } from './message.mjs';
9
9
  import { completionHook } from '../after-confirm.mjs';
10
+ import { demoEffectsEnabled } from '../../../demo/effects.mjs';
10
11
  export const STEP_UP_ACTIONS = Object.freeze(['providers:unlink', 'providers:relink', 'domains:change', 'owner:transfer', 'export', 'delete', 'credentials:mint', 'email:change']);
11
12
  export const STEP_UP_SECONDS = 600;
12
13
 
@@ -48,7 +49,7 @@ export function createEmailLinkLifecycle({ config: input, clock = Date.now, mail
48
49
  ...linkMessage(config, token, url.href),
49
50
  headers: { 'Auto-Submitted': 'auto-generated' } });
50
51
  } catch { await revoke(); deny('mail_unavailable', 503); }
51
- if (result?.status !== 'accepted' && !(result?.status === 'development' && config.local)) {
52
+ if (result?.status !== 'accepted' && !(result?.status === 'development' && (config.local || demoEffectsEnabled()))) {
52
53
  // Even ambiguous delivery cannot leave a valid, unreported auth link.
53
54
  await revoke(); deny('mail_unavailable', 503);
54
55
  }
@@ -3,7 +3,7 @@
3
3
  // with…" for each linked, reachable provider and offers a configured email link;
4
4
  // a hidden provider's button is simply absent.
5
5
  import { escapeHtml } from '../http.mjs';
6
- import { safeReturnTo } from '../policy.mjs';
6
+ import { normalizeEmail, safeReturnTo } from '../policy.mjs';
7
7
  import { pageResponse } from '../page.mjs';
8
8
 
9
9
  const NOTICES = {
@@ -28,12 +28,19 @@ function noticeFor(code, emailAvailable) {
28
28
  if (['oidc_provider_unavailable', 'oidc_relink_required', 'oidc_provider_unlinked', 'oidc_unavailable', 'oidc_provider_version_unsupported'].includes(code)) return emailAvailable ? UNAVAILABLE : ['alert', 'That sign-in provider is not available right now. Try again later.'];
29
29
  return code.startsWith('oidc_') ? (emailAvailable ? UNFINISHED : ['alert', 'Signing in with that provider did not finish. Try again.']) : null;
30
30
  }
31
+ // `login_hint` prefills the email field, as in OpenID Connect. Anything that is
32
+ // not a complete email address is ignored; the form is never submitted for the visitor.
33
+ function emailHint(value) {
34
+ if (value === null) return '';
35
+ try { return normalizeEmail(value); } catch { return ''; }
36
+ }
31
37
  const hidden = returnTo => `<input type="hidden" name="returnTo" value="${escapeHtml(returnTo)}">`;
32
38
 
33
39
  /**
34
40
  * Handles GET and HEAD of the configured sign-in path; null for anything else.
35
41
  * setup(request) may return { instructions } while the first owner is unclaimed;
36
42
  * links(request) may return [{ href, label }] shown under the form (same-origin paths only).
43
+ * `?login_hint=<email>` prefills the email field of the email-link form.
37
44
  */
38
45
  export function createSignInHandler(auth, { setup, links, defaultReturnTo = '/app' } = {}) {
39
46
  const path = new URL(auth.presentation.signInPath, 'https://signin.invalid').pathname;
@@ -42,6 +49,7 @@ export function createSignInHandler(auth, { setup, links, defaultReturnTo = '/ap
42
49
  if (url.pathname !== path || !['GET', 'HEAD'].includes(request.method)) return null;
43
50
  const branding = auth.presentation;
44
51
  const returnTo = safeReturnTo(url.searchParams.get('returnTo'), defaultReturnTo);
52
+ const hint = emailHint(url.searchParams.get('login_hint'));
45
53
  const providers = auth.providers ? (await auth.providers.list()).filter(p => p.visible) : [];
46
54
  const parts = [];
47
55
  const emailAvailable = auth.emailSignInAvailable;
@@ -56,7 +64,7 @@ export function createSignInHandler(auth, { setup, links, defaultReturnTo = '/ap
56
64
  parts.push(`<div class="stack">${providers.map(p => `<form method="post" action="${escapeHtml(p.startPath)}">${hidden(returnTo)}<button class="secondary" type="submit">Continue with ${escapeHtml(p.label)}</button></form>`).join('')}</div>`);
57
65
  if (emailAvailable) parts.push('<p class="divider">or</p>');
58
66
  }
59
- if (emailAvailable) parts.push(`<form method="post" action="/auth/magic-link">${hidden(returnTo)}<label for="signin-email">Email</label><input id="signin-email" name="email" type="email" autocomplete="email" required maxlength="254"><button type="submit">Email a sign-in link</button></form>`);
67
+ if (emailAvailable) parts.push(`<form method="post" action="/auth/magic-link">${hidden(returnTo)}<label for="signin-email">Email</label><input id="signin-email" name="email" type="email" autocomplete="email" required maxlength="254"${hint ? ` value="${escapeHtml(hint)}"` : ''}><button type="submit">Email a sign-in link</button></form>`);
60
68
  for (const link of (await links?.(request)) ?? []) {
61
69
  if (typeof link?.href === 'string' && /^\/(?!\/)[^\s\\]*$/.test(link.href) && typeof link.label === 'string') parts.push(`<p class="secondary-link"><a href="${escapeHtml(link.href)}">${escapeHtml(link.label)}</a></p>`);
62
70
  }
@@ -66,10 +66,18 @@ export function localInstaller(hooks = {}) {
66
66
  if (['dev','preview'].includes(verb) && hooks.secrets?.originKey) context.vars[hooks.secrets.originKey] = context.origin;
67
67
  store.addSecrets?.(Object.entries(context.vars).filter(([key]) => /secret|token|password/i.test(key)).map(([, value]) => value));
68
68
  if (['installer', 'setup', 'build'].includes(verb) && hooks.build) await build(context, hooks);
69
- // A demo (dev with options.demo) starts on fresh state in options.demo.state:
70
- // migrate it, then claim the saved owner there exactly as setup does.
69
+ // Every dev start applies pending local migrations before starting the app.
70
+ // A demo uses only options.demo.state, then claims the owner there.
71
71
  const demo = verb === 'dev' && Boolean(options.demo);
72
- if ((['installer', 'setup'].includes(verb) || demo) && hooks.migrate) await phase(context, hooks, 'migrate', hooks.migrate);
72
+ if (['installer', 'setup', 'dev'].includes(verb) && hooks.migrate) {
73
+ try { await phase(context, hooks, 'migrate', hooks.migrate); }
74
+ catch (error) {
75
+ if (verb !== 'dev' || signal?.aborted) throw error;
76
+ const failure = approvedFailure(error);
77
+ throw commandFailure(`${store.redact(failure?.message ?? error.message)}\nLocal migrations failed. Fix the error and run rer setup before trying again.`, failure ?? {});
78
+ }
79
+ }
80
+ await options.beforeStart?.(context);
73
81
  if (['installer', 'setup', 'dev', 'preview'].includes(verb) && hooks.start) await start(context, verb === 'preview' ? {...hooks,start:options.preview} : verb === 'dev' && options.dev ? { ...hooks, start: options.dev } : hooks);
74
82
  if ((['installer', 'setup'].includes(verb) || demo) && hooks.owner) {
75
83
  if (typeof hooks.owner === 'function' || Array.isArray(hooks.owner)) await phase(context, hooks, 'owner', hooks.owner);
@@ -3,6 +3,7 @@ import { privateDirectory } from './private-files.mjs';
3
3
  import { localInstaller } from './adapter.mjs';
4
4
  import { selectLocalState, LocalStateSafetyError } from './local/state.mjs';
5
5
  import {operatorPrerequisites} from './operator-prerequisites.mjs';
6
+ import { migrateOperator } from './operator-migrations.mjs';
6
7
  import { installOperator } from './operator-install.mjs';
7
8
  import { projectViteBinary } from './project-vite.mjs';
8
9
  import { join, delimiter } from 'node:path';
@@ -19,8 +20,7 @@ export function operatorInstaller({ database, features, prepare, prepareData })
19
20
  values: ({ origin }) => ({ AUTH_LOCAL: 'true', AUTH_ORIGIN: origin, MAIL_PROVIDER: 'development', MAIL_FROM: 'auth@localhost.test' }),
20
21
  },
21
22
  build: ['pnpm', ['run', 'build:app']],
22
- // A demo migrates its own fresh state folder, never the checkout's.
23
- migrate: ({ demo }) => ['pnpm', ['exec', 'wrangler', 'd1', 'migrations', 'apply', database, '--local', '--persist-to', demo?.state ?? '.wrangler/state', '--config', 'dist/server/wrangler.json']],
23
+ migrate: context => migrateOperator(context, database),
24
24
  // Setup uses the local entry for owner-side dependency approval without mail.
25
25
  start: developmentTarget,
26
26
  owner: { existingOwnerViaSignIn: true, displayName: input => input.displayName || 'Owner' },
@@ -0,0 +1,48 @@
1
+ import { randomUUID } from 'node:crypto';
2
+ import { readFile, readdir, unlink } from 'node:fs/promises';
3
+ import { join, resolve } from 'node:path';
4
+ import { DatabaseSync } from 'node:sqlite';
5
+ import { privateDirectory, writePrivateFile } from './private-files.mjs';
6
+ import { selectLocalState } from './local/state.mjs';
7
+ import { labels } from './adapter-labels.mjs';
8
+
9
+ async function appliedNames(state, table) {
10
+ const directory = join(state, 'v3/d1/miniflare-D1DatabaseObject'), names = new Set();
11
+ let files;
12
+ try { files = await readdir(directory); } catch (error) { if (error.code === 'ENOENT') return names; throw error; }
13
+ for (const file of files.filter(name => name.endsWith('.sqlite'))) {
14
+ const db = new DatabaseSync(join(directory, file), { readOnly: true });
15
+ try {
16
+ if (db.prepare("SELECT 1 FROM sqlite_master WHERE type='table' AND name=?").get(table)) {
17
+ for (const row of db.prepare(`SELECT name FROM "${table.replaceAll('"', '""')}"`).all()) names.add(row.name);
18
+ }
19
+ } finally { db.close(); }
20
+ }
21
+ return names;
22
+ }
23
+
24
+ // Vite's last build copied only the migrations that existed then. Keep its D1
25
+ // identity, but give Wrangler the complete current source inventory, including
26
+ // files just acquired by git pull. The temporary config contains no app vars.
27
+ export async function migrateOperator(context, database) {
28
+ const { root, demo, store } = context;
29
+ const config = JSON.parse(await readFile(join(root, 'dist/server/wrangler.json'), 'utf8'));
30
+ const binding = config.d1_databases?.find(item => item.database_name === database || item.binding === database);
31
+ if (!binding) throw new Error(`Local migration database ${database} is missing from the built configuration. Run rer setup.`);
32
+ const state = resolve(root, demo?.state ?? await selectLocalState(root));
33
+ const inventory = resolve(root, 'migrations/core');
34
+ const names = (await readdir(inventory)).filter(name => name.endsWith('.sql')).sort();
35
+ const table = binding.migrations_table ?? 'd1_migrations';
36
+ const before = await appliedNames(state, table);
37
+ const directory = await privateDirectory(root, ['.rer', 'local']);
38
+ const path = join(directory, `migrations-${randomUUID()}.json`);
39
+ await writePrivateFile(path, JSON.stringify({ name: config.name, compatibility_date: config.compatibility_date,
40
+ d1_databases: [{ ...binding, migrations_dir: inventory, migrations_pattern: `${inventory}/*.sql` }] }));
41
+ try {
42
+ await context.run(labels.migrate, 'pnpm', ['exec', 'wrangler', 'd1', 'migrations', 'apply', database,
43
+ '--local', '--persist-to', state, '--config', path], { step: 'setup' });
44
+ const after = await appliedNames(state, table);
45
+ const applied = names.filter(name => !before.has(name) && after.has(name));
46
+ if (applied.length) store.report(`Applied local migrations: ${applied.join(', ')}`);
47
+ } finally { await unlink(path); }
48
+ }