@runeditrun/rer 0.2.22 → 0.2.24

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 +19 -0
  2. package/cli/bounded.mjs +5 -1
  3. package/cli/delivery-declarations.mjs +2 -2
  4. package/cli/demo-host.mjs +1 -1
  5. package/cli/deploy-command.mjs +7 -5
  6. package/cli/deploy-inputs.mjs +4 -1
  7. package/cli/deploy-observation.mjs +20 -2
  8. package/cli/deploy-owner.mjs +12 -7
  9. package/cli/deploy.mjs +9 -6
  10. package/cli/deployment-record.mjs +52 -0
  11. package/cli/local.mjs +11 -3
  12. package/cli/managed-server.mjs +2 -1
  13. package/cli/output.mjs +1 -1
  14. package/cli/production-auth.mjs +7 -27
  15. package/cli/production-mail.mjs +72 -0
  16. package/cli/signin.mjs +11 -6
  17. package/cli/site.mjs +2 -2
  18. package/global/CHANGELOG.md +25 -0
  19. package/modules/container/README.md +8 -3
  20. package/modules/container/adapters/d1.mjs +1 -1
  21. package/modules/container/build.mjs +1 -1
  22. package/modules/container/host.mjs +7 -4
  23. package/modules/container/transfer.mjs +0 -1
  24. package/modules/container/websockets.mjs +54 -0
  25. package/modules/container/worker-engine.mjs +3 -3
  26. package/modules/demo/README.md +4 -0
  27. package/modules/demo/label.mjs +7 -4
  28. package/modules/demo/responses.mjs +1 -1
  29. package/modules/demo-host/README.md +34 -9
  30. package/modules/demo-host/capacity.mjs +2 -2
  31. package/modules/demo-host/container.mjs +19 -7
  32. package/modules/demo-host/placement.mjs +19 -5
  33. package/modules/demo-host/plan.mjs +11 -6
  34. package/modules/demo-host/start-script.mjs +2 -1
  35. package/modules/demo-host/startup.mjs +3 -3
  36. package/modules/demo-host/worker.mjs +36 -13
  37. package/modules/deploy-kit/README.md +35 -2
  38. package/modules/deploy-kit/diagnostics.mjs +16 -1
  39. package/modules/deploy-kit/owner-cli.mjs +3 -3
  40. package/modules/deploy-kit/owner-remove.mjs +23 -5
  41. package/modules/deploy-kit/owner-signin.mjs +1 -1
  42. package/modules/deploy-kit/pagination.mjs +99 -0
  43. package/modules/deploy-kit/provider.mjs +30 -70
  44. package/modules/deploy-kit/r2-objects.mjs +6 -17
  45. package/modules/deploy-kit/site-readback.mjs +67 -0
  46. package/modules/deploy-kit/site.mjs +17 -31
  47. package/modules/deploy-kit/uploaded-worker.mjs +9 -3
  48. package/modules/erasure/queue.mjs +0 -2
  49. package/modules/job-queue/cli.mjs +1 -1
  50. package/modules/mail/README.md +14 -5
  51. package/modules/mail/src/adapters/rer/contract.mjs +33 -5
  52. package/modules/mail/src/adapters/rer/index.mjs +4 -1
  53. package/modules/mail/src/core/transport.mjs +9 -3
  54. package/modules/operator-auth/README.md +5 -0
  55. package/modules/operator-auth/identity/email-link/index.mjs +5 -0
  56. package/modules/operator-auth/identity/oidc/jwt.mjs +1 -1
  57. package/modules/portability/bridge.mjs +3 -3
  58. package/modules/portability/catalogue.mjs +1 -1
  59. package/modules/portability/cli-options.mjs +1 -1
  60. package/modules/portability/legacy-files.mjs +1 -1
  61. package/modules/portability/legacy-safety.mjs +3 -3
  62. package/modules/portability/payloads.mjs +1 -1
  63. package/modules/release/source.mjs +1 -1
  64. package/onboarding/local/operation.mjs +4 -2
  65. package/onboarding/local/owner.mjs +9 -3
  66. package/onboarding/local/state-files.mjs +17 -0
  67. package/onboarding/process-diagnostics.mjs +25 -5
  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
package/cli/README.md CHANGED
@@ -125,6 +125,14 @@ rebuild preview. A build that regenerates its own files declares them as
125
125
  `generatedOutputs` on the command adapter (see the seed command contract); those
126
126
  paths are not inputs, while any other file touched during the build is refused by name. Both use the same `.wrangler/state` and saved owner. Dev opens signed in through `RER_OPEN`, including with the legacy
127
127
  `--login` flag. Stop before changing modes.
128
+
129
+ Local startup holds the checkout's exclusive operation lock until serving stops.
130
+ Its state-holder inspection selects only regular files under `.wrangler/state`,
131
+ including SQLite sidecars. Dev and demo give `lsof` three seconds to answer. A confirmed
132
+ holder is refused with its PID and process name. If inspection cannot answer,
133
+ dev (including demo) continues under the held checkout lock; another
134
+ cooperating launch cannot acquire it. This lock does not inventory unmanaged
135
+ processes. Setup, reset and preview still require their state inspection to complete.
128
136
  Stop dev or preview before build, verification or data transfer; use the
129
137
  documented `--stop` flag or Ctrl-C.
130
138
 
@@ -181,6 +189,17 @@ secrets after the provider verifies the owned deployment. Local setup and demo
181
189
  do not require production mail credentials. Preview serves production output
182
190
  and prints its ready address without a captured-mail sign-in flow.
183
191
 
192
+ The production preflight also reads the product's `artifact.specInputs` in
193
+ `rer-packaging.json`, `packaging.json` or `scripts/delivery/base/packaging.json`,
194
+ and `management/integration/deployment-spec.json`. Public inputs come from
195
+ `publicVariableNames` or fixed `publicVariables`; credentials come from
196
+ `secretNames` and `optionalSecretNames`. Native `SENDGRID_API_KEY` and
197
+ `RESEND_API_KEY` satisfy their respective providers. When `MAIL_PROVIDER` is
198
+ `later` or absent, a declared native provider key plus a declared `MAIL_FROM`
199
+ resolves the deferred choice for preflight. An explicitly selected provider
200
+ still requires its own credentials. Undeclared environment values do not count;
201
+ the product's deploy adapter remains responsible for applying these settings.
202
+
184
203
  Idle timeout is `--idle-timeout SECONDS`, then `RER_SERVER_IDLE_SECONDS`, then
185
204
  43200 seconds (12 hours). Only positive integer seconds are accepted. HTTP requests,
186
205
  including assets, reset inactivity; a live request/stream prevents idle
