@runeditrun/rer 0.2.105 → 0.2.107

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/README.md CHANGED
@@ -435,7 +435,7 @@ declaration refuses completion. A kit or custom-hook deploy, except `--dry-run`,
435
435
  first refuses uncommitted tracked source, naming the files, before any build or
436
436
  upload.
437
437
 
438
- The owner deployment declaration may set top-level `"productDirectory": ".rer/deploy/product"` for a product staged by the build or deploy hook. It must name a normalized checkout-relative subdirectory: no absolute path, backslash, empty, `.` or `..` segment. The directory must exist after the build or hook, with no symlink on its path. rer reads this field and passes `--product` only to the kit's packaging commands (`local-plan`, `deploy` and `health`). A public dry run passes `options.dryRun` to the seed deploy hook for offline preflight; without a custom hook, the owner deployer runs the build lifecycle. Both paths return `dryRun: true`, `deployed: false` and `providerChecked: false` while listing missing real-deploy inputs. Hooks must keep this preflight offline; the wrapper validates legacy-hook artifacts with the local plan without contacting Cloudflare. A hook that invokes the kit itself still supplies `--product` on its own invocation; the wrapper reads the declaration for its own steps. Omitting the field keeps packaging at the checkout root. State, root ownership, secret changes and removal keep their existing locations and behavior; dry run needs no credentials and never reads target secrets.
438
+ The owner deployment declaration may set top-level `"productDirectory": ".rer/deploy/product"` for a product staged by the build or deploy hook. It must name a normalized checkout-relative subdirectory: no absolute path, backslash, empty, `.` or `..` segment. The directory must exist after the build or hook, with no symlink on its path. rer reads this field and passes `--product` only to the kit's packaging commands (`local-plan`, `deploy` and `health`). A public dry run passes `options.dryRun` to the seed deploy hook for offline preflight; without a custom hook, the owner deployer runs the build lifecycle. Both paths return `dryRun: true`, `deployed: false` and `providerChecked: false` while listing missing real-deploy inputs. Hooks must keep this preflight offline; the wrapper validates the artifacts of a legacy hook that returned a kit `state` with the local plan without contacting Cloudflare. A hook that returns no `state` has validated its own plan, and the declaration it names may be a stand-in a real deploy never plans against, so the wrapper skips that plan. Either way rer prints one `deploy: local dry run complete` line after its own plan step (or its skip) succeeds; a failure in that step names it. A hook that invokes the kit itself still supplies `--product` on its own invocation; the wrapper reads the declaration for its own steps. Omitting the field keeps packaging at the checkout root. State, root ownership, secret changes and removal keep their existing locations and behavior; dry run needs no credentials and never reads target secrets.
439
439
 
440
440
  For a hosted owner claim, deploy reuses the name saved by `rer setup` in the
441
441
  checkout's `.seed/installer/setup-answers.json`, under the adapter's
@@ -446,7 +446,8 @@ without a saved or supplied name, it refuses before upload. Names use the same
446
446
  validation as `setup --owner-name`: nonblank, at most 200 characters and no
447
447
  Unicode Cc or Cf control characters. Nameless installers retain their existing
448
448
  deployment behavior. A dry run never prompts for or requires a missing owner
449
- name, never saves a name, and never claims a hosted owner. An explicitly supplied
449
+ name, never saves a name, and never claims a hosted owner, but its needed-for-a-real-deploy
450
+ list names the owner name unless a saved answer or a held claim exists. An explicitly supplied
450
451
  name still must be valid and supported by the installer.
451
452
 
452
453
  For real deployments, an adapter that validates the hosted owner email in its
