@runeditrun/rer 0.2.5 → 0.2.7

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/README.md CHANGED
@@ -104,6 +104,9 @@ A seed that declares a run site prints one more line after those,
104
104
  `RER_SITE http://127.0.0.1:8788`: a local preview of its static run site (its
105
105
  marketing homepage, `/run` and docs) on the first free port above the app's. It
106
106
  stops with the app.
107
+ Later, `rer setup --owner-email YOU` (or `--answers`) with the real owner
108
+ replaces that local owner in place and keeps all local data, saying so in one
109
+ line; a checkout whose database holds any other owner is still refused.
107
110
  It never prompts and never re-runs setup on a checkout that is already set up. A
108
111
  setup a launch started that was stopped or failed is run again by the next
109
112
  `rer dev`, keeping the owner and origin it saved, unless a setup has finished
package/cli/README.md CHANGED
@@ -282,7 +282,11 @@ sign-in address; a hook that reports no deployment, or whose app never names
282
282
  the commit, fails with what happened and claims nothing. When the hook deployed
283
283
  through the kit's standard deployment record, rer also records successful
284
284
  ownership separately from retired secrets and removes the setup token before
285
- returning success; a hook that keeps its own record keeps its token. An owner
285
+ returning success. A hook that deploys with the kit under its own state file
286
+ returns that file as `state` (`cli/deploy-hook-record.mjs` keeps the pointer):
287
+ every later step (inspect, setup token, owner record, `--set-secret`,
288
+ `--unset-secret`, `--remove --yes`) reads that record, so rer claims and retires
289
+ the token the same way; a hook that keeps an unnamed record keeps its token. An owner
286
290
  already claimed by the hook is kept without another bootstrap. An existing owner
287
291
  is explicitly reported as kept. Function owner hooks run their complete
288
292
  bootstrap flow; setup manifest paths do not replace it. A missing or ambiguous
@@ -8,9 +8,11 @@ import { mutationReadinessFailure } from './deploy-readiness.mjs';
8
8
  import { observeOwner } from './deploy-observation.mjs';
9
9
  import { committedSource } from './deploy-source.mjs';
10
10
  import { hookOrigin, waitForSource } from './deploy-hook.mjs';
11
+ import { rememberHookState, hookState } from './deploy-hook-record.mjs';
11
12
  import { main as owner } from '../modules/deploy-kit/owner-cli.mjs';
12
13
  import { localOnlyBinding, ownerWorkerName } from '../modules/deploy-kit/owner.mjs';
13
14
  import { refuseLocalModels } from '../modules/deploy-kit/local-only.mjs';
15
+ import { providerRefusal } from '../modules/deploy-kit/diagnostics.mjs';
14
16
  import { shared } from './shared.mjs';
15
17
 
