@runeditrun/rer 0.2.21 → 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 (45) hide show
  1. package/cli/README.md +7 -0
  2. package/cli/demo-host.mjs +5 -5
  3. package/cli/deploy-command.mjs +2 -2
  4. package/cli/deploy.mjs +3 -1
  5. package/cli/export.mjs +1 -1
  6. package/cli/managed-server.mjs +5 -2
  7. package/cli/production-auth.mjs +19 -5
  8. package/modules/container/README.md +10 -0
  9. package/modules/container/build.mjs +7 -11
  10. package/modules/container/host.mjs +3 -1
  11. package/modules/container/ingress.mjs +15 -4
  12. package/modules/container/migration-inventory.mjs +33 -0
  13. package/modules/container/migrations.mjs +16 -2
  14. package/modules/delivery-producer/migrations.mjs +61 -0
  15. package/modules/demo/effects.mjs +4 -0
  16. package/modules/demo-host/README.md +27 -17
  17. package/modules/demo-host/capacity.mjs +1 -1
  18. package/modules/demo-host/container.mjs +65 -37
  19. package/modules/demo-host/pages.mjs +1 -1
  20. package/modules/demo-host/plan.mjs +19 -6
  21. package/modules/demo-host/remove.mjs +9 -7
  22. package/modules/demo-host/start-script.mjs +10 -1
  23. package/modules/demo-host/startup.mjs +4 -2
  24. package/modules/demo-host/worker.mjs +19 -2
  25. package/modules/dependencies/approval.mjs +3 -2
  26. package/modules/dependencies/index.mjs +2 -2
  27. package/modules/deploy-kit/README.md +4 -2
  28. package/modules/deploy-kit/diagnostics.mjs +9 -0
  29. package/modules/deploy-kit/provider-transport.mjs +56 -0
  30. package/modules/deploy-kit/provider.mjs +22 -20
  31. package/modules/operator-auth/README.md +4 -0
  32. package/modules/operator-auth/accounts/credentials.mjs +2 -2
  33. package/modules/operator-auth/accounts/email-change.mjs +2 -2
  34. package/modules/operator-auth/accounts/provider-control.mjs +3 -3
  35. package/modules/operator-auth/accounts/store.mjs +9 -8
  36. package/modules/operator-auth/dev/cli-session.mjs +5 -4
  37. package/modules/operator-auth/dev/index.mjs +5 -5
  38. package/modules/operator-auth/dev-gate.mjs +4 -2
  39. package/modules/operator-auth/identity/email-link/index.mjs +2 -1
  40. package/modules/operator-auth/signin/index.mjs +10 -2
  41. package/onboarding/adapter.mjs +11 -3
  42. package/onboarding/operator-installer.mjs +2 -2
  43. package/onboarding/operator-migrations.mjs +48 -0
  44. package/onboarding/process-table.mjs +45 -19
  45. package/package.json +1 -1
@@ -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
+ }
@@ -7,6 +7,21 @@ const execute = promisify(execFile)
7
7
  // One bounded wait for any process inspection; a loaded machine can take over a
8
8
  // second to list processes, which must not abort an otherwise healthy cleanup.
9
9
  export const inspectionMs = 5000
10
+ // A snapshot taken while processes start or exit can hold a row ps has not yet
11
+ // finished, or ps itself can fail for an instant. Such a read says nothing
12
+ // about ownership; it is repeated within the same bound rather than ending a
13
+ // launch whose own processes are accounted for.
14
+ const transient = (message) => Object.assign(new Error(message), { transient: true })
15
+ const retryMs = 10
16
+ async function withinBound(timeout, attempt) {
17
+ const deadline = Date.now() + timeout
18
+ for (;;) {
19
+ try { return await attempt(Math.max(1, deadline - Date.now())) } catch (error) {
20
+ if (!error.transient || Date.now() + retryMs >= deadline) throw error
21
+ await delay(retryMs)
22
+ }
23
+ }
24
+ }
10
25
  export const validPid = (pid) => Number.isSafeInteger(pid) && pid > 0 && pid <= 0x7fffffff
11
26
 
12
27
  // Inspect numeric identity and the executable name, never private argv.
@@ -60,20 +75,23 @@ async function processGroup(pgid, signal) {
60
75
  }
61
76
  return group
62
77
  }
63
- const { stdout } = await execute('/bin/ps', [
64
- '-ax', '-o', 'pid=', '-o', 'ppid=', '-o', 'pgid=', '-o', 'uid=', '-o', 'stat=', '-o', 'lstart=',
65
- ], { env: { ...process.env, LC_ALL: 'C', TZ: 'UTC' }, signal, killSignal: 'SIGKILL', maxBuffer: 8 * 1024 * 1024 })
78
+ let stdout
79
+ try {
80
+ ({ stdout } = await execute('/bin/ps', [
81
+ '-ax', '-o', 'pid=', '-o', 'ppid=', '-o', 'pgid=', '-o', 'uid=', '-o', 'stat=', '-o', 'lstart=',
82
+ ], { env: { ...process.env, LC_ALL: 'C', TZ: 'UTC' }, signal, killSignal: 'SIGKILL', maxBuffer: 8 * 1024 * 1024 }))
83
+ } catch (error) { if (signal.aborted) throw error; throw transient('Could not read process identities.') }
66
84
  const group = []