package/cli/bounded.mjs CHANGED
@@ -66,7 +66,11 @@ export async function boundedCommand(project,options,argv,out){
66
66
  out.error(new RerError('cancelled',`Stopped by ${termination} after owned children were stopped.`,exitCode));
67
67
  out.result(false,exitCode);
68
68
  }else if(finalEvent&&finalEvent.exitCode===exitCode){
69
- if(errorEvent)out.error(new RerError(errorEvent.code,store.redact(errorEvent.message),exitCode));
69
+ if(errorEvent){
70
+ let deployment={};
71
+ try{deployment=JSON.parse(store.redact(JSON.stringify({environment:errorEvent.environment,availableDeployments:errorEvent.availableDeployments})));}catch{}
72
+ out.error(new RerError(errorEvent.code,store.redact(errorEvent.message),exitCode,deployment));
73
+ }
70
74
  const {version,verb,event,ok,exitCode:childExit,...details}=finalEvent;
71
75
  // Redaction can cut through a value that matches a credential; the outcome stands without its details.
72
76
  let shown;try{shown=JSON.parse(store.redact(JSON.stringify(details)));}catch{shown={};}
@@ -4,7 +4,7 @@ import { contained } from './project.mjs';
4
4
 
5
5
  // Source policy and its committed integration projection. Inspect declarations
6
6
  // without requiring a build or executing the seed's packaging code.
7
- const sources = [
7
+ export const deliveryDeclarationSources = [
8
8
  ['rer-packaging.json', value => value?.artifact?.specInputs],
9
9
  ['packaging.json', value => value?.artifact?.specInputs],
10
10
  ['scripts/delivery/base/packaging.json', value => value?.artifact?.specInputs],
@@ -13,7 +13,7 @@ const sources = [
13
13
 
14
14
  export async function deliveryDeclarationClauses(root) {
15
15
  const clauses = [];
16
- for (const [path, select] of sources) {
16
+ for (const [path, select] of deliveryDeclarationSources) {
17
17
  let text;
18
18
  try { text = await readFile(await contained(root, path, { optional: true }), 'utf8'); }
19
19
  catch (error) {
package/cli/demo-host.mjs CHANGED
@@ -20,7 +20,7 @@ export async function demoHostCommand(project, options, store, signal, out, oper
20
20
  if (!(app.platforms ?? ['workers']).includes('container')) throw refuse('A hosted demo runs the seed\'s container image: declare "container" in deploy.json platforms first.');
21
21
  let plan;
22
22
  try { plan = demoPlan({ project: app.project, environment: options.environment ?? 'production', compatibilityDate: app.compatibilityDate, originVar: app.originVar, hostVariables: app.container?.hostVariables, declaration, turnstileSiteKey: process.env.TURNSTILE_SITE_KEY?.trim() }); }
23
- catch (error) { throw invalid(`The demo deploy declaration is invalid (${error.message}). deploy-demo.json holds {"version": 1, "domain": "<run site apex>", "name": "<product name>"}, optionally "maxInstances", "instanceType" (${INSTANCE_TYPES.join(', ')}; default basic) and plain "settings".`); }
23
+ catch (error) { throw invalid(`The demo deploy declaration is invalid (${error.message}). deploy-demo.json holds {"version": 1, "domain": "<run site apex>", "name": "<product name>"}, optionally "maxInstances", "instanceType" (${INSTANCE_TYPES.join(', ')}; default basic), "ownerEmail" (the demo owner's address; default owner@demo.invalid) and plain "settings".`); }
24
24
  if (options.remove) return removeDemo(plan, store, signal);
25
25
  if (process.env.RER_DEMO_OPERATOR_TOKEN && (process.env.RER_DEMO_OPERATOR_TOKEN.length < 32 || process.env.RER_DEMO_OPERATOR_TOKEN.length > 512)) throw invalid('RER_DEMO_OPERATOR_TOKEN must contain 32 to 512 characters.');
26
26
  const folder = join(project.root, '.rer', 'demo-host');
@@ -8,14 +8,14 @@ import { deployEnvironment, deployAgain } from './deploy-inputs.mjs';
8
8
  import { claimHostedOwner } from './deploy-owner.mjs';
9
9
  import { checkHostedSetup, hostedSetupFailure } from './deploy-setup.mjs';
10
10
  import { mutationReadinessFailure } from './deploy-readiness.mjs';
11
- import { observeOwner } from './deploy-observation.mjs';
11
+ import { observeOwner, ownerExchangeFailure } from './deploy-observation.mjs';
12
12
  import { committedSource } from './deploy-source.mjs';
13
13
  import { hookOrigin, waitForSource } from './deploy-hook.mjs';
14
14
  import { rememberHookState, hookState } from './deploy-hook-record.mjs';
15
15
  import { main as owner } from '../modules/deploy-kit/owner-cli.mjs';
16
16
  import { localOnlyBinding, ownerWorkerName } from '../modules/deploy-kit/owner.mjs';
17
17
  import { refuseLocalModels } from '../modules/deploy-kit/local-only.mjs';
18
- import { providerRefusal, providerTransport } from '../modules/deploy-kit/diagnostics.mjs';
18
+ import { providerFailure } from '../modules/deploy-kit/diagnostics.mjs';
19
19
  import { shared } from './shared.mjs';
20
20
 
21
21
  export function validateDeployOptions(options) {
@@ -108,7 +108,7 @@ export async function deployCommand(context) {
108
108
  // current version independently of the original upload's spent deadline.
109
109
  const state = await inspect(origin);
110
110
  if ((state?.origin ?? origin) !== origin || claims.some(item => item.origin !== origin)) throw new Error('owner-claim-origin-mismatch');
111
- if (claims.some(item => !item.outcome)) throw new Error('owner-claim-failed');
111
+ if (claims.some(item => !item.outcome)) { const error = new Error('owner-claim-failed'); error.ownerExchange = claims.find(item => !item.outcome); throw error; }
112
112
  claimed = claims.at(-1)?.outcome;
113
113
  step = 'wait for the deployed source';
114
114
  await waitForSource({ origin, sourceSha, versionId: state?.versionId ?? (!claims.length && !deployed.owner ? uploaded?.versionId : undefined), again: deployAgain(options) });
@@ -136,7 +136,9 @@ export async function deployCommand(context) {
136
136
  if (setup) throw commandFailure(redact(setup));
137
137
  const readiness = mutationReadinessFailure(error, { again, redact });
138
138
  if (readiness) throw commandFailure(readiness);
139
- const refused = providerRefusal(error) ?? providerTransport(error);
140
- throw commandFailure(redact(`${state} Failed at ${step}: ${error.message}${refused ? ` (${refused})` : ''}${error.cause ? ` (${error.cause})` : ''}. Fix the cause and run ${again} again using the same environment credentials. ${outcome && recorded ? `To retire the token without rebuilding: ${again} --unset-secret ${setupManifest?.steps?.find(item => item.type === 'owner-claim')?.tokenField ?? 'SETUP_TOKEN'}.` : ''}`));
139
+ const refused = providerFailure(error,redact);
140
+ const exchange = error.ownerExchange ?? (error.message === 'owner-claim-failed' ? observedClaims.lastExchange ?? observedClaims.at(-1) : undefined);
141
+ const ownerCause = ownerExchangeFailure(exchange);
142
+ throw commandFailure(redact(`${state} Failed at ${step}: ${error.message}${refused ? ` (${refused})` : ''}${ownerCause ? ` (${ownerCause})` : ''}${error.cause ? ` (${error.cause})` : ''}. Fix the cause and run ${again} again using the same environment credentials. ${outcome && recorded ? `To retire the token without rebuilding: ${again} --unset-secret ${setupManifest?.steps?.find(item => item.type === 'owner-claim')?.tokenField ?? 'SETUP_TOKEN'}.` : ''}`));
141
143
  }
142
144
  }
@@ -39,7 +39,10 @@ export async function withDeployEnvironment(root, options, run) {
39
39
  const { env } = await deployEnvironment({ root, options, declaration: {} });
40
40
  const { createRedaction, credentialValues } = await shared('redaction.mjs');
41
41
  const redaction = createRedaction();
42
- redaction.addSecrets([...credentialValues(env), ...Object.entries(env).filter(([key, value]) => saved[key] !== value).map(([, value]) => value)]);
42
+ // Provider names are public enum values. Masking "resend" would also hide
43
+ // RESEND_API_KEY in the preflight's instruction for the missing credential.
44
+ const publicProvider = (key, value) => key === 'MAIL_PROVIDER' && /^(resend|sendgrid|cloudflare|rer|later)$/.test(value);
45
+ redaction.addSecrets([...credentialValues(env), ...Object.entries(env).filter(([key, value]) => saved[key] !== value && !publicProvider(key, value)).map(([, value]) => value)]);
43
46
  Object.assign(process.env, env);
44
47
  try { return await run(redaction); }
45
48
  catch (error) { if (typeof error?.message === 'string') error.message = redaction.redact(error.message); throw error; }
@@ -12,7 +12,11 @@ export async function observeOwner({ paths, inspect, beforeClaim, addSecret, dep
12
12
  if (paths.includes(url.pathname) && (init.method ?? (input instanceof Request ? input.method : 'GET')).toUpperCase() === 'POST') {
13
13
  try { body = JSON.parse(typeof init.body === 'string' ? init.body : input instanceof Request ? await input.clone().text() : 'null'); } catch {}
14
14
  }
15
- if (typeof body?.token !== 'string' || !body.token) return fetch(input, init);
15
+ if (typeof body?.token !== 'string' || !body.token) {
16
+ const response = await fetch(input,init);
17
+ if (claims.some(item => item.origin === url.origin)) claims.lastExchange = await exchange(response,url,init.method ?? 'GET');
18
+ return response;
19
+ }
16
20
  addSecret(body.token);
17
21
  const deployed = await inspect(url.origin);
18
22
  if (deployed && url.origin !== deployed.origin) throw new Error('owner-claim-origin-mismatch');
@@ -24,9 +28,23 @@ export async function observeOwner({ paths, inspect, beforeClaim, addSecret, dep
24
28
  try { code = (await response.clone().json()).error; } catch {}
25
29
  }
26
30
  const outcome = response.status === 303 ? 'claimed' : response.status === 409 && code === 'already_initialized' ? 'kept' : undefined;
27
- claims.push({ origin: url.origin, outcome, status: response.status });
31
+ const observed = {...await exchange(response,url,'POST'),outcome};
32
+ claims.push(observed); claims.lastExchange = observed;
28
33
  return response;
29
34
  };
30
35
  try { return await observeReadiness(() => run(claims)); }
31
36
  finally { globalThis.fetch = fetch; }
32
37
  }
38
+
39
+ async function exchange(response,url,method) {
40
+ let code;
41
+ if (response.status >= 400) { try { code = (await response.clone().json()).error; } catch {} }
42
+ return {origin:url.origin,path:url.pathname,method,status:response.status,
43
+ ...(typeof code === 'string' && /^[a-zA-Z0-9_-]{1,80}$/.test(code) ? {code} : {}),
44
+ ...(response.status === 303 && !response.headers.has('set-cookie') ? {missingCookie:true} : {})};
45
+ }
46
+
47
+ export function ownerExchangeFailure(exchange) {
48
+ if (!exchange || typeof exchange.path !== 'string' || !Number.isInteger(exchange.status)) return undefined;
49
+ return `${exchange.method === 'GET' ? 'GET' : 'POST'} ${exchange.path.split('?')[0]} returned HTTP ${exchange.status}${exchange.code ? ` (${exchange.code})` : ''}${exchange.missingCookie ? ' (no Set-Cookie header)' : ''}`;
50
+ }
@@ -1,5 +1,5 @@
1
1
  import { ownerClaimRequest } from './deploy-claim-request.mjs';
2
- import { observeOwner } from './deploy-observation.mjs';
2
+ import { observeOwner, ownerExchangeFailure } from './deploy-observation.mjs';
3
3
  import { randomBytes } from 'node:crypto';
4
4
 
5
5
  // After a healthy deploy, the hosted app's first owner is the setup owner: rer
@@ -28,7 +28,7 @@ export async function claimHostedOwner({ hook, setupManifest, declaration, deplo
28
28
  try { if (!deployed.ownerClaim) await recordClaim?.(outcome); await secret(['--unset', tokenKey], env); }
29
29
  catch (cause) {
30
30
  if (cause.secretChange) { cause.owner = outcome; cause.tokenKey = tokenKey; cause.ownerFinalization = true; throw cause; }
31
- const error = new Error('owner-token-retirement-failed'); error.owner = outcome; error.tokenKey = tokenKey; error.cause = cause.message; throw error; }
31
+ const error = new Error('owner-token-retirement-failed'); error.owner = outcome; error.tokenKey = tokenKey; error.cause = cause; throw error; }
32
32
  return outcome;
33
33
  };
34
34
  // Only a recorded successful bootstrap proves ownership; --unset-secret alone
@@ -53,11 +53,16 @@ export async function claimHostedOwner({ hook, setupManifest, declaration, deplo
53
53
  }
54
54
  if (typeof hook === 'function') {
55
55
  const context = { origin: deployed.origin, vars: { ...env, [tokenKey]: token }, input: {}, store, signal, ownerClaim: claim, fail: () => ownerFailure('the seed owner hook failed') };
56
- let observed;
56
+ let observed, exchanges = [];
57
57
  try {
58
58
  if (deployed.observedOwner) await hook(context);
59
- else await observeOwner({ paths: ['/auth/bootstrap', claim?.path].filter(Boolean), inspect, addSecret, deployed: () => deployed, tokenKey }, async claims => { await hook(context); observed = claims.at(-1)?.outcome; });
60
- } catch (cause) { if (cause.message === 'owner-claim-failed') throw cause; throw ownerFailure(cause.message); }
59
+ else await observeOwner({ paths: ['/auth/bootstrap', claim?.path].filter(Boolean), inspect, addSecret, deployed: () => deployed, tokenKey }, async claims => { exchanges = claims; await hook(context); observed = claims.at(-1)?.outcome; });
60
+ } catch (cause) {
61
+ const exchange = exchanges.lastExchange ?? exchanges.at(-1);
62
+ const error = cause.message === 'owner-claim-failed' ? cause : ownerFailure(cause.message);
63
+ if (exchange) { error.ownerExchange = exchange; error.cause = ownerExchangeFailure(exchange); }
64
+ throw error;
65
+ }
61
66
  // Function hooks can keep existing owners without returning a value. Observe
62
67
  // their actual response, instead of assuming that a resolved promise claimed.
63
68
  const outcome = context.ownerClaimed ?? observed ?? deployed.observedOwner?.();
@@ -69,12 +74,12 @@ export async function claimHostedOwner({ hook, setupManifest, declaration, deplo
69
74
  try {
70
75
  response = await ownerClaimRequest(fetch, new URL(hook.path ?? '/auth/bootstrap', deployed.origin), { method: 'POST',
71
76
  headers: { Origin: deployed.origin, 'Content-Type': 'application/json' }, body: JSON.stringify({ token, displayName, returnTo: hook.returnTo ?? '/' }) }, {deployed, tokenKey, signal});
72
- } catch (error) { throw ownerFailure(['owner-claim-origin-mismatch','owner-claim-redirected','owner-claim-readiness-timeout'].includes(error.message) ? error.message : 'the hosted application did not answer'); }
77
+ } catch (error) { throw ownerFailure(`POST ${new URL(hook.path ?? '/auth/bootstrap',deployed.origin).pathname}: ` + (['owner-claim-origin-mismatch','owner-claim-redirected','owner-claim-readiness-timeout'].includes(error.message) ? error.message : 'the hosted application did not answer')); }
73
78
  if (response.status !== 303) { try { const body = await response.json(); if (typeof body?.error === 'string' && /^[a-z_]{1,64}$/.test(body.error)) code = body.error; } catch {} }
74
79
  else await response.body?.cancel();
75
80
  const outcome = response.status === 303 ? 'claimed' : response.status === 409 && code === 'already_initialized' ? 'kept' : undefined;
76
81
  const advice = code !== 'invalid_setup_token' ? '' : !secret ? `; the Worker holds another setup token: have the deploy hook return the one it deployed as setupToken, or set it as ${item.environment} with --env-file` : given ? `; the ${item.environment} you supplied is not the deployed setup token: leave it unset and rer issues a fresh one` : '';
77
- if (!outcome) throw ownerFailure(`HTTP ${response.status} (${code})${advice}`);
82
+ if (!outcome) throw ownerFailure(`POST ${new URL(hook.path ?? '/auth/bootstrap',deployed.origin).pathname} returned HTTP ${response.status} (${code})${advice}`);
78
83
  return retire(outcome);
79
84
  }
80
85
 
package/cli/deploy.mjs CHANGED
@@ -1,6 +1,6 @@
1
1
  import { requireProductionAuth } from './production-auth.mjs';
2
2
  import { readFile } from 'node:fs/promises';
3
- import { deployDiagnostic, providerTransport } from '../modules/deploy-kit/diagnostics.mjs';
3
+ import { deployDiagnostic, providerFailure } from '../modules/deploy-kit/diagnostics.mjs';
4
4
  import { shared } from './shared.mjs';
5
5
  import { contained } from './project.mjs';
6
6
  import { missing, invalid, refuse, RerError } from './errors.mjs';
@@ -13,6 +13,7 @@ import { checkHostedSetup, hostedSetupFailure } from './deploy-setup.mjs';
13
13
  import { mutationReadinessFailure } from './deploy-readiness.mjs';
14
14
  import { committedSource } from './deploy-source.mjs';
15
15
  import { hookState, forgetHookState } from './deploy-hook-record.mjs';
16
+ import { deploymentRecord } from './deployment-record.mjs';
16
17
 
17
18
  export function ownerDeploy(declarationPath, lifecycle) {
18
19
  // rer verify serves the build with this declaration's vars and secrets.
@@ -29,6 +30,7 @@ export function ownerDeploy(declarationPath, lifecycle) {
29
30
  const retry = options.remove ? `${again} --remove --yes` : options.setSecret ? `${again} --set-secret ${options.setSecret}` : options.unsetSecret ? `${again} --unset-secret ${options.unsetSecret}` : again;
30
31
  if (change.length > 1 || change.length && options.dryRun) throw invalid(`Use ${change.join(', ')}${options.dryRun ? ' and --dry-run' : ''} on separate runs.`);
31
32
  if (options.remove && !options.yes) throw invalid(`${again} --remove deletes this environment's Worker and every D1, R2, KV and queue rer created for it, with their data. Add --yes to confirm.`);
33
+ const recordedState = change.length ? await deploymentRecord(root, options) : undefined;
32
34
  // A dry run reads the settings file too, so a refused key fails here and not only on the real deploy.
33
35
  if (options.dryRun && options.envFile) await deployEnvironment({ root, options, declaration, localOnlyKeys });
34
36
  if (!change.length) {
@@ -62,7 +64,7 @@ export function ownerDeploy(declarationPath, lifecycle) {
62
64
  let step = 'deploy', deployed;
63
65
  try {
64
66
  // A custom hook's own state file, when its deploy named one.
65
- const state = await hookState(root, environment);
67
+ const state = change.length ? recordedState : await hookState(root, environment);
66
68
  if (options.remove) {
67
69
  step = 'remove';
68
70
  const result = await owner('remove', state ? ['--state', state] : []);
@@ -117,14 +119,14 @@ function failureText({ error, step, created, again, retry, secretChange, deploye
117
119
  const at = step === 'deploy' ? diagnostic?.step ?? 'prepare deploy' : step;
118
120
  const input = /^missing-secret-([A-Z][A-Z0-9_]*)$/.exec(code)?.[1];
119
121
  if (input) return `Deploy needs ${input}, which the deploy declaration lists as a secret and the Worker does not hold it. Set ${input} in the environment or in an --env-file file (an owned 0600 file of KEY=VALUE lines), then run the same command again. Nothing was uploaded.${created.length ? ` Resources created this attempt: ${created.join(', ')}.` : ''}`;
120
- if (code === 'remove-incomplete') return `Removal stopped with ${error.remaining.join(', ')} still present${error.failed.length ? ` (${error.failed.map(item => `${item.resource}: ${item.code}`).join('; ')})` : ''}. Removed: ${error.removed.join(', ') || 'nothing'}. Confirmed owned R2 buckets are emptied automatically; unproved buckets are never purged. Run ${again} --remove --yes again to finish.`;
121
- if (code === 'nothing-to-remove') return `This checkout has no rer deployment record for this environment, so --remove deletes nothing. Run it from the checkout that deployed it.`;
122
- if (code === 'owner-token-retirement-failed') return `The application is deployed at ${deployed?.origin}; owner ${error.owner}; setup token retirement failed (${redact(String(error.cause))}). Run ${again} --unset-secret ${error.tokenKey ?? 'SETUP_TOKEN'} using the same environment credentials, or run ${again} again to finish.`;
122
+ if (code === 'remove-incomplete') return `Removal stopped with ${error.remaining.join(', ')} still present${error.failed.length ? ` (${error.failed.map(item => `${item.resource}: ${providerFailure(item.error, redact) ?? item.code}`).join('; ')})` : ''}. Removed: ${error.removed.join(', ') || 'nothing'}. Confirmed owned R2 buckets are emptied automatically; unproved buckets are never purged. Run ${again} --remove --yes again to finish.`;
123
+ if (code === 'nothing-to-remove') return `The deployment record selected by ${again} has no resources that rer owns, so --remove deletes nothing.`;
124
+ if (code === 'owner-token-retirement-failed') return `The application is deployed at ${deployed?.origin}; owner ${error.owner}; setup token retirement failed (${redact(String(error.cause))}${providerFailure(error,redact) ? `; ${providerFailure(error,redact)}` : ''}). Run ${again} --unset-secret ${error.tokenKey ?? 'SETUP_TOKEN'} using the same environment credentials, or run ${again} again to finish.`;
123
125
  if (code === 'owner-claim-failed') return `The application is deployed at ${deployed?.origin}, but claiming its owner failed: ${redact(String(error.cause))}. Owner claim and setup token retirement are not confirmed; run ${again} again using the same environment credentials to finish.`;
124
126
  const resource = diagnostic?.resource ?? (error.resource ? redact(String(error.resource)) : undefined);
125
127
  if (code === 'resource-not-listed') return `Deploy stopped at ${at}: ${resource} was created, but Cloudflare's account listing still does not show it after two minutes. Nothing was uploaded.\nResources created this attempt: ${created.join(', ') || 'none'}.\nRun ${again} again once the listing catches up: it reuses ${resource}. To delete what this environment created instead: ${again} --remove --yes.`;
126
128
  const lines = [`Deploy failed at ${at}: ${code}${resource ? ` (${resource})` : ''}${diagnostic?.providerCodes?.length ? ` (provider ${diagnostic.providerCodes.join(', ')})` : ''}.`];
127
- const transport = providerTransport(error, redact);
129
+ const transport = providerFailure(error, redact);
128
130
  if (transport) lines.push(`${transport}.`);
129
131
  if (diagnostic?.output && diagnostic.output !== '(no provider output)') lines.push(`First redacted output lines:\n${diagnostic.output}`);
130
132
  lines.push(`Resources created this attempt: ${created.join(', ') || 'none'}.`);
@@ -134,6 +136,7 @@ function failureText({ error, step, created, again, retry, secretChange, deploye
134
136
 
135
137
  function recovery({ code, at, resource, again, retry, secretChange }) {
136
138
  const remove = `${again} --remove --yes`, removing = retry === remove;
139
+ if (code === 'provider-incomplete-pagination') return `Cloudflare did not supply a complete list. Inspect the named GET call in Cloudflare, resolve its missing continuation, then run ${retry} again with the same account and environment. Keep the deployment record so rer can reuse its resources.`;
137
140
  if (code === 'owned-resource-replaced' || code === 'resource-name-collision') return `rer refuses to change a resource it did not create or that was replaced after it did; nothing was changed. Choose another --environment name, or remove the other resource yourself.`;
138
141
  // A lost create answer: the resource may exist, and rer cannot prove it made it.
139
142
  if (resource && (code === 'uncertain-resource-create' || code === 'provider-transport-failed' && at.startsWith('create '))) {
@@ -0,0 +1,52 @@
1
+ import { access, readFile, readdir } from 'node:fs/promises';
2
+ import { join } from 'node:path';
3
+ import { hookState } from './deploy-hook-record.mjs';
4
+ import { deployAgain } from './deploy-inputs.mjs';
5
+ import { contained } from './project.mjs';
6
+ import { RerError } from './errors.mjs';
7
+
8
+ const recordPath = environment => join('.rer', 'deploy', `${environment}.json`);
9
+
10
+ // Existing-deployment commands share the same hook pointer and default record.
11
+ // A first deploy still creates its record through the kit as before.
12
+ export async function deploymentRecord(root, options) {
13
+ const environment = options.environment ?? 'production';
14
+ const state = await hookState(root, environment);
15
+ const path = await contained(root, state ?? recordPath(environment), { optional: true });
16
+ try { await access(path); }
17
+ catch (error) {
18
+ if (error.code !== 'ENOENT') throw error;
19
+ const availableDeployments = (await environments(root)).map(environment => ({ environment, command: commandFor(options, environment) }));
20
+ const held = availableDeployments.length
21
+ ? `It holds:\n${availableDeployments.map(item => ` ${item.environment}: ${item.command}`).join('\n')}`
22
+ : 'This checkout holds no deployment environments. Run it from the checkout that deployed it.';
23
+ const signin = options.verb === 'signin';
24
+ throw new RerError(signin ? 'safety_refusal' : 'command_failed', `No deployment of the ${environment} environment in this checkout. ${held}`, signin ? 4 : 1, { environment, availableDeployments });
25
+ }
26
+ return state;
27
+ }
28
+
29
+ async function environments(root) {
30
+ let entries;
31
+ try { entries = await readdir(await contained(root, '.rer/deploy', { optional: true })); }
32
+ catch (error) { if (error.code === 'ENOENT') return []; throw error; }
33
+ const names = new Set(entries.flatMap(name => /^([a-z][a-z0-9]*(?:-[a-z0-9]+)*)(?:\.hook)?\.json$/.exec(name)?.slice(1) ?? []).filter(name => name.length <= 32));
34
+ const held = await Promise.all([...names].map(async environment => {
35
+ try {
36
+ const state = await hookState(root, environment);
37
+ const path = await contained(root, state ?? recordPath(environment));
38
+ const record = JSON.parse(await readFile(path, 'utf8'));
39
+ return record?.kind === 'rer-deploy-owner-state' && record.environment === environment ? environment : undefined;
40
+ } catch { return undefined; } // An unrelated or broken file is not a held deployment.
41
+ }));
42
+ return held.filter(Boolean).sort();
43
+ }
44
+
45
+ function commandFor(options, environment) {
46
+ const again = deployAgain({ ...options, environment });
47
+ if (options.verb === 'signin') return again.replace(/^rer deploy/, 'rer signin');
48
+ if (options.remove) return `${again} --remove --yes`;
49
+ if (options.setSecret) return `${again} --set-secret ${options.setSecret}`;
50
+ if (options.unsetSecret) return `${again} --unset-secret ${options.unsetSecret}`;
51
+ return again;
52
+ }
package/cli/local.mjs CHANGED
@@ -98,12 +98,20 @@ export async function reset(project, options, out) {
98
98
  return { paths: inventory };
99
99
  }
100
100
 
101
- export async function refuseLegacyProcess(project,{reset=false,verb='dev'}={}) {
101
+ export async function refuseLegacyProcess(project,{reset=false,verb='dev',operation}={}) {
102
102
  let selected;try{selected=await selectedOrigin(project,{});}catch(error){if(!reset)throw error;}
103
103
  // Confirmed reset can recover malformed settings; checkout/state custody is
104
104
  // still checked even when there is no usable saved origin.
105
- const {localProcessConflict,inspectionContext}=await shared('process-diagnostics.mjs');
105
+ const {localProcessConflict,inspectionContext,uncheckedInspection}=await shared('process-diagnostics.mjs');
106
106
  // The front door holds a door origin's port, not this checkout.
107
- const conflict=await localProcessConflict(project.root,selected?.door?undefined:selected?.savedOrigin,inspectionContext({verb}));
107
+ let conflict;
108
+ try{conflict=await localProcessConflict(project.root,selected?.door?undefined:selected?.savedOrigin,inspectionContext({verb}));}
109
+ catch(error){
110
+ // Startup already holds the exclusive checkout operation through teardown.
111
+ // An unanswered observation must not defeat that cooperating-launch proof.
112
+ // Setup/reset retain their destructive-operation inspection requirement.
113
+ if(operation?.token&&verb==='dev'&&uncheckedInspection(error))return {lockProof:true};
114
+ throw error;
115
+ }
108
116
  if(conflict)throw refuse(`A local process holds ${conflict.reason}: PID ${conflict.pid} (${conflict.command}). Stop it with kill -TERM ${conflict.pid}, then retry. Use rer dev --stop or rer preview --stop for a registered server.`);
109
117
  }
@@ -85,9 +85,10 @@ export async function managedServer(project,options,out,{clock={}}={}){
85
85
  throw Error('Unknown management operation');
86
86
  });
87
87
  await stateSafety(project);
88
- await refuseLegacyProcess(project,{verb:options.verb});
89
88
  const {localOperation}=await shared('local/operation.mjs');
90
89
  try{operation=await localOperation(project.root);}catch(error){throw refuse(error.message);}
90
+ const ownership=await refuseLegacyProcess(project,{verb:options.verb,operation});
91
+ if(ownership?.lockProof)out.progress('Local process inspection did not answer; continuing with the exclusive checkout launch lock.\n');
91
92
  const {recoverInterrupted}=await shared('local/recovery.mjs');await recoverInterrupted(project.root,operation);
92
93
  const {loadInstallerSeed}=await shared('setup-manifest.mjs');
93
94
  const seed=project.adapter.setup?await loadInstallerSeed(project.root,project.adapter):undefined;project.setupManifest=seed?.manifest;
package/cli/output.mjs CHANGED
@@ -19,7 +19,7 @@ export function output(options) {
19
19
  else if (!['describe', 'check', 'dev', 'preview', 'setup'].includes(options.verb) || !ok) this.human(`${options.verb}: ${ok ? 'complete' : 'failed'} (exit ${exitCode})`);
20
20
  },
21
21
  error(error) {
22
- if (structuredResult) this.event('error', { code: error.code, message: error.message, exitCode: error.exitCode });
22
+ if (structuredResult) this.event('error', { code: error.code, message: error.message, exitCode: error.exitCode, ...(error.availableDeployments ? { environment: error.environment, availableDeployments: error.availableDeployments } : {}) });
23
23
  else write(2, error.message + '\n');
24
24
  },
25
25
  };
@@ -1,9 +1,8 @@
1
1
  import { refuse } from './errors.mjs';
2
- import { mailbox } from './parse.mjs';
3
2
  import { main as owner } from '../modules/deploy-kit/owner-cli.mjs';
4
3
  import { hookState } from './deploy-hook-record.mjs';
5
4
  import { savedSetupAnswers } from './setup-answers.mjs';
6
- import { validateRerConfig } from '../modules/mail/src/adapters/rer/contract.mjs';
5
+ import { productionMail } from './production-mail.mjs';
7
6
 
8
7
  // Validate the shared email/identity contract using the bindings that will reach
9
8
  // the runtime. Independently authored authentication remains the adapter's job.
@@ -11,26 +10,14 @@ export async function requireProductionAuth({ root, declaration, env, setupManif
11
10
  const dependencies = setupManifest?.dependencies?.filter(item => item.interface === 'oidc-provider@1') ?? [];
12
11
  const bindings = { ...declaration.vars };
13
12
  for (const secret of declaration.secrets ?? []) if (env[secret.environment]?.trim()) bindings[secret.binding] = env[secret.environment];
14
- if (!setupManifest?.steps?.some(step => step.type === 'owner-claim') && !dependencies.length && !('MAIL_PROVIDER' in bindings) && !declaration.secrets?.some(item => item.binding === 'MAIL_API_KEY')) return;
15
- const provider = bindings.MAIL_PROVIDER;
16
- let mailSelected = ['resend', 'sendgrid', 'cloudflare', 'rer'].includes(provider) && mailbox(bindings.MAIL_FROM);
17
- let relaySelected = true;
18
- if (provider === 'rer') {
19
- try { validateRerConfig({ relayUrl: bindings.MAIL_RELAY_URL }); } catch { relaySelected = false; mailSelected = false; }
20
- }
21
- // Secrets arrive under the seed's declared runtime binding, which need not
22
- // be the shared facade's MAIL_API_KEY (for example native SendGrid auth).
23
- const credentialKeys = ['MAIL_API_KEY', ...(provider === 'sendgrid' ? ['SENDGRID_API_KEY'] : [])];
24
- const declaredCredentials = credentialKeys.filter(key => declaration.secrets?.some(item => item.binding === key));
25
- const required = provider === 'cloudflare' ? ['MAIL_ACCOUNT_ID'] : [];
26
- const hasMailSecrets = live => credentialKeys.some(key => bindings[key]?.trim() || live.includes(key))
27
- && required.every(key => bindings[key]?.trim() || live.includes(key));
28
- if (mailSelected && hasMailSecrets([])) return;
29
- if (mailSelected && !options.dryRun && declarationPath) {
13
+ const mail = await productionMail(root, declaration, env);
14
+ if (!setupManifest?.steps?.some(step => step.type === 'owner-claim') && !dependencies.length && !mail.declared) return;
15
+ if (mail.configured()) return;
16
+ if (mail.canInspect && !options.dryRun && declarationPath) {
30
17
  try {
31
18
  const state = await hookState(root, options.environment ?? 'production');
32
19
  const existing = await owner(['inspect', '--declaration', declarationPath, '--environment', options.environment ?? 'production', ...(state ? ['--state', state] : [])], env, { cwd: root, localOnlyKeys: adapter?.localOnlyKeys });
33
- if (hasMailSecrets(existing.liveSecrets)) return;
20
+ if (mail.configured(existing.liveSecrets)) return;
34
21
  } catch (error) {
35
22
  if (!['missing-owner-receipt', 'missing-input'].includes(error.message)) throw refuse(`Production sign-in could not verify the existing deployment and its mail secrets${/^[a-z][a-z0-9-]{0,80}$/.test(error.message)?` (${error.message})`:''}. Restore provider access and the owned deployment record before retrying.`);
36
23
  }
@@ -41,12 +28,5 @@ export async function requireProductionAuth({ root, declaration, env, setupManif
41
28
  if (dependencies.some(item => {
42
29
  try { const value = answers?.[item.address] ?? bindings[item.address], issuer = new URL(value); return issuer.protocol === 'https:' && issuer.origin === value && !issuer.username && !issuer.password; } catch { return false; }
43
30
  })) return;
44
- const missing = [
45
- ...(!['resend', 'sendgrid', 'cloudflare', 'rer'].includes(provider) ? ['MAIL_PROVIDER (resend, sendgrid, cloudflare or rer)'] : []),
46
- ...(!mailbox(bindings.MAIL_FROM) ? ['MAIL_FROM'] : []),
47
- ...(!credentialKeys.some(key => bindings[key]?.trim()) ? [declaredCredentials.join(' or ') || credentialKeys.join(' or ')] : []),
48
- ...required.filter(key => !bindings[key]?.trim()),
49
- ...(!relaySelected ? ['MAIL_RELAY_URL (assigned HTTPS relay URL)'] : []),
50
- ];
51
- throw refuse(`Production sign-in is not configured. Configure outbound email; missing or invalid: ${missing.join(', ')}. Or select and approve an Auth SSO install through the declared oidc-provider@1 setup dependency. Local dev and demo use automatic RER_OPEN sign-in. Nothing was built or uploaded.`);
31
+ throw refuse(`Production sign-in is not configured. Configure outbound email; missing or invalid: ${mail.missing}. Or select and approve an Auth SSO install through the declared oidc-provider@1 setup dependency. Local dev and demo use automatic RER_OPEN sign-in. Nothing was built or uploaded.`);
52
32
  }
@@ -0,0 +1,72 @@
1
+ import { readFile } from 'node:fs/promises';
2
+ import { contained } from './project.mjs';
3
+ import { refuse } from './errors.mjs';
4
+ import { mailbox } from './parse.mjs';
5
+ import { deliveryDeclarationSources } from './delivery-declarations.mjs';
6
+ import { validateRerConfig } from '../modules/mail/src/adapters/rer/contract.mjs';
7
+
8
+ const providers = ['resend', 'sendgrid', 'cloudflare', 'rer'];
9
+ const nativeCredential = { sendgrid: 'SENDGRID_API_KEY', resend: 'RESEND_API_KEY' };
10
+ const present = value => typeof value === 'string' && Boolean(value.trim());
11
+
12
+ // Packaging can declare inputs that a product's deploy adapter adds to the
13
+ // root declaration later. Read that source contract, never arbitrary ambient
14
+ // keys or the adapter's executable source, before any build or provider write.
15
+ export async function productionMail(root, declaration, env) {
16
+ const bindings = { ...declaration.vars }, secrets = new Set(), publicInputs = new Set(), declaredProviders = new Set();
17
+ for (const secret of declaration.secrets ?? []) {
18
+ secrets.add(secret.binding);
19
+ if (present(env[secret.environment])) bindings[secret.binding] = env[secret.environment];
20
+ }
21
+ for (const [path, select] of deliveryDeclarationSources) {
22
+ let text;
23
+ try { text = await readFile(await contained(root, path, { optional: true }), 'utf8'); }
24
+ catch (error) { if (error.code === 'ENOENT') continue; throw error; }
25
+ let spec;
26
+ try { spec = select(JSON.parse(text)); }
27
+ catch { throw refuse(`Restore a valid mail deployment declaration at ${path}. Nothing was built or uploaded.`); }
28
+ if (!spec) continue;
29
+ for (const name of spec.publicVariableNames ?? []) publicInputs.add(name);
30
+ for (const [name, value] of Object.entries(spec.publicVariables ?? {})) {
31
+ if (!(name in bindings) || name === 'MAIL_PROVIDER' && bindings[name] === 'later') bindings[name] = value;
32
+ }
33
+ for (const name of [...(spec.secretNames ?? []), ...(spec.optionalSecretNames ?? [])]) {
34
+ secrets.add(name);
35
+ // A root secret's explicit environment-to-binding mapping wins.
36
+ if (!declaration.secrets?.some(secret => secret.binding === name) && present(env[name])) bindings[name] = env[name];
37
+ }
38
+ for (const provider of spec.mail?.providers ?? []) if (providers.includes(provider)) declaredProviders.add(provider);
39
+ }
40
+ for (const name of publicInputs) if (present(env[name])) bindings[name] = env[name];
41
+ const provider = bindings.MAIL_PROVIDER;
42
+ const deferred = !provider || provider === 'later';
43
+ const choices = new Set(declaredProviders);
44
+ if (deferred) for (const [name, key] of Object.entries(nativeCredential)) if (secrets.has(key)) choices.add(name);
45
+ const selected = deferred ? [...choices] : providers.includes(provider) ? [provider] : [];
46
+ const routes = selected.map(provider => {
47
+ const credentialKeys = deferred && nativeCredential[provider] && !declaredProviders.has(provider) ? [nativeCredential[provider]]
48
+ : ['MAIL_API_KEY', ...(nativeCredential[provider] ? [nativeCredential[provider]] : [])];
49
+ const declaredCredentials = credentialKeys.filter(key => secrets.has(key));
50
+ return live => {
51
+ let relaySelected = true;
52
+ if (provider === 'rer') try { validateRerConfig({ relayUrl: bindings.MAIL_RELAY_URL }); } catch { relaySelected = false; }
53
+ const has = key => present(bindings[key]) || secrets.has(key) && live.includes(key);
54
+ return [
55
+ ...(!mailbox(bindings.MAIL_FROM) ? ['MAIL_FROM'] : []),
56
+ ...(!credentialKeys.some(has) ? [declaredCredentials.join(' or ') || credentialKeys.join(' or ')] : []),
57
+ ...(provider === 'cloudflare' && !has('MAIL_ACCOUNT_ID') ? ['MAIL_ACCOUNT_ID'] : []),
58
+ ...(!relaySelected ? ['MAIL_RELAY_URL (assigned HTTPS relay URL)'] : []),
59
+ ];
60
+ };
61
+ });
62
+ return {
63
+ declared: 'MAIL_PROVIDER' in bindings || publicInputs.has('MAIL_PROVIDER') || secrets.has('MAIL_API_KEY') || selected.length > 0,
64
+ configured: (live = []) => routes.some(missing => missing(live).length === 0),
65
+ canInspect: mailbox(bindings.MAIL_FROM) && routes.length > 0,
66
+ missing: routes.length ? routes.map(missing => missing([]).join(', ')).join(' or ') : [
67
+ 'MAIL_PROVIDER (resend, sendgrid, cloudflare or rer)',
68
+ ...(!mailbox(bindings.MAIL_FROM) ? ['MAIL_FROM'] : []),
69
+ 'MAIL_API_KEY',
70
+ ].join(', '),
71
+ };
72
+ }
package/cli/signin.mjs CHANGED
@@ -1,7 +1,7 @@
1
1
  import { declarationFor } from './deploy-command.mjs';
2
2
  import { deployEnvironment, deployAgain } from './deploy-inputs.mjs';
3
- import { hookState } from './deploy-hook-record.mjs';
4
- import { missing, refuse, RerError } from './errors.mjs';
3
+ import { deploymentRecord } from './deployment-record.mjs';
4
+ import { invalid, missing, refuse, RerError } from './errors.mjs';
5
5
  import { shared } from './shared.mjs';
6
6
  import { main as owner } from '../modules/deploy-kit/owner-cli.mjs';
7
7
  import { deployDiagnostic, providerRefusal } from '../modules/deploy-kit/diagnostics.mjs';
@@ -15,25 +15,30 @@ export async function signinCommand(project, options, out, { fetch } = {}) {
15
15
  if (project.profile !== 'first-party' || typeof project.adapter?.deploy !== 'function') throw refuse('rer signin needs a seed with an owner-account deploy declaration.');
16
16
  const root = project.root, environment = options.environment ?? 'production', again = deployAgain(options).replace(/^rer deploy/, 'rer signin');
17
17
  const { path, value: declaration } = await declarationFor(root, project.adapter);
18
+ const state = await deploymentRecord(root, { ...options, verb: 'signin' });
18
19
  const { env } = await deployEnvironment({ root, options, declaration, localOnlyKeys: project.adapter.localOnlyKeys ?? [] });
19
20
  if (['CLOUDFLARE_ACCOUNT_ID', 'CLOUDFLARE_API_TOKEN'].some(name => !env[name]?.trim())) throw missing('rer signin uses the Cloudflare credentials that deployed this environment: set CLOUDFLARE_ACCOUNT_ID and CLOUDFLARE_API_TOKEN in the environment or an --env-file, then run it again.');
20
21
  const { createRedaction, credentialValues } = await shared('redaction.mjs');
21
22
  const redaction = createRedaction();
22
23
  redaction.addSecrets([...credentialValues(env), env.CLOUDFLARE_ACCOUNT_ID]);
23
- const state = await hookState(root, environment);
24
24
  let result;
25
25
  try { result = await owner(['signin', '--declaration', path, '--environment', environment, ...(state ? ['--state', state] : [])], env, { cwd: root, localOnlyKeys: project.adapter.localOnlyKeys ?? [], ...(fetch ? { fetch } : {}) }); }
26
- catch (error) { throw failure(error, { environment, again, redact: redaction.redact }); }
26
+ catch (error) { throw failure(error, { environment, again, adapter: project.adapter, redact: redaction.redact }); }
27
27
  const minutes = Math.round((result.expiresAt - Date.now()) / 60000);
28
28
  if (!options.json) out.human(`One-time sign-in link for the owner ${result.email}. It works once, only for that owner, and expires in ${minutes} minutes. rer does not save it; open it now:\n${result.link}`);
29
29
  return { owner: result.email, expiresAt: result.expiresAt, ...(options.json ? { link: result.link } : {}) };
30
30
  }
31
31
 
32
- function failure(error, { environment, again, redact }) {
32
+ function failure(error, { environment, again, adapter, redact }) {
33
33
  const code = deployDiagnostic(error, redact)?.code ?? error.message;
34
34
  if (code === 'missing-owner-receipt') return refuse(`This checkout has no completed rer deployment of the ${environment} environment. Run rer signin from the checkout that deployed it (rer deploy --environment ${environment}).`);
35
35
  if (code === 'owned-resource-replaced') return refuse(`The ${environment} Worker is no longer the one this checkout deployed, so rer will not sign anyone in to it. Run rer deploy --environment ${environment} first.`);
36
- if (code === 'owner-signin-unsupported') return refuse(`The ${environment} deployment's database has no owner sign-in table. Update the seed to a rer that includes operator-auth's accounts/schema/owner-signin.sql migration, run rer deploy --environment ${environment}, then ${again}.`);
36
+ if (code === 'owner-signin-unsupported') {
37
+ const path = adapter.signInPath;
38
+ if (path !== undefined && (typeof path !== 'string' || path.length > 2048 || !path.startsWith('/') || path.startsWith('//') || /[\\\s\u0000-\u001f\u007f-\u009f]/u.test(path))) return invalid('The adapter signInPath must be a same-origin browser path such as /login. Correct the seed declaration, then run rer signin again.');
39
+ const destination = new URL(path ?? '/setup', error.origin).href;
40
+ return refuse(redact(`The ${environment} deployment signs owners in through the seed's own sign-in flow. ${path ? `Open ${destination} to sign in.` : `Open ${destination} for the seed's owner recovery.`} rer signin cannot issue a link for this seed.`));
41
+ }
37
42
  if (code === 'owner-signin-ambiguous') return refuse(`More than one D1 database of the ${environment} deployment holds an owner sign-in table, so rer cannot tell which one signs in the owner. Nothing was written.`);
38
43
  if (code === 'owner-not-claimed') return refuse(`No owner has claimed the ${environment} deployment yet. Run rer deploy --environment ${environment}: it claims the owner. Nothing was written.`);
39
44
  const refusal = providerRefusal(error, redact);
package/cli/site.mjs CHANGED
@@ -113,7 +113,7 @@ export async function siteCommand(project, options, store, signal, out) {
113
113
  if (!options.json) for (const line of human) out.human(line);
114
114
  const { cloudflare } = await import('../modules/deploy-kit/provider.mjs');
115
115
  const { collectFiles } = await import('../modules/deploy-kit/artifact.mjs');
116
- const { siteDeploy } = await import('../modules/deploy-kit/site.mjs');
116
+ const { siteDeploy, siteReadbackSummary } = await import('../modules/deploy-kit/site.mjs');
117
117
  const environment = options.environment ?? 'production';
118
118
  try {
119
119
  const api = cloudflare({ accountId: process.env.CLOUDFLARE_ACCOUNT_ID, token: process.env.CLOUDFLARE_API_TOKEN });
@@ -122,7 +122,7 @@ export async function siteCommand(project, options, store, signal, out) {
122
122
  return { dryRun: false, deployed: true, origin: result.origin, site: summary };
123
123
  } catch (error) {
124
124
  if (error instanceof RerError) throw error;
125
- throw new RerError('deploy_refused', `Run site deploy stopped: ${/^[a-z0-9-]{1,80}$/.test(error.message) ? error.message : 'site-deploy-failed'}${error.resource ? ` (${error.resource})` : ''}.`, 1);
125
+ throw new RerError('deploy_refused', `Run site deploy stopped: ${/^[a-z0-9-]{1,80}$/.test(error.message) ? error.message : 'site-deploy-failed'}${error.resource ? ` (${error.resource})` : ''}.${siteReadbackSummary(error)}`, 1);
126
126
  }
127
127
  }
128
128