@@ -81,13 +81,15 @@ export async function deployCommand(context) {
81
81
  deployGuide(declaration);
82
82
  const settings = adapter.hooks?.secrets ?? adapter.settings;
83
83
  // Required secrets have been checked; retain the production sign-in guidance.
84
- const dryRun = async result => {
84
+ const dryRun = async (result, { planned = true, extraNeeded } = {}) => {
85
85
  const production = await deployEnvironment({ root, options, declaration, setupManifest, settings, localOnlyKeys });
86
- const plan = result?.plan ?? (await owner(['local-plan', '--declaration', path, '--environment', options.environment ?? 'production', ...await deployProductArguments(root, deployProductDirectory(declaration))], production.env, { cwd: root, localOnlyKeys })).plan;
86
+ const plan = result?.plan ?? (!planned ? undefined : (await owner(['local-plan', '--declaration', path, '--environment', options.environment ?? 'production', ...await deployProductArguments(root, deployProductDirectory(declaration))], production.env, { cwd: root, localOnlyKeys })).plan);
87
87
  result = { ...result, dryRun: true, deployed: false, providerChecked: false, plan };
88
88
  const { signIn, mailOff } = await requireProductionAuth({ root, declaration, env: production.env, setupManifest, setupSeed: context.setupSeed, adapter, declarationPath: path, options }) ?? {};
89
- if (mailOff) store.report(mailOffNotice(mailOff, options.environment ?? 'production'));
90
- const needed = [...new Set([...neededForRealDeploy({ declaration, env: production.env, signIn, secretsChecked: false }), ...(result.neededForRealDeploy ?? [])])];
89
+ if (mailOff) store.report(mailOffNotice(mailOff, options.environment ?? 'production'), { names: mailOff.credentialNames });
90
+ // The one completion line: rer's own plan step (or its deliberate skip) succeeded. A hook's own line says only that the hook finished.
91
+ store.report('deploy: local dry run complete; no credentials were needed, no Cloudflare requests were made and nothing was changed remotely. Target secrets and remote readiness were not checked.');
92
+ const needed = [...new Set([...neededForRealDeploy({ declaration, env: production.env, signIn, secretsChecked: false }), ...(result.neededForRealDeploy ?? []), ...(extraNeeded ?? [])])];
91
93
  reportNeeded(store, needed);
92
94
  if (declaration.secrets?.some(item => item.binding === 'INSTALLATION_KEY')) store.report('deploy: INSTALLATION_KEY is a private generated binding; INSTALLATION_KEY_PREVIOUS is optional and managed only during rotation or an explicit retired-key reopen. Values are withheld.');
93
95
  return needed.length && result && typeof result === 'object' ? { ...result, neededForRealDeploy: needed } : result;
@@ -122,13 +124,15 @@ export async function deployCommand(context) {
122
124
  for (const value of [...kinds.privateValues(env), env.CLOUDFLARE_ACCOUNT_ID, ...(declaration.secrets ?? []).map(item => env[item.environment])].filter(Boolean)) addSecret(value);
123
125
  const environment = options.environment ?? 'production';
124
126
  // The hook uploads every value it is given: a generated secret it gets is the one the Worker keeps.
125
- if (!options.dryRun) await keepHookSecrets({ root, environment, declaration, setupManifest, env, generated, reused, rotated, again: deployAgain(options), report: line => store.report(line) });
127
+ if (!options.dryRun) await keepHookSecrets({ root, environment, declaration, setupManifest, env, generated, reused, rotated, again: deployAgain(options), report: (line, more) => store.report(line, more) });
126
128
  // A hook keeping the kit's record in its own state file named it; every kit
127
129
  // step after the hook (inspect, secret, record-owner) reads that record.
128
130
  let hookRecord = await hookState(root, environment);
129
131
  const command = async (verb, extra = [], values = env, more = {}) => owner([verb, '--declaration', path, '--environment', environment, ...(hookRecord ? ['--state', hookRecord] : []), ...(['dry-run', 'local-plan', 'deploy', 'health'].includes(verb) ? await deployProductArguments(root, productDirectory) : []), ...extra], values, { cwd: root, localOnlyKeys, ...more });
130
132
  // A hook that deployed through the kit's standard record lets rer issue and
131
133
  // retire the setup token; a hook keeping an unnamed record of its own keeps its token.
134
+ // The hook reads that record: settle a secret change an earlier run left pending first, and stop if it cannot be.
135
+ if (!options.dryRun && hookRecord) await command('settle');
132
136
  let recorded, hookReturned = false;
133
137
  const inspect = async (origin = deployed?.origin) => {
134
138
  try { return recorded = await command('inspect', [], env, hookReturned ? {} : {propagation:observedReadiness(origin)?.propagation}); }
@@ -154,8 +158,10 @@ export async function deployCommand(context) {
154
158
  await deployProductArguments(root, productDirectory);
155
159
  await refuseLocalEnvOutput(root, adapter.devIdentity?.output, { uploaded: !options.dryRun });
156
160
  if (options.dryRun) {
157
- const { plan } = await command('local-plan');
158
- return dryRun({ ...deployed, plan });
161
+ step = 'plan the deploy locally';
162
+ // A hook that returned no kit state validated its own plan, and the declaration it names may be a stand-in a real deploy never plans against.
163
+ const plan = deployed?.state ? (await command('local-plan')).plan : deployed?.plan;
164
+ return dryRun({ ...deployed, plan }, { planned: false, extraNeeded: ownerInput.neededForRealDeploy });
159
165
  }
160
166
  await rememberHookState(root, environment, deployed?.state);
161
167
  hookRecord = await hookState(root, environment);
@@ -181,7 +187,7 @@ export async function deployCommand(context) {
181
187
  const { setupToken: _, ...result } = deployed;
182
188
  return { ...result, ...(claimed ? { owner: claimed } : {}), dependenciesLinked: true };
183
189
  });
184
- if (claimed) store.report(`${claimed === 'claimed' ? 'Claimed the hosted owner' : 'The hosted owner was already claimed and was kept'}${recorded ? '; the one-time setup token was removed' : ''}. ${mailOff ? mailOffNotice(mailOff, environment) : `Sign in by email at ${result.origin}.`}`);
190
+ if (claimed) store.report(`${claimed === 'claimed' ? 'Claimed the hosted owner' : 'The hosted owner was already claimed and was kept'}${recorded ? '; the one-time setup token was removed' : ''}. ${mailOff ? mailOffNotice(mailOff, environment, recorded?.liveSecrets) : `Sign in by email at ${result.origin}.`}`, { names: mailOff?.credentialNames });
185
191
  return result;
186
192
  } catch (error) {
187
193
  if (error instanceof DeployProductError) throw error;
@@ -193,7 +199,7 @@ export async function deployCommand(context) {
193
199
  if (error.hookFailure) throw commandFailure(store.redact?.(redaction.redact(error.message)) ?? redaction.redact(error.message));
194
200
  if (error instanceof RerError && !deployed?.deployed && !recorded) { error.message = store.redact?.(redaction.redact(error.message)) ?? redaction.redact(error.message); throw error; }
195
201
  const outcome = error.owner ?? claimed ?? observedClaims.at(-1)?.outcome;
196
- const state = deployed?.deployed || recorded ? `The application is deployed at ${deployed?.origin ?? recorded.origin}; ${outcome ? `owner ${outcome}` : 'owner claim is not confirmed'}${recorded ? '; setup token retirement is not confirmed' : ''}.` : 'The custom deploy did not finish; inspect its deployment record before recovery.';
202
+ const state = deployed?.deployed || recorded ? `The application is deployed at ${deployed?.origin ?? recorded.origin}; ${outcome ? `owner ${outcome}` : 'owner claim is not confirmed'}${recorded ? '; setup token retirement is not confirmed' : ''}.` : options.dryRun ? 'The dry run did not finish; nothing was deployed.' : 'The custom deploy did not finish; inspect its deployment record before recovery.';
197
203
  const redact = value => store.redact?.(redaction.redact(value)) ?? redaction.redact(value);
198
204
  const setup = hostedSetupFailure(error, { origin: deployed?.origin ?? recorded?.origin, again });
199
205
  if (setup) throw commandFailure(redact(setup));
@@ -22,11 +22,11 @@ export async function deployOwnerInput({ root, adapter, setupSeed, options, sign
22
22
  }
23
23
  const advice = 'Deploy needs your owner name; run rer deploy --owner-name "Your name" (or rer setup --owner-name "Your name"). Nothing was uploaded.';
24
24
  if (!displayName?.trim()) {
25
- // A local plan never bootstraps an owner or asks for their name.
26
- if (options.dryRun) return { input };
27
25
  // A recorded bootstrap keeps its owner; resolving inputs needs no provider read.
28
26
  const held = (await heldDeployments(root)).find(item => item.environment === (options.environment ?? 'production'));
29
27
  if (['claimed', 'kept'].includes(held?.record.ownerClaim?.outcome)) return { input };
28
+ // A local plan never bootstraps an owner or asks for their name, but the first real deploy stops without one.
29
+ if (options.dryRun) return { input, neededForRealDeploy: ['owner name (--owner-name or rer setup)'] };
30
30
  if (options.nonInteractive || options.json || !process.stdin.isTTY) throw missing(advice);
31
31
  const prompt = createInterface({ input: process.stdin, output: process.stderr });
32
32
  const closed = new Promise((_, reject) => prompt.once('close', () => reject(missing(advice))));
@@ -96,6 +96,6 @@ export async function keepHookSecrets({ root, environment, declaration, setupMan
96
96
  export async function keepSecrets({ root, environment, kept, env, generated, reused, report }) {
97
97
  await saveSecrets(root, environment, Object.fromEntries(kept.filter(item => generated.includes(item.binding)).map(item => [item.binding, env[item.environment]])));
98
98
  const file = savedSecretsFile(environment), them = names => names.length > 1 ? 'them' : 'it';
99
- if (generated.length) report(`rer generated ${generated.join(', ')} for this deployment and keeps ${them(generated)} in ${file} (private; Git ignores it), so a redeploy reuses ${them(generated)}. To deploy this environment from another checkout, copy that file there.`);
100
- if (reused.length) report(`rer reused ${reused.join(', ')} kept in ${file}.`);
99
+ if (generated.length) report(`rer generated ${generated.join(', ')} for this deployment and keeps ${them(generated)} in ${file} (private; Git ignores it), so a redeploy reuses ${them(generated)}. To deploy this environment from another checkout, copy that file there.`, { names: generated });
100
+ if (reused.length) report(`rer reused ${reused.join(', ')} kept in ${file}.`, { names: reused });
101
101
  }
package/cli/deploy.mjs CHANGED
@@ -70,7 +70,6 @@ export function ownerDeploy(declarationPath, lifecycle) {
70
70
  if (options.dryRun) {
71
71
  const {plan} = await owner('local-plan');
72
72
  store.report(`Would deploy: ${JSON.stringify(plan)}`);
73
- store.report('deploy: local dry run complete; no credentials were needed, no Cloudflare requests were made and nothing was changed remotely. Target secrets and remote readiness were not checked.');
74
73
  return { dryRun: true, deployed: false, providerChecked: false, plan };
75
74
  }
76
75
  // A custom hook's own state file, when its deploy named one.
@@ -98,7 +97,7 @@ export function ownerDeploy(declarationPath, lifecycle) {
98
97
  }
99
98
  await owner('secret', ['--set', binding, ...(state ? ['--state', state] : [])]);
100
99
  await keepSecrets({ root, environment, kept, env, generated: [binding], reused: [], report: () => {} });
101
- store.report(`Rotated ${binding} on this environment's Worker to a fresh value kept in .rer/deploy/${environment}.secrets.env, recorded its new version and verified hosted readiness.`);
100
+ store.report(`Rotated ${binding} on this environment's Worker to a fresh value kept in .rer/deploy/${environment}.secrets.env, recorded its new version and verified hosted readiness.`, { names: [binding] });
102
101
  }
103
102
  return { rotated, deployed: false };
104
103
  }
@@ -106,7 +105,7 @@ export function ownerDeploy(declarationPath, lifecycle) {
106
105
  step = 'secrets';
107
106
  const bindings = (options.setSecret ?? options.unsetSecret).split(','), flag = options.setSecret ? '--set' : '--unset';
108
107
  await owner('secret', [...bindings.flatMap(binding => [flag, binding]), ...(state ? ['--state', state] : [])]);
109
- store.report(`${options.setSecret ? 'Set' : 'Removed'} ${bindings.join(', ')} on this environment's Worker as one new version, recorded it and verified hosted readiness.`);
108
+ store.report(`${options.setSecret ? 'Set' : 'Removed'} ${bindings.join(', ')} on this environment's Worker as one new version, recorded it and verified hosted readiness.`, { names: bindings });
110
109
  return { bindings, present: Boolean(options.setSecret), deployed: false };
111
110
  }
112
111
  store.report(`Deploying the ${environment} environment to your Cloudflare account.`);
@@ -114,10 +113,10 @@ export function ownerDeploy(declarationPath, lifecycle) {
114
113
  deployed = await owner('deploy', [], env, { notice: line => store.report(line), onCreated: resource => created.push(redaction.redact(resource)) });
115
114
  // A generated value the kit did not send stays unknown: the Worker kept its own.
116
115
  const sent = supplied.filter(name => deployed.sentSecrets.includes(name)), keptSent = [...generated, ...reused].filter(name => sent.includes(name));
117
- await keepSecrets({ root, environment, kept, env, generated: generated.filter(name => sent.includes(name)), reused: reused.filter(name => sent.includes(name)), report: line => store.report(line) });
116
+ await keepSecrets({ root, environment, kept, env, generated: generated.filter(name => sent.includes(name)), reused: reused.filter(name => sent.includes(name)), report: (line, more) => store.report(line, more) });
118
117
  const other = sent.filter(name => !keptSent.includes(name));
119
- if (other.length) store.report(`rer supplied ${other.join(', ')} from the local setup owner and fresh generated values.`);
120
- if (deployed.optionalUnset) store.report(`Optional secrets not set: ${deployed.optionalUnset.join(', ')}. The application runs without them; set one later with ${again} --set-secret NAME.`);
118
+ if (other.length) store.report(`rer supplied ${other.join(', ')} from the local setup owner and fresh generated values.`, { names: other });
119
+ if (deployed.optionalUnset) store.report(`Optional secrets not set: ${deployed.optionalUnset.join(', ')}. The application runs without them; set one later with ${again} --set-secret NAME.`, { names: deployed.optionalUnset });
121
120
  step = 'health';
122
121
  await owner('health', [], env, {propagation:deployed.propagation});
123
122
  step = 'claim owner';
@@ -133,8 +132,8 @@ export function ownerDeploy(declarationPath, lifecycle) {
133
132
  // The app claims the OWNER_EMAIL the Worker holds: the local one only when this run uploaded it.
134
133
  const email = declared(claim?.emailField);
135
134
  const named = !email ? '' : deployed.sentSecrets.includes(email.binding) && env[email.environment] ? ` (${env[email.environment]})` : ` (the ${email.binding} already set on the Worker)`;
136
- if (claimed) store.report(`${claimed === 'claimed' ? 'Claimed the hosted owner' : 'The hosted owner was already claimed and was kept'}${named}; the one-time setup token was removed. ${mailOff ? mailOffNotice(mailOff, environment) : `Sign in by email at ${deployed.origin}.`}`);
137
- else if (mailOff) store.report(mailOffNotice(mailOff, environment));
135
+ if (claimed) store.report(`${claimed === 'claimed' ? 'Claimed the hosted owner' : 'The hosted owner was already claimed and was kept'}${named}; the one-time setup token was removed. ${mailOff ? mailOffNotice(mailOff, environment, liveSecrets) : `Sign in by email at ${deployed.origin}.`}`, { names: mailOff?.credentialNames });
136
+ else if (mailOff) store.report(mailOffNotice(mailOff, environment, liveSecrets), { names: mailOff.credentialNames });
138
137
  return { deployed: true, origin: deployed.origin, ...(claimed ? { owner: claimed } : {}), dependenciesLinked: true };
139
138
  } catch (error) {
140
139
  if (error instanceof RerError) throw error;
@@ -4,9 +4,17 @@ import { hookState } from './deploy-hook-record.mjs';
4
4
  import { savedSetupAnswers } from './setup-answers.mjs';
5
5
  import { productionMail, mailOffSignInCommand } from './production-mail.mjs';
6
6
 
7
- // What a deploy says when outbound email is deliberately off: the state and the way in.
8
- export function mailOffNotice({ signIn }, environment = 'production') {
9
- return `Outbound email is off (MAIL_PROVIDER=none): no mail credential is bound and this installation sends nothing. Sign in without mail with \`${signIn}\` for the ${environment} environment, from this checkout with the Cloudflare credentials that deployed it. Turn mail on later with rer deploy --environment ${environment} --set-secret and the provider inputs.`;
7
+ // What a deploy says when outbound email is deliberately off: the state and the way in. A seed that
8
+ // declares its mail credential secrets (`mail.credentialSecretNames`) gets this line only when it is
9
+ // true: with the Worker's bound secret names in `live`, a bound mail secret is named instead, and
10
+ // without them (a dry run reads no secrets) the line says the bound secrets were not read.
11
+ export function mailOffNotice({ signIn, credentialNames = [] }, environment = 'production', live) {
12
+ if (credentialNames.length && Array.isArray(live)) {
13
+ const bound = credentialNames.filter(name => live.includes(name));
14
+ if (bound.length) return `Outbound email is configured by the secrets bound on this environment's Worker: ${bound.join(', ')} (names only; values are never printed). This deploy's MAIL_PROVIDER=none setting does not remove them; turn mail off with rer deploy --environment ${environment} --unset-secret and these names. Sign in without mail with \`${signIn}\` for the ${environment} environment, from this checkout with the Cloudflare credentials that deployed it.`;
15
+ }
16
+ const unread = credentialNames.length && !Array.isArray(live) ? ` The bound secrets were not read: if one of ${credentialNames.join(', ')} is bound on the Worker, outbound email is configured by it.` : '';
17
+ return `Outbound email is off (MAIL_PROVIDER=none): no mail credential is bound and this installation sends nothing. Sign in without mail with \`${signIn}\` for the ${environment} environment, from this checkout with the Cloudflare credentials that deployed it. Turn mail on later with rer deploy --environment ${environment} --set-secret and the provider inputs.${unread}`;
10
18
  }
11
19
 
12
20
  // Validate the shared email/identity contract using the bindings that will reach
@@ -23,7 +31,7 @@ export async function requireProductionAuth({ root, declaration, env, setupManif
23
31
  const mailOffSignIn = mail.off ? declaredSignIn : undefined;
24
32
  if (mailOffSignIn) {
25
33
  if (mail.offConflicts.length) throw refuse(`MAIL_PROVIDER=none turns outbound email off, and ${mail.offConflicts.join(', ')} would bind a way to send. Remove ${mail.offConflicts.length > 1 ? 'them' : 'it'} or choose a mail provider. Nothing was built or uploaded.`);
26
- return { mailOff: { signIn: mailOffSignIn } };
34
+ return { mailOff: { signIn: mailOffSignIn, credentialNames: mail.credentialNames } };
27
35
  }
28
36
  if (mail.senderIssue && options.verb === 'deploy' && !(options.dryRun && mail.fixtureSender)) throw refuse(`${mail.senderIssue} Nothing was built or uploaded.`);
29
37
  if (mail.configured()) return;
@@ -3,6 +3,7 @@ import { contained } from './project.mjs';
3
3
  import { refuse } from './errors.mjs';
4
4
  import { parseAddress } from '../modules/mail/src/core/validation.mjs';
5
5
  import { deliveryDeclarationSources } from './delivery-declarations.mjs';
6
+ import { mailCredentialSecretNames } from '../modules/delivery-producer/declarations.mjs';
6
7
  import { validateRerConfig } from '../modules/mail/src/adapters/rer/contract.mjs';
7
8
  import { validateMailSenders } from '../modules/delivery-producer/mail.mjs';
8
9
  import { sourceMailSenders } from './deploy-variables.mjs';
@@ -40,7 +41,7 @@ export function mailOffSignInCommand(adapter) {
40
41
  // root declaration later. Read that source contract, never arbitrary ambient
41
42
  // keys or the adapter's executable source, before any build or provider write.
42
43
  export async function productionMail(root, declaration, env, declarationPath = 'deploy.json', adapter, mailOffSignIn = mailOffSignInCommand(adapter)) {
43
- const bindings = { ...declaration.vars }, secrets = new Set(), publicInputs = new Set(), declaredProviders = new Set();
44
+ const bindings = { ...declaration.vars }, secrets = new Set(), publicInputs = new Set(), declaredProviders = new Set(), credentialDeclarations = [];
44
45
  const senders = [{ source: `${declarationPath} vars.MAIL_FROM`, value: declaration.vars?.MAIL_FROM }];
45
46
  senders.push(...await sourceMailSenders(root, adapter));
46
47
  let senderFix = `Edit vars.MAIL_FROM in ${declarationPath}`;
@@ -79,7 +80,12 @@ export async function productionMail(root, declaration, env, declarationPath = '
79
80
  }
80
81
  }
81
82
  for (const provider of spec.mail?.providers ?? []) if (providers.includes(provider)) declaredProviders.add(provider);
83
+ try { credentialDeclarations.push(...mailCredentialSecretNames(spec.mail).map(name => ({ name, path }))); }
84
+ catch (error) { throw refuse(`Restore a valid mail credential declaration at ${path}: ${error.message}. Nothing was built or uploaded.`); }
82
85
  }
86
+ // The seed's declared mail credentials are secrets of this deployment, or the declaration is wrong.
87
+ for (const { name, path } of credentialDeclarations) if (!secrets.has(name)) throw refuse(`${path} mail.credentialSecretNames names ${name}, which the deployment does not declare as a secret. Declare it in ${declarationPath} secrets or in the secret names of ${path}, or remove it from the list. Nothing was built or uploaded.`);
88
+ const credentialNames = [...new Set(credentialDeclarations.map(item => item.name))];
83
89
  for (const name of publicInputs) if (present(env[name])) {
84
90
  if (name === 'MAIL_FROM') senders.push({ source: 'public MAIL_FROM (environment or --env-file)', value: env[name] });
85
91
  bindings[name] = env[name];
@@ -128,6 +134,7 @@ export async function productionMail(root, declaration, env, declarationPath = '
128
134
  });
129
135
  return {
130
136
  off,
137
+ credentialNames,
131
138
  offConflicts: off ? sendingBindings.filter(key => present(bindings[key])) : [],
132
139
  declared: 'MAIL_PROVIDER' in bindings || publicInputs.has('MAIL_PROVIDER') || secrets.has('MAIL_API_KEY') || selected.length > 0,
133
140
  senderIssue,
@@ -1,5 +1,34 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.2.107
4
+
5
+ ### Deploy mail notice and secret names
6
+
7
+ - `rer deploy` no longer says "Outbound email is off (MAIL_PROVIDER=none): no mail credential is bound" when mail secrets are bound. A seed lists its mail credential secrets in the new optional `mail.credentialSecretNames` (beside `mail.providers` in its deployment-spec declaration; a non-empty list, each name a secret the deployment declares, no duplicates, no values; `rer deploy` refuses a name the deployment does not declare). When any listed name is bound on the Worker, the deploy prints one line naming the bound secret names (never values) and saying outbound email is configured by them; when none is, the off line is unchanged, and a dry run says it did not read the bound secrets. rer does not guess mail secrets from name patterns, and a seed without the key is unchanged.
8
+ - rer's confirmation lines no longer redact secret names. `rer deploy --set-secret EMAIL_PROVIDER,...` printed `[REDACTED]_DOMAIN` when a secret's value (`mailgun`) or another name (`MAILGUN_SENDING_KEY`) matched part of a name. The lines that list names (set, unset, rotate, generated, reused, supplied, optional-unset, the mail notice) keep each name whole; values are still redacted everywhere, including in the text around the names.
9
+
10
+ ### Business roster erasure
11
+
12
+ - Erasing an operator now also retires them from the Business-signed roster. In the same erasure transaction, `agentErasureStatements` deletes the person's `bs_team` row, removes their entry from the stored `bs_settings.document` (the verified payload; no signature is stored or re-signed), and redacts an editor identity in `bs_overrides`/`bs_audit` to the erasure marker; before, their name, email and operator id stayed there. A seed gets this only by declaring it: its erasure map must declare `agent_door_state` with `retire: { refs }`, and the erasure subject must carry `operatorPolicyRefs`. A seed whose map does not declare it keeps the old behaviour (the roster entry stays), so this release does not close the leak for a seed until that seed has adopted 0.2.107 and added the declaration. A seed without the agent door appends `rosterRetirementStatements(db, refs, { erasure_id })` to its own erasure transaction instead.
13
+ - Value-free digests in the new `bs_retired` table make the Business's next signed revision that still lists an erased person apply as retired: everyone else applies, they get no account, row or invitation, and the ack carries `retired: [email]`, until the Business sends a larger member `invite`.
14
+ - A person erased by an older release, whose roster row and stored document entry an old erasure left behind, is retired at runtime, not by a migration. A team adapter may return `gone` (the `operatorId`s of stored rows whose native identity no longer exists, by the adapter's own check); on the Business's next revision the Business-settings module writes the digests and invite number to `bs_retired`, purges the row and drops the document entry in that apply's batch, so a revision still listing them applies as retired instead of inviting them again. `auth.businessTeam` reports a stored operator it can no longer find (it answered `conflict` for that row before). An adapter that never returns `gone`, such as one bound to another accounts table, changes no stored row.
15
+ - This release is not code only: it adds migration `0044_business_retired.sql` (source `modules/business-settings/schema/0003_business_retired.sql`). It creates the table `bs_retired` and nothing else: no purge, no data rewrite, no row read or changed. Every seed with a Business roster must copy it into its own forward migration sequence and land it; without it person erasure refuses with `business_roster_missing_table:bs_retired` and a revision that lists team members refuses. Seeds get all of this by adopting 0.2.107, landing the migration and declaring the erasure refs; none of it is live in any deployed seed until that seed adopts and deploys it.
16
+
17
+ ## 0.2.106
18
+
19
+ ### `rer deploy --dry-run`
20
+
21
+ - `rer deploy --dry-run` no longer fails after a validated seed hook when the declaration the hook names is a stand-in (for example Lamp's `hosted-check.json`, which has no `version`). rer's own `local-plan` after the hook now runs only when the hook returned a kit `state`; a real deploy and the kit's `ownerPlan` are unchanged.
22
+ - `rer deploy --dry-run` prints one rer completion line, `deploy: local dry run complete; ...`, only after rer's own plan step (or its skip) succeeded, so a hook's own completion line is no longer the last word before a failure. A failure in that step now says `Failed at plan the deploy locally` and, under `--dry-run`, no longer tells you to inspect a deployment record that does not exist.
23
+ - A passing `rer deploy --dry-run` now lists `owner name (--owner-name or rer setup)` under what a real deploy needs, unless a saved answer or a held owner claim exists, because the first real deploy stops without one (exit 3).
24
+
25
+ ### Owner-mode deploys and sign-in
26
+
27
+ - Retiring the setup token (or any `--unset-secret`/`--set-secret` change) no longer fails and leaves the change pending when Cloudflare's Worker deployments or versions answer is momentarily partial. Owner-mode settling now replays such a read within the same bounded window as account lists; a read that stays partial still fails with `provider-partial-list` and never records the change as settled. This also applies to `rer signin` and to the settle step before a deploy.
28
+ - `rer deploy` with a custom deploy hook now settles a secret change an earlier run left pending, reading the live Worker version back, before it runs the hook, so the hook sees the true deployment record. This applies when an earlier deploy left a deployment record; a first deploy has nothing to settle. If the change cannot be settled the deploy fails before the hook runs.
29
+ - `rer signin` prints the link at the deployment's recorded origin (a custom domain) instead of always the workers.dev address. The link stays single-use, valid for 15 minutes, and is printed once.
30
+ - Code only: no migration is added. Seeds get these fixes by adopting 0.2.106.
31
+
3
32
  ## 0.2.105
4
33
 
5
34
  ### Business authority and relay privacy
@@ -11,8 +11,21 @@ const status = (value, label) => {
11
11
  if (!Number.isInteger(value) || value < 100 || value > 599) throw Error(`Invalid ${label}`);
12
12
  };
13
13
 
14
+ /**
15
+ * The secret names a seed declares as its outbound mail credentials, `mail.credentialSecretNames`:
16
+ * optional, a non-empty list of binding names, no duplicates, never values. Whether each is a secret
17
+ * the deployment declares is checked where the deployment's secrets are known (`rer deploy`).
18
+ */
19
+ export function mailCredentialSecretNames(mail) {
20
+ if (mail?.credentialSecretNames === undefined) return [];
21
+ const names = strings(mail.credentialSecretNames, 'mail credentialSecretNames', bindingPattern);
22
+ if (!names.length) throw Error('Invalid mail credentialSecretNames: name at least one secret or remove the list');
23
+ return names;
24
+ }
25
+
14
26
  /** Preserve source-owned preview and setup declarations, without authorizing effects. */
15
27
  export function validateDeclarations(spec) {
28
+ mailCredentialSecretNames(spec.mail);
16
29
  if (spec.providerEffects !== undefined) {
17
30
  if (strings(spec.providerEffects, 'providerEffects', /^[a-z][a-z0-9-]{0,63}$/).length > 32) throw Error('Too many provider effects');
18
31
  }
@@ -25,7 +25,7 @@ export function publicMailSender(spec) {
25
25
  /** Managed mail is an explicit capability, independent of direct provider adapters. */
26
26
  export function usesManagedMail(mail) {
27
27
  if (mail === undefined) return false;
28
- keys(mail, ['providers'], 'mail');
28
+ keys(mail, ['providers', 'credentialSecretNames'], 'mail');
29
29
  const providers = strings(mail.providers, 'mail providers', /^(rer|resend|sendgrid|cloudflare)$/);
30
30
  if (!providers.length) throw Error('Mail requires at least one provider');
31
31
  return providers.includes('rer');
@@ -105,7 +105,7 @@ Ownership lives in a state file, by default `.rer/deploy/<environment>.json` und
105
105
  - **Partial failure and resume.** The kit records each create as `pending` before the request and `created` with the provider id after it. A failed create leaves `pending`. On the next run an absent pending name is created again, and a present one is refused as `uncertain-resource-create`, because a lost response cannot prove who created it. Inspect it: if it is the empty resource from the interrupted run, delete it and re-run. A Worker upload is recorded as created when the upload succeeds, so a failure after it resumes with one fresh upload. If the response to the very first upload is lost, the Worker exists but is still `pending`. The kit records the upload's fingerprint before sending it. When an upload's response or its readback is lost (a first upload or a redeploy), the next run accepts the live version as this deploy's own only when it carries that fingerprint both as its `RER_DEPLOY_FINGERPRINT` binding and as its `rer-deploy:<fingerprint>` annotation: it records the live version id, deployment id and etag, then resumes with one fresh upload. Any other live version is refused, as `uncertain-resource-create` with no prior receipt and as `owned-resource-replaced` with one. If the uncertain Worker cannot be authenticated, inspect it and delete it only after confirming that it is the kit-created Worker and that its Durable Object data is disposable. Back up any needed data before deleting it. Migration claims keep the rules under Migration safety.
106
106
  - **Drift.** A created resource that has gone is refused as `owned-resource-missing`; one replaced under the same name is refused as `owned-resource-replaced`. The kit never deletes or recreates them. This covers D1, KV, Queues and R2 (a bucket is identified by its creation date; a state file written before that was recorded keeps working and is not checked for that bucket). For the Worker, the live deployment (version id, deployment id and etag) must be the last receipt's before any write; someone else's upload under the same name is refused as `owned-resource-replaced` and never overwritten. Immediately before the Worker PUT, the kit rechecks every saved resource identity, including resources omitted from the current plan, then the Worker identity. A replacement during provisioning or asset upload is refused before the upload intent or receipt is saved. An interrupted successful upload may resume only when the live version id, deployment id and etag match the identity saved immediately after that upload, or, when its readback was lost before that identity was saved, when the live version carries the fingerprint saved immediately before that upload (binding and annotation). A receipt's historical fingerprint never overrides a receipt mismatch.
107
107
  - **Lost upgrade response.** An interrupted upload can resume when its saved upload intent authenticates the live version by the pending fingerprint binding and annotation, or by its saved provider identity. Otherwise deployment refuses the mismatch. A [Cloudflare rollback](https://developers.cloudflare.com/workers/versions-and-deployments/rollbacks/) creates a new deployment, so it does not restore the recorded identity.
108
- - **Settling listings.** Right after a create or delete, an account listing can briefly disagree with its own page counts (`provider-partial-list`: on 13 October 2026 D1's `total_count` lagged its rows by about 7 seconds after a create). Owner-mode deploy, health and removal discard such a snapshot and list again from the start for up to 120 seconds with a short backoff; a partial listing is never accepted.
108
+ - **Settling listings.** Right after a create or delete, an account listing can briefly disagree with its own page counts (`provider-partial-list`: on 13 October 2026 D1's `total_count` lagged its rows by about 7 seconds after a create). Owner-mode deploy, health, removal, secret changes and sign-in discard such a snapshot and list again from the start for up to 120 seconds with a short backoff; a partial listing is never accepted. The same applies to the GET reads of a Worker's deployments and versions that settle a pending secret change.
109
109
  - **One run at a time.** A deploy takes an exclusive lock file, `<state file>.lock`, for the whole run and removes it at the end, even after a failure. A second run on the same state file is refused as `owner-state-locked` before any provider request. If a run was killed (power loss, `kill -9`) and no deploy is running, delete the lock file by hand.
110
110
 
111
111
  The CLI prints JSON: refusal codes and resource names only, never inputs, tokens or provider bodies.
@@ -20,7 +20,7 @@ import { validateMigrations } from './migrations.mjs';
20
20
  import { publicOrigin } from './public-origin.mjs';
21
21
 
22
22
  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.';
23
- const usage = 'usage: owner-cli.mjs deploy|dry-run|local-plan|health|remove|inspect|record-owner|signin|rekey --declaration <file> --environment <name> [--product <dir>] [--state <file>] [--outcome claimed|kept] | secret ... --set NAME [--set NAME]|--unset NAME [--unset NAME]';
23
+ const usage = 'usage: owner-cli.mjs deploy|dry-run|local-plan|health|remove|inspect|record-owner|signin|rekey|settle --declaration <file> --environment <name> [--product <dir>] [--state <file>] [--outcome claimed|kept] | secret ... --set NAME [--set NAME]|--unset NAME [--unset NAME]';
24
24
 
25
25
  // The public offline command also contains legacy hooks that call kit dry-run.
26
26
  // Keep their plan local without changing direct kit callers or real deploys.
@@ -42,7 +42,7 @@ export async function main(argv = process.argv.slice(2), env = process.env, {fet
42
42
  catch { throw new Error('usage'); }
43
43
  const {positionals:[requestedCommand,...rest],values} = parsed;
44
44
  const command = localPlans.getStore() && requestedCommand === 'dry-run' ? 'local-plan' : requestedCommand;
45
- if (!['deploy','dry-run','local-plan','health','secret','remove','inspect','record-owner','signin','rekey'].includes(command) || rest.length || !values.declaration || !values.environment) throw new Error('usage');
45
+ if (!['deploy','dry-run','local-plan','health','secret','remove','inspect','record-owner','signin','rekey','settle'].includes(command) || rest.length || !values.declaration || !values.environment) throw new Error('usage');
46
46
  if (localPlans.getStore() && command !== 'local-plan') throw new Error('offline-deploy-refuses-provider-operation');
47
47
  if ((command === 'secret') !== (values.set !== undefined || values.unset !== undefined) || values.set !== undefined && values.unset !== undefined) throw new Error('usage');
48
48
  if (values.outcome !== undefined && command !== 'record-owner' || command === 'record-owner' && !['claimed','kept'].includes(values.outcome)) throw new Error('usage');
@@ -110,12 +110,14 @@ export async function main(argv = process.argv.slice(2), env = process.env, {fet
110
110
  const undeclared = named.filter(binding => !declared.some(entry => entry?.binding === binding));
111
111
  if (undeclared.length) { const error = new Error('undeclared-secret'); error.resource = undeclared.map(binding => `secret:${binding}`).join(', '); throw error; }
112
112
  const changes = named.map(binding => ({binding, value:values.set === undefined ? undefined : env[declared.find(entry => entry?.binding === binding).environment]}));
113
- return {ok:true,...await ownerSecret({api,target,statePath,changes,fetch,healthOptions}).catch(error => { throw api.annotateFailure(error,'secrets'); })};
113
+ return {ok:true,...await ownerSecret({api,target,statePath,changes,fetch,healthOptions,settle}).catch(error => { throw api.annotateFailure(error,'secrets'); })};
114
114
  }
115
115
  // A secret rer retired (the spent setup token) is no longer part of the plan.
116
116
  // A dry run only reads state: settling an interrupted change may write it.
117
- const state = command === 'dry-run' ? await readOwnerState(statePath,target) : await settleOwnerState({api,target,statePath});
117
+ const state = command === 'dry-run' ? await readOwnerState(statePath,target) : await settleOwnerState({api,target,statePath,settle});
118
118
  if (command === 'dry-run') assert(!state.pendingSecret, 'secret-change-unsettled');
119
+ // Settled or refused: a caller about to run foreign code never proceeds on an unsettled record.
120
+ if (command === 'settle') { assert(!state.pendingSecret, 'secret-change-unsettled'); return {ok:true}; }
119
121
  const {retiredSecrets = []} = state;
120
122
  if (command === 'record-owner') return withStateLock(statePath, async () => {
121
123
  const current = await readOwnerState(statePath, target);
@@ -127,7 +129,7 @@ export async function main(argv = process.argv.slice(2), env = process.env, {fet
127
129
  return {ok:true, owner:values.outcome};
128
130
  });
129
131
  // The link is a credential: returned to the caller once, never written to the state file.
130
- if (command === 'signin') return {ok:true,...await ownerSignin({api,target,statePath}).catch(error => { throw api.annotateFailure(error,'signin'); })};
132
+ if (command === 'signin') return {ok:true,...await ownerSignin({api,target,statePath,settle}).catch(error => { throw api.annotateFailure(error,'signin'); })};
131
133
  if (command === 'inspect') {
132
134
  assert(!localOnlyBinding(declaration, localOnlyKeys), 'local-only-binding');
133
135
  assert(state.receipt && !state.pendingUpload && !state.pendingSecret, 'missing-owner-receipt');
@@ -4,7 +4,7 @@ import { activeWorker } from './worker.mjs';
4
4
  import { secretNames, validSecretNames } from './owner-secret-names.mjs';
5
5
  import { waitHealth } from './health-request.mjs';
6
6
  import { definiteProviderRefusal } from './provider.mjs';
7
- import { readOwnerState, writeOwnerState, withStateLock, withScopeHints, sameDeployment, refuse, recordSecretChange, settlePendingSecret } from './owner.mjs';
7
+ import { readOwnerState, writeOwnerState, withStateLock, withScopeHints, withSettledLists, sameDeployment, refuse, recordSecretChange, settlePendingSecret } from './owner.mjs';
8
8
  import { uploadSecretCopy, deploySecretCopy } from './owner-secret-copy.mjs';
9
9
 
10
10
  /** Set (each `value` given) or remove Worker secrets of the owner's last deployment as one
@@ -20,8 +20,8 @@ import { uploadSecretCopy, deploySecretCopy } from './owner-secret-copy.mjs';
20
20
  * deployment is still live. An ambiguous one-secret rotation
21
21
  * re-PUTs the value before accepting its successor as proof of the rotation.
22
22
  * A removed declared secret is retired: later plans omit it until it is set again. */
23
- export async function ownerSecret({api: provider, target, statePath, changes, fetch = globalThis.fetch, healthOptions = {}, windowMs = 30000, clock = () => performance.now(), sleep = ms => new Promise(resolve => setTimeout(resolve, ms))}) {
24
- const api = withScopeHints(provider);
23
+ export async function ownerSecret({api: provider, target, statePath, changes, fetch = globalThis.fetch, healthOptions = {}, settle = {}, windowMs = 30000, clock = () => performance.now(), sleep = ms => new Promise(resolve => setTimeout(resolve, ms))}) {
24
+ const api = withSettledLists(withScopeHints(provider),settle);
25
25
  const bindings = changes.map(change => change.binding), present = changes[0]?.value !== undefined;
26
26
  assert(bindings.length && bindings.every(identifier) && validSecretNames(bindings), 'invalid-secret-name');
27
27
  assert(changes.every(change => (change.value !== undefined) === present), 'mixed-secret-change');
@@ -2,7 +2,7 @@ import { randomBytes, randomUUID } from 'node:crypto';
2
2
  import { assert } from './validation.mjs';
3
3
  import { query } from './migrations.mjs';
4
4
  import { literal } from './migration-ledger.mjs';
5
- import { readOwnerState, sameDeployment } from './owner.mjs';
5
+ import { readOwnerState, sameDeployment, withScopeHints, withSettledLists } from './owner.mjs';
6
6
  import { activeWorker } from './worker.mjs';
7
7
  import { OWNER_SIGNIN_PATH, OWNER_SIGNIN_SECONDS, ownerSigninDigest } from '../operator-auth/owner-signin-grant.mjs';
8
8
 
@@ -10,7 +10,8 @@ import { OWNER_SIGNIN_PATH, OWNER_SIGNIN_SECONDS, ownerSigninDigest } from '../o
10
10
  * one-time grant for the claimed owner into the deployment's own auth D1 and return the
11
11
  * link. Only the token's SHA-256 reaches the database; the token itself exists only in
12
12
  * the returned link. Refuses unless the live Worker is the one this record deployed. */
13
- export async function ownerSignin({ api, target, statePath, clock = Date.now }) {
13
+ export async function ownerSignin({ api: provider, target, statePath, clock = Date.now, settle = {} }) {
14
+ const api = withSettledLists(withScopeHints(provider), settle);
14
15
  const state = await readOwnerState(statePath, target);
15
16
  assert(state.receipt && !state.pendingUpload && !state.pendingSecret, 'missing-owner-receipt');
16
17
  const live = await activeWorker(api, target.worker);
@@ -18,7 +19,7 @@ export async function ownerSignin({ api, target, statePath, clock = Date.now })
18
19
  const ids = Object.values(state.owned.d1).filter(entry => entry.status === 'created' && entry.id).map(entry => entry.id);
19
20
  const holding = [];
20
21
  for (const id of ids) if ((await query(api, id, "SELECT name FROM sqlite_master WHERE type='table' AND name='oa_owner_signins'"))[0].results.length) holding.push(id);
21
- if (!holding.length) throw Object.assign(new Error('owner-signin-unsupported'), { origin: target.origin });
22
+ if (!holding.length) throw Object.assign(new Error('owner-signin-unsupported'), { origin: state.receipt.origin ?? target.origin });
22
23
  assert(holding.length === 1, 'owner-signin-ambiguous');
23
24
  const token = randomBytes(32).toString('base64url'), id = randomUUID(), now = clock();
24
25
  // The recorded owner: the claimed (bootstrap) owner first, as operator-auth's own owner() reads it.
@@ -28,7 +29,8 @@ export async function ownerSignin({ api, target, statePath, clock = Date.now })
28
29
  ORDER BY b.claim_id IS NULL, o.created_at, o.id LIMIT 1`);
29
30
  const [owner] = (await query(api, holding[0], `SELECT o.email FROM oa_owner_signins g JOIN oa_operators o ON o.id=g.operator_id WHERE g.id=${literal(id)}`))[0].results;
30
31
  assert(owner, 'owner-not-claimed');
31
- const link = new URL(OWNER_SIGNIN_PATH, target.origin);
32
+ // A deployment on a custom domain records the origin it serves; the account's workers.dev one is the fallback.
33
+ const link = new URL(OWNER_SIGNIN_PATH, state.receipt.origin ?? target.origin);
32
34
  link.searchParams.set('token', token);
33
35
  return { link: link.href, email: owner.email, expiresAt: now + OWNER_SIGNIN_SECONDS * 1000 };
34
36
  }
@@ -5,6 +5,7 @@ import { mkdir, open, rename, rm, writeFile } from 'node:fs/promises';
5
5
  import { dirname } from 'node:path';
6
6
  import { assert, hash, identifier, resourceName, uuid, validatePlan } from './validation.mjs';
7
7
  import { definiteProviderRefusal } from './provider.mjs';
8
+ import { providerListShape } from './pagination.mjs';
8
9
  import { regularBytes } from './artifact.mjs';
9
10
  import { resourceKinds, findResource, checkCronOwnership } from './resources.mjs';
10
11
  import { secretBindings, activeWorker, deployedFingerprint } from './worker.mjs';
@@ -68,19 +69,24 @@ export function withScopeHints(api) {
68
69
  * again from the start for up to `windowMs`; a partial listing is never accepted. */
69
70
  export const LIST_WINDOW_MS = 120000;
70
71
  const settleable = error => ['provider-partial-list','provider-pagination-changed'].includes(error.message);
72
+ /** Owner mode replays a list read, and a GET of a path the provider reads as a list (a Worker's
73
+ * deployments or versions), until a complete snapshot arrives or the window closes. */
71
74
  export function withSettledLists(api, {windowMs = LIST_WINDOW_MS, clock = () => performance.now(), sleep = ms => new Promise(resolve => setTimeout(resolve, ms))} = {}) {
72
75
  if (api.settledLists) return api;
73
- const list = async (...args) => {
76
+ const settled = read => async (...args) => {
74
77
  const start = clock();
75
78
  for (let delay = 500; ; delay = Math.min(delay * 2, 4000)) {
76
- try { return await api.list(...args); }
79
+ try { return await read(...args); }
77
80
  catch (error) {
78
81
  if (!settleable(error) || clock() - start + delay > windowMs) throw error;
79
82
  await sleep(delay);
80
83
  }
81
84
  }
82
85
  };
83
- return {...api, settledLists:true, unsettled:api, list};
86
+ const list = settled((...args) => api.list(...args));
87
+ const readRequest = settled((path, options) => api.request(path, options));
88
+ const request = (path, options = {}) => (!options.method || options.method === 'GET') && providerListShape(path) ? readRequest(path, options) : api.request(path, options);
89
+ return {...api, settledLists:true, unsettled:api, list, request};
84
90
  }
85
91
  /** Waits until the account's listing shows a resource this run just created, so no later
86
92
  * read mistakes it for a missing or replaced one. One that never appears is named. */
@@ -310,8 +316,8 @@ export async function settlePendingSecret(api, worker, state, {preflight = false
310
316
  return true;
311
317
  }
312
318
  /** Settle a pending secret change under the state lock, before a plan reads the retired list. */
313
- export async function settleOwnerState({api: provider, target, statePath}) {
314
- const api = withScopeHints(provider);
319
+ export async function settleOwnerState({api: provider, target, statePath, settle = {}}) {
320
+ const api = withSettledLists(withScopeHints(provider),settle);
315
321
  return withStateLock(statePath, async () => {
316
322
  const state = await readOwnerState(statePath, target);
317
323
  if (await settlePendingSecret(api, target.worker, state, {preflight:true})) await writeOwnerState(statePath, state);
@@ -24,7 +24,7 @@ export function businessTeam(context) {
24
24
  WHERE o.role='owner' AND o.status='active' ORDER BY b.claim_id IS NULL,o.created_at,o.id LIMIT 1))`,
25
25
  args: [...guard.args, operator.id, operator.email, operator.version] }));
26
26
  const fence = store.actorFence(actor, clock());
27
- const pending = [], rows = [];
27
+ const pending = [], rows = [], gone = [];
28
28
  // Abort the whole caller transaction if ownership changed, even when this
29
29
  // document contains only conflicts or unchanged members.
30
30
  const statements = [[`INSERT INTO oa_auth_audit(id,actor_id,action,value,created_at)
@@ -54,7 +54,10 @@ export function businessTeam(context) {
54
54
  // current sign-in address. Self-service email changes keep this ID.
55
55
  let target = prior ? await store.operator(prior.operatorId) : await store.byEmail(email);
56
56
  const oldRole = target?.role;
57
- if (target?.role === 'owner' || !prior && (email === owner.email || target) || prior && !target) {
57
+ // The native operator is gone (an erasure removed it): the module retires the stored row and its listing,
58
+ // so no conflict row is kept and the Business's next listing of them stays retired.
59
+ if (prior && !target) { gone.push(prior.operatorId); continue; }
60
+ if (target?.role === 'owner' || !prior && (email === owner.email || target)) {
58
61
  // Never adopt an unrelated account, or discard a recorded identity
59
62
  // because its old address now belongs to another account.
60
63
  if (member || prior) rows.push({ email, operatorId: prior?.operatorId ?? null, invite: member?.invite ?? prior.invite, state: 'conflict' });
@@ -84,7 +87,7 @@ export function businessTeam(context) {
84
87
  } else if (target.displayName !== name) target = await update(target, { ...target, displayName: name }, 'operators:role');
85
88
  rows.push({ email, operatorId: target.id, invite: member.invite, state: target.status });
86
89
  }
87
- return { statements: statements.map(([sql, args]) => store.statement(sql, args)), rows,
90
+ return { statements: statements.map(([sql, args]) => store.statement(sql, args)), rows, gone,
88
91
  async afterCommit() { for (const send of pending) await send(); } };
89
92
  },
90
93
  });
@@ -46,7 +46,17 @@ export async function createCommands(directory,state,{terminal=text=>writeSync(1
46
46
  if(!closed)log.write(text);
47
47
  writeTerminal(text);
48
48
  };
49
- const report=text=>emit(redaction.redact(String(text))+'\n');
49
+ // A line that lists secret NAMES keeps each name whole: a name is not a secret, even when a value
50
+ // equals it or one of its parts. The text around the names is redacted exactly as any other line.
51
+ const redactBesideNames=(text,names)=>{
52
+ const listed=[...new Set((names??[]).filter(name=>typeof name==='string'&&name))].sort((a,b)=>b.length-a.length);
53
+ if(!listed.length)return redaction.redact(text);
54
+ const pattern=new RegExp(`(?<![A-Za-z0-9_])(?:${listed.map(name=>name.replace(/[.*+?^${}()|[\]\\]/g,'\\$&')).join('|')})(?![A-Za-z0-9_])`,'g');
55
+ let result='',from=0;
56
+ for(const match of text.matchAll(pattern)){result+=redaction.redact(text.slice(from,match.index))+match[0];from=match.index+match[0].length;}
57
+ return result+redaction.redact(text.slice(from));
58
+ };
59
+ const report=(text,{names}={})=>emit(redactBesideNames(String(text),names)+'\n');
50
60
  const failure=(label,detail={},capture)=>{
51
61
  const outcome=`exit ${detail.code??'none'}, signal ${detail.signal??'none'}`;
52
62
  const status=detail.reason==='cancel'?`cancelled (${outcome})`:detail.reason==='deadline'?`readiness deadline exceeded (${outcome})`:detail.error?`could not start${detail.errorCode?` (${detail.errorCode})`:''} (${outcome})`:outcome;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@runeditrun/rer",
3
- "version": "0.2.105",
3
+ "version": "0.2.107",
4
4
  "description": "The rer command: install, set up, run and launch Run Edit Run checkouts.",
5
5
  "license": "MIT",
6
6
  "type": "module",