@runeditrun/rer 0.2.104 → 0.2.106

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
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 ?? [])])];
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;
@@ -129,6 +131,8 @@ export async function deployCommand(context) {
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);
@@ -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))));
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.
@@ -1,5 +1,27 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.2.106
4
+
5
+ ### `rer deploy --dry-run`
6
+
7
+ - `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.
8
+ - `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.
9
+ - 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).
10
+
11
+ ### Owner-mode deploys and sign-in
12
+
13
+ - 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.
14
+ - `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.
15
+ - `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.
16
+ - Code only: no migration is added. Seeds get these fixes by adopting 0.2.106.
17
+
18
+ ## 0.2.105
19
+
20
+ ### Business authority and relay privacy
21
+
22
+ - A Business-sponsored approval saved by an agent door older than rer 0.2.96 (its persisted principal has no `source`) no longer executes after its Business stops. Approval execution now treats a saved principal with no `source`, a non-embedded door and a consent id as Business-admitted, so it is refused as `sponsor_unavailable` once the Business stops or its stop state is unreadable, like an approval saved with a `source`. Local approvals (no `consent`) and embedded approvals are unchanged.
23
+ - Code only: no migration is added, and the 0.2.104 migration `0043` is unchanged. Seeds adopting 0.2.105 get this refusal without tagging their saved approval rows.
24
+
3
25
  ## 0.2.104
4
26
 
5
27
  ### Business authority and relay privacy
@@ -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);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@runeditrun/rer",
3
- "version": "0.2.104",
3
+ "version": "0.2.106",
4
4
  "description": "The rer command: install, set up, run and launch Run Edit Run checkouts.",
5
5
  "license": "MIT",
6
6
  "type": "module",