67
85
  for (const line of stdout.split('\n').filter((line) => line.trim())) {
68
86
  const match = line.match(/^\s*(\d+)\s+(\d+)\s+(\d+)\s+(\d+)\s+(\S+)\s+(.{24})\s*$/)
69
- if (!match) throw new Error('Could not read process identities.')
87
+ if (!match) throw transient('Could not read process identities.')
70
88
  const [, id, parent, groupId, uid, state, birth] = match
71
89
  const pid = Number(id)
72
90
  const ppid = Number(parent)
73
91
  if (pgid === undefined && (pid === 0 || Number(groupId) === 0)) continue
74
92
  if (pgid !== undefined && Number(groupId) !== pgid) continue
75
93
  if (!validPid(pid) || !validPid(Number(groupId)) || !Number.isSafeInteger(ppid) || ppid < 0 || !Number.isFinite(Date.parse(birth))) {
76
- throw new Error('Invalid process identity.')
94
+ throw transient('Invalid process identity.')
77
95
  }
78
96
  group.push({ pid, ppid, pgid: Number(groupId), uid: Number(uid), state, birth })
79
97
  }
@@ -86,30 +104,38 @@ async function processGroup(pgid, signal) {
86
104
  export async function readProcessIdentity(pid, timeout = inspectionMs) {
87
105
  if (!validPid(pid) || !(timeout > 0)) throw new Error('Invalid process identity deadline.')
88
106
  if (process.platform === 'linux') return linuxProcess(pid, undefined, AbortSignal.timeout(timeout))
107
+ return withinBound(timeout, (remaining) => psIdentity(pid, remaining))
108
+ }
109
+
110
+ async function psIdentity(pid, timeout) {
89
111
  let stdout
90
112
  try {
91
113
  ({ stdout } = await execute('/bin/ps', ['-p', String(pid), '-o', 'pid=', '-o', 'ppid=', '-o', 'pgid=', '-o', 'uid=', '-o', 'stat=', '-o', 'lstart=', '-o', 'comm='],
92
114
  { env: { ...process.env, LC_ALL: 'C', TZ: 'UTC' }, timeout, killSignal: 'SIGKILL', maxBuffer: 1024 * 1024 }))
93
- } catch (error) { if (error.code === 1 && !error.stdout?.trim()) return; throw new Error('Could not inspect process identity.') }
115
+ } catch (error) { if (error.code === 1 && !error.stdout?.trim()) return; throw transient('Could not inspect process identity.') }
94
116
  const match = stdout.match(/^\s*(\d+)\s+(\d+)\s+(\d+)\s+(\d+)\s+(\S+)\s+(.{24})\s+(.+?)\s*$/)
95
- if (!match) throw new Error('Invalid process identity.')
117
+ if (!match) throw transient('Invalid process identity.')
96
118
  const [, id, parent, groupId, uid, state, birth, command] = match
97
- if (Number(id) !== pid || !validPid(Number(groupId)) || !Number.isFinite(Date.parse(birth + ' UTC'))) throw new Error('Invalid process identity.')
119
+ if (Number(id) !== pid || !validPid(Number(groupId)) || !Number.isFinite(Date.parse(birth + ' UTC'))) throw transient('Invalid process identity.')
98
120
  return { pid, ppid: Number(parent), pgid: Number(groupId), uid: Number(uid), state, birth, command }
99
121
  }
100
122
 
101
- export async function readProcessTable(timeout = inspectionMs, pgid) {
123
+ // `read` is the process edge: it returns the table or throws; tests supply a
124
+ // failing one.
125
+ export async function readProcessTable(timeout = inspectionMs, pgid, read = processGroup) {
102
126
  if (!(timeout > 0)) throw new Error('Process inspection deadline expired.')
103
- const controller = new AbortController()
104
- let timer
105
- try {
106
- return await Promise.race([processGroup(pgid, controller.signal), new Promise((_, reject) => {
107
- timer = setTimeout(() => {
108
- controller.abort()
109
- reject(new Error('Process inspection deadline expired.'))
110
- }, timeout)
111
- })])
112
- } finally { clearTimeout(timer) }
127
+ return withinBound(timeout, async (remaining) => {
128
+ const controller = new AbortController()
129
+ let timer
130
+ try {
131
+ return await Promise.race([read(pgid, controller.signal), new Promise((_, reject) => {
132
+ timer = setTimeout(() => {
133
+ controller.abort()
134
+ reject(new Error('Process inspection deadline expired.'))
135
+ }, remaining)
136
+ })])
137
+ } finally { clearTimeout(timer) }
138
+ })
113
139
  }
114
140
 
115
141
  export const sameBirth = (left, right) => validPid(left?.pid) && left.pid === right?.pid && left.birth === right?.birth
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@runeditrun/rer",
3
- "version": "0.2.21",
3
+ "version": "0.2.22",
4
4
  "description": "The rer command: install, set up, run and launch Run Edit Run checkouts.",
5
5
  "license": "MIT",
6
6
  "type": "module",