@runeditrun/rer 0.2.21 → 0.2.23

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 (72) hide show
  1. package/cli/README.md +26 -0
  2. package/cli/bounded.mjs +5 -1
  3. package/cli/delivery-declarations.mjs +2 -2
  4. package/cli/demo-host.mjs +5 -5
  5. package/cli/deploy-command.mjs +2 -2
  6. package/cli/deploy-inputs.mjs +4 -1
  7. package/cli/deploy.mjs +7 -3
  8. package/cli/deployment-record.mjs +52 -0
  9. package/cli/export.mjs +1 -1
  10. package/cli/local.mjs +11 -3
  11. package/cli/managed-server.mjs +7 -3
  12. package/cli/output.mjs +1 -1
  13. package/cli/production-auth.mjs +7 -13
  14. package/cli/production-mail.mjs +72 -0
  15. package/cli/signin.mjs +11 -6
  16. package/global/CHANGELOG.md +9 -0
  17. package/modules/container/README.md +18 -3
  18. package/modules/container/build.mjs +8 -12
  19. package/modules/container/host.mjs +9 -4
  20. package/modules/container/ingress.mjs +15 -4
  21. package/modules/container/migration-inventory.mjs +33 -0
  22. package/modules/container/migrations.mjs +16 -2
  23. package/modules/container/websockets.mjs +54 -0
  24. package/modules/container/worker-engine.mjs +2 -2
  25. package/modules/delivery-producer/migrations.mjs +61 -0
  26. package/modules/demo/README.md +4 -0
  27. package/modules/demo/effects.mjs +4 -0
  28. package/modules/demo/label.mjs +7 -4
  29. package/modules/demo/responses.mjs +1 -1
  30. package/modules/demo-host/README.md +32 -19
  31. package/modules/demo-host/capacity.mjs +3 -3
  32. package/modules/demo-host/container.mjs +65 -37
  33. package/modules/demo-host/pages.mjs +1 -1
  34. package/modules/demo-host/plan.mjs +19 -6
  35. package/modules/demo-host/remove.mjs +9 -7
  36. package/modules/demo-host/start-script.mjs +10 -1
  37. package/modules/demo-host/startup.mjs +4 -2
  38. package/modules/demo-host/worker.mjs +28 -7
  39. package/modules/dependencies/approval.mjs +3 -2
  40. package/modules/dependencies/index.mjs +2 -2
  41. package/modules/deploy-kit/README.md +4 -2
  42. package/modules/deploy-kit/diagnostics.mjs +9 -0
  43. package/modules/deploy-kit/owner-signin.mjs +1 -1
  44. package/modules/deploy-kit/provider-transport.mjs +56 -0
  45. package/modules/deploy-kit/provider.mjs +22 -20
  46. package/modules/mail/README.md +14 -5
  47. package/modules/mail/src/adapters/rer/contract.mjs +33 -5
  48. package/modules/mail/src/adapters/rer/index.mjs +4 -1
  49. package/modules/mail/src/core/transport.mjs +9 -3
  50. package/modules/operator-auth/README.md +9 -0
  51. package/modules/operator-auth/accounts/credentials.mjs +2 -2
  52. package/modules/operator-auth/accounts/email-change.mjs +2 -2
  53. package/modules/operator-auth/accounts/provider-control.mjs +3 -3
  54. package/modules/operator-auth/accounts/store.mjs +9 -8
  55. package/modules/operator-auth/dev/cli-session.mjs +5 -4
  56. package/modules/operator-auth/dev/index.mjs +5 -5
  57. package/modules/operator-auth/dev-gate.mjs +4 -2
  58. package/modules/operator-auth/identity/email-link/index.mjs +7 -1
  59. package/modules/operator-auth/signin/index.mjs +10 -2
  60. package/onboarding/adapter.mjs +11 -3
  61. package/onboarding/local/operation.mjs +4 -2
  62. package/onboarding/local/owner.mjs +9 -3
  63. package/onboarding/local/state-files.mjs +17 -0
  64. package/onboarding/operator-installer.mjs +2 -2
  65. package/onboarding/operator-migrations.mjs +48 -0
  66. package/onboarding/process-diagnostics.mjs +25 -5
  67. package/onboarding/process-table.mjs +45 -19
  68. package/package.json +1 -1
  69. package/scripts/publish-check/README.md +5 -2
  70. package/scripts/publish-check/content_identities.py +1 -1
  71. package/scripts/publish-check/json_identity.py +10 -1
  72. package/scripts/publish-check/public_hygiene.py +30 -4
