@runeditrun/rer 0.2.42 → 0.2.44

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (58) hide show
  1. package/README.md +21 -15
  2. package/cli/README.md +3 -1
  3. package/cli/browser-runtime.mjs +17 -8
  4. package/cli/business/command.mjs +1 -1
  5. package/cli/business/keychain.mjs +1 -1
  6. package/cli/business/lease.mjs +1 -1
  7. package/cli/business/questions.mjs +2 -2
  8. package/cli/contract.mjs +1 -1
  9. package/cli/deploy-command.mjs +12 -0
  10. package/cli/deploy-readiness.mjs +2 -2
  11. package/cli/deploy.mjs +17 -4
  12. package/cli/hydration/browser.mjs +2 -2
  13. package/cli/lifecycle.mjs +18 -5
  14. package/cli/main.mjs +1 -0
  15. package/cli/parse.mjs +9 -3
  16. package/cli/port.mjs +3 -3
  17. package/cli/portability-worker.mjs +3 -1
  18. package/cli/portability.mjs +7 -3
  19. package/cli/sqlite-notice.mjs +11 -0
  20. package/global/CHANGELOG.md +20 -0
  21. package/global/README.md +21 -15
  22. package/global/cli/install.mjs +9 -4
  23. package/global/cli/path-link.mjs +42 -9
  24. package/global/cli/repository.mjs +4 -1
  25. package/global/launch/facts.mjs +3 -3
  26. package/global/main.mjs +5 -1
  27. package/global/rer.mjs +1 -1
  28. package/global/run.mjs +64 -0
  29. package/global/update/command.mjs +1 -1
  30. package/install.sh +8 -7
  31. package/modules/dependencies/README.md +5 -2
  32. package/modules/dependencies/index.mjs +4 -3
  33. package/modules/dependencies/protocol.mjs +7 -5
  34. package/modules/deploy-kit/README.md +1 -0
  35. package/modules/deploy-kit/owner-cli.mjs +8 -6
  36. package/modules/deploy-kit/owner-secret-copy.mjs +38 -0
  37. package/modules/deploy-kit/owner-secret-names.mjs +1 -1
  38. package/modules/deploy-kit/owner-secret.mjs +39 -18
  39. package/modules/deploy-kit/owner.mjs +23 -14
  40. package/modules/deploy-kit/provider.mjs +20 -3
  41. package/modules/operator-auth/README.md +5 -0
  42. package/modules/operator-auth/accounts/display-name.mjs +23 -0
  43. package/modules/operator-auth/identity/oidc/config.mjs +10 -8
  44. package/modules/operator-auth/index.d.mts +2 -0
  45. package/modules/operator-auth/routes.mjs +4 -3
  46. package/modules/operator-auth/service.mjs +2 -0
  47. package/modules/operator-auth/signin/index.mjs +3 -3
  48. package/modules/portability/README.md +13 -1
  49. package/modules/portability/import.mjs +19 -7
  50. package/modules/portability/legacy-safety.mjs +4 -20
  51. package/modules/portability/restore-safety.mjs +23 -0
  52. package/modules/release/catalogue.mjs +1 -1
  53. package/onboarding/port-probe.mjs +4 -2
  54. package/onboarding/process-diagnostics.mjs +4 -1
  55. package/onboarding/schema/setup-validation.mjs +1 -1
  56. package/onboarding/theme.mjs +1 -1
  57. package/onboarding/ui/app.js +1 -1
  58. package/package.json +1 -1
@@ -39,6 +39,13 @@ async function writeLauncher(paths) {
39
39
  await rename(temporary, paths.launcher);
40
40
  }
41
41
 