16
18
  export function validateDeployOptions(options) {
@@ -53,9 +55,13 @@ export async function deployCommand(context) {
53
55
  const redaction = createRedaction();
54
56
  const addSecret = value => { redaction.addSecrets([value]); store.addSecrets?.([value]); };
55
57
  for (const value of [...credentialValues(env), env.CLOUDFLARE_ACCOUNT_ID, ...(declaration.secrets ?? []).map(item => env[item.environment])].filter(Boolean)) addSecret(value);
56
- const command = (verb, extra = [], values = env) => owner([verb, '--declaration', path, '--environment', options.environment ?? 'production', ...extra], values, { cwd: root, localOnlyKeys });
58
+ const environment = options.environment ?? 'production';
59
+ // A hook keeping the kit's record in its own state file named it; every kit
60
+ // step after the hook (inspect, secret, record-owner) reads that record.
61
+ let hookRecord = await hookState(root, environment);
62
+ const command = (verb, extra = [], values = env) => owner([verb, '--declaration', path, '--environment', environment, ...(hookRecord ? ['--state', hookRecord] : []), ...extra], values, { cwd: root, localOnlyKeys });
57
63
  // A hook that deployed through the kit's standard record lets rer issue and
58
- // retire the setup token; a hook keeping its own record keeps its token.
64
+ // retire the setup token; a hook keeping an unnamed record of its own keeps its token.
59
65
  let recorded;
60
66
  const inspect = async () => {
61
67
  try { return recorded = await command('inspect'); }
@@ -76,6 +82,8 @@ export async function deployCommand(context) {
76
82
  Object.assign(process.env, saved);
77
83
  }
78
84
  if (options.dryRun) return deployed;
85
+ await rememberHookState(root, environment, deployed?.state);
86
+ hookRecord = await hookState(root, environment);
79
87
  const origin = hookOrigin(deployed, deployAgain(options));
80
88
  step = 'wait for the deployed source';
81
89
  await waitForSource({ origin, sourceSha, again: deployAgain(options) });
@@ -103,6 +111,7 @@ export async function deployCommand(context) {
103
111
  const redact = value => store.redact?.(redaction.redact(value)) ?? redaction.redact(value);
104
112
  const readiness = mutationReadinessFailure(error, { again, redact });
105
113
  if (readiness) throw commandFailure(readiness);
106
- throw commandFailure(redact(`${state} Failed at ${step}: ${error.message}${error.cause ? ` (${error.cause})` : ''}. Fix the cause and run ${again} again using the same environment credentials. ${outcome && recorded ? `To retire the token without rebuilding: ${again} --unset-secret ${setupManifest?.steps?.find(item => item.type === 'owner-claim')?.tokenField ?? 'SETUP_TOKEN'}.` : ''}`));
114
+ const refused = providerRefusal(error);
115
+ throw commandFailure(redact(`${state} Failed at ${step}: ${error.message}${refused ? ` (${refused})` : ''}${error.cause ? ` (${error.cause})` : ''}. Fix the cause and run ${again} again using the same environment credentials. ${outcome && recorded ? `To retire the token without rebuilding: ${again} --unset-secret ${setupManifest?.steps?.find(item => item.type === 'owner-claim')?.tokenField ?? 'SETUP_TOKEN'}.` : ''}`));
107
116
  }
108
117
  }
@@ -0,0 +1,32 @@
1
+ // A custom deploy hook that deploys with the kit under its own state file returns
2
+ // that file as `state`. rer keeps a pointer to it beside its own records, so
3
+ // `rer deploy --remove` finds and removes what the hook deployed.
4
+ import { readFile, rm } from 'node:fs/promises';
5
+ import { isAbsolute, join, relative } from 'node:path';
6
+ import { contained } from './project.mjs';
7
+ import { invalid } from './errors.mjs';
8
+ import { shared } from './shared.mjs';
9
+
10
+ const pointer = environment => join('.rer', 'deploy', `${environment}.hook.json`);
11
+
12
+ export async function rememberHookState(root, environment, state) {
13
+ if (state === undefined) return;
14
+ if (typeof state !== 'string' || !state) throw invalid('A deploy hook returns state as the path of its kit state file in this checkout.');
15
+ const path = isAbsolute(state) ? relative(root, state) : state;
16
+ await contained(root, path);
17
+ const { privateDirectory, writePrivateFile } = await shared('private-files.mjs');
18
+ await privateDirectory(root, ['.rer', 'deploy']);
19
+ await writePrivateFile(join(root, pointer(environment)), JSON.stringify({ state: path }) + '\n');
20
+ }
21
+
22
+ // The hook's state file for this environment, or undefined when no hook named one.
23
+ export async function hookState(root, environment) {
24
+ let text;
25
+ try { text = await readFile(join(root, pointer(environment)), 'utf8'); } catch (error) { if (error.code === 'ENOENT') return undefined; throw error; }
26
+ let state;
27
+ try { ({ state } = JSON.parse(text)); } catch { throw invalid(`${pointer(environment)} is malformed. Restore it, or remove it to fall back to rer's own deployment record.`); }
28
+ await contained(root, state, { optional: true });
29
+ return state;
30
+ }
31
+
32
+ export const forgetHookState = (root, environment) => rm(join(root, pointer(environment)), { force: true });
@@ -23,7 +23,8 @@ export async function claimHostedOwner({ hook, setupManifest, declaration, deplo
23
23
  if (!item) { if (claim) throw ownerFailure('the deploy declaration does not name the owner setup token secret'); return undefined; }
24
24
  const retire = async outcome => {
25
25
  if (!secret) return outcome;
26
- try { await recordClaim?.(outcome); await secret(['--unset', tokenKey], env); }
26
+ // A recorded claim stays as recorded: a later deploy keeps that owner.
27
+ try { if (!deployed.ownerClaim) await recordClaim?.(outcome); await secret(['--unset', tokenKey], env); }
27
28
  catch (cause) {
28
29
  if (cause.secretChange) { cause.owner = outcome; cause.tokenKey = tokenKey; cause.ownerFinalization = true; throw cause; }
29
30
  const error = new Error('owner-token-retirement-failed'); error.owner = outcome; error.tokenKey = tokenKey; error.cause = cause.message; throw error; }
package/cli/deploy.mjs CHANGED
@@ -10,6 +10,7 @@ import { deployEnvironment, deployAgain } from './deploy-inputs.mjs';
10
10
  import { claimHostedOwner } from './deploy-owner.mjs';
11
11
  import { mutationReadinessFailure } from './deploy-readiness.mjs';
12
12
  import { committedSource } from './deploy-source.mjs';
13
+ import { hookState, forgetHookState } from './deploy-hook-record.mjs';
13
14
 
14
15
  export function ownerDeploy(declarationPath, lifecycle) {
15
16
  // rer verify serves the build with this declaration's vars and secrets.
@@ -56,16 +57,19 @@ export function ownerDeploy(declarationPath, lifecycle) {
56
57
  const created = [];
57
58
  let step = 'deploy', deployed;
58
59
  try {
60
+ // A custom hook's own state file, when its deploy named one.
61
+ const state = await hookState(root, environment);
59
62
  if (options.remove) {
60
63
  step = 'remove';
61
- const result = await owner('remove');
64
+ const result = await owner('remove', state ? ['--state', state] : []);
65
+ await forgetHookState(root, environment);
62
66
  store.report(`Removed ${result.removed.join(', ') || 'nothing (already gone)'}; read back: none of them remains.`);
63
67
  return { removed: result.removed, deployed: false };
64
68
  }
65
69
  if (change.length) {
66
70
  step = 'secrets';
67
71
  const binding = options.setSecret ?? options.unsetSecret;
68
- await owner('secret', [options.setSecret ? '--set' : '--unset', binding]);
72
+ await owner('secret', [options.setSecret ? '--set' : '--unset', binding, ...(state ? ['--state', state] : [])]);
69
73
  store.report(`${options.setSecret ? `Set ${binding}` : `Removed ${binding}`} on this environment's Worker, recorded its new version and verified hosted readiness.`);
70
74
  return { binding, present: Boolean(options.setSecret), deployed: false };
71
75
  }
package/cli/lifecycle.mjs CHANGED
@@ -59,6 +59,7 @@ async function runLifecycle(project, options, out, deployRedaction) {
59
59
  if (options.verb !== 'outbox' && !options.site) try { operation = await localOperation(project.root, process.env.RER_LOCAL_OPERATION); } catch (error) { throw refuse(error.message); }
60
60
  const { recoverInterrupted } = await shared('local/recovery.mjs');
61
61
  if (operation) await recoverInterrupted(project.root, operation);
62
+ if (project.ownerReplacement) await replaceOwner(project, options, out);
62
63
  }
63
64
  const { createCommands } = await shared('commands.mjs');
64
65
  const { privateDirectory } = await shared('private-files.mjs');
@@ -178,6 +179,20 @@ async function runningRecord(root) {
178
179
  return (state.running ?? []).find(record => record.checkout === checkout);
179
180
  }
180
181
 
182
+ // Under the local operation, before the app starts: the zero-setup owner's
183
+ // row and saved owner setting become the real owner's, and one line says so.
184
+ async function replaceOwner(project, options, out) {
185
+ const { from, to } = project.ownerReplacement, { replaceLocalOwner } = await shared('local/owner.mjs');
186
+ await replaceLocalOwner(project.root, from, to, message => refuse(message));
187
+ const secrets = project.adapter.hooks?.secrets, key = localSettingKeys(project).email;
188
+ if (secrets) {
189
+ const { readSettings, replaceSavedSetting } = await shared('adapter-settings.mjs');
190
+ if ((await readSettings(project.root, secrets)).values[key]?.toLowerCase() === from.toLowerCase()) await replaceSavedSetting(project.root, secrets, key, to);
191
+ }
192
+ if (options.json) out.event('owner-replaced', { from, to });
193
+ else out.human(`Replacing the zero-setup local owner ${from} with ${to}. Local data is kept.`);
194
+ }
195
+
181
196
  // One plain line saying which port this checkout uses, and what moved.
182
197
  function announcePort(out, options, selected) {
183
198
  if (selected.door) { if (options.json) out.event('origin', { url: selected.url, door: true }); else out.human(`Using ${selected.url} for this checkout, served through the front door.`); return; }
@@ -3,15 +3,22 @@ import { shared } from './shared.mjs';
3
3
 
4
4
  // A version check owns its descendants just like a lifecycle command. Cleanup
5
5
  // starts at leader exit, even when quiet descendants still hold the pipes.
6
- // The package manager never sees the caller's credentials.
7
- export async function probePnpm(root, store, signal, env = process.env) {
6
+ // The package manager never sees the caller's credentials. A failed probe's
7
+ // error carries `reason`: what pnpm did instead of printing its version.
8
+ export async function probePnpm(root, store, signal, env = process.env, timeoutMs = 10000) {
8
9
  const { dependencyEnvironment } = await shared('dependency-environment.mjs');
9
- const probeSignal = AbortSignal.any([signal, AbortSignal.timeout(10000)].filter(Boolean));
10
+ const timeout = AbortSignal.timeout(timeoutMs), probeSignal = AbortSignal.any([signal, timeout].filter(Boolean));
10
11
  const child = store.spawn('Checking pinned pnpm', 'pnpm', ['--version'], { cwd: root, env: dependencyEnvironment(env), signal: probeSignal });
11
- let version = '';
12
+ let version = '', errors = '';
12
13
  child.stdout.on('data', chunk => { version = (version + chunk).slice(-1024); });
13
- const code = await new Promise(resolve => { child.once('error', () => resolve(null)); child.once('exit', code => resolve(code)); });
14
+ child.stderr.on('data', chunk => { errors = (errors + chunk).slice(0, 4096); });
15
+ const { code, exitSignal, error } = await new Promise(resolve => { child.once('error', error => resolve({ code: null, error })); child.once('exit', (code, exitSignal) => resolve({ code, exitSignal })); });
14
16
  await store.stop(child);
15
- if (probeSignal.aborted || code !== 0) throw missing('The pinned pnpm version probe failed. Select the documented tool.');
16
- return version.trim();
17
+ if (code === 0 && !probeSignal.aborted) return version.trim();
18
+ const line = (store.redact?.(errors) ?? errors).split('\n').map(text => text.trim()).find(Boolean)?.slice(0, 200);
19
+ const reason = timeout.aborted ? `pnpm --version gave no answer within ${timeoutMs / 1000} s`
20
+ : error ? `pnpm could not start (${error.code ?? error.message})`
21
+ : code === null ? `pnpm --version was stopped by ${exitSignal}`
22
+ : `pnpm --version exited ${code}${line ? `: ${line}` : ''}`;
23
+ throw Object.assign(missing(`The pinned pnpm version probe failed (${reason}). Select the documented tool.`), { reason });
17
24
  }
@@ -3,6 +3,7 @@
3
3
  import { mkdtemp, readFile, rm } from 'node:fs/promises';
4
4
  import { delimiter, dirname, join } from 'node:path';
5
5
  import { homedir, tmpdir } from 'node:os';
6
+ import { setTimeout as delay } from 'node:timers/promises';
6
7
  import { cachedPnpm, downloadPnpm } from './pnpm-runtime.mjs';
7
8
  import { missing, RerError } from './errors.mjs';
8
9
  import { shellQuote } from './node-runtime-cache.mjs';
@@ -16,9 +17,9 @@ export async function projectPnpmPin(root) {
16
17
  if (!pin) throw missing('This first-party checkout must declare an exact pnpm version in package.json packageManager. Correct that declaration, then rerun rer.');
17
18
  return pin;
18
19
  }
19
- async function probe(root, env, signal, store) {
20
- try { return await probePnpm(root, store, signal, env); }
21
- catch (error) { if (signal?.aborted) throw error; return undefined; }
20
+ async function probe(root, env, signal, store, timeoutMs) {
21
+ try { return { version: await probePnpm(root, store, signal, env, timeoutMs) }; }
22
+ catch (error) { if (signal?.aborted) throw error; return { reason: error.reason ?? error.message }; }
22
23
  }
23
24
  export async function ensureProjectPnpm(root, options = {}) {
24
25
  if (options.store) return ensure(root, options);
@@ -46,7 +47,7 @@ export async function ensureProjectPnpm(root, options = {}) {
46
47
  }
47
48
  async function ensure(root, { env = process.env, signal, report = () => {}, store }, pin) {
48
49
  pin ??= await projectPnpmPin(root);
49
- if (await probe(root, env, signal, store) === pin) return env;
50
+ if ((await probe(root, env, signal, store)).version === pin) return env;
50
51
  let directory = await cachedPnpm(pin, env);
51
52
  if (!directory) {
52
53
  report(`Fetching pnpm ${pin} for this project; rer keeps it in its own cache.`);
@@ -61,7 +62,14 @@ async function ensure(root, { env = process.env, signal, report = () => {}, stor
61
62
  // this process's Node before the caller's PATH, but cannot be shadowed by a
62
63
  // different pnpm installed in that Node's bin directory.
63
64
  const supplied = { ...env, PATH: [directory, dirname(process.execPath), env.PATH].filter(Boolean).join(delimiter) };
64
- if (await probe(root, supplied, signal, store) !== pin) throw missing(`The verified pnpm ${pin} did not report the project version. Run ${shellQuote(join(directory, 'pnpm'))} --version to inspect it, then rerun rer.`);
65
- Object.assign(env, supplied);
66
- return env;
65
+ // A fresh pnpm's first run can stall or fail once (a cold start on a busy
66
+ // machine): the check settles with a bounded retry, then names what failed.
67
+ let result;
68
+ for (const [attempt, timeoutMs] of [10000, 20000, 30000].entries()) {
69
+ if (attempt) await delay(1000, undefined, { signal });
70
+ result = await probe(root, supplied, signal, store, timeoutMs);
71
+ if (result.version === pin) { Object.assign(env, supplied); return env; }
72
+ }
73
+ const failed = result.version === undefined ? result.reason : `it reported ${JSON.stringify(result.version.slice(0, 64))}`;
74
+ throw missing(`The verified pnpm ${pin} did not report the project version after 3 tries (${failed}). Run ${shellQuote(join(directory, 'pnpm'))} --version to inspect it, then rerun rer.`);
67
75
  }
@@ -1,5 +1,5 @@
1
1
  import {randomBytes} from 'node:crypto';
2
- import {readFile} from 'node:fs/promises';
2
+ import {readFile,realpath} from 'node:fs/promises';
3
3
  import {createInterface} from 'node:readline/promises';
4
4
  import {Writable} from 'node:stream';
5
5
  import {contained} from './project.mjs';
@@ -82,10 +82,12 @@ export async function setupInput(project, options, vars, signal, { origin } = {}
82
82
  }
83
83
  if(!mailbox(answers[names.email]))throw invalid('Provide a valid plain owner mailbox.');
84
84
  answers[names.email]=answers[names.email].toLowerCase();
85
- const {assertLocalOwner}=await shared('local/owner.mjs');
86
- const owners=await assertLocalOwner(project.root,answers[names.email],message=>refuse(message),project.adapter.hooks?.localOwner,`${names.email} in ${project.adapter.hooks?.secrets?.file??'.dev.vars'}`);
85
+ const {assertLocalOwner,zeroSetupOwner}=await shared('local/owner.mjs');
86
+ const {owners,placeholder}=await assertLocalOwner(project.root,answers[names.email],message=>refuse(message),project.adapter.hooks?.localOwner,`${names.email} in ${project.adapter.hooks?.secrets?.file??'.dev.vars'}`);
87
+ // The zero-setup owner gives way to the real one; lifecycle renames it in place.
88
+ if(placeholder&&placeholder.toLowerCase()!==answers[names.email])project.ownerReplacement={from:placeholder,to:answers[names.email]};
87
89
  if(savedEmail&&!mailbox(savedEmail))throw refuse('Saved owner is malformed. Restore private settings or run rer reset --yes.');
88
- if(savedEmail&&savedEmail.toLowerCase()!==answers[names.email]){
90
+ if(savedEmail&&savedEmail.toLowerCase()!==answers[names.email]&&(owners.length?!placeholder:savedEmail.toLowerCase()!==zeroSetupOwner(await realpath(project.root)))){
89
91
  if(owners.length)throw refuse(`Private setting ${names.email} differs from the retained database owner. Restore ${names.email} in ${project.adapter.hooks?.secrets?.file??'.dev.vars'} to ${answers[names.email]}, then run rer setup --owner-email ${answers[names.email]}; or back up data and run rer reset --yes. Private bytes were kept.`);
90
92
  throw refuse(`Owner conflicts with the saved installation (${savedEmail}). Run rer setup --owner-email ${savedEmail}, or back up data, run rer dev --stop, then rer reset --yes followed by rer setup --owner-email ${answers[names.email]}. Reset deletes local data.`);
91
93
  }
@@ -1,5 +1,27 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.2.7
4
+
5
+ - `rer deploy` after a custom deploy hook that returned its own kit state file as `state` reads that record for every finalization step (inspect, the setup token, the owner record), so it issues a setup token, claims the hosted owner, retires the token and exits 0, instead of failing with `HTTP 403 (invalid_setup_token)` because it looked only at `.rer/deploy/<environment>.json`. `--set-secret` and `--unset-secret` read the same record. An untouched repeat still writes nothing.
6
+
7
+ ### Upgrade notes
8
+
9
+ - None: a hook that already returns `state` (0.2.6 upgrade note) gets its owner claimed on its next `rer deploy`.
10
+
11
+ ## 0.2.6
12
+
13
+ - A job-queue client no longer crashes with an unhandled `write EPIPE` when a process probing its identity or policy socket closes before the answer is written (a probe that timed out under load); the prober reports its own timeout or reset. This stopped Orbit's release producer twice.
14
+ - `rer setup --owner-email YOU` (or `--answers`) on a checkout whose local owner is still the `owner@<checkout>.test` that the zero-setup `rer dev` created replaces that owner with you in place: the same account under your address, all local data kept, and one line saying so. A database that holds any other owner is still refused, as before.
15
+ - An untouched repeat `rer deploy` after the hosted owner was claimed writes nothing: retiring the setup token no longer changes the build fingerprint (so the Worker is not uploaded again), and the recorded claim stays `claimed`.
16
+ - The pinned pnpm check settles with a bounded retry: a fresh pnpm's version check is tried up to three times (10, 20 and 30 seconds), and if it still fails, rer says what pnpm did: no answer in time, could not start, its exit code and first error line, or the version it reported. The first `rer import` on a fresh clone no longer stops there when the same command succeeds on retry.
17
+ - A provider call Cloudflare refuses carries the call and Cloudflare's own error codes and messages (account id and token removed, each message cut to 300 characters); `rer deploy` names them when a custom deploy hook fails on one, instead of only `provider-http-400`.
18
+ - `rer deploy --remove --yes` removes what a custom deploy hook deployed under its own kit state file when the hook returned that file as `state`, and reads every resource back gone.
19
+
20
+ ### Upgrade notes
21
+
22
+ - A custom deploy hook that keeps its own kit state file returns it as `state` in its result (the kit's `deploy` result names it as `state`), so `rer deploy --remove --yes` can find what it deployed.
23
+ - A deployment that an earlier rer redeployed after its owner claim uploads its Worker once more on the next `rer deploy` (the fingerprint again names the retired setup token); repeats after that write nothing.
24
+
3
25
  ## 0.2.5
4
26
 
5
27
  - `rer deploy` with a seed's own deploy hook claims the hosted owner from what the hook returns, `{ deployed: true, origin }`, once the origin's `/health` names the checkout's commit, and prints the sign-in address. A hook that keeps its own deployment record (Penny's does) no longer ends in `missing-owner-receipt` with a live, unclaimed app; such a hook returns `setupToken` too when its Worker holds a setup token other than the `SETUP_TOKEN` rer passed it. A hook that reports no deployment, or whose app never names the commit, fails saying so and claims nothing.
package/global/README.md CHANGED
@@ -104,6 +104,9 @@ A seed that declares a run site prints one more line after those,
104
104
  `RER_SITE http://127.0.0.1:8788`: a local preview of its static run site (its
105
105
  marketing homepage, `/run` and docs) on the first free port above the app's. It
106
106
  stops with the app.
107
+ Later, `rer setup --owner-email YOU` (or `--answers`) with the real owner
108
+ replaces that local owner in place and keeps all local data, saying so in one
109
+ line; a checkout whose database holds any other owner is still refused.
107
110
  It never prompts and never re-runs setup on a checkout that is already set up. A
108
111
  setup a launch started that was stopped or failed is run again by the next
109
112
  `rer dev`, keeping the owner and origin it saved, unless a setup has finished
@@ -2,7 +2,7 @@
2
2
  import { execFile } from 'node:child_process';
3
3
  import { stat } from 'node:fs/promises';
4
4
  import { createServer } from 'node:net';
5
- import { basename, join } from 'node:path';
5
+ import { join } from 'node:path';
6
6
  import { promisify } from 'node:util';
7
7
  import { listeningPorts } from '../../onboarding/process-diagnostics.mjs';
8
8
  import { LaunchFailure } from './failure.mjs';
@@ -64,11 +64,6 @@ export async function setupNeeded(root, described, last) {
64
64
  return await finishedSince(root, described, last.at) ? undefined : 'resume';
65
65
  }
66
66
 
67
- export function localOwner(root) {
68
- const label = basename(root).toLowerCase().replace(/[^a-z0-9-]+/g, '-').replace(/^-+|-+$/g, '').slice(0, 63) || 'checkout';
69
- return `owner@${label}.test`;
70
- }
71
-
72
67
  async function bindable(host, port) {
73
68
  const socket = createServer();
74
69
  try { await new Promise((resolve, reject) => { socket.once('error', reject); socket.listen({ port, host, exclusive: true }, resolve); }); return true; }
@@ -10,7 +10,8 @@ import { liveServers } from '../registry.mjs';
10
10
  import { checkCapacity, personEnvironment, pinPolicy } from './capacity.mjs';
11
11
  import { bringBackDoor, doorPlan } from './door.mjs';
12
12
  import { LaunchFailure } from './failure.mjs';
13
- import { describeCheckout, freePort, localOwner, needsInstall, portTaken, setupNeeded } from './facts.mjs';
13
+ import { describeCheckout, freePort, needsInstall, portTaken, setupNeeded } from './facts.mjs';
14
+ import { zeroSetupOwner } from '../../onboarding/local/owner.mjs';
14
15
  import { claimPort, installState, savedPorts, setupState } from './state.mjs';
15
16
  import { runVerb } from './steps.mjs';
16
17
  import { localDefaults } from './local-defaults.mjs';
@@ -67,7 +68,7 @@ export async function prepare({ root, args, env, report, directory, log, childre
67
68
  await step(setupState, ['setup', ...hostArgs], {}, setupEnv);
68
69
  } else if (setup === 'fresh' && plan.freshAtDoor) {
69
70
  // With the door enabled, a fresh checkout is set up at its door origin.
70
- const owner = localOwner(checkout);
71
+ const owner = zeroSetupOwner(checkout);
71
72
  report({ phase: 'setup', message: `setting up a local owner (${owner}) at its front-door address` });
72
73
  await step(setupState, ['setup', '--owner-email', owner, '--door'], { owner, door: true }, setupEnv);
73
74
  await bringBackDoor({ ...plan, atDoor: true }, env, report);
@@ -76,7 +77,7 @@ export async function prepare({ root, args, env, report, directory, log, childre
76
77
  // An interrupted setup resumes on the port it chose while that port is free.
77
78
  // A port another process takes between choosing it and setup refusing it is
78
79
  // passed over for the next free one; a port the person passed is kept.
79
- const owner = localOwner(checkout), explicit = flagValue(args, '--port');
80
+ const owner = zeroSetupOwner(checkout), explicit = flagValue(args, '--port');
80
81
  let from = last?.port;
81
82
  for (let attempt = 1; ; attempt++) {
82
83
  const held = explicit ? [] : [...(await liveServers(childEnv)).map(record => record.port), ...await savedPorts(checkout, childEnv)];
@@ -107,13 +107,14 @@ Ownership lives in a state file, by default `.rer/deploy/<environment>.json` und
107
107
  - **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.
108
108
 
109
109
  The CLI prints JSON: refusal codes and resource names only, never inputs, tokens or provider bodies.
110
+ A refused provider call also carries `providerRefusal` on the thrown error: the call (`PUT /workers/scripts/<name>`) and Cloudflare's own codes and messages, with the account id and token removed and each message cut to 300 characters. `rer deploy` names it when a custom deploy hook fails on one.
110
111
 
111
112
  ### rer deploy: inputs, the hosted owner, secret changes and removal
112
113
 
113
114
  `rer deploy` runs these steps for a seed whose adapter uses `ownerDeploy` from `cli/deploy.mjs`.
114
115
 
115
116
  - **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 a fresh random value for each secret field the manifest generates (`generate`), such as the session secret and the setup token; a value the Worker already holds is kept. A still-missing secret stops the run before any write with a message that names it.
116
- - **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. 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.
117
+ - **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.
117
118
  - **Secret changes.** `rer deploy --set-secret NAME` (value from the environment or `--env-file`, under the declaration's environment name) and `--unset-secret NAME` change one declared secret of the recorded Worker without a build. Before writing, rer records the starting version and the exact live names of all other secrets, never their values. Accepted or ambiguous writes retain that intent until readback confirms the change; explicit refusals clear it. An ambiguous failure, or a later command's preflight, can clear an unapplied intent only when the live deployment still matches the receipt and the newest listed version matches it too. A surviving intent blocks further mutations until consistency returns; retry the same command then. Recovery requires the recorded immediate successor (or the recorded confirming rotation's successor), the receipt's script etag and fingerprint, the intended binding's presence, and an unchanged set of other secret names. Ambiguous rotations require a confirming PUT before reporting success. Older intents without names may recover only from the exact starting version's historical bindings, with its id, etag and fingerprint verified; unavailable or malformed historical bindings refuse adoption. Each historical binding must have an exact provider type supported by this kit; unrecognized types cannot prove that a name was not a secret. Added, removed or renamed other secrets refuse deploy and removal before writes. Values remain opaque: these checks cannot distinguish an otherwise identical outside change to the pending binding.
118
119
  - **Removal.** `rer deploy --remove --yes` deletes what the state file says rer created for this environment: the Worker (schedules first; its Durable Objects go with it) and each D1, R2, KV and queue that is still the one rer created, after checking all of them before the first delete. A replaced or uncertain resource refuses the whole removal, except a resource whose create answer was lost: under this environment's derived name it is deleted once it is confirmed empty (a D1 with no tables, a KV namespace with no keys, an R2 bucket, which the provider refuses to delete while it holds objects); one holding data is refused as `uncertain-resource-not-empty`, and a queue, whose backlog rer cannot read, as `uncertain-resource-unverifiable` (delete it by hand if it is the empty one from the interrupted run). It then reads back that none is still listed and deletes the state file. An R2 bucket must be empty; a bucket with objects stays, the state file keeps it, and a later `--remove --yes` finishes. Resources rer did not create are never touched.
119
120
 
@@ -11,8 +11,10 @@ import { verifyHealth } from './health.mjs';
11
11
  /** Controller-owned plan, inert validated artifact bytes; no project imports or subprocesses.
12
12
  * `createResources` defaults to creating only without a prior receipt. Owner-account
13
13
  * mode creates owned resources itself first, then passes false. `uploadWithoutReceipt`
14
- * re-uploads an identical build when no receipt survived, instead of refusing the no-op. */
15
- export async function deploy({api,plan,artifact,artifactSha256,previousReceipt,repeatOnly=false,createResources=!previousReceipt,uploadWithoutReceipt=false,onReceipt,onHealth,readiness={},env={},fetch=globalThis.fetch,healthOptions={}}) {
14
+ * re-uploads an identical build when no receipt survived, instead of refusing the no-op.
15
+ * `declaredSecrets` (default `plan.secrets`) are the secrets the fingerprint names: owner mode
16
+ * passes the declaration's, so retiring the spent setup token leaves the build unchanged. */
17
+ export async function deploy({api,plan,artifact,artifactSha256,previousReceipt,repeatOnly=false,createResources=!previousReceipt,uploadWithoutReceipt=false,onReceipt,onHealth,readiness={},env={},fetch=globalThis.fetch,healthOptions={},declaredSecrets=plan.secrets}) {
16
18
  validatePlan(plan); validateArtifact(artifact);
17
19
  await verifyServiceGrants(api, plan);
18
20
  for (const item of plan.d1) validateMigrations(item.migrations);
@@ -24,7 +26,7 @@ export async function deploy({api,plan,artifact,artifactSha256,previousReceipt,r
24
26
  const secrets = await secretBindings(api,plan.worker,plan,env,Boolean(existing));
25
27
  const resources = await reconcileResources(api,plan,{create:createResources});
26
28
  const baseConfig = renderConfig(plan,resources,api.accountId,artifact.source.sha,'',artifact.main,artifact.assets.length > 0);
27
- const fingerprint = hash({plan,config:baseConfig,source:artifact.source,modules:artifact.modules.map(({path,sha256}) => ({path,sha256})),assets:artifact.assets.map(({path,sha256}) => ({path,sha256}))});
29
+ const fingerprint = hash({plan:{...plan,secrets:declaredSecrets},config:baseConfig,source:artifact.source,modules:artifact.modules.map(({path,sha256}) => ({path,sha256})),assets:artifact.assets.map(({path,sha256}) => ({path,sha256}))});
28
30
  const config = renderConfig(plan,resources,api.accountId,artifact.source.sha,fingerprint,artifact.main,artifact.assets.length > 0);
29
31
  const bindings = bindingsFor(config,resources,plan);
30
32
  const namespaces = await durableNamespaces(api,plan);
@@ -16,6 +16,14 @@ export function deployDiagnostic(error, redact) {
16
16
  ...(detail.providerCodes?.length ? {providerCodes:detail.providerCodes} : {}),
17
17
  output:(detail.output ? (redact ? clean(detail.output) : '(provider output withheld; rer deploy provides redacted details)') : '(no provider output)').split(/\r?\n/).slice(0,8).map(line=>line.slice(0,500)).join('\n')};
18
18
  }
19
+ /** One line naming the provider call that was refused and what Cloudflare said, from
20
+ * the error's own `providerRefusal` (set by any copy of the kit); undefined otherwise. */
21
+ export function providerRefusal(error, redact = String) {
22
+ const refusal = error?.providerRefusal;
23
+ if (typeof refusal?.operation !== 'string' || !Array.isArray(refusal.errors)) return undefined;
24
+ const said = refusal.errors.map(item => [item?.code, typeof item?.message === 'string' ? redact(item.message).slice(0,300) : undefined].filter(part => part !== undefined && part !== '').join(' ')).filter(Boolean).slice(0,3);
25
+ return `Cloudflare refused ${redact(refusal.operation).slice(0,200)}${said.length ? `: ${said.join('; ')}` : ''}`;
26
+ }
19
27
  function operation(path, options = {}) {
20
28
  const write = options.method && options.method !== 'GET';
21
29
  if (/\/d1\/database\/[^/]+\/query/.test(path)) return 'migrate D1';
@@ -82,7 +82,9 @@ export async function main(argv = process.argv.slice(2), env = process.env, {fet
82
82
  }
83
83
  // Dispatch is the provider's: on some accounts a new Cron starts only at the account scheduler's next refresh.
84
84
  if (plan.crons.length) notice(cronNotice);
85
- const {receipt,created,sentSecrets} = await ownerDeploy({api,target,plan,artifact,statePath,env,fetch,healthOptions,settle}).catch(error => {
85
+ // The fingerprint names every declared secret, retired ones too: an untouched repeat after the claim is a no-op.
86
+ const declaredSecrets = current === declaration ? plan.secrets : ownerPlan(target,declaration,artifact,{localOnlyKeys}).secrets;
87
+ const {receipt,created,sentSecrets} = await ownerDeploy({api,target,plan,artifact,statePath,env,fetch,healthOptions,settle,declaredSecrets}).catch(error => {
86
88
  api.annotateFailure(error,error.message.startsWith('missing-secret-') ? 'secrets' : undefined);
87
89
  throw error;
88
90
  });
@@ -338,15 +338,15 @@ export async function withStateLock(path, run) {
338
338
 
339
339
  /** Find or create every declared resource under the owner's account, migrate, upload and check health.
340
340
  * Ownership preflight precedes provider writes. A re-run of the same build writes nothing. */
341
- export async function ownerDeploy({api: provider, target, plan, artifact, statePath, env = {}, fetch = globalThis.fetch, healthOptions = {}, readiness = {}, settle = {}}) {
341
+ export async function ownerDeploy({api: provider, target, plan, artifact, statePath, env = {}, fetch = globalThis.fetch, healthOptions = {}, readiness = {}, settle = {}, declaredSecrets = plan.secrets}) {
342
342
  assert(typeof statePath === 'string' && statePath.length, 'missing-owner-state-path');
343
343
  const api = withSettledLists(withScopeHints(provider),settle);
344
344
  assert(target?.accountId === api.accountId, 'owner-account-mismatch');
345
345
  validatePlan(plan); assertOwnerNames(target, plan);
346
346
  for (const item of plan.d1) validateMigrations(item.migrations);
347
- return withStateLock(statePath, () => deployLocked({api, target, plan, artifact, statePath, env, fetch, healthOptions, readiness, settle}));
347
+ return withStateLock(statePath, () => deployLocked({api, target, plan, artifact, statePath, env, fetch, healthOptions, readiness, settle, declaredSecrets}));
348
348
  }
349
- async function deployLocked({api, target, plan, artifact, statePath, env, fetch, healthOptions, readiness, settle}) {
349
+ async function deployLocked({api, target, plan, artifact, statePath, env, fetch, healthOptions, readiness, settle, declaredSecrets}) {
350
350
  const state = await readOwnerState(statePath, target);
351
351
  const save = () => writeOwnerState(statePath, state);
352
352
  if (await settlePendingSecret(api, target.worker, state, {preflight:true})) await save();
@@ -395,7 +395,7 @@ async function deployLocked({api, target, plan, artifact, statePath, env, fetch,
395
395
  return result;
396
396
  }};
397
397
  const receipt = await deploy({api:observed, plan, artifact, artifactSha256:hash(artifact), previousReceipt:state.receipt ?? undefined,
398
- createResources:false, uploadWithoutReceipt:true, env, fetch, healthOptions, readiness,
398
+ createResources:false, uploadWithoutReceipt:true, env, fetch, healthOptions, readiness, declaredSecrets,
399
399
  onReceipt: async candidate => { if (candidate.changed || !state.receipt) { state.receipt = candidate; delete state.pendingUpload; delete state.pendingSecret; await save(); } },
400
400
  // Keep each first-health attempt beside the identity it belongs to.
401
401
  onHealth: async candidate => { if (candidate.changed) { state.receipt = candidate; await save(); } }});
@@ -56,6 +56,13 @@ export function cloudflare({ accountId, token, fetch: request = globalThis.fetch
56
56
  if (!response.ok || payload?.success === false) {
57
57
  const error = new Error(response.ok ? 'provider-unsuccessful-or-malformed' : `provider-http-${response.status}`);
58
58
  error.status = response.status;
59
+ // What Cloudflare refused, on the error itself so any caller (a custom hook
60
+ // with its own copy of the kit too) can say it: the call, and Cloudflare's own
61
+ // codes and messages, without credentials and bounded.
62
+ const bounded = text => redactAuth(text).replace(/[\x00-\x1f\x7f-\x9f]+/g,' ').trim().slice(0,300);
63
+ const said = (Array.isArray(payload?.errors) ? payload.errors : []).filter(x => Number.isSafeInteger(x?.code) || typeof x?.message === 'string').slice(0,3)
64
+ .map(x => ({...(Number.isSafeInteger(x.code) ? {code:x.code} : {}),...(typeof x.message === 'string' ? {message:bounded(x.message)} : {})}));
65
+ error.providerRefusal = {operation:`${method} ${path.split('?')[0]}`,errors:said.length || payload !== undefined || !output.trim() ? said : [{message:bounded(output.trim().split('\n')[0])}]};
59
66
  throw recordDeployFailure(error,{providerCodes:(Array.isArray(payload?.errors) ? payload.errors : []).filter(x => Number.isSafeInteger(x?.code)).map(x=>x.code).slice(0,8),
60
67
  output:redactAuth(Array.isArray(payload?.errors) ? payload.errors.filter(x=>typeof x?.message==='string').map(x=>x.message).join('\n') : output)});
61
68
  }
@@ -11,7 +11,9 @@ export async function identity() {
11
11
  const token = randomUUID(), socket = join(tmpdir(), `rer-job-${token}.sock`);
12
12
  // Darwin's TMPDIR can be long; use the short system temporary directory then.
13
13
  const path = Buffer.byteLength(socket) < 100 ? socket : `/tmp/rer-job-${token}.sock`;
14
- const server = createServer(client => { client.end(token); });
14
+ // A prober that timed out or exited may close before the answer is written;
15
+ // the prober reports that itself, so the answer's EPIPE or ECONNRESET is dropped.
16
+ const server = createServer(client => { client.on('error', () => {}); client.end(token); });
15
17
  await new Promise((resolve, reject) => { server.once('error', reject); server.listen(path, resolve); });
16
18
  await chmod(path, 0o600);
17
19
  const { title, ...processIdentity } = await processInfo(process.pid);
@@ -23,7 +23,8 @@ export async function callerPolicy(env=process.env) {
23
23
  const lifetime=await identity(),token=randomUUID(),path=`/tmp/rer-policy-${token}.sock`;
24
24
  // An invalid inherited claim fails closed even when the child changes CI.
25
25
  const ci=!value&&env.CI==='true';
26
- const server=createServer(socket=>socket.end(JSON.stringify({token,ci})));
26
+ // As with identity: a prober that closed first reports that itself.
27
+ const server=createServer(socket=>{socket.on('error',()=>{});socket.end(JSON.stringify({token,ci}));});
27
28
  await new Promise((resolve,reject)=>{server.once('error',reject);server.listen(path,resolve);});await chmod(path,0o600);
28
29
  return {ci,environment:{RER_JOB_POLICY:JSON.stringify({path,token,owner:lifetime.info})},async close(){await new Promise(resolve=>server.close(resolve));await unlink(path).catch(error=>{if(error.code!=='ENOENT')throw error;});await lifetime.close();}};
29
30
  }
@@ -124,11 +124,20 @@ export async function replaceSavedOrigin(root, options, origin) {
124
124
  return rewriteOrigin(root, options, (await readSettings(root, options)).values, origin);
125
125
  }
126
126
 
127
- async function rewriteOrigin(root, options, values, origin) {
128
- const key = options.originKey ?? 'AUTH_ORIGIN';
129
- const current = await readSettings(root, options), format = options.format ?? 'dotenv', merged = { ...values, [key]: origin };
130
- const text = format === 'json' ? JSON.stringify(merged, null, 1) + '\n' : current.text.replace(new RegExp(`^${key}=.*$`, 'm'), `${key}=${dotenvValue(origin)}`);
131
- if (format !== 'json' && localVariables(text)[key] !== origin) throw new Error(`Could not move ${key} in ${options.file ?? '.dev.vars'}; put ${key}=${origin} on its own line.`);
127
+ // Rewrite only one saved setting (setup replacing the zero-setup owner). The
128
+ // caller holds the local operation lock.
129
+ export async function replaceSavedSetting(root, options, key, value) {
130
+ return rewriteSetting(root, options, (await readSettings(root, options)).values, key, value);
131
+ }
132
+
133
+ function rewriteOrigin(root, options, values, origin) {
134
+ return rewriteSetting(root, options, values, options.originKey ?? 'AUTH_ORIGIN', origin);
135
+ }
136
+
137
+ async function rewriteSetting(root, options, values, key, value) {
138
+ const current = await readSettings(root, options), format = options.format ?? 'dotenv', merged = { ...values, [key]: value };
139
+ const text = format === 'json' ? JSON.stringify(merged, null, 1) + '\n' : current.text.replace(new RegExp(`^${key}=.*$`, 'm'), `${key}=${dotenvValue(value)}`);
140
+ if (format !== 'json' && localVariables(text)[key] !== value) throw new Error(`Could not change ${key} in ${options.file ?? '.dev.vars'}; put ${key}=${value} on its own line.`);
132
141
  await writePrivateFile(current.path, text);
133
142
  return merged;
134
143
  }
@@ -1,20 +1,27 @@
1
- import {readdir,lstat} from 'node:fs/promises';
2
- import {join} from 'node:path';
1
+ import {readdir,lstat,realpath} from 'node:fs/promises';
2
+ import {basename,join} from 'node:path';
3
3
  import {DatabaseSync} from 'node:sqlite';
4
4
 
5
- // Read only the canonical local D1 files, before settings/build/migrations can
6
- // mutate anything. An unrelated database does not establish an owner claim.
7
- export async function localOwners(root){
8
- const found=[];
5
+ // The owner the zero-setup `rer dev` gives a checkout before its real owner is known.
6
+ export function zeroSetupOwner(checkout){
7
+ const label=basename(checkout).toLowerCase().replace(/[^a-z0-9-]+/g,'-').replace(/^-+|-+$/g,'').slice(0,63)||'checkout';
8
+ return `owner@${label}.test`;
9
+ }
10
+ async function databases(root){
9
11
  let directory=root;
10
12
  for(const part of ['.wrangler','state','v3','d1','miniflare-D1DatabaseObject']){
11
13
  directory=join(directory,part);let status;try{status=await lstat(directory);}catch(error){if(error.code==='ENOENT')return []; throw error;}
12
14
  if(status.isSymbolicLink()||!status.isDirectory())throw Error('Canonical local state is unsafe. Preserve it and recover its placement before setup.');
13
15
  }
14
- for(const file of await readdir(directory,{withFileTypes:true})){
15
- if(!file.isFile()||!file.name.endsWith('.sqlite'))continue;
16
+ return (await readdir(directory,{withFileTypes:true})).filter(file=>file.isFile()&&file.name.endsWith('.sqlite')).map(file=>join(directory,file.name));
17
+ }
18
+ // Read only the canonical local D1 files, before settings/build/migrations can
19
+ // mutate anything. An unrelated database does not establish an owner claim.
20
+ export async function localOwners(root){
21
+ const found=[];
22
+ for(const path of await databases(root)){
16
23
  let db,owners=[];
17
- try{db=new DatabaseSync(join(directory,file.name),{readOnly:true});
24
+ try{db=new DatabaseSync(path,{readOnly:true});
18
25
  const tables=new Set(db.prepare("SELECT name FROM sqlite_master WHERE type='table'").all().map(row=>row.name));
19
26
  if(tables.has('oa_operators'))owners=db.prepare("SELECT email FROM oa_operators WHERE role='owner' AND status='active'").all();
20
27
  }finally{db?.close();}
@@ -22,13 +29,31 @@ export async function localOwners(root){
22
29
  }
23
30
  return [...new Set(found)];
24
31
  }
32
+ // Returns the existing owners, and `placeholder` when the canonical database's
33
+ // only owner is still this checkout's zero-setup owner: setup replaces it.
25
34
  export async function assertLocalOwner(root,email,failure=message=>Error(message),inspect,setting='private owner email setting'){
26
35
  const owners=inspect?await inspect(root):await localOwners(root);
27
36
  if(!Array.isArray(owners)||owners.some(owner=>typeof owner!=='string'))throw failure('The localOwner hook must return existing owner email addresses without changing state.');
37
+ const placeholder=!inspect&&owners.length===1&&owners[0].toLowerCase()===zeroSetupOwner(await realpath(root))?owners[0]:undefined;
38
+ if(placeholder)return {owners,placeholder};
28
39
  if(owners.length&&!owners.some(owner=>owner.toLowerCase()===email.toLowerCase())){
29
40
  const address=safeOwner(owners[0]);
30
41
  throw failure(`Local database already belongs to ${address}. Restore ${setting} to ${address}, then run rer setup --owner-email ${address}; or back up data, run rer dev --stop, then rer reset --yes followed by rer setup --owner-email ${safeOwner(email)}. Reset deletes local data. Existing data and private settings were kept.`);
31
42
  }
32
- return owners;
43
+ return {owners};
44
+ }
45
+ // The placeholder owner's own row takes the real owner's address, so every
46
+ // record that names the owner by id stays theirs. Its version moves on, which
47
+ // retires sign-in links issued to the placeholder.
48
+ export async function replaceLocalOwner(root,from,to,failure=message=>Error(message)){
49
+ for(const path of await databases(root)){
50
+ const db=new DatabaseSync(path);
51
+ try{
52
+ const tables=new Set(db.prepare("SELECT name FROM sqlite_master WHERE type='table'").all().map(row=>row.name));
53
+ if(!tables.has('oa_operators'))continue;
54
+ if(db.prepare('SELECT 1 FROM oa_operators WHERE lower(email)=lower(?) AND lower(email)<>lower(?)').get(to,from))throw failure(`${safeOwner(to)} already has an account in the local database, so the zero-setup owner ${safeOwner(from)} was kept. Run rer setup --owner-email ${safeOwner(from)}, or back up data and run rer reset --yes.`);
55
+ db.prepare("UPDATE oa_operators SET email=?,version=version+1 WHERE lower(email)=lower(?) AND role='owner' AND status='active'").run(to,from);
56
+ }finally{db.close();}
57
+ }
33
58
  }
34
59
  export const safeOwner=email=>email.length<=254&&/^[a-zA-Z0-9.!+_%\-]+@[a-zA-Z0-9\-]+(?:\.[a-zA-Z0-9\-]+)+$/.test(email)?email:'<existing-owner-email>';
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@runeditrun/rer",
3
- "version": "0.2.5",
3
+ "version": "0.2.7",
4
4
  "description": "The rer command: install, set up, run and launch Run Edit Run checkouts.",
5
5
  "license": "MIT",
6
6
  "type": "module",