@@ -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');
@@ -148,17 +148,26 @@ await sender.send({
148
148
 
149
149
  Pass `relayUrl` only for `rer`. It must be the assigned HTTPS URL, without URL
150
150
  credentials, query or fragment. The adapter sends one POST with Bearer
151
- authentication and `redirect: 'error'`. Its JSON contains one mailbox `to`,
151
+ authentication and `redirect: 'manual'` (Cloudflare Workers reject
152
+ `redirect: 'error'`); a 3xx is never followed. Its JSON contains one mailbox `to`,
152
153
  `subject`, `text` and optional nonempty `html`. RER owns the sender and
153
154
  installation identity; `from` and `deliveryId` are not transmitted. Subjects
154
155
  must be nonempty, without newlines and at most 200 characters. Plain text is
155
156
  required; each body is limited to 65,536 characters and the JSON to 128 KiB.
156
- Other recipients, attachments, reply-to, headers and unsubscribe features are
157
- unsupported and fail before dispatch.
157
+
158
+ The relay sets `Auto-Submitted: auto-generated` on every message, so the
159
+ adapter accepts that header and does not transmit it; other `Auto-Submitted`
160
+ values are refused. `List-Unsubscribe` (one or two `<https:…>`/`<mailto:…>`
161
+ entries, at most 2,000 characters) travels as `listUnsubscribe`, and
162
+ `List-Unsubscribe-Post: List-Unsubscribe=One-Click` as `listUnsubscribePost:
163
+ true`, which requires an HTTPS entry. The structured `unsubscribe` request
164
+ assembles the same headers. Other recipients, attachments, reply-to and every
165
+ other header are unsupported and fail before dispatch.
158
166
 
159
167
  HTTP 202 returns `accepted` with no provider message ID. HTTP 400, 401, 402,
160
- 403 and 413 return `rejected`; 429 returns `rate_limited`; 502 and 503 return
161
- `uncertain`. Network failures and refused redirects are also `uncertain`.
168
+ 403 and 413 return `rejected`, and so does any 3xx (`provider_redirected`);
169
+ 429 returns `rate_limited`; 502 and 503 return `uncertain`. Network failures
170
+ are also `uncertain`.
162
171
  The usual application delivery policy decides whether to retry or stop; the
163
172
  adapter makes no retries and never reads or logs provider error bodies.
164
173
 
@@ -1,5 +1,9 @@
1
1
  import { fail } from '../../core/errors.mjs';
2
2
 
3
+ // The relay's own List-Unsubscribe rule: one or two <https:…>/<mailto:…> entries.
4
+ const listEntries = /^[ \t]*<([^<>\s]+)>[ \t]*(?:,[ \t]*<([^<>\s]+)>[ \t]*)?$/;
5
+ const relayMailbox = /^[^\s@]+@[^\s@]+\.[^\s@]{2,}$/;
6
+
3
7
  export function validateRerConfig(config) {
4
8
  let url;
5
9
  try { url = new URL(config.relayUrl); } catch { fail('rer_relay_url_required'); }
@@ -8,14 +12,38 @@ export function validateRerConfig(config) {
8
12
  url.href !== config.relayUrl) fail('invalid_rer_relay_url');
9
13
  }
10
14
 
15
+ /** Relay request fields for the headers it supports; it sets Auto-Submitted: auto-generated itself. */
16
+ export function rerHeaderFields(headers = {}) {
17
+ const fields = {};
18
+ for (const [name, value] of Object.entries(headers)) {
19
+ const lower = name.toLowerCase();
20
+ if (lower === 'auto-submitted') {
21
+ if (value.trim().toLowerCase() !== 'auto-generated') fail('unsupported_provider_setting');
22
+ } else if (lower === 'list-unsubscribe') fields.listUnsubscribe = value;
23
+ else if (lower === 'list-unsubscribe-post') {
24
+ if (value !== 'List-Unsubscribe=One-Click') fail('invalid_list_unsubscribe_post');
25
+ fields.listUnsubscribePost = true;
26
+ } else fail('unsupported_provider_setting');
27
+ }
28
+ let https = false;
29
+ if (fields.listUnsubscribe !== undefined) {
30
+ const entries = fields.listUnsubscribe.length <= 2000 && fields.listUnsubscribe.match(listEntries);
31
+ if (!entries) fail('invalid_list_unsubscribe');
32
+ for (const entry of entries.slice(1).filter(Boolean)) {
33
+ if (/^https:\/\//i.test(entry)) https = true;
34
+ else if (!/^mailto:/i.test(entry) || !relayMailbox.test(entry.slice(7))) fail('invalid_list_unsubscribe');
35
+ }
36
+ }
37
+ if (fields.listUnsubscribePost && !https) fail('invalid_list_unsubscribe_post');
38
+ return fields;
39
+ }
40
+
11
41
  export function validateRerMessage(message) {
12
42
  if (message.to.length !== 1) fail('rer_one_recipient_required');
13
43
  // The relay cannot preserve these features. Refuse them rather than silently
14
- // dropping recipients, attachments, threading or unsubscribe instructions.
15
- if (['cc', 'bcc', 'replyTo', 'attachments', 'unsubscribe'].some(field => message[field] !== undefined) ||
16
- (message.headers !== undefined && Reflect.ownKeys(message.headers).length > 0)) {
17
- fail('unsupported_provider_setting');
18
- }
44
+ // dropping recipients, attachments or threading.
45
+ if (['cc', 'bcc', 'replyTo', 'attachments'].some(field => message[field] !== undefined)) fail('unsupported_provider_setting');
46
+ rerHeaderFields(message.headers);
19
47
  if (!message.subject.trim() || message.subject.length > 200) fail('invalid_subject');
20
48
  if (!message.text?.trim() || message.text.length > 65_536 ||
21
49
  (message.html !== undefined && message.html.length > 65_536)) fail('invalid_body');
@@ -1,6 +1,7 @@
1
1
  import { validateConfig, validateMessage, parseAddress } from '../../core/validation.mjs';
2
2
  import { fail } from '../../core/errors.mjs';
3
- import { requestProvider, classifyHttpStatus, sendResult } from '../../core/transport.mjs';
3
+ import { requestProvider, redirected, classifyHttpStatus, sendResult } from '../../core/transport.mjs';
4
+ import { rerHeaderFields } from './contract.mjs';
4
5
 
5
6
  /** One Managed relay submission. RER owns the sender and installation identity. */
6
7
  export async function sendRer(config, message, dependencies = {}) {
@@ -12,6 +13,7 @@ export async function sendRer(config, message, dependencies = {}) {
12
13
  subject: message.subject,
13
14
  text: message.text,
14
15
  ...(message.html ? { html: message.html } : {}),
16
+ ...rerHeaderFields(message.headers),
15
17
  });
16
18
  if (new TextEncoder().encode(body).byteLength > 128 * 1024) fail('rer_message_too_large');
17
19
  const response = await requestProvider(config.relayUrl, {
@@ -21,6 +23,7 @@ export async function sendRer(config, message, dependencies = {}) {
21
23
  body,
22
24
  }, dependencies);
23
25
  if (response === null) return sendResult('rer', 'uncertain', null, 'transport_uncertain');
26
+ if (response === redirected) return sendResult('rer', 'rejected', null, 'provider_redirected');
24
27
  // Do not consume provider bodies: they may contain credentials or personal data.
25
28
  if (response.status === 202) return sendResult('rer', 'accepted');
26
29
  const status = classifyHttpStatus(response.status) ?? 'uncertain';
@@ -1,6 +1,10 @@
1
1
  import { validateSendResult } from './validation.mjs';
2
2
 
3
- /** One bounded request. Fetch exceptions never escape with credential/body text. */
3
+ /** What a caller that asked for redirect: 'error' receives for any 3xx. */
4
+ export const redirected = Object.freeze({ redirected: true });
5
+
6
+ /** One bounded request. Fetch exceptions never escape with credential/body text.
7
+ * Workers reject redirect: 'error', so every request is manual and never follows. */
4
8
  export async function requestProvider(url, init, dependencies = {}) {
5
9
  const timeout = dependencies.timeoutMilliseconds ?? 15_000;
6
10
  let timer;
@@ -8,8 +12,10 @@ export async function requestProvider(url, init, dependencies = {}) {
8
12
  const deadline = new Promise(resolve => { timer = setTimeout(() => resolve(null), timeout); });
9
13
  return await Promise.race([
10
14
  Promise.resolve().then(() => (dependencies.fetch ?? globalThis.fetch)(url, {
11
- ...init, redirect: init.redirect === 'error' ? 'error' : 'manual', signal: AbortSignal.timeout(timeout),
12
- })).then(response => response instanceof Response ? response : null, () => null),
15
+ ...init, redirect: 'manual', signal: AbortSignal.timeout(timeout),
16
+ })).then(response => !(response instanceof Response) ? null
17
+ : init.redirect === 'error' && (response.type === 'opaqueredirect' || response.status >= 300 && response.status < 400) ? redirected
18
+ : response, () => null),
13
19
  deadline,
14
20
  ]);
15
21
  } catch { return null; }
@@ -425,6 +425,11 @@ owner invitation cancellation, and owner activation or deactivation. Unchanged
425
425
  roles/statuses and non-owner status changes retain their usual authorization.
426
426
  The existing version fences and last-active-owner protection still apply after
427
427
  the proof succeeds.
428
+ With the `RER_DEMO=1` demo guard active, the configured owner's authenticated
429
+ session supplies this proof inside its own visitor container because mail is
430
+ mocked. Authentication still checks the container's own session secret and
431
+ store; another visitor's session is refused. Ordinary hosted instances keep
432
+ requiring the real proof described above.
428
433
  Creating a server-declared owner dev persona also requires the signed-in owner's
429
434
  fresh local proof in addition to the checkout key. Its creation repeats the actor
430
435
  session/version fence in the database write.
@@ -566,6 +571,10 @@ file that differs from the pinned revision (`SC-05.auth-copy.*`); the runtime im
566
571
  server-only, reconcile the seed's route integration, and run that seed's real auth
567
572
  and browser checks.
568
573
 
574
+ The sign-in page fills in its email field from `?login_hint=<email>` (a complete
575
+ address; anything else is ignored; never submitted for the visitor), so a link
576
+ from the platform's Open app or a seed's own page can pass the claimed owner.
577
+
569
578
  Wire `config.branding` with the seed's `productName`, `accentColor` and
570
579
  `signInPath`; the defaults are `your workspace`, `#334155` and `/signin`. Keep
571
580
  `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
  }
@@ -58,6 +59,11 @@ export function createEmailLinkLifecycle({ config: input, clock = Date.now, mail
58
59
  // Authentication already required the local key gate for this session.
59
60
  // Dev confirms actions directly rather than sending an unusable mail link.
60
61
  if (config.local && actor.kind === 'dev') return;
62
+ // The demo's mail is mocked. Its configured owner can confirm directly,
63
+ // after authentication against this visitor's isolated session store.
64
+ // Another demo's cookie cannot authenticate here; ordinary runtimes never
65
+ // install the demo guard, even if a caller supplies demo request headers.
66
+ if (demoEffectsEnabled() && actor.operator.role === 'owner' && actor.operator.email === config.OWNER_EMAIL) return;
61
67
  if (!await store.steppedUp(actor, clock() - STEP_UP_SECONDS * 1000, clock())) deny('step_up_required', 403);
62
68
  }
63
69
  const authenticate = request => store.authenticate(request);
@@ -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,12 +3,14 @@ import { link, lstat, open, readFile, rename, unlink } from 'node:fs/promises'
3
3
  import { join } from 'node:path'
4
4
  import { privateDirectory } from './files.mjs'
5
5
  import { processStart } from './process-table.mjs'
6
- import {processName} from '../process-diagnostics.mjs'
6
+ import {processName,inspectionContext,uncheckedInspection} from '../process-diagnostics.mjs'
7
7
 
8
8
  const busy = async (path) => {
9
9
  let owner;try{owner=JSON.parse(await readFile(path,'utf8'));}catch{}
10
10
  const pid=Number.isSafeInteger(owner?.pid)&&owner.pid>0?owner.pid:undefined;
11
- const identity=pid?`PID ${pid} (${await processName(pid)})`:'an unidentified process';
11
+ let command='process';
12
+ if(pid)try{command=await processName(pid,inspectionContext({budgetMs:1000}));}catch(error){if(!uncheckedInspection(error))throw error;}
13
+ const identity=pid?`PID ${pid} (${command})`:'an unidentified process';
12
14
  return Object.assign(new Error(`An active local operation owns the state: ${identity}. Stop it with rer dev --stop or rer preview --stop; for an unmanaged process, stop PID ${pid ?? 'shown in the lock'} before retrying.`), {code: 'LOCAL_OPERATION_BUSY', ownerPid: pid});
13
15
  }
14
16
  const graceMs = 10000
@@ -1,6 +1,12 @@
1
1
  import {readdir,lstat,realpath} from 'node:fs/promises';
2
2
  import {basename,join} from 'node:path';
3
- import {DatabaseSync} from 'node:sqlite';
3
+
4
+ // Importing the owner-name helper must not load the database engine or emit
5
+ // its runtime warning before the launcher registers its worker.
6
+ async function openDatabase(path,options={}){
7
+ const {DatabaseSync}=await import('node:sqlite');
8
+ return new DatabaseSync(path,options);
9
+ }
4
10
 
5
11
  // The owner the zero-setup `rer dev` gives a checkout before its real owner is known.
6
12
  export function zeroSetupOwner(checkout){
@@ -21,7 +27,7 @@ export async function localOwners(root){
21
27
  const found=[];
22
28
  for(const path of await databases(root)){
23
29
  let db,owners=[];
24
- try{db=new DatabaseSync(path,{readOnly:true});
30
+ try{db=await openDatabase(path,{readOnly:true});
25
31
  const tables=new Set(db.prepare("SELECT name FROM sqlite_master WHERE type='table'").all().map(row=>row.name));
26
32
  if(tables.has('oa_operators'))owners=db.prepare("SELECT email FROM oa_operators WHERE role='owner' AND status='active'").all();
27
33
  }finally{db?.close();}
@@ -47,7 +53,7 @@ export async function assertLocalOwner(root,email,failure=message=>Error(message
47
53
  // retires sign-in links issued to the placeholder.
48
54
  export async function replaceLocalOwner(root,from,to,failure=message=>Error(message)){
49
55
  for(const path of await databases(root)){
50
- const db=new DatabaseSync(path);
56
+ const db=await openDatabase(path);
51
57
  try{
52
58
  const tables=new Set(db.prepare("SELECT name FROM sqlite_master WHERE type='table'").all().map(row=>row.name));
53
59
  if(!tables.has('oa_operators'))continue;
@@ -0,0 +1,17 @@
1
+ import {readdir} from 'node:fs/promises';
2
+ import {join} from 'node:path';
3
+
4
+ // Select only regular files in canonical state, including SQLite sidecars.
5
+ // Do not follow links into other checkouts or pass directories to lsof.
6
+ export async function stateFiles(directory) {
7
+ let entries;
8
+ try{entries=await readdir(directory,{withFileTypes:true});}
9
+ catch(error){if(error.code==='ENOENT')return [];throw error;}
10
+ const files=[];
11
+ for(const entry of entries){
12
+ const path=join(directory,entry.name);
13
+ if(entry.isDirectory())files.push(...await stateFiles(path));
14
+ else if(entry.isFile())files.push(path);
15
+ }
16
+ return files;
17
+ }
@@ -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' },