42
+ // The next step, then (when needed) the exact line that puts rer on PATH, last.
43
+ // install.sh running a command itself, and rer update, set RER_INSTALL_NO_NEXT.
44
+ async function closing(paths) {
45
+ const advice = await pathAdvice(paths);
46
+ return `${process.env.RER_INSTALL_NO_NEXT ? '' : 'Next, start an app: rer dev <owner>/<repo>\n'}${advice ? advice + '\n' : ''}`;
47
+ }
48
+
42
49
  export async function install({ quiet = false } = {}) {
43
50
  const paths = layout(), manifest = ownManifest(), digest = await packageDigest(ownRoot);
44
51
  const name = `${manifest.version}-${digest.slice(0, 8)}`, channel = process.env.RER_INSTALL_CHANNEL === 'script' ? 'script' : 'npx';
@@ -52,8 +59,7 @@ export async function install({ quiet = false } = {}) {
52
59
  let present = false;
53
60
  try { present = await packageDigest(join(paths.versions, name)) === digest; } catch (error) { if (error.code !== 'ENOENT') throw error; }
54
61
  if (present && current === join('versions', name) && launcher.text === script && record?.channel === channel) {
55
- const advice = await pathAdvice(paths);
56
- if (!quiet) process.stdout.write(`rer ${manifest.version} is already current (${join(paths.versions, name)}). Nothing changed.\n${advice ? advice + '\n' : ''}`);
62
+ if (!quiet) process.stdout.write(`rer ${manifest.version} is already current (${join(paths.versions, name)}). Nothing changed.\n${await closing(paths)}`);
57
63
  return 0;
58
64
  }
59
65
  if (!present) { await rm(join(paths.versions, name), { recursive: true, force: true }); await copyVersion(paths, name); }
@@ -66,7 +72,6 @@ export async function install({ quiet = false } = {}) {
66
72
  for (const entry of await readdir(paths.versions)) if (!keep.has(entry) && !entry.startsWith('.staging-')) await rm(join(paths.versions, entry), { recursive: true, force: true });
67
73
  await writeFile(paths.record, JSON.stringify({ channel, links: record?.links ?? [], previous: previousName && keep.has(previousName) ? previousName : null }, null, 2) + '\n', { mode: 0o644 });
68
74
  if (launcher.text !== script) await writeLauncher(paths);
69
- const advice = await pathAdvice(paths);
70
- if (!quiet) process.stdout.write(`Installed rer ${manifest.version} in ${join(paths.versions, name)}.\n${paths.launcher} runs it.${previousName ? ` The previous version (${previousName}) is kept.` : ''}\n${advice ? advice + '\n' : ''}`);
75
+ if (!quiet) process.stdout.write(`Installed rer ${manifest.version} in ${join(paths.versions, name)}.\n${paths.launcher} runs it.${previousName ? ` The previous version (${previousName}) is kept.` : ''}\n${await closing(paths)}`);
71
76
  return 0;
72
77
  }
@@ -1,8 +1,7 @@
1
1
  // Installation writes only the canonical launcher in ~/.local/bin.
2
2
  // Other PATH commands are reported, never replaced or linked alongside.
3
- import { access, constants, lstat, readlink, stat } from 'node:fs/promises';
3
+ import { access, constants, lstat, readFile, readlink, stat } from 'node:fs/promises';
4
4
  import { basename, delimiter, join, resolve } from 'node:path';
5
- import { shellQuote } from '../../cli/node-runtime-cache.mjs';
6
5
 
7
6
  // Older installs recorded extra PATH links; uninstall can still remove those.
8
7
  export async function ownedPathLink(path, launcher) {
@@ -10,8 +9,43 @@ export async function ownedPathLink(path, launcher) {
10
9
  catch (error) { if (error.code === 'ENOENT' || error.code === 'EINVAL') return false; throw error; }
11
10
  }
12
11
 
12
+ const exists = path => access(path).then(() => true, () => false);
13
+
14
+ // The files a new terminal of this shell reads, and the one line that puts
15
+ // ~/.local/bin on PATH in this terminal and, through the startup file, in new
16
+ // ones. rer never runs it: the person does.
17
+ export async function shellStartup(home, env = process.env, platform = process.platform) {
18
+ const shell = basename(env.SHELL ?? ''), add = 'export PATH="$HOME/.local/bin:$PATH"';
19
+ if (shell === 'fish') return { files: ['.config/fish/config.fish', '.config/fish/fish_variables'].map(file => join(home, file)), line: 'fish_add_path ~/.local/bin' };
20
+ if (shell === 'zsh') {
21
+ const directory = env.ZDOTDIR || home;
22
+ return { files: ['.zshenv', '.zprofile', '.zshrc', '.zlogin'].map(file => join(directory, file)), line: `echo '${add}' >> ${env.ZDOTDIR ? '"$ZDOTDIR/.zshrc"' : '~/.zshrc'} && ${add}` };
23
+ }
24
+ const files = shell === 'bash' ? ['.bash_profile', '.bash_login', '.profile', '.bashrc'] : ['.profile'];
25
+ // macOS terminals start bash as a login shell, which reads only the first of
26
+ // its profiles that exists; elsewhere a terminal's bash reads ~/.bashrc.
27
+ let file = '.profile';
28
+ if (shell === 'bash' && platform !== 'darwin') file = '.bashrc';
29
+ else if (shell === 'bash') {
30
+ file = '.bash_profile';
31
+ for (const candidate of files.slice(0, 3)) if (await exists(join(home, candidate))) { file = candidate; break; }
32
+ }
33
+ return { files: files.map(name => join(home, name)), line: `echo '${add}' >> ~/${file} && ${add}` };
34
+ }
35
+
36
+ // Whether a startup file already puts ~/.local/bin on PATH for new terminals.
37
+ async function persistent(files) {
38
+ for (const file of files) {
39
+ try { if ((await readFile(file, 'utf8')).includes('.local/bin')) return true; }
40
+ catch (error) { if (!['ENOENT', 'EISDIR', 'EACCES'].includes(error.code)) throw error; }
41
+ }
42
+ return false;
43
+ }
44
+
45
+ // Empty when `rer` already runs this launcher in this terminal and new ones.
46
+ // Otherwise the advice ends with the exact line to run.
13
47
  export async function pathAdvice(paths, env = process.env) {
14
- const entries = [...new Set((env.PATH ?? '').split(delimiter).map(entry => resolve(entry)))];
48
+ const entries = [...new Set((env.PATH ?? '').split(delimiter).filter(Boolean).map(entry => resolve(entry)))];
15
49
  const bin = resolve(paths.bin), lines = [];
16
50
  let firstCommand;
17
51
  for (const directory of entries) {
@@ -24,11 +58,10 @@ export async function pathAdvice(paths, env = process.env) {
24
58
  lines.push(`Left existing rer at ${candidate} unchanged.`);
25
59
  } catch (error) { if (!['ENOENT', 'EACCES', 'ENOTDIR'].includes(error.code)) throw error; }
26
60
  }
27
- if (!entries.includes(bin) || firstCommand !== paths.launcher) {
28
- const command = basename(env.SHELL ?? '') === 'fish'
29
- ? `set -gx PATH ${shellQuote(paths.bin)} $PATH`
30
- : `export PATH=${shellQuote(paths.bin)}:"$PATH"`;
31
- lines.push(`Add ~/.local/bin to PATH in this shell: ${command}`);
32
- }
61
+ const startup = await shellStartup(paths.home, env);
62
+ const first = entries.includes(bin) && firstCommand === paths.launcher;
63
+ if (first && await persistent(startup.files)) return lines.join('\n');
64
+ const why = first ? 'New terminals will not find rer yet.' : firstCommand ? `Another rer (${firstCommand}) comes first on your PATH.` : 'rer is not on your PATH yet.';
65
+ lines.push(`${why} Run this line; it puts ~/.local/bin first on PATH in this terminal and in new ones:`, ` ${startup.line}`);
33
66
  return lines.join('\n');
34
67
  }
@@ -64,7 +64,10 @@ export async function checkoutRepository({ url, root, directory }) {
64
64
  }
65
65
  }
66
66
  await mkdir(resolve(root, '..'), { recursive: true });
67
- const code = await runCommand('git', ['clone', '--depth', '1', '--', url, root]);
67
+ // Every commit and release tag, so `git checkout <tag>` adopts an older
68
+ // release; file contents arrive when a checkout needs them (a host without
69
+ // partial clone sends them all).
70
+ const code = await runCommand('git', ['clone', '--filter=blob:none', '--', url, root]);
68
71
  if (code !== 0) throw refuse(`Could not clone into ${directory}. Check the git URL and access, then rerun the command.`);
69
72
  }
70
73
 
@@ -3,7 +3,7 @@ import { execFile } from 'node:child_process';
3
3
  import { stat } from 'node:fs/promises';
4
4
  import { join } from 'node:path';
5
5
  import { promisify } from 'node:util';
6
- import { inspectionContext } from '../../onboarding/process-diagnostics.mjs';
6
+ import { searchContext } from '../../onboarding/process-diagnostics.mjs';
7
7
  import { probePort } from '../../onboarding/port-probe.mjs';
8
8
  import { LaunchFailure } from './failure.mjs';
9
9
 
@@ -77,10 +77,10 @@ export async function portTaken(port) {
77
77
  export async function freePort(ports, claim, env = process.env) {
78
78
  const from = Number(env.RER_DEV_PORT_FROM ?? 8787);
79
79
  if (!Number.isInteger(from) || from < 1 || from > 65535) throw new LaunchFailure(2, 'RER_DEV_PORT_FROM must be a port number.');
80
- const held = new Set(ports.filter(Boolean)), context = inspectionContext();
80
+ const held = new Set(ports.filter(Boolean)), context = searchContext();
81
81
  for (let port = from; port <= 65535; port++) {
82
82
  if (held.has(port)) continue;
83
- const result = await probePort('127.0.0.1', port, { context, hosts: ['127.0.0.1', '::1'], anyAddress: true });
83
+ const result = await probePort('127.0.0.1', port, { context, hosts: ['127.0.0.1', '::1'], anyAddress: true, searching: true });
84
84
  if (!result.available) {
85
85
  if (performance.now() >= context.deadline) throw new LaunchFailure(4, `Could not find a free port from ${from} in time (system busy). Run rer dev again or pass rer dev --port PORT with a free port.`);
86
86
  continue;
package/global/main.mjs CHANGED
@@ -22,6 +22,9 @@ pins (installed first by any verb when node_modules holds another), else its ven
22
22
  RER_READY and a sign-in link. Without a terminal it returns once the app is
23
23
  ready and leaves it running (--detach and --foreground override); allow up
24
24
  to 10 minutes on a first launch, or rerun it to reattach. rer dev --stop stops it.
25
+ rer run SCRIPT [ARGS]
26
+ Run a package.json script with the pnpm and Node the checkout pins (rer keeps
27
+ them off PATH): where a project's docs say pnpm run X, run rer run X.
25
28
  rer list [DIR] The checkouts in DIR (default: here), newest first, with whether rer dev can
26
29
  launch them, whether they are set up, and their running URL. --json for data.
27
30
  rer business ... Pair a Business device, store local vendor keys, inspect tasks and disconnect.
@@ -66,6 +69,7 @@ export async function main(argv) {
66
69
  if (verb === 'cli') return (await import('./cli/command.mjs')).cliCommand(argv.slice(1));
67
70
  if (verb === 'list') return (await import('./list.mjs')).listCommand(argv.slice(1));
68
71
  if (verb === 'door') return (await import('./door/command.mjs')).doorCommand(argv.slice(1));
72
+ if (verb === 'run') return (await import('./run.mjs')).runScript(argv.slice(1));
69
73
  if (repositoryCommands[verb] && argv.includes('--help')) {
70
74
  const { help } = await import('../cli/parse.mjs');
71
75
  process.stdout.write(`${help(verb)}\n${repositoryCommands[verb].usage}\n${repositoryCommands[verb].effects}\n${repositoryHelp}`);
@@ -136,7 +140,7 @@ export async function main(argv) {
136
140
  }
137
141
  if (mode === 'package' && installsFirst.has(verb)) await (await import('./launch/install-pinned.mjs')).settledPin(target.root);
138
142
  if (verb === 'describe' && !argv.includes('--help')) return (await import('./cli/describe.mjs')).describeCommand(target);
139
- if (first && dispatcher(target.root).mode !== 'bundled' && ['install', 'verify'].includes(verb) && !argv.includes('--help') && !argv.includes('--site')) {
143
+ if (first && dispatcher(target.root).mode !== 'bundled' && verb === 'verify' && !argv.includes('--help') && !argv.includes('--site')) {
140
144
  const code = await (await import('./browser-runtime.mjs')).browserPreflight(target.root, target.args);
141
145
  if (code !== undefined) return code;
142
146
  }
package/global/rer.mjs CHANGED
@@ -26,7 +26,7 @@ if (process.platform === 'win32') {
26
26
  process.stderr.write('rer needs Node ' + minimum + ' or later; this is Node ' + process.versions.node + '. Install a newer Node, then run rer again.\n');
27
27
  process.exitCode = 1;
28
28
  } else {
29
- import('./main.mjs').then(function (module) { return module.main(process.argv.slice(2)); }).then(function (code) {
29
+ import('../cli/sqlite-notice.mjs').then(function () { return import('./main.mjs'); }).then(function (module) { return module.main(process.argv.slice(2)); }).then(function (code) {
30
30
  if (code !== undefined) process.exitCode = code;
31
31
  });
32
32
  }
package/global/run.mjs ADDED
@@ -0,0 +1,64 @@
1
+ // rer run SCRIPT [ARGS]: `pnpm run SCRIPT ARGS` in a checkout, with the pnpm
2
+ // and Node it pins. rer keeps both in its own cache, off PATH, so a project's
3
+ // documented `pnpm run ...` works as `rer run ...` right after rer install.
4
+ // A script that runs Playwright gets the checkout's browser first, on first need.
5
+ import { spawn } from 'node:child_process';
6
+ import { readFile } from 'node:fs/promises';
7
+ import { constants } from 'node:os';
8
+ import { delimiter, dirname, join } from 'node:path';
9
+ import { locate } from './checkout.mjs';
10
+
11
+ export const runUsage = `Usage: rer run [--cwd DIR] [SCRIPT [ARGS...]]
12
+ Runs a package.json script of this checkout as pnpm run SCRIPT ARGS would, with the
13
+ pnpm and Node the checkout pins (rer keeps them off PATH). Without SCRIPT it lists
14
+ the scripts. Where a project's docs say pnpm run X -- ARGS, run rer run X -- ARGS.
15
+ `;
16
+
17
+ // The checkout's pinned Node, when it differs from this one (RER_NODE_AUTO=0 keeps this one).
18
+ async function projectNode(root, env) {
19
+ const { projectNodePin, installedRuntime } = await import('../cli/node-runtime-discovery.mjs');
20
+ const version = await projectNodePin(root);
21
+ if (!version || version === process.versions.node || env.RER_NODE_AUTO === '0') return;
22
+ const { downloadRuntime } = await import('../cli/node-runtime-download.mjs');
23
+ const { missing, RerError } = await import('../cli/errors.mjs');
24
+ let binary = await installedRuntime(version);
25
+ try { binary ??= await downloadRuntime(version); }
26
+ catch (error) { if (error instanceof RerError) throw error; throw missing(`This project pins Node ${version}, which could not be fetched (${error.message}). Retry with a working connection, or set RER_NODE_AUTO=0 to use Node ${process.versions.node}.`); }
27
+ env.PATH = [dirname(binary), env.PATH].filter(Boolean).join(delimiter);
28
+ }
29
+
30
+ export async function runScript(args) {
31
+ let cwd;
32
+ if (['--help', '-h'].includes(args[0])) { process.stdout.write(runUsage); return 0; }
33
+ if (args[0] === '--cwd') {
34
+ cwd = args[1];
35
+ if (!cwd?.trim() || cwd.startsWith('-')) { process.stderr.write(`A folder is required for --cwd.\n${runUsage}`); return 2; }
36
+ args = args.slice(2);
37
+ }
38
+ const target = locate(cwd ? ['run', '--cwd', cwd] : ['run']);
39
+ if (!target.root || !['first-party', 'independent'].includes(target.profile)) {
40
+ process.stderr.write(`rer run runs inside a checkout: a folder with OPERATIONS.json at or above this one, or --cwd DIR.\n`);
41
+ return 2;
42
+ }
43
+ const { ensureProjectPnpm } = await import('../cli/project-pnpm.mjs');
44
+ const { RerError } = await import('../cli/errors.mjs');
45
+ try {
46
+ await ensureProjectPnpm(target.root, { report: text => process.stderr.write(text + '\n') });
47
+ await projectNode(target.root, process.env);
48
+ } catch (error) { if (!(error instanceof RerError)) throw error; process.stderr.write(error.message + '\n'); return error.exitCode; }
49
+ let scripts = {};
50
+ try { scripts = JSON.parse(await readFile(join(target.root, 'package.json'), 'utf8')).scripts ?? {}; } catch {}
51
+ if (args[0] && /\bplaywright\b/.test(scripts[args[0]] ?? '')) {
52
+ const code = await (await import('./browser-runtime.mjs')).browserPreflight(target.root, ['run']);
53
+ if (code !== undefined) return code;
54
+ }
55
+ const child = spawn('pnpm', ['run', ...args], { cwd: target.root, env: process.env, stdio: 'inherit' });
56
+ const forward = new Map(['SIGINT', 'SIGTERM', 'SIGHUP'].map(signal => [signal, () => child.kill(signal)]));
57
+ for (const [signal, handler] of forward) process.on(signal, handler);
58
+ try {
59
+ return await new Promise((resolve, reject) => {
60
+ child.once('error', reject);
61
+ child.once('exit', (code, signal) => resolve(code ?? 128 + (constants.signals[signal] ?? 0)));
62
+ });
63
+ } finally { for (const [signal, handler] of forward) process.off(signal, handler); }
64
+ }
@@ -82,7 +82,7 @@ export async function update(args) {
82
82
  }
83
83
  }
84
84
  if (channel === 'npm-global') return await npmGlobal(release.version);
85
- return await run(process.execPath, [join(work, 'package/global/rer.mjs'), 'cli', 'install'], { ...process.env, RER_INSTALL_CHANNEL: channel });
85
+ return await run(process.execPath, [join(work, 'package/global/rer.mjs'), 'cli', 'install'], { ...process.env, RER_INSTALL_CHANNEL: channel, RER_INSTALL_NO_NEXT: '1' });
86
86
  } catch (error) {
87
87
  if (!(error instanceof UpdateFailure)) throw error;
88
88
  process.stderr.write(`rer update: ${error.message} rer ${current} is still selected.\n`);
package/install.sh CHANGED
@@ -11,7 +11,8 @@
11
11
  # differently from this script's own check), and installs through the
12
12
  # package's own `rer cli install`: the same layout as
13
13
  # `npx -y @runeditrun/rer cli install`. A failure leaves any previous install
14
- # selected and working. It never edits shell profiles.
14
+ # selected and working. It never edits shell profiles: when ~/.local/bin is not
15
+ # on PATH for new terminals, its last line is the one to run that adds it.
15
16
  #
16
17
  # Needs curl and tar. If Node 22 or later is absent, installs the pinned official
17
18
  # Node release in rer's own data directory. macOS/Linux x64/arm64; Windows: WSL2.
@@ -139,13 +140,13 @@ if (process.argv[5] !== '' && Number(process.argv[5]) !== total) stop('the archi
139
140
  NODE
140
141
  mkdir "$work/stage"
141
142
  tar -xzf "$work/rer.tgz" -C "$work/stage" || fail "could not unpack rer $version; nothing was installed."
142
- RER_INSTALL_CHANNEL=script node "$work/stage/package/global/rer.mjs" cli install </dev/null \
143
+ # It ends with the next step and, when rer is not on PATH in new terminals,
144
+ # the exact line that puts it there (no npx: Node may be rer's own).
145
+ no_next=
146
+ if [ "$#" -gt 0 ]; then no_next=1; fi
147
+ RER_INSTALL_CHANNEL=script RER_INSTALL_NO_NEXT=$no_next node "$work/stage/package/global/rer.mjs" cli install </dev/null \
143
148
  || fail "rer cli install failed; any previous install is still selected."
144
- if [ "$#" -eq 0 ]; then
145
- # The same next step a Run page gives; no npx, since Node may be rer's own.
146
- printf 'Next, start a seed: rer dev <owner>/<repo>\n'
147
- return
148
- fi
149
+ if [ "$#" -eq 0 ]; then return; fi
149
150
  PATH="$HOME/.local/bin:$PATH"
150
151
  export PATH
151
152
  "$HOME/.local/bin/rer" "$@"
@@ -22,8 +22,11 @@ The unqualified JWKS URL selects the identity interface. The application retains
22
22
  its private key in the server database. Sector/install identity survives re-link,
23
23
  provider moves and export/import. Keys are isolated per interface.
24
24
 
25
- Provider origins and metadata endpoints require HTTPS. The application's local
26
- runtime explicitly permits loopback HTTP; deployed registration requires HTTPS.
25
+ Provider origins and metadata endpoints require HTTPS. Under `rer dev` (the
26
+ `local` option, which needs a loopback app origin) a provider may instead be
27
+ another locally running seed at `http://127.0.0.1`, `http://[::1]` or
28
+ `http://localhost` on any port, so two local seeds can link; every other `http`
29
+ address and every hosted deploy still requires HTTPS.
27
30
  Every provider serves `/.well-known/rer-dependencies` with the same graph fields,
28
31
  including its `provides` list and selected dependency provider origins. The CLI
29
32
  traverses these documents before setup effects, including selected optional
@@ -2,13 +2,14 @@ import { nativeDependencyAuthority } from './native.mjs';
2
2
  import { approveSetup, approveOwner, approvalFence, callbacksFor } from './approval.mjs';
3
3
  import { dependencyStore } from './store.mjs';
4
4
  import { publicKey, assertion, digest } from './crypto.mjs';
5
+ import { isLoopbackHost } from '../operator-auth/loopback.mjs';
5
6
  import { CALLBACK, INTERFACE, PATHS, NETWORK, insist, originOf, providerMetadata } from './protocol.mjs';
6
7
  import { readJson } from '../operator-auth/identity/oidc/network.mjs';
7
8
  import { readInput } from '../operator-auth/input.mjs';
8
9
  import { ownerFence, pinStatement } from './authority.mjs';
9
10
  export { INTERFACE, CALLBACK, PATHS } from './protocol.mjs';
10
11
  export function createDependencies({db,origin,name,provider,interfaces=[{interface:INTERFACE,provider,paths:PATHS}],provides=[],local=false,auth,claimOwner,clock=Date.now,fetch:fetcher=globalThis.fetch}) {
11
- originOf(origin,local);insist(Array.isArray(provides) && new Set(provides).size===provides.length && provides.every(value=>/^[a-z][a-z0-9-]*@[1-9][0-9]*$/.test(value)));
12
+ originOf(origin,local);insist(!local || isLoopbackHost(new URL(origin).hostname));insist(Array.isArray(provides) && new Set(provides).size===provides.length && provides.every(value=>/^[a-z][a-z0-9-]*@[1-9][0-9]*$/.test(value)));
12
13
  insist(Array.isArray(interfaces) && new Set(interfaces.map(d=>d.interface)).size===interfaces.length && interfaces.every(d=>/^[a-z][a-z0-9-]*@[1-9][0-9]*$/.test(d.interface) && Array.isArray(d.paths) && new Set(d.paths).size===d.paths.length && d.paths.every(p=>typeof p==='string' && /^\/[A-Za-z0-9_~/-]+$/.test(p) && !p.startsWith('//'))));
13
14
  const store=dependencyStore(db);
14
15
  const native=auth?.native?nativeDependencyAuthority(auth.accounts.dependencies):null;
@@ -34,7 +35,7 @@ export function createDependencies({db,origin,name,provider,interfaces=[{interfa
34
35
  const pendingPin=native?null:await store.first('SELECT provider_id AS id,issuer,client_id AS clientId,linked_at AS linkedAt FROM oa_provider_session_pins WHERE session_id=?',pending.approved_session);
35
36
  const initialApproval=await approvalFence(pending,contract,expected,callbacks,clock(),pendingPin,native);
36
37
  insist(await store.first(`SELECT 1 WHERE ${initialApproval.sql}`,...initialApproval.args),'local_owner_proof_required',403);
37
- const metadata=await providerMetadata(expected,fetcher,contract),installation=await store.installation(contract);
38
+ const metadata=await providerMetadata(expected,fetcher,contract,local),installation=await store.installation(contract);
38
39
  const codeDigest=await digest(expected+'\0'+data.code);
39
40
  const consumed=await store.first('INSERT INTO rer_dependency_codes(digest,created_at) VALUES(?,?) ON CONFLICT DO NOTHING RETURNING digest',codeDigest,clock());
40
41
  insist(consumed?.digest===codeDigest,'link_code_used',409);
@@ -101,7 +102,7 @@ export function createDependencies({db,origin,name,provider,interfaces=[{interfa
101
102
  insist(request.headers.get('origin')===origin,'invalid_link_origin',403);
102
103
  if(path==='/auth/dependencies/unlink')return await unlink(request);
103
104
  if(path==='/auth/dependencies/relink' || path==='/auth/dependencies/setup') {
104
- const input=await readInput(request),contract=input.interface??INTERFACE;originOf(input.issuer);const declared=interfaces.find(d=>d.interface===contract);insist(declared);
105
+ const input=await readInput(request),contract=input.interface??INTERFACE;originOf(input.issuer,local);const declared=interfaces.find(d=>d.interface===contract);insist(declared);
105
106
  const callbacks=callbacksFor(origin,declared);
106
107
  if(path==='/auth/dependencies/setup') await approveSetup({db,auth,request,input,contract,callbacks,clock});
107
108
  else await approveOwner({store,actor:await owner(request,'providers:relink'),input,contract,callbacks,clock,native});
@@ -6,19 +6,21 @@ export const CALLBACK = '/.well-known/rer-link/callback';
6
6
  export const PATHS = ['/auth/oidc/auth/callback','/auth/oidc/auth/logout'];
7
7
  export const NETWORK = { timeoutMs:5000 };
8
8
  export function insist(value, code = 'invalid_link', status = 400) { if (!value) throw Object.assign(new Error(code),{code,status}); }
9
+ // https always; plain http only to a loopback host while the app runs under `rer dev`.
10
+ const schemeAllowed=(u,local)=>u.protocol==='https:' || local && u.protocol==='http:' && isLoopbackHost(u.hostname);
9
11
  export function originOf(value, local = false) {
10
12
  let u;try { u=new URL(value); } catch { insist(false); }
11
- insist(u.origin===value && !u.username && !u.password && (u.protocol==='https:' || local && u.protocol==='http:' && isLoopbackHost(u.hostname)));
13
+ insist(u.origin===value && !u.username && !u.password && schemeAllowed(u,local));
12
14
  return u.origin;
13
15
  }
14
- export async function providerMetadata(issuer, fetcher, contract = INTERFACE) {
15
- originOf(issuer);
16
- const p={...PRESETS.auth,id:'auth',issuer,endpointOrigins:[issuer],tokenAuthMethod:'private_key_jwt',keyAlgorithm:'ES256',minimumVersion:MINIMUM_PROVIDER_VERSION};
16
+ export async function providerMetadata(issuer, fetcher, contract = INTERFACE, local = false) {
17
+ originOf(issuer,local);
18
+ const p={...PRESETS.auth,id:'auth',issuer,endpointOrigins:[issuer],local,tokenAuthMethod:'private_key_jwt',keyAlgorithm:'ES256',minimumVersion:MINIMUM_PROVIDER_VERSION};
17
19
  const oidc=contract===INTERFACE?await discover(fetcher,p,NETWORK):{};
18
20
  const link=await readJson(fetcher,`${issuer}/.well-known/rer-provider`,NETWORK);
19
21
  insist(link.issuer===issuer && (link.interface===contract || Array.isArray(link.provides) && new Set(link.provides).size===link.provides.length && link.provides.every(i=>typeof i==='string' && /^[a-z][a-z0-9-]*@[1-9][0-9]*$/.test(i)) && link.provides.includes(contract)) && link.version===1,'unsupported_link_interface',502);
20
22
  for (const name of ['initiate','redeem','deregister']) {
21
- const u=new URL(link[name]);insist(u.origin===issuer && u.protocol==='https:' && !u.search && !u.hash && !u.username && !u.password,'untrusted_link_endpoint',502);
23
+ const u=new URL(link[name]);insist(u.origin===issuer && schemeAllowed(u,local) && !u.search && !u.hash && !u.username && !u.password,'untrusted_link_endpoint',502);
22
24
  }
23
25
  return {...oidc,link};
24
26
  }
@@ -117,6 +117,7 @@ A transport failure carries `providerTransport`: the operation, sanitized endpoi
117
117
 
118
118
  - **Inputs.** Declared secrets come from the environment, then `--env-file FILE` (an owned 0600 file of `KEY=VALUE` lines), which wins. For a secret the Worker does not hold yet, rer supplies the setup manifest's owner email (`emailField`) from the local setup's private settings, and for each secret field the manifest generates (`generate`) the value rer keeps for this environment in `.rer/deploy/<environment>.secrets.env` (0600, ignored by Git), else a fresh random value, which rer keeps once the Worker holds it (the one-time setup token is always fresh and never kept); a value the Worker already holds is kept. The build runs with the checkout's local settings files moved aside, and a `dist/` holding a `.dev.vars*`, `.env*` or `*.env` file is refused by name before any provider request. A still-missing secret stops the run before any write with a message that names it, unless its declaration says `"optional": true`: then the deploy binds nothing for it and reports it as not set, and `--set-secret` adds it later.
119
119
  - **Hosted owner.** After deploy and health pass, rer claims the setup owner on the hosted app: it POSTs the setup token to the seed's standard owner step (`hooks.owner`, by default `/auth/bootstrap`). 303 means claimed; `409 already_initialized` means an owner was already claimed and is kept. Then rer deletes the token secret from the Worker, records the new Worker version in the state file, and lists the token in `retiredSecrets`, so later plans no longer declare it. The build fingerprint still names it, and the recorded claim stays as recorded, so an untouched repeat deploy writes nothing. A Worker that still holds a token rer did not upload in this run (an older deploy) first gets a fresh token through the same recorded secret change. Dependency approvals that need the token run before the claim. A seed with an owner step function, an identity-provider claim, or no declared token secret claims its owner its own way.
120
+ - **Several secrets at once.** `rer deploy --set-secret MAIL_API_KEY --set-secret MAIL_FROM` or `rer deploy --set-secret MAIL_API_KEY,MAIL_FROM` (likewise `--unset-secret A,B`) changes all of them in one new Worker version or none: a group of secrets is never half set. Every named secret must be declared and, for `--set-secret`, have its value in the environment or `--env-file`; otherwise rer names each missing one and changes nothing. One secret uses Cloudflare's secret call. Several are one copy of the live version through the Versions API (its own modules, assets and compatibility settings, every other binding inherited), then deployed at 100%: Cloudflare's per-secret calls each make a version, and its settings call can add secrets but not remove them (measured 17 October 2026). The copy carries a marker rer records first, so a copy whose answer was lost is recognised, and one uploaded but not deployed is deployed by the same command run again.
120
121
  - **Secret changes.** `rer deploy --set-secret NAME` (value from the environment or `--env-file`, under the declaration's environment name), `--unset-secret NAME` and `--rotate-secret NAME[,NAME]` (a fresh value for a secret rer generates, kept in `.rer/deploy/<environment>.secrets.env` once set) change declared secrets 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.
121
122
  - **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 D1 or KV whose create answer was lost: under this environment's derived name it is deleted once confirmed empty (a D1 with no tables, a KV namespace with no keys); one holding data is refused as `uncertain-resource-not-empty`, and an uncertain queue, whose backlog rer cannot read, as `uncertain-resource-unverifiable` (delete it by hand if it is the empty one from the interrupted run).
122
123
 
@@ -17,7 +17,7 @@ import { refuseLocalModels } from './local-only.mjs';
17
17
  import { publicOrigin } from './public-origin.mjs';
18
18
 
19
19
  export const cronNotice = 'This Worker has a Cron Trigger. Cloudflare may take up to about two hours to start its first scheduled run on some accounts.';
20
- const usage = 'usage: owner-cli.mjs deploy|health|remove|inspect|record-owner|signin --declaration <file> --environment <name> [--product <dir>] [--state <file>] [--outcome claimed|kept] | secret ... --set NAME|--unset NAME';
20
+ const usage = 'usage: owner-cli.mjs deploy|health|remove|inspect|record-owner|signin --declaration <file> --environment <name> [--product <dir>] [--state <file>] [--outcome claimed|kept] | secret ... --set NAME [--set NAME]|--unset NAME [--unset NAME]';
21
21
 
22
22
  /** The owner's committed source and existing local build. Run the seed's build first. */
23
23
  async function ownerArtifact(root, product) {
@@ -30,7 +30,7 @@ async function ownerArtifact(root, product) {
30
30
  /** Inputs: CLOUDFLARE_ACCOUNT_ID and CLOUDFLARE_API_TOKEN, plus the secrets the declaration names on first deploy. */
31
31
  export async function main(argv = process.argv.slice(2), env = process.env, {fetch = globalThis.fetch, cwd = process.cwd(), healthOptions, propagation, settle, localOnlyKeys = [], notice = line => console.error(line), onCreated} = {}) {
32
32
  let parsed;
33
- try { parsed = parseArgs({args:argv,allowPositionals:true,strict:true,options:{declaration:{type:'string'},environment:{type:'string'},product:{type:'string',default:''},state:{type:'string'},set:{type:'string'},unset:{type:'string'},outcome:{type:'string'}}}); }
33
+ try { parsed = parseArgs({args:argv,allowPositionals:true,strict:true,options:{declaration:{type:'string'},environment:{type:'string'},product:{type:'string',default:''},state:{type:'string'},set:{type:'string',multiple:true},unset:{type:'string',multiple:true},outcome:{type:'string'}}}); }
34
34
  catch { throw new Error('usage'); }
35
35
  const {positionals:[command,...rest],values} = parsed;
36
36
  if (!['deploy','health','secret','remove','inspect','record-owner','signin'].includes(command) || rest.length || !values.declaration || !values.environment) throw new Error('usage');
@@ -66,10 +66,12 @@ export async function main(argv = process.argv.slice(2), env = process.env, {fet
66
66
  const statePath = values.state ? resolve(root,values.state) : join(root,'.rer','deploy',`${target.environment}.json`);
67
67
  if (command === 'remove') return {ok:true,...await ownerRemove({api,target,statePath}).catch(error => { throw api.annotateFailure(error,'remove'); })};
68
68
  if (command === 'secret') {
69
- const binding = values.set ?? values.unset, item = (Array.isArray(declaration.secrets) ? declaration.secrets : []).find(entry => entry?.binding === binding);
70
- if (!item) { const error = new Error('undeclared-secret'); error.resource = `secret:${binding}`; throw error; }
71
- const value = values.set === undefined ? undefined : env[item.environment];
72
- return {ok:true,...await ownerSecret({api,target,statePath,binding,value,fetch,healthOptions}).catch(error => { throw api.annotateFailure(error,'secrets'); })};
69
+ // Every named secret is changed in one Worker version, or none is.
70
+ const named = [...new Set(values.set ?? values.unset)], declared = Array.isArray(declaration.secrets) ? declaration.secrets : [];
71
+ const undeclared = named.filter(binding => !declared.some(entry => entry?.binding === binding));
72
+ if (undeclared.length) { const error = new Error('undeclared-secret'); error.resource = undeclared.map(binding => `secret:${binding}`).join(', '); throw error; }
73
+ const changes = named.map(binding => ({binding, value:values.set === undefined ? undefined : env[declared.find(entry => entry?.binding === binding).environment]}));
74
+ return {ok:true,...await ownerSecret({api,target,statePath,changes,fetch,healthOptions}).catch(error => { throw api.annotateFailure(error,'secrets'); })};
73
75
  }
74
76
  // A secret rer retired (the spent setup token) is no longer part of the plan.
75
77
  const state = await settleOwnerState({api,target,statePath});
@@ -0,0 +1,38 @@
1
+ import { assert, uuid } from './validation.mjs';
2
+
3
+ // Several secrets change as ONE Worker version, so a half-changed group never runs.
4
+ // Cloudflare's per-secret calls each deploy a version of their own, and its settings
5
+ // call adds secrets but never removes one (both measured on 17 October 2026). A copy
6
+ // of the live version does both: its own modules, assets and compatibility settings,
7
+ // every binding inherited except the named secrets, which it sets or leaves out. The
8
+ // copy carries a marker rer saved before uploading it, so a copy whose answer was lost,
9
+ // or that was uploaded but not yet deployed, is recognised as this change and no other.
10
+ export const copyMessage = marker => `rer-secrets:${marker}`;
11
+
12
+ /** Upload the copy (not yet deployed) and return its version id. */
13
+ export async function uploadSecretCopy(api, worker, live, {changes, marker}) {
14
+ const {parts, entry} = await api.workerContent(worker, live.versionId);
15
+ const runtime = live.version?.resources?.script_runtime, bindings = live.version?.resources?.bindings;
16
+ assert(typeof runtime?.compatibility_date === 'string' && Array.isArray(bindings), 'invalid-active-version');
17
+ const named = new Set(changes.map(change => change.binding));
18
+ const metadata = {main_module:entry, compatibility_date:runtime.compatibility_date, compatibility_flags:runtime.compatibility_flags ?? [],
19
+ bindings:[...bindings.filter(row => !named.has(row.name)).map(row => ({type:'inherit',name:row.name})),
20
+ ...changes.filter(change => change.value !== undefined).map(change => ({type:'secret_text',name:change.binding,text:change.value}))],
21
+ keep_assets:true, annotations:{'workers/message':copyMessage(marker)}};
22
+ const data = new FormData();
23
+ data.set('metadata', new Blob([JSON.stringify(metadata)], {type:'application/json'}));
24
+ for (const [name, file] of parts) data.set(name, file, name);
25
+ const version = await api.request(`/workers/scripts/${worker}/versions?bindings_inherit=strict`, {method:'POST', body:data});
26
+ assert(uuid(version?.id), 'invalid-secret-copy');
27
+ return version.id;
28
+ }
29
+
30
+ /** Send all traffic to the copy. */
31
+ export const deploySecretCopy = (api, worker, versionId) => api.request(`/workers/scripts/${worker}/deployments`, {method:'POST', body:{strategy:'percentage', versions:[{version_id:versionId, percentage:100}]}});
32
+
33
+ /** The newest version is this change's copy, uploaded right after the receipt's version and not deployed. */
34
+ export async function undeployedCopy(api, worker, {pendingSecret, receipt}, versions) {
35
+ if (!pendingSecret.copy || versions[1]?.id !== receipt.provider.versionId || !uuid(versions[0]?.id)) return null;
36
+ const copy = await api.request(`/workers/scripts/${worker}/versions/${versions[0].id}`);
37
+ return copy?.id === versions[0].id && copy.annotations?.['workers/message'] === copyMessage(pendingSecret.copy) ? copy.id : null;
38
+ }
@@ -27,5 +27,5 @@ export async function pendingSecretNames(api, worker, {pendingSecret, receipt})
27
27
  if (anchor?.id !== pendingSecret.versionId || anchor?.resources?.script?.etag !== receipt.provider.etag
28
28
  || !Array.isArray(bindings) || !bindings.every(row => row && typeof row === 'object' && !Array.isArray(row) && historicalBindingTypes.has(row.type))
29
29
  || !validSecretNames(bindings.map(row => row.name)) || deployedFingerprint({bindings}) !== receipt.fingerprint) return null;
30
- return bindings.filter(row => row.type === 'secret_text' && row.name !== pendingSecret.binding).map(row => row.name);
30
+ return bindings.filter(row => row.type === 'secret_text' && !pendingSecret.bindings.includes(row.name)).map(row => row.name);
31
31
  }
@@ -1,45 +1,64 @@
1
+ import { randomBytes } from 'node:crypto';
1
2
  import { assert, identifier } from './validation.mjs';
2
3
  import { activeWorker } from './worker.mjs';
3
- import { secretNames } from './owner-secret-names.mjs';
4
+ import { secretNames, validSecretNames } from './owner-secret-names.mjs';
4
5
  import { waitHealth } from './health-request.mjs';
5
6
  import { definiteProviderRefusal } from './provider.mjs';
6
7
  import { readOwnerState, writeOwnerState, withStateLock, withScopeHints, sameDeployment, refuse, recordSecretChange, settlePendingSecret } from './owner.mjs';
8
+ import { uploadSecretCopy, deploySecretCopy } from './owner-secret-copy.mjs';
7
9
 
8
- /** Set (`value` given) or remove one Worker secret of the owner's last deployment, then
9
- * record the Worker version the change made in the state file, so the next deploy
10
+ /** Set (each `value` given) or remove Worker secrets of the owner's last deployment as one
11
+ * new Worker version, then record that version in the state file, so the next deploy
10
12
  * recognises its own Worker. A Worker someone else replaced is refused untouched.
13
+ * One secret uses Cloudflare's secret call; several are one copy of the live version
14
+ * (owner-secret-copy.mjs). Every change sets all its secrets or removes all of them.
11
15
  * The change is recorded as pending first: if the provider applies it but rer never
12
16
  * sees it settle, a later run can recognise its immediate successor (see settlePendingSecret).
13
17
  * Both success and ambiguous failure read back for up to `windowMs`. An explicit refusal
14
18
  * clears the pending record. An accepted write keeps its intent until confirmed.
15
19
  * An ambiguous failure clears it only when readback corroborates that the receipt's
16
- * deployment is still live. An ambiguous rotation
20
+ * deployment is still live. An ambiguous one-secret rotation
17
21
  * re-PUTs the value before accepting its successor as proof of the rotation.
18
22
  * A removed declared secret is retired: later plans omit it until it is set again. */
19
- export async function ownerSecret({api: provider, target, statePath, binding, value, fetch = globalThis.fetch, healthOptions = {}, windowMs = 30000, clock = () => performance.now(), sleep = ms => new Promise(resolve => setTimeout(resolve, ms))}) {
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))}) {
20
24
  const api = withScopeHints(provider);
21
- assert(identifier(binding), 'invalid-secret-name');
22
- assert(value === undefined || typeof value === 'string' && value.trim(), `missing-secret-${binding}`);
25
+ const bindings = changes.map(change => change.binding), present = changes[0]?.value !== undefined;
26
+ assert(bindings.length && bindings.every(identifier) && validSecretNames(bindings), 'invalid-secret-name');
27
+ assert(changes.every(change => (change.value !== undefined) === present), 'mixed-secret-change');
28
+ for (const {binding, value} of changes) assert(value === undefined || typeof value === 'string' && value.trim(), `missing-secret-${binding}`);
23
29
  return withStateLock(statePath, async () => {
24
30
  const state = await readOwnerState(statePath, target);
25
31
  assert(state.receipt && !state.pendingUpload, 'missing-owner-receipt');
26
- if (await settlePendingSecret(api, target.worker, state, {preflight:true})) await writeOwnerState(statePath, state);
32
+ // A copy uploaded but never deployed is that earlier change: finish it first.
33
+ const deployCopy = version => deploySecretCopy(api, target.worker, version);
34
+ if (await settlePendingSecret(api, target.worker, state, {preflight:true, deployCopy})) await writeOwnerState(statePath, state);
27
35
  const live = await activeWorker(api, target.worker);
28
36
  if (!live) throw refuse('owned-resource-missing', 'worker', target.worker);
29
37
  if (!sameDeployment(live, state.receipt.provider)) throw refuse('owned-resource-replaced', 'worker', target.worker);
30
38
  assert(!state.pendingSecret, 'secret-change-unsettled');
31
- const path = `/workers/scripts/${target.worker}/secrets`, present = value !== undefined;
39
+ const path = `/workers/scripts/${target.worker}/secrets`;
32
40
  const names = secretNames(await api.request(path));
33
41
  assert(names, 'invalid-secret-list');
34
- const existed = names.includes(binding), changed = present || existed;
35
- state.pendingSecret = {binding, present, versionId:state.receipt.provider.versionId, names:names.filter(name => name !== binding).sort()}; await writeOwnerState(statePath, state);
36
- let failure, unchanged = false, confirming = false;
37
- const put = () => api.request(path, {method:'PUT', body:{name:binding, text:value, type:'secret_text'}});
42
+ // Removing secrets the Worker does not hold changes nothing; the rest of a removal still runs.
43
+ const writes = present ? changes : changes.filter(change => names.includes(change.binding));
44
+ const existed = writes.some(change => names.includes(change.binding)), changed = writes.length > 0, copy = writes.length > 1;
45
+ state.pendingSecret = {bindings, present, versionId:state.receipt.provider.versionId, names:names.filter(name => !bindings.includes(name)).sort(), ...(copy ? {copy:randomBytes(16).toString('hex')} : {})};
46
+ await writeOwnerState(statePath, state);
47
+ let failure, unchanged = false, confirming = false, uploaded = false;
48
+ const put = () => api.request(path, {method:'PUT', body:{name:writes[0].binding, text:writes[0].value, type:'secret_text'}});
38
49
  try {
39
- if (present) await put();
40
- else if (changed) await api.request(`${path}/${binding}`, {method:'DELETE'});
50
+ if (copy) {
51
+ const version = await uploadSecretCopy(api, target.worker, live, {changes:writes, marker:state.pendingSecret.copy});
52
+ uploaded = true;
53
+ await deploySecretCopy(api, target.worker, version);
54
+ }
55
+ else if (present) await put();
56
+ else if (changed) await api.request(`${path}/${writes[0].binding}`, {method:'DELETE'});
41
57
  } catch (error) {
42
- if (definiteProviderRefusal(error)) { delete state.pendingSecret; await writeOwnerState(statePath, state); throw error; }
58
+ // A refused upload changed nothing. A copy uploaded but refused deployment stays
59
+ // pending: the same command deploys it next time, as this change and no other.
60
+ if (definiteProviderRefusal(error) && !uploaded) { delete state.pendingSecret; await writeOwnerState(statePath, state); throw error; }
61
+ if (definiteProviderRefusal(error)) { await writeOwnerState(statePath, state); throw error; }
43
62
  failure = error;
44
63
  }
45
64
  try {
@@ -48,7 +67,9 @@ export async function ownerSecret({api: provider, target, statePath, binding, va
48
67
  try {
49
68
  if (await settlePendingSecret(api, target.worker, state, {
50
69
  observe: current => { unchanged = sameDeployment(current, state.receipt.provider); },
51
- ...(failure && present && existed ? {confirm: async current => {
70
+ // A copy whose upload or deployment answer was lost is deployed here once it is found.
71
+ ...(copy ? {deployCopy} : {}),
72
+ ...(failure && present && existed && !copy ? {confirm: async current => {
52
73
  confirming = true;
53
74
  state.pendingSecret.repeatVersionId = current.versionId;
54
75
  await writeOwnerState(statePath, state);
@@ -71,7 +92,7 @@ export async function ownerSecret({api: provider, target, statePath, binding, va
71
92
  await writeOwnerState(statePath, state);
72
93
  throw failure ?? error;
73
94
  }
74
- const result = {worker:target.worker, binding, present, versionId:state.receipt.provider.versionId};
95
+ const result = {worker:target.worker, bindings, present, versionId:state.receipt.provider.versionId};
75
96
  // Settlement is durable before readiness: a failed hosted check must never
76
97
  // erase the applied mutation or cause the next command to reject our version.
77
98
  state.receipt.health = {ok:false,versionId:result.versionId};