@runeditrun/rer 0.2.57 → 0.2.58

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.
package/cli/contract.mjs CHANGED
@@ -11,7 +11,7 @@ const definitions = {
11
11
  build: [['--site'], 'Production build with private local settings excluded and restored. --site instead writes the static run site (homepage, /run, docs) to its declared folder and prints that folder.'],
12
12
  verify: [[], 'Run the complete internal verification target.'],
13
13
  reset: [['--yes'], 'Confirmed removal of the declared local inventory only.'],
14
- deploy: [['--owner-name', '--environment', '--dry-run', '--site', '--demo', '--host', '--env-file', '--image', '--bind-address', '--http-port', '--https-port', '--remove', '--yes', '--set-secret', '--unset-secret', '--rotate-secret'], 'Owner-account deployment and health; dry run performs local validation/build only. Builds and deploy hooks run with the checkout\'s local settings files moved aside, and a build output holding one (.dev.vars, .env) is refused. Declared secrets come from the environment or --env-file (an owned 0600 KEY=VALUE file); a new Worker gets the local setup owner and fresh generated secrets when they are not given. rer keeps the secrets it generates in .rer/deploy/ENVIRONMENT.secrets.env (0600) and reuses them on every redeploy; it refuses to generate a replacement for one a live Worker holds, and --rotate-secret NAME[,NAME] replaces them on purpose. After a healthy deploy rer claims the setup owner on the hosted app with the saved setup owner name and the one-time setup token, then removes the token. If the installer declares an owner-name field and no name is saved, deploy asks once and saves it; --non-interactive requires --owner-name NAME before any upload. --set-secret NAME[,NAME] (each value from the environment or --env-file; repeat the flag or join names with commas) and --unset-secret NAME[,NAME] change those secrets of the deployed Worker without a build, all of them in one new Worker version or none, and record that version; a missing value refuses before any change. --remove --yes deletes what this environment\'s deploy record says rer created (Worker, D1, R2, KV, queues), reads back that each is gone, and touches nothing else. --site deploys the run site instead: an assets-only Worker on its custom domain with www redirected; with --dry-run it builds the site and prints the plan with no provider request. --demo deploys the hosted demo instead (deploy-demo.json): a front Worker on demo.<domain> giving each visitor their own signed-in, throwaway native Worker isolate of this seed with real public reads/checks and simulated external writes; --dry-run writes it to .rer/demo-host with no provider request; --demo --remove --yes deletes that demo (its Worker, demo.<domain> Custom Domain, each only while the record its deploy left proves it the demo\'s), reads back that each is gone, and is a no-op once it is.'],
14
+ deploy: [['--owner-name', '--environment', '--dry-run', '--site', '--demo', '--host', '--env-file', '--image', '--bind-address', '--http-port', '--https-port', '--remove', '--yes', '--set-secret', '--unset-secret', '--rotate-secret'], 'Owner-account deployment and health; dry run validates/builds locally and reads target secret bindings with Cloudflare credentials, without provider writes. Missing required secrets fail as in deploy; missing credentials or unreadable target secrets also fail. Builds and deploy hooks run with the checkout\'s local settings files moved aside, and a build output holding one (.dev.vars, .env) is refused. Declared secrets come from the environment or --env-file (an owned 0600 KEY=VALUE file); a new Worker gets the local setup owner and fresh generated secrets when they are not given. rer keeps the secrets it generates in .rer/deploy/ENVIRONMENT.secrets.env (0600) and reuses them on every redeploy; it refuses to generate a replacement for one a live Worker holds, and --rotate-secret NAME[,NAME] replaces them on purpose. After a healthy deploy rer claims the setup owner on the hosted app with the saved setup owner name and the one-time setup token, then removes the token. If the installer declares an owner-name field and no name is saved, deploy asks once and saves it; --non-interactive requires --owner-name NAME before any upload. --set-secret NAME[,NAME] (each value from the environment or --env-file; repeat the flag or join names with commas) and --unset-secret NAME[,NAME] change those secrets of the deployed Worker without a build, all of them in one new Worker version or none, and record that version; a missing value refuses before any change. --remove --yes deletes what this environment\'s deploy record says rer created (Worker, D1, R2, KV, queues), reads back that each is gone, and touches nothing else. --site deploys the run site instead: an assets-only Worker on its custom domain with www redirected; with --dry-run it builds the site and prints the plan with no provider request. --demo deploys the hosted demo instead (deploy-demo.json): a front Worker on demo.<domain> giving each visitor their own signed-in, throwaway native Worker isolate of this seed with real public reads/checks and simulated external writes; --dry-run writes it to .rer/demo-host with no provider request; --demo --remove --yes deletes that demo (its Worker, demo.<domain> Custom Domain, each only while the record its deploy left proves it the demo\'s), reads back that each is gone, and is a no-op once it is.'],
15
15
  export: [['--target', '--output', '--origin', '--session-file'], 'Complete supported archive of the local copy on this computer, with integrity and exclusions, written to --output. The hosted install cannot be exported yet: --origin or --target remote refuses (exit 2) before any effect and names the command that saves the hosted database.'],
16
16
  import: [['--target', '--input', '--journal', '--origin', '--session-file', '--yes', '--legacy-v1', '--acknowledge-unverified-metadata', '--output'], 'Confirmed atomic restore into an empty destination; --journal LATER_ARCHIVE also fences rows that installation erased since. Backup-only local v1 recovery requires --legacy-v1 --acknowledge-unverified-metadata and a new --output v2 archive; --journal requires normal v2 import.'],
17
17
  doctor: [[], 'Read-only installed tool, configuration and state diagnostics.'],
@@ -4,6 +4,7 @@ import { readFile, readdir } from 'node:fs/promises';
4
4
  import { contained } from './project.mjs';
5
5
  import { invalid, refuse, RerError } from './errors.mjs';
6
6
  import { ownerDeploy } from './deploy.mjs';
7
+ import { secretFailureMessage } from './deploy-secret-error.mjs';
7
8
  import { deployEnvironment, deployAgain } from './deploy-inputs.mjs';
8
9
  import { claimHostedOwner } from './deploy-owner.mjs';
9
10
  import { deployOwnerInput } from './deploy-owner-input.mjs';
@@ -78,11 +79,11 @@ export async function deployCommand(context) {
78
79
  if (local) throw refuse(`${path} names the local-only key ${local} as a deploy binding or secret. Remove it; local dev keys never reach a deployment.`);
79
80
  deployGuide(declaration);
80
81
  const settings = adapter.hooks?.secrets ?? adapter.settings;
81
- // What a dry run went ahead without, listed when it completes.
82
+ // Required secrets have been checked; retain the production sign-in guidance.
82
83
  const dryRun = async result => {
83
84
  const production = await deployEnvironment({ root, options, declaration, setupManifest, settings, localOnlyKeys });
84
85
  const { signIn } = await requireProductionAuth({ root, declaration, env: production.env, setupManifest, setupSeed: context.setupSeed, adapter, declarationPath: path, options }) ?? {};
85
- const needed = neededForRealDeploy({ declaration, env: production.env, signIn });
86
+ const needed = neededForRealDeploy({ declaration, env: production.env, signIn, secretsChecked: true });
86
87
  reportNeeded(store, needed);
87
88
  return needed.length && result && typeof result === 'object' ? { ...result, neededForRealDeploy: needed } : result;
88
89
  };
@@ -134,7 +135,10 @@ export async function deployCommand(context) {
134
135
  }
135
136
  hookReturned = true;
136
137
  await refuseLocalEnvOutput(root, adapter.devIdentity?.output, { uploaded: !options.dryRun });
137
- if (options.dryRun) return dryRun(deployed);
138
+ if (options.dryRun) {
139
+ await command('dry-run');
140
+ return dryRun(deployed);
141
+ }
138
142
  await rememberHookState(root, environment, deployed?.state);
139
143
  hookRecord = await hookState(root, environment);
140
144
  const origin = hookOrigin(deployed, deployAgain(options));
@@ -163,6 +167,9 @@ export async function deployCommand(context) {
163
167
  } catch (error) {
164
168
  const again = deployAgain(options);
165
169
  const { commandFailure } = await shared('failures.mjs');
170
+ const secrets = secretFailureMessage(error);
171
+ if (secrets) throw commandFailure(secrets);
172
+ if (options.dryRun && error.message === 'missing-input') throw new RerError('missing_input', `Dry run cannot read the target secret bindings without ${error.inputs.join(' and ')}. Set the Cloudflare credentials in the environment or an owned 0600 --env-file, then run the same command again.`, 3);
166
173
  if (error.hookFailure) throw commandFailure(store.redact?.(redaction.redact(error.message)) ?? redaction.redact(error.message));
167
174
  if (error instanceof RerError && !deployed?.deployed && !recorded) { error.message = store.redact?.(redaction.redact(error.message)) ?? redaction.redact(error.message); throw error; }
168
175
  const outcome = error.owner ?? claimed ?? observedClaims.at(-1)?.outcome;
@@ -29,22 +29,24 @@ function credentialHelp(declaration) {
29
29
  return [`Create an account API token at ${tokenPage} with these account permissions: ${needed.join(', ')}. Copy your account ID from the Cloudflare dashboard.`];
30
30
  }
31
31
 
32
- export function missingCredentialsMessage(declaration, env) {
32
+ export function missingCredentialsMessage(declaration, env, { dryRun = false, signIn } = {}) {
33
33
  const absent = cloudflareCredentials.filter(name => !env[name]?.trim());
34
- return [`${absent.join(' and ')} ${absent.length > 1 ? 'are' : 'is'} required to deploy to your Cloudflare account. Nothing was deployed.`,
34
+ return [...(dryRun ? ['Dry run cannot read the target secret bindings without Cloudflare credentials.'] : []),
35
+ `${absent.join(' and ')} ${absent.length > 1 ? 'are' : 'is'} required to deploy to your Cloudflare account. Nothing was deployed.`,
35
36
  ...credentialHelp(declaration),
36
- 'Set them in your environment or an owned 0600 --env-file, then run the same deploy command again.'].join('\n');
37
+ 'Set them in your environment or an owned 0600 --env-file, then run the same deploy command again.',
38
+ ...(dryRun ? ['Needed for a real deploy (the dry run could not check the target):', ...neededForRealDeploy({declaration,env,signIn}).map(item => ` - ${item}`)] : [])].join('\n');
37
39
  }
38
40
 
39
- // What a dry run went ahead without: the Cloudflare values, each required
40
- // declared secret not supplied, and production sign-in's missing mail inputs.
41
- export function neededForRealDeploy({ declaration, env, signIn }) {
41
+ // Setup guidance and failed dry-run inputs. After target resolution, held
42
+ // secrets no longer count as missing local inputs.
43
+ export function neededForRealDeploy({ declaration, env, signIn, secretsChecked = false }) {
42
44
  const declared = (Array.isArray(declaration.secrets) ? declaration.secrets : []).filter(item => item?.environment);
43
45
  // Sign-in names its inputs by binding; a person sets the environment name the declaration maps to it.
44
46
  const mail = signIn && declared.reduce((text, item) => item.binding === item.environment ? text : text.replace(new RegExp(`\\b${item.binding}\\b`, 'g'), item.environment), signIn);
45
47
  const listed = name => cloudflareCredentials.includes(name) || mail && new RegExp(`\\b${name}\\b`).test(mail);
46
- const secrets = [...new Set(declared.filter(item => !item.optional && !env[item.environment]?.trim()).map(item => item.environment))].filter(name => !listed(name));
47
- const credentials = cloudflareCredentials.filter(name => !env[name]?.trim());
48
+ const secrets = secretsChecked ? [] : [...new Set(declared.filter(item => !item.optional && !env[item.environment]?.trim()).map(item => item.environment))].filter(name => !listed(name));
49
+ const credentials = secretsChecked ? [] : cloudflareCredentials.filter(name => !env[name]?.trim());
48
50
  return [
49
51
  ...(credentials.length ? [`${credentials.join(' and ')} (${credentialHelp(declaration).join(' ')})`] : []),
50
52
  ...secrets,
@@ -0,0 +1,8 @@
1
+ // Both deploy paths render the shared resolver's complete missing-input list.
2
+ export function secretFailureMessage(error) {
3
+ if (error.message === 'token-scope-missing-workers') return `Cannot read the target's secret list; required secret bindings could not be checked. The Cloudflare token needs Workers Scripts permission (${error.message}). Nothing was uploaded.`;
4
+ const first = /^missing-secret-([A-Z][A-Z0-9_]*)$/.exec(error.message)?.[1];
5
+ if (!first) return;
6
+ const names = error.missingSecrets?.map(({binding,environment}) => binding === environment ? binding : `${binding} (${environment})`) ?? [first];
7
+ return `Deploy needs ${names.join(', ')}, which the deploy declaration lists as ${names.length === 1 ? 'a secret' : 'secrets'} and the Worker does not hold. Set ${names.length === 1 ? 'its value' : 'their values'} in the named environment inputs or in an --env-file file (an owned 0600 file of KEY=VALUE lines), then run the same command again. Nothing was uploaded.`;
8
+ }
package/cli/deploy.mjs CHANGED
@@ -5,8 +5,8 @@ import { shared } from './shared.mjs';
5
5
  import { settingKinds } from './deploy-settings.mjs';
6
6
  import { contained } from './project.mjs';
7
7
  import { missing, invalid, refuse, RerError } from './errors.mjs';
8
- import { ownerPlan, ownerWorkerName, localOnlyBinding } from '../modules/deploy-kit/owner.mjs';
9
- import { packageBuild } from '../modules/deploy-kit/prepare.mjs';
8
+ import { localOnlyBinding } from '../modules/deploy-kit/owner.mjs';
9
+ import { secretFailureMessage } from './deploy-secret-error.mjs';
10
10
  import { refuseLocalModels } from '../modules/deploy-kit/local-only.mjs';
11
11
  import { deployEnvironment, deployAgain } from './deploy-inputs.mjs';
12
12
  import { claimHostedOwner } from './deploy-owner.mjs';
@@ -38,31 +38,20 @@ export function ownerDeploy(declarationPath, lifecycle) {
38
38
  const recordedState = change.length ? await deploymentRecord(root, options) : undefined;
39
39
  // A dry run reads the settings file too, so a refused key fails here and not only on the real deploy.
40
40
  if (options.dryRun && options.envFile) await deployEnvironment({ root, options, declaration, localOnlyKeys });
41
- let production, ownerInput;
41
+ let production, ownerInput, signIn;
42
42
  if (!change.length) {
43
43
  production = await deployEnvironment({ root, options, declaration, setupManifest, settings: lifecycle.settings, localOnlyKeys });
44
- await requireProductionAuth({ root, declaration, env: production.env, setupManifest, setupSeed, adapter: lifecycle, declarationPath, options });
44
+ ({signIn} = await requireProductionAuth({ root, declaration, env: production.env, setupManifest, setupSeed, adapter: lifecycle, declarationPath, options }) ?? {});
45
45
  if (!options.dryRun) committedSource(root, options);
46
46
  ownerInput = await deployOwnerInput({ root, adapter, setupSeed, options, signal });
47
47
  await withoutLocalSettings(root, { settings: lifecycle.settings, operationToken }, () => lifecycle.run(root, {}, store, () => {}, signal, { verb: 'build', operationToken }));
48
48
  await checkBuild();
49
49
  await refuseLocalEnvOutput(root);
50
50
  }
51
- if (options.dryRun) {
52
- // Locally validate the real declaration/artifact without ownerTarget's
53
- // account lookup. This synthetic target is validation data, not a provider.
54
- const worker = ownerWorkerName(declaration.project, environment);
55
- const artifact = await packageBuild({ root, source: { sha: '0'.repeat(40), tree: '0'.repeat(40) }, runIdentity: { id: '0', attempt: '1' }, productDirectory: '' });
56
- ownerPlan({ project: declaration.project, environment, worker, origin: `https://${worker}.example.invalid` }, declaration, artifact, { localOnlyKeys, env: production.env });
57
- const optional = (Array.isArray(declaration.secrets) ? declaration.secrets : []).filter(item => item?.optional && !production.env[item.environment]?.trim()).map(item => item.binding);
58
- if (optional.length) store.report(`deploy: optional secrets not supplied: ${optional.join(', ')}. A Worker that does not hold one deploys without it.`);
59
- store.report('deploy: dry run complete; no deployment occurred and no provider request was made.');
60
- return { dryRun: true, deployed: false };
61
- }
62
51
  const { env, supplied, generated, reused, rotated } = await deployEnvironment({ root, options, declaration, setupManifest, settings: lifecycle.settings, localOnlyKeys });
63
52
  if (options.setSecret || options.unsetSecret) secretChangeInputs(declaration, options, env, again);
64
53
  const kept = keptSecrets(declaration, setupManifest);
65
- if (cloudflareCredentials.some(name => !env[name]?.trim())) throw missing(missingCredentialsMessage(declaration, env));
54
+ if (cloudflareCredentials.some(name => !env[name]?.trim())) throw missing(missingCredentialsMessage(declaration, env, {dryRun:options.dryRun,signIn}));
66
55
  const { main } = await import('../modules/deploy-kit/owner-cli.mjs');
67
56
  const { createRedaction } = await shared('redaction.mjs');
68
57
  const redaction = createRedaction();
@@ -74,6 +63,12 @@ export function ownerDeploy(declarationPath, lifecycle) {
74
63
  const created = [];
75
64
  let step = 'deploy', deployed;
76
65
  try {
66
+ if (options.dryRun) {
67
+ const {optionalUnset} = await owner('dry-run');
68
+ if (optionalUnset.length) store.report(`deploy: optional secrets not supplied: ${optionalUnset.join(', ')}. A Worker that does not hold one deploys without it.`);
69
+ store.report('deploy: dry run complete; target secret bindings checked; no deployment occurred.');
70
+ return { dryRun: true, deployed: false };
71
+ }
77
72
  // A custom hook's own state file, when its deploy named one.
78
73
  const state = change.length ? recordedState : await hookState(root, environment);
79
74
  if (options.remove) {
@@ -164,8 +159,8 @@ function failureText({ error, step, created, again, retry, secretChange, deploye
164
159
  const diagnostic = deployDiagnostic(error, redact);
165
160
  const code = diagnostic?.code ?? (/^[a-zA-Z0-9_-]{1,120}$/.test(error.message) ? redact(error.message) : 'deploy-failed');
166
161
  const at = step === 'deploy' ? diagnostic?.step ?? 'prepare deploy' : step;
167
- const input = /^missing-secret-([A-Z][A-Z0-9_]*)$/.exec(code)?.[1];
168
- 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(', ')}.` : ''}`;
162
+ const secrets = secretFailureMessage(error);
163
+ if (secrets) return secrets;
169
164
  if (code === 'nothing-to-remove') return `The deployment record selected by ${again} has no resources that rer owns, so --remove deletes nothing.`;
170
165
  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.`;
171
166
  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.`;
@@ -1,5 +1,9 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.2.58
4
+
5
+ - **Deploy dry runs validate required target secrets.** `rer deploy --dry-run` uses the real deploy secret-binding resolver and refuses with the same exit and message when required bindings are missing. It names every missing binding and its environment input, accepts secrets already held by the Worker, and makes no target writes. Missing credentials or read permission also refuse (#275).
6
+
3
7
  ## 0.2.57
4
8
 
5
9
  - **Large release scans finish within the publication budget.** The JSON identity pass tracks UTF-8 byte offsets incrementally. Orbit's scan finishes in 79 seconds instead of exceeding the 300-second deadline, with identical findings (#270).
@@ -115,6 +115,8 @@ A transport failure carries `providerTransport`: the operation, sanitized endpoi
115
115
 
116
116
  `rer deploy` runs these steps for a seed whose adapter uses `ownerDeploy` from `cli/deploy.mjs`.
117
117
 
118
+ - **Dry run.** Application `rer deploy --dry-run` builds and validates locally, then calls `owner-cli.mjs dry-run` to read the selected target and resolve required secrets with the same `secretBindings` function as deploy. All missing required bindings and their environment names are reported together, with identical nonzero exit and error in human and JSON output. Held secrets are inherited, supplied values are accepted without upload, absent optional secrets stay unset, and recorded retired secrets stay retired. Cloudflare credentials are required; a failed secret-list read fails the command. Dry run does not settle pending secret changes, write deployment state, upload, change secrets or create resources. An unsettled secret change must be completed by its original command first.
119
+
118
120
  - **Inputs.** Declared secrets come from the environment, then `--env-file FILE` (an owned 0600 file of `KEY=VALUE` lines), which wins. For a secret the Worker does not hold yet, rer supplies the setup manifest's owner email (`emailField`) from the local setup's private settings, and for each secret field the manifest generates (`generate`) the value rer keeps for this environment in `.rer/deploy/<environment>.secrets.env` (0600, ignored by Git), else a fresh random value, which rer keeps once the Worker holds it (the one-time setup token is always fresh and never kept); a value the Worker already holds is kept. The build runs with the checkout's local settings files moved aside, and a `dist/` holding a `.dev.vars*`, `.env*` or `*.env` file is refused by name before any provider request. A still-missing secret stops the run before any write with a message that names it, unless its declaration says `"optional": true`: then the deploy binds nothing for it and reports it as not set, and `--set-secret` adds it later.
119
121
  - **Hosted owner.** After deploy and health pass, rer claims the setup owner on the hosted app: it POSTs the setup token to the seed's standard owner step (`hooks.owner`, by default `/auth/bootstrap`). 303 means claimed; `409 already_initialized` means an owner was already claimed and is kept. Then rer deletes the token secret from the Worker, records the new Worker version in the state file, and lists the token in `retiredSecrets`, so later plans no longer declare it. The build fingerprint still names it, and the recorded claim stays as recorded, so an untouched repeat deploy writes nothing. A Worker that still holds a token rer did not upload in this run (an older deploy) first gets a fresh token through the same recorded secret change. Dependency approvals that need the token run before the claim. A seed with an owner step function, an identity-provider claim, or no declared token secret claims its owner its own way.
120
122
  - **Several secrets at once.** `rer deploy --set-secret MAIL_API_KEY --set-secret MAIL_FROM` or `rer deploy --set-secret MAIL_API_KEY,MAIL_FROM` (likewise `--unset-secret A,B`) changes all of them in one new Worker version or none: a group of secrets is never half set. Every named secret must be declared and, for `--set-secret`, have its value in the environment or `--env-file`; otherwise rer names each missing one and changes nothing. One secret uses Cloudflare's secret call. Several are one copy of the live version through the Versions API (its own modules, assets and compatibility settings, every other binding inherited), then deployed at 100%: Cloudflare's per-secret calls each make a version, and its settings call can add secrets but not remove them (measured 17 October 2026). The copy carries a marker rer records first, so a copy whose answer was lost is recognised, and one uploaded but not deployed is deployed by the same command run again.
@@ -8,8 +8,8 @@ import { assert, hexId } from './validation.mjs';
8
8
  import { regularBytes } from './artifact.mjs';
9
9
  import { packageBuild } from './prepare.mjs';
10
10
  import { cloudflare } from './provider.mjs';
11
- import { ownerTarget, ownerWorkerName, ownerPlan, ownerDeploy, ownerHealth, settleOwnerState, sameDeployment, localOnlyBinding, withStateLock, readOwnerState, writeOwnerState } from './owner.mjs';
12
- import { activeWorker } from './worker.mjs';
11
+ import { ownerTarget, ownerWorkerName, ownerPlan, ownerDeploy, ownerHealth, settleOwnerState, sameDeployment, localOnlyBinding, withStateLock, readOwnerState, writeOwnerState, workerSettings, withScopeHints } from './owner.mjs';
12
+ import { activeWorker, secretBindings } from './worker.mjs';
13
13
  import { ownerSecret } from './owner-secret.mjs';
14
14
  import { ownerRemove } from './owner-remove.mjs';
15
15
  import { ownerSignin } from './owner-signin.mjs';
@@ -17,7 +17,7 @@ import { refuseLocalModels } from './local-only.mjs';
17
17
  import { publicOrigin } from './public-origin.mjs';
18
18
 
19
19
  export const cronNotice = 'This Worker has a Cron Trigger. Cloudflare may take up to about two hours to start its first scheduled run on some accounts.';
20
- const usage = 'usage: owner-cli.mjs deploy|health|remove|inspect|record-owner|signin --declaration <file> --environment <name> [--product <dir>] [--state <file>] [--outcome claimed|kept] | secret ... --set NAME [--set NAME]|--unset NAME [--unset NAME]';
20
+ const usage = 'usage: owner-cli.mjs deploy|dry-run|health|remove|inspect|record-owner|signin --declaration <file> --environment <name> [--product <dir>] [--state <file>] [--outcome claimed|kept] | secret ... --set NAME [--set NAME]|--unset NAME [--unset NAME]';
21
21
 
22
22
  /** The owner's committed source and existing local build. Run the seed's build first. */
23
23
  async function ownerArtifact(root, product) {
@@ -33,7 +33,7 @@ export async function main(argv = process.argv.slice(2), env = process.env, {fet
33
33
  try { parsed = parseArgs({args:argv,allowPositionals:true,strict:true,options:{declaration:{type:'string'},environment:{type:'string'},product:{type:'string',default:''},state:{type:'string'},set:{type:'string',multiple:true},unset:{type:'string',multiple:true},outcome:{type:'string'}}}); }
34
34
  catch { throw new Error('usage'); }
35
35
  const {positionals:[command,...rest],values} = parsed;
36
- if (!['deploy','health','secret','remove','inspect','record-owner','signin'].includes(command) || rest.length || !values.declaration || !values.environment) throw new Error('usage');
36
+ if (!['deploy','dry-run','health','secret','remove','inspect','record-owner','signin'].includes(command) || rest.length || !values.declaration || !values.environment) throw new Error('usage');
37
37
  if ((command === 'secret') !== (values.set !== undefined || values.unset !== undefined) || values.set !== undefined && values.unset !== undefined) throw new Error('usage');
38
38
  if (values.outcome !== undefined && command !== 'record-owner' || command === 'record-owner' && !['claimed','kept'].includes(values.outcome)) throw new Error('usage');
39
39
  await refuseLocalModels(resolve(cwd));
@@ -47,6 +47,12 @@ export async function main(argv = process.argv.slice(2), env = process.env, {fet
47
47
  assert(typeof declaration?.project === 'string','missing-owner-project');
48
48
  // Validate even direct kit invocations before any provider request or write.
49
49
  publicOrigin(declaration, env);
50
+ let artifact;
51
+ if (command === 'dry-run') {
52
+ artifact = await packageBuild({root,source:{sha:'0'.repeat(40),tree:'0'.repeat(40)},runIdentity:{id:'0',attempt:'1'},productDirectory:values.product});
53
+ const worker = ownerWorkerName(declaration.project,values.environment);
54
+ ownerPlan({project:declaration.project,environment:values.environment,worker,origin:`https://${worker}.example.invalid`},declaration,artifact,{localOnlyKeys,env});
55
+ }
50
56
  // Removal reads identity before each object DELETE and may span many pages.
51
57
  // Bound each response, not the owner's bucket size; failures retain ownership.
52
58
  let requestWindow = propagation?.uploaded ? propagation.window : undefined;
@@ -74,7 +80,9 @@ export async function main(argv = process.argv.slice(2), env = process.env, {fet
74
80
  return {ok:true,...await ownerSecret({api,target,statePath,changes,fetch,healthOptions}).catch(error => { throw api.annotateFailure(error,'secrets'); })};
75
81
  }
76
82
  // A secret rer retired (the spent setup token) is no longer part of the plan.
77
- const state = await settleOwnerState({api,target,statePath});
83
+ // A dry run only reads state: settling an interrupted change may write it.
84
+ const state = command === 'dry-run' ? await readOwnerState(statePath,target) : await settleOwnerState({api,target,statePath});
85
+ if (command === 'dry-run') assert(!state.pendingSecret, 'secret-change-unsettled');
78
86
  const {retiredSecrets = []} = state;
79
87
  if (command === 'record-owner') return withStateLock(statePath, async () => {
80
88
  const current = await readOwnerState(statePath, target);
@@ -97,8 +105,14 @@ export async function main(argv = process.argv.slice(2), env = process.env, {fet
97
105
  return {ok:true, origin:target.origin, versionId:live.versionId, retiredSecrets, ownerClaim:state.ownerClaim, liveSecrets:rows.map(row => row.name)};
98
106
  }
99
107
  const current = retiredSecrets.length && Array.isArray(declaration.secrets) ? {...declaration,secrets:declaration.secrets.filter(item => !retiredSecrets.includes(item?.binding))} : declaration;
100
- const artifact = await ownerArtifact(root,values.product);
108
+ artifact ??= await ownerArtifact(root,values.product);
101
109
  const plan = ownerPlan(target,current,artifact,{localOnlyKeys,env});
110
+ if (command === 'dry-run') {
111
+ const checked = withScopeHints(api);
112
+ const exists = await workerSettings(checked,target.worker) !== null;
113
+ const {unset} = await secretBindings(checked,target.worker,plan,env,exists);
114
+ return {ok:true,dryRun:true,deployed:false,optionalUnset:unset};
115
+ }
102
116
  if (command === 'health') {
103
117
  const readiness = {...(healthOptions?.now ? {clock:healthOptions.now} : {}), ...(healthOptions?.sleep ? {sleep:healthOptions.sleep} : {}),
104
118
  ...healthOptions?.readiness,single:true,totalMs:30000,
@@ -130,10 +144,10 @@ export async function main(argv = process.argv.slice(2), env = process.env, {fet
130
144
  /** Prints refusal codes and resource names only; never inputs, tokens or provider bodies. */
131
145
  export function report(error) {
132
146
  const diagnostic = deployDiagnostic(error);
133
- if (diagnostic) return {ok:false,...diagnostic};
147
+ if (diagnostic) return {ok:false,...diagnostic,...(error.missingSecrets ? {missingSecrets:error.missingSecrets} : {})};
134
148
  if (error.message === 'missing-input') return {ok:false,code:'missing-input',inputs:error.inputs};
135
149
  if (error.message === 'usage') return {ok:false,code:'usage',usage};
136
- return {ok:false,code:/^[a-zA-Z0-9_-]{1,120}$/.test(error.message) ? error.message : 'owner-deploy-failed',...(error.resource ? {resource:error.resource} : {})};
150
+ return {ok:false,code:/^[a-zA-Z0-9_-]{1,120}$/.test(error.message) ? error.message : 'owner-deploy-failed',...(error.resource ? {resource:error.resource} : {}),...(error.missingSecrets ? {missingSecrets:error.missingSecrets} : {})};
137
151
  }
138
152
  if (process.argv[1] && import.meta.url === pathToFileURL(resolve(process.argv[1])).href) {
139
153
  try { console.log(JSON.stringify(await main())); }
@@ -49,10 +49,16 @@ export async function secretBindings(api, worker, plan, env, exists) {
49
49
  const supplied = item => typeof env[item.environment] === 'string' && env[item.environment].trim();
50
50
  // An optional secret neither held nor supplied stays unbound; the app treats it as not connected.
51
51
  const unset = plan.secrets.filter(item => item.optional && !names.includes(item.binding) && !supplied(item)).map(item => item.binding);
52
+ const missingSecrets = plan.secrets.filter(item => !item.optional && !names.includes(item.binding) && !supplied(item))
53
+ .map(({binding,environment}) => ({binding,environment}));
54
+ if (missingSecrets.length) {
55
+ const error = new Error(`missing-secret-${missingSecrets[0].environment}`);
56
+ error.missingSecrets = missingSecrets;
57
+ throw error;
58
+ }
52
59
  for (const item of plan.secrets) {
53
60
  if (names.includes(item.binding)) bindings.push({type:'inherit',name:item.binding});
54
61
  else if (!unset.includes(item.binding)) {
55
- assert(supplied(item), `missing-secret-${item.environment}`);
56
62
  bindings.push({type:'secret_text',name:item.binding,text:env[item.environment]});
57
63
  }
58
64
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@runeditrun/rer",
3
- "version": "0.2.57",
3
+ "version": "0.2.58",
4
4
  "description": "The rer command: install, set up, run and launch Run Edit Run checkouts.",
5
5
  "license": "MIT",
6
6
  "type": "module",