@runeditrun/rer 0.2.76 → 0.2.77

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/cli/README.md CHANGED
@@ -455,3 +455,58 @@ contain only the filename, path, size and modification time. Sensitive-looking
455
455
  outbound names are dropped entirely and counted in `withheld`. Symlinks, build
456
456
  outputs and dependency trees are skipped. Unsupported syntax yields no signal;
457
457
  an empty result is not proof that a repository has no business dependencies.
458
+
459
+ `INSTALLATION_KEY` has a dedicated rotation path: `rer deploy --rotate-secret INSTALLATION_KEY`
460
+ saves current and previous values privately before publishing both as one Worker
461
+ version, reseals and verifies all dependency keys in the recorded D1, then retires
462
+ the previous binding. Routine rotation uses only the current/previous pair;
463
+ older retired keys require explicit reopen. By default, every retired key remains
464
+ in the same private 0600,
465
+ Git-ignored `.rer/deploy/<environment>.secrets.env` custody as `SESSION_SECRET`,
466
+ in `INSTALLATION_KEY_RETIRED=<kid>:<value>[,<kid>:<value>...]`. Retired values
467
+ never enter routine Worker bindings or installation archives. Back up this file
468
+ securely and copy it when moving the deployment to another checkout. If rotation
469
+ stops, run the same command again; it resumes the saved pair. Manual set/unset of
470
+ these bindings is refused.
471
+
472
+ Retain each retired key until no D1 Time Travel recovery point or exported backup
473
+ predates the completed rotation that retired it or otherwise needs that key.
474
+ After any rotation or reopen has finished, edit
475
+ `.rer/deploy/<environment>.secrets.env` and remove only its `<kid>:<value>` entry
476
+ from `INSTALLATION_KEY_RETIRED`, keeping valid comma separators; remove the
477
+ assignment if no entries remain. Preserve the current key, all other entries
478
+ and the file's owned 0600 permissions. There is no per-key removal command;
479
+ reopening a removed ID refuses before provider writes unless its custody is restored.
480
+
481
+ A D1 backup or Time Travel restore from before a rotation can restore ciphertext
482
+ that needs retired keys. Select a retained key explicitly:
483
+
484
+ ```sh
485
+ rer deploy --reopen-installation-key KID
486
+ ```
487
+
488
+ Use the envelope's installation `kid` or its entry in private retired custody;
489
+ this ID is different from the signing JWK's ID. Include the original deployment's
490
+ `--environment` and `--env-file` when applicable. This command publishes the
491
+ current key and selected retired key as `INSTALLATION_KEY_PREVIOUS`, reseals all
492
+ dependency keys through the recorded D1, verifies them under the current key,
493
+ then removes the previous binding while retaining all retired custody. It skips
494
+ the build and upload hook. CLI-side reopen rekey receives every validated retired key
495
+ in custody, allowing a mid-rotation snapshot with multiple retired envelope IDs
496
+ to reopen with either ID; these additional keys are never Worker bindings.
497
+ Reopen/rekey prints the D1 `key_ids` tail and custody availability for each history
498
+ ID before opening rows, even when the tail is unavailable. A whole pre-rotation
499
+ restore whose history tail is unavailable reports `installation_key_unavailable`;
500
+ `installation_key_version_unknown` applies to a known row ID only after that
501
+ history custody check succeeds.
502
+ A failure preserves the exact pair and reopen marker;
503
+ repeat the same command before other deploy changes. Missing retired custody
504
+ refuses with `installation_key_unavailable` before any provider write: recover
505
+ the private file before reopening. For backups spanning several rotations,
506
+ retain every historical key they need; unrelated ciphertext never silently regenerates keys.
507
+
508
+ Base versions before #367 cannot open sealed dependency keys. Roll forward to a
509
+ sealing-capable Base version after restoring D1; rolling code back cannot decrypt
510
+ the rows. The CLI has no old-Base capability receipt or code rollback command,
511
+ so it cannot preflight an out-of-band provider rollback. Current Base rejects a
512
+ sealed key passed to its plaintext signing path with `installation_key_sealed_rollback`.
package/cli/contract.mjs CHANGED
@@ -11,7 +11,7 @@ const definitions = {
11
11
  build: [['--site'], 'Production build with private local settings excluded and restored. --site instead writes the static run site (homepage, /run, docs) to its declared folder and prints that folder.'],
12
12
  verify: [[], 'Run the complete internal verification target.'],
13
13
  reset: [['--yes'], 'Confirmed removal of the declared local inventory only.'],
14
- deploy: [['--owner-name', '--environment', '--dry-run', '--site', '--demo', '--host', '--env-file', '--image', '--bind-address', '--http-port', '--https-port', '--remove', '--yes', '--set-secret', '--unset-secret', '--rotate-secret'], 'Owner-account deployment and health; dry run validates/builds locally and reads target secret bindings with Cloudflare credentials, without provider writes. Missing required secrets fail as in deploy; missing credentials or unreadable target secrets also fail. Builds and deploy hooks run with the checkout\'s local settings files moved aside, and a build output holding one (.dev.vars, .env) is refused. Declared secrets come from the environment or --env-file (an owned 0600 KEY=VALUE file); a new Worker gets the local setup owner and fresh generated secrets when they are not given. rer keeps the secrets it generates in .rer/deploy/ENVIRONMENT.secrets.env (0600) and reuses them on every redeploy; it refuses to generate a replacement for one a live Worker holds, and --rotate-secret NAME[,NAME] replaces them on purpose. After a healthy deploy rer claims the setup owner on the hosted app with the saved setup owner name and the one-time setup token, then removes the token. If the installer declares an owner-name field and no name is saved, deploy asks once and saves it; --non-interactive requires --owner-name NAME before any upload. --set-secret NAME[,NAME] (each value from the environment or --env-file; repeat the flag or join names with commas) and --unset-secret NAME[,NAME] change those secrets of the deployed Worker without a build, all of them in one new Worker version or none, and record that version; a missing value refuses before any change. --remove --yes deletes what this environment\'s deploy record says rer created (Worker, D1, R2, KV, queues), reads back that each is gone, and touches nothing else. --site deploys the run site instead: an assets-only Worker on its custom domain with www redirected; with --dry-run it builds the site and prints the plan with no provider request. --demo deploys the hosted demo instead (deploy-demo.json): a front Worker on demo.<domain> giving each visitor their own signed-in, throwaway native Worker isolate of this seed with real public reads/checks and simulated external writes; --dry-run writes it to .rer/demo-host with no provider request; --demo --remove --yes deletes that demo (its Worker, demo.<domain> Custom Domain, each only while the record its deploy left proves it the demo\'s), reads back that each is gone, and is a no-op once it is.'],
14
+ deploy: [['--owner-name', '--environment', '--dry-run', '--site', '--demo', '--host', '--env-file', '--image', '--bind-address', '--http-port', '--https-port', '--remove', '--yes', '--set-secret', '--unset-secret', '--rotate-secret', '--reopen-installation-key'], 'Owner-account deployment and health; dry run validates/builds locally and reads target secret bindings with Cloudflare credentials, without provider writes. Missing required secrets fail as in deploy; missing credentials or unreadable target secrets also fail. Builds and deploy hooks run with the checkout\'s local settings files moved aside, and a build output holding one (.dev.vars, .env) is refused. Declared secrets come from the environment or --env-file (an owned 0600 KEY=VALUE file); a new Worker gets the local setup owner and fresh generated secrets when they are not given. rer keeps the secrets it generates in .rer/deploy/ENVIRONMENT.secrets.env (0600) and reuses them on every redeploy; it refuses to generate a replacement for one a live Worker holds, and --rotate-secret NAME[,NAME] replaces them on purpose. After a healthy deploy rer claims the setup owner on the hosted app with the saved setup owner name and the one-time setup token, then removes the token. If the installer declares an owner-name field and no name is saved, deploy asks once and saves it; --non-interactive requires --owner-name NAME before any upload. --set-secret NAME[,NAME] (each value from the environment or --env-file; repeat the flag or join names with commas) and --unset-secret NAME[,NAME] change those secrets of the deployed Worker without a build, all of them in one new Worker version or none, and record that version; a missing value refuses before any change. --reopen-installation-key KID temporarily binds a retired installation key from private custody, reseals restored dependency keys under the current key, verifies them and removes the previous binding. --remove --yes deletes what this environment\'s deploy record says rer created (Worker, D1, R2, KV, queues), reads back that each is gone, and touches nothing else. --site deploys the run site instead: an assets-only Worker on its custom domain with www redirected; with --dry-run it builds the site and prints the plan with no provider request. --demo deploys the hosted demo instead (deploy-demo.json): a front Worker on demo.<domain> giving each visitor their own signed-in, throwaway native Worker isolate of this seed with real public reads/checks and simulated external writes; --dry-run writes it to .rer/demo-host with no provider request; --demo --remove --yes deletes that demo (its Worker, demo.<domain> Custom Domain, each only while the record its deploy left proves it the demo\'s), reads back that each is gone, and is a no-op once it is.'],
15
15
  export: [['--target', '--output', '--origin', '--session-file'], 'For owner move-in, run rer dev and open /app/import: export people there, then upload through the destination door. Developer-only installation backup: complete supported archive of the local copy on this computer, with integrity and exclusions, written to --output. The hosted install cannot be exported yet: --origin or --target remote refuses (exit 2) before any effect and names the command that saves the hosted database.'],
16
16
  import: [['--target', '--input', '--journal', '--origin', '--session-file', '--yes', '--legacy-v1', '--acknowledge-unverified-metadata', '--output'], 'For owner move-in, run rer dev and open /app/import: upload, review and apply through the door. Developer-only installation recovery: confirmed atomic restore into an empty destination; --journal LATER_ARCHIVE also fences rows that installation erased since. Backup-only local v1 recovery requires --legacy-v1 --acknowledge-unverified-metadata and a new --output v2 archive; --journal requires normal v2 import.'],
17
17
  doctor: [[], 'Read-only installed tool, configuration and state diagnostics.'],
@@ -26,7 +26,7 @@ import { withoutLocalSettings, refuseLocalEnvOutput } from './local-env.mjs';
26
26
  import { deployProductDirectory, deployProductArguments, DeployProductError } from './deploy-product.mjs';
27
27
 
28
28
  export function validateDeployOptions(options) {
29
- const changes = [options.remove && '--remove', options.setSecret && '--set-secret', options.unsetSecret && '--unset-secret', options.rotateSecret && '--rotate-secret'].filter(Boolean);
29
+ const changes = [options.remove && '--remove', options.setSecret && '--set-secret', options.unsetSecret && '--unset-secret', options.rotateSecret && '--rotate-secret', options.reopenInstallationKey && '--reopen-installation-key'].filter(Boolean);
30
30
  if (changes.length > 1 || changes.length && options.dryRun) throw invalid(`Use ${changes.join(', ')}${options.dryRun ? ' and --dry-run' : ''} on separate runs.`);
31
31
  if (options.remove && !options.yes) throw invalid(`${deployAgain(options)} --remove deletes this environment's Worker and every D1, R2, KV and queue rer created for it, with their data. Add --yes to confirm.`);
32
32
  }
@@ -86,11 +86,13 @@ export async function deployCommand(context) {
86
86
  const { signIn } = await requireProductionAuth({ root, declaration, env: production.env, setupManifest, setupSeed: context.setupSeed, adapter, declarationPath: path, options }) ?? {};
87
87
  const needed = neededForRealDeploy({ declaration, env: production.env, signIn, secretsChecked: true });
88
88
  reportNeeded(store, needed);
89
+ if (declaration.secrets?.some(item => item.binding === 'INSTALLATION_KEY')) store.report('deploy: INSTALLATION_KEY is a private generated binding; INSTALLATION_KEY_PREVIOUS is optional and managed only during rotation or an explicit retired-key reopen. Values are withheld.');
89
90
  return needed.length && result && typeof result === 'object' ? { ...result, neededForRealDeploy: needed } : result;
90
91
  };
91
92
  // Custom hooks historically ignored these flags. Only the ownership controller
92
93
  // may perform them; neither a build nor a custom upload runs here.
93
- if (options.remove || options.setSecret || options.unsetSecret) return ownerDeploy(path, adapter)(context);
94
+ if (options.remove || options.setSecret || options.unsetSecret || options.reopenInstallationKey) return ownerDeploy(path, adapter)(context);
95
+ if (options.rotateSecret?.split(',').includes('INSTALLATION_KEY')) return ownerDeploy(path, adapter)(context);
94
96
  // A hook that deployed through the kit keeps what its Worker holds: rotate there as a secret change.
95
97
  if (options.rotateSecret && !adapter.deploy.managesHostedOwner && await hookState(root, options.environment ?? 'production')) return ownerDeploy(path, adapter)(context);
96
98
  if (adapter.deploy.managesHostedOwner) { const result = await adapter.deploy(context); return options.dryRun ? dryRun(result) : result; }
@@ -1,7 +1,7 @@
1
1
  import { randomBytes } from 'node:crypto';
2
2
  import { relative } from 'node:path';
3
3
  import { shared } from './shared.mjs';
4
- import { invalid } from './errors.mjs';
4
+ import { invalid, refuse } from './errors.mjs';
5
5
  import { readDeployEnvFile } from '../modules/deploy-kit/env-file.mjs';
6
6
  import { publicOrigin } from '../modules/deploy-kit/public-origin.mjs';
7
7
  import { keptSecrets, rotations, savedSecrets } from './deploy-secrets.mjs';
@@ -39,12 +39,24 @@ export async function deployEnvironment({ root, options, declaration, setupManif
39
39
  }
40
40
  // withDeployEnvironment reads only the --env-file, with no declaration to rotate in.
41
41
  const kept = keptSecrets(declaration, setupManifest), rotate = setupManifest || declaration.project ? rotations(options, kept, env) : [];
42
- const saved = kept.some(absent) ? await savedSecrets(root, options.environment ?? 'production') : {};
42
+ const saved = kept.some(absent) || kept.some(item => item.binding === 'INSTALLATION_KEY') ? await savedSecrets(root, options.environment ?? 'production') : {};
43
+ if (kept.some(item => item.binding === 'INSTALLATION_KEY')) {
44
+ const installation = kept.find(item => item.binding === 'INSTALLATION_KEY'), previous = secrets.find(item => item.binding === 'INSTALLATION_KEY_PREVIOUS');
45
+ if (previous && env[previous.environment]?.trim()) throw refuse('INSTALLATION_KEY_PREVIOUS is managed by --rotate-secret INSTALLATION_KEY; leave it unset in the environment and --env-file.');
46
+ if (saved.INSTALLATION_KEY && env[installation.environment]?.trim() && env[installation.environment] !== saved.INSTALLATION_KEY) throw refuse('A supplied INSTALLATION_KEY differs from this environment\'s private custody. Use --rotate-secret INSTALLATION_KEY to change it safely.');
47
+ if ((options.setSecret ?? options.unsetSecret ?? '').split(',').some(name => ['INSTALLATION_KEY', 'INSTALLATION_KEY_PREVIOUS'].includes(name))) throw refuse('Installation keys cannot be set or removed manually. Use --rotate-secret INSTALLATION_KEY to publish both keys, reseal dependency keys and retire the previous key safely.');
48
+ if (saved.INSTALLATION_KEY_PREVIOUS && !options.remove) {
49
+ if (saved.INSTALLATION_KEY_REOPEN && options.reopenInstallationKey !== saved.INSTALLATION_KEY_REOPEN) throw refuse(`Installation key reopen is unfinished. Run the same deploy command with --reopen-installation-key ${saved.INSTALLATION_KEY_REOPEN} to resume before another deployment or secret change.`);
50
+ if (!saved.INSTALLATION_KEY_REOPEN && !rotate.includes('INSTALLATION_KEY')) throw refuse('Installation key rotation is unfinished. Run the same deploy command with --rotate-secret INSTALLATION_KEY to resume before another deployment or secret change.');
51
+ }
52
+ if (rotate.includes('INSTALLATION_KEY') && !saved.INSTALLATION_KEY) throw refuse('Installation key rotation requires the current key in the private deployment secrets file. Restore that file from the checkout that deployed this environment; generating a replacement would lose access to dependency keys.');
53
+ }
43
54
  const generated = [], reused = [];
44
55
  for (const field of setupManifest?.fields ?? []) {
45
56
  const item = field.kind === 'secret' && field.generate ? secrets.find(entry => entry?.binding === field.name) : undefined;
46
57
  if (!absent(item)) continue;
47
- const keep = kept.includes(item), value = keep && !rotate.includes(item.binding) ? saved[item.binding] : undefined;
58
+ const keep = kept.includes(item), resuming = item.binding === 'INSTALLATION_KEY' && saved.INSTALLATION_KEY_PREVIOUS;
59
+ const value = keep && (!rotate.includes(item.binding) || resuming) ? saved[item.binding] : undefined;
48
60
  env[item.environment] = value ?? randomBytes(32).toString(field.generate);
49
61
  supplied.push(item.binding);
50
62
  if (value) reused.push(item.binding); else if (keep) generated.push(item.binding);
@@ -0,0 +1,71 @@
1
+ import { savedSecrets, saveSecrets, savedSecretsFile, liveSecretNames } from './deploy-secrets.mjs';
2
+ import { refuse, RerError } from './errors.mjs';
3
+ import { installationKeyId } from '../modules/dependencies/sealing.mjs';
4
+ import { retiredInstallationKeys as parseRetiredKeys } from '../modules/dependencies/custody.mjs';
5
+ import { shared } from './shared.mjs';
6
+ import { join } from 'node:path';
7
+
8
+ /** Save the first deployment key before a Worker can receive it, including when
9
+ * its upload answer is lost. Never confuse a newly generated value with a live key. */
10
+ export async function keepInstallationKey({ root, environment, declaration, env, generated }) {
11
+ const secret = declaration.secrets?.find(item => item.binding === 'INSTALLATION_KEY');
12
+ if (!secret || (await savedSecrets(root, environment)).INSTALLATION_KEY) return;
13
+ if (generated.includes(secret.binding) && (await liveSecretNames(env, declaration, environment)).includes(secret.binding)) throw refuse('The Worker already holds INSTALLATION_KEY, but this checkout has no current key. Restore the private deployment secrets file before continuing.');
14
+ if (env[secret.environment]) await saveSecrets(root, environment, { INSTALLATION_KEY: env[secret.environment] });
15
+ }
16
+
17
+ /** Persist both keys before publishing either; a retry always uses this exact pair. */
18
+ export async function rotateInstallationKey({ root, environment, declaration, env, owner, state, report, addSecrets }) {
19
+ const current = declaration.secrets?.find(item => item.binding === 'INSTALLATION_KEY');
20
+ const previous = declaration.secrets?.find(item => item.binding === 'INSTALLATION_KEY_PREVIOUS');
21
+ if (!current || !previous?.optional) throw refuse('Installation key rotation requires declared INSTALLATION_KEY and optional INSTALLATION_KEY_PREVIOUS bindings.');
22
+ const saved = await savedSecrets(root, environment);
23
+ if (!saved.INSTALLATION_KEY) throw refuse('Restore the current installation key in the private deployment secrets file before rotating it.');
24
+ if (saved.INSTALLATION_KEY_REOPEN) throw refuse('Installation key reopen is unfinished. Resume --reopen-installation-key with the saved key ID before rotating.');
25
+ const pair = { INSTALLATION_KEY: saved.INSTALLATION_KEY_PREVIOUS ? saved.INSTALLATION_KEY : env[current.environment], INSTALLATION_KEY_PREVIOUS: saved.INSTALLATION_KEY_PREVIOUS ?? saved.INSTALLATION_KEY };
26
+ if (!pair.INSTALLATION_KEY || pair.INSTALLATION_KEY === pair.INSTALLATION_KEY_PREVIOUS) throw refuse('Installation key rotation requires distinct current and previous keys.');
27
+ const retired = await retiredInstallationKeys(saved);
28
+ retired.set(await installationKeyId(pair.INSTALLATION_KEY_PREVIOUS), pair.INSTALLATION_KEY_PREVIOUS);
29
+ addSecrets([...Object.values(pair), ...retired.values()]);
30
+ await saveSecrets(root, environment, { ...pair, INSTALLATION_KEY_RETIRED: serializeRetired(retired) });
31
+ // Routine rotation must not revive envelopes from older retired eras.
32
+ await resealAndRetire({root, environment, current, previous, pair, retired:new Map(), env, state, owner, report});
33
+ report('Rotated INSTALLATION_KEY, resealed every dependency key, and removed INSTALLATION_KEY_PREVIOUS after verifying the owned Worker. Retired keys remain in private custody for older D1 restores.');
34
+ }
35
+
36
+ /** Explicitly reopen one retained historical key without changing current custody. */
37
+ export async function reopenInstallationKey({ root, environment, declaration, env, owner, state, kid, report, addSecrets }) {
38
+ const current = declaration.secrets?.find(item => item.binding === 'INSTALLATION_KEY');
39
+ const previous = declaration.secrets?.find(item => item.binding === 'INSTALLATION_KEY_PREVIOUS');
40
+ if (!current || !previous?.optional) throw refuse('Installation key reopen requires declared INSTALLATION_KEY and optional INSTALLATION_KEY_PREVIOUS bindings.');
41
+ const saved = await savedSecrets(root, environment), retired = await retiredInstallationKeys(saved);
42
+ if (!saved.INSTALLATION_KEY || !retired.has(kid)) throw unavailable('The requested retired installation key is not in this environment\'s private custody. Restore the private deployment secrets file from the deploying checkout, or relink dependencies. Nothing was uploaded.');
43
+ if (saved.INSTALLATION_KEY_PREVIOUS && (saved.INSTALLATION_KEY_REOPEN !== kid || saved.INSTALLATION_KEY_PREVIOUS !== retired.get(kid))) throw refuse('Another installation key operation is unfinished. Resume its recorded rotation or reopen first.');
44
+ const pair = { INSTALLATION_KEY: saved.INSTALLATION_KEY, INSTALLATION_KEY_PREVIOUS: retired.get(kid) };
45
+ addSecrets([...Object.values(pair), ...retired.values()]);
46
+ await saveSecrets(root, environment, {...pair, INSTALLATION_KEY_REOPEN:kid});
47
+ await resealAndRetire({root, environment, current, previous, pair, retired, env, state, owner, report});
48
+ report(`Reopened retired installation key ${kid}, resealed and verified every dependency key with the current key, and removed INSTALLATION_KEY_PREVIOUS. Retired custody is retained.`);
49
+ }
50
+
51
+ const unavailable = message => new RerError('installation_key_unavailable', message, 4);
52
+ const serializeRetired = retired => [...retired].map(([kid, value]) => `${kid}:${value}`).join(',');
53
+
54
+ async function retiredInstallationKeys(saved) {
55
+ try { return await parseRetiredKeys(saved.INSTALLATION_KEY_RETIRED); }
56
+ catch { throw unavailable('Retired installation key custody is invalid. Restore the private deployment secrets file before rotating or reopening. Nothing was uploaded.'); }
57
+ }
58
+
59
+ async function resealAndRetire({root, environment, current, previous, pair, retired, env, state, owner, report}) {
60
+ const values = { ...env, [current.environment]: pair.INSTALLATION_KEY, [previous.environment]: pair.INSTALLATION_KEY_PREVIOUS };
61
+ const extra = state ? ['--state', state] : [];
62
+ await owner('secret', ['--set', current.binding, '--set', previous.binding, ...extra], values);
63
+ await owner('rekey', extra, {...values, INSTALLATION_KEY_RETIRED:serializeRetired(retired)}, {notice:report});
64
+ await owner('secret', ['--unset', previous.binding, ...extra], values);
65
+ // The retired key stays private after its binding is read back absent.
66
+ const retained = await savedSecrets(root, environment);
67
+ delete retained.INSTALLATION_KEY_PREVIOUS;
68
+ delete retained.INSTALLATION_KEY_REOPEN;
69
+ const { writePrivateFile } = await shared('private-files.mjs');
70
+ await writePrivateFile(join(root, savedSecretsFile(environment)), Object.entries(retained).map(([name, value]) => `${name}=${value}\n`).join(''));
71
+ }
@@ -87,6 +87,8 @@ export async function keepHookSecrets({ root, environment, declaration, setupMan
87
87
  const held = kept.filter(item => fresh.includes(item.binding) && live.includes(item.binding));
88
88
  if (held.length) throw refuseRotation({ worker: ownerWorkerName(declaration.project, environment), held, environment, again });
89
89
  }
90
+ const { keepInstallationKey } = await import('./deploy-installation-key.mjs');
91
+ await keepInstallationKey({ root, environment, declaration, env, generated });
90
92
  await keepSecrets({ root, environment, kept, env, generated, reused, report });
91
93
  }
92
94
 
package/cli/deploy.mjs CHANGED
@@ -20,6 +20,7 @@ import { cloudflareCredentials, missingCredentialsMessage } from './deploy-needs
20
20
  import { keptSecrets, keepSecrets, forgetSecrets } from './deploy-secrets.mjs';
21
21
  import { withoutLocalSettings, refuseLocalEnvOutput } from './local-env.mjs';
22
22
  import { deployProductDirectory, deployProductArguments } from './deploy-product.mjs';
23
+ import { rotateInstallationKey, reopenInstallationKey, keepInstallationKey } from './deploy-installation-key.mjs';
23
24
 
24
25
  export function ownerDeploy(declarationPath, lifecycle) {
25
26
  // rer verify serves the build with this declaration's vars and secrets.
@@ -31,9 +32,9 @@ export function ownerDeploy(declarationPath, lifecycle) {
31
32
  if (local) throw refuse(`${declarationPath} names the local-only key ${local} as a deploy binding or secret. Remove it; local dev keys never reach a deployment.`);
32
33
  const environment = options.environment ?? 'production';
33
34
  const again = deployAgain(options);
34
- const change = [options.remove && '--remove', options.setSecret && '--set-secret', options.unsetSecret && '--unset-secret', options.rotateSecret && '--rotate-secret'].filter(Boolean);
35
+ const change = [options.remove && '--remove', options.setSecret && '--set-secret', options.unsetSecret && '--unset-secret', options.rotateSecret && '--rotate-secret', options.reopenInstallationKey && '--reopen-installation-key'].filter(Boolean);
35
36
  // The command that finishes what this run started: the same verb, never a plain deploy in its place.
36
- const retry = options.remove ? `${again} --remove --yes` : options.setSecret ? `${again} --set-secret ${options.setSecret}` : options.unsetSecret ? `${again} --unset-secret ${options.unsetSecret}` : options.rotateSecret ? `${again} --rotate-secret ${options.rotateSecret}` : again;
37
+ const retry = options.remove ? `${again} --remove --yes` : options.setSecret ? `${again} --set-secret ${options.setSecret}` : options.unsetSecret ? `${again} --unset-secret ${options.unsetSecret}` : options.rotateSecret ? `${again} --rotate-secret ${options.rotateSecret}` : options.reopenInstallationKey ? `${again} --reopen-installation-key ${options.reopenInstallationKey}` : again;
37
38
  if (change.length > 1 || change.length && options.dryRun) throw invalid(`Use ${change.join(', ')}${options.dryRun ? ' and --dry-run' : ''} on separate runs.`);
38
39
  if (options.remove && !options.yes) throw invalid(`${again} --remove deletes this environment's Worker and every D1, R2, KV and queue rer created for it, with their data. Add --yes to confirm.`);
39
40
  const productDirectory = change.length ? undefined : deployProductDirectory(declaration);
@@ -81,10 +82,19 @@ export function ownerDeploy(declarationPath, lifecycle) {
81
82
  store.report(`Removed ${result.removed.join(', ') || 'nothing (already gone)'}; read back: none of them remains.`);
82
83
  return { removed: result.removed, deployed: false };
83
84
  }
85
+ if (options.reopenInstallationKey) {
86
+ step = 'secrets';
87
+ await reopenInstallationKey({ root, environment, declaration, env, owner, state, kid: options.reopenInstallationKey, report: line => store.report(line), addSecrets: values => { redaction.addSecrets(values); store.addSecrets?.(values); } });
88
+ return { reopened: options.reopenInstallationKey, deployed: false };
89
+ }
84
90
  if (options.rotateSecret) {
85
91
  // The kit never replaces a secret its Worker holds: rotation is this explicit change, kept once it is live.
86
92
  step = 'secrets';
87
93
  for (const binding of rotated) {
94
+ if (binding === 'INSTALLATION_KEY') {
95
+ await rotateInstallationKey({ root, environment, declaration, env, owner, state, report: line => store.report(line), addSecrets: values => { redaction.addSecrets(values); store.addSecrets?.(values); } });
96
+ continue;
97
+ }
88
98
  await owner('secret', ['--set', binding, ...(state ? ['--state', state] : [])]);
89
99
  await keepSecrets({ root, environment, kept, env, generated: [binding], reused: [], report: () => {} });
90
100
  store.report(`Rotated ${binding} on this environment's Worker to a fresh value kept in .rer/deploy/${environment}.secrets.env, recorded its new version and verified hosted readiness.`);
@@ -99,6 +109,7 @@ export function ownerDeploy(declarationPath, lifecycle) {
99
109
  return { bindings, present: Boolean(options.setSecret), deployed: false };
100
110
  }
101
111
  store.report(`Deploying the ${environment} environment to your Cloudflare account.`);
112
+ await keepInstallationKey({ root, environment, declaration, env, generated });
102
113
  deployed = await owner('deploy', [], env, { notice: line => store.report(line), onCreated: resource => created.push(redaction.redact(resource)) });
103
114
  // A generated value the kit did not send stays unknown: the Worker kept its own.
104
115
  const sent = supplied.filter(name => deployed.sentSecrets.includes(name)), keptSent = [...generated, ...reused].filter(name => sent.includes(name));
@@ -48,6 +48,8 @@ function commandFor(options, environment) {
48
48
  if (options.verb === 'signin') return again.replace(/^rer deploy/, 'rer signin');
49
49
  if (options.remove) return `${again} --remove --yes`;
50
50
  if (options.setSecret) return `${again} --set-secret ${options.setSecret}`;
51
+ if (options.reopenInstallationKey) return `${again} --reopen-installation-key ${options.reopenInstallationKey}`;
52
+ if (options.rotateSecret) return `${again} --rotate-secret ${options.rotateSecret}`;
51
53
  if (options.unsetSecret) return `${again} --unset-secret ${options.unsetSecret}`;
52
54
  return again;
53
55
  }
package/cli/main.mjs CHANGED
@@ -64,7 +64,7 @@ export async function main(argv = process.argv.slice(2)) {
64
64
  }
65
65
  // A hosted address never exports this computer's copy under its name.
66
66
  if (options.verb === 'export' && project.profile === 'first-party') await (await import('./hosted-export.mjs')).refuseHostedExport(project, options);
67
- if (options.verb === 'deploy' && !options.site && !options.demo && !options.remove && !options.setSecret && !options.unsetSecret) {
67
+ if (options.verb === 'deploy' && !options.site && !options.demo && !options.remove && !options.setSecret && !options.unsetSecret && !options.reopenInstallationKey) {
68
68
  const { deliveryDeclarationClauses } = await import('./delivery-declarations.mjs');
69
69
  const failures = (await deliveryDeclarationClauses(project.root)).filter(clause => !clause.ok);
70
70
  if (failures.length) throw new RerError('invalid_deployment_declaration', failures.map(clause => clause.message).join('\n'), 1);
package/cli/parse.mjs CHANGED
@@ -94,9 +94,10 @@ export function parse(argv, cwd = process.cwd(), { independent = false, deferTai
94
94
  options[key] = names.join(',');
95
95
  }
96
96
  if (options.rotateSecret !== undefined && !/^[A-Z][A-Z0-9_]{0,63}(?:,[A-Z][A-Z0-9_]{0,63}){0,15}$/.test(options.rotateSecret)) throw invalid('--rotate-secret names generated secret bindings, separated by commas, such as SESSION_SECRET.');
97
- if(verb==='deploy'&&options.demo&&(options.site||['platform','image','bindAddress','httpPort','httpsPort','envFile','host','setSecret','unsetSecret','rotateSecret'].some(key=>options[key]!==undefined)))throw invalid('--demo takes only --environment, --dry-run and --remove --yes: the hosted demo is its own Worker on demo.<domain>.');
97
+ if (options.reopenInstallationKey !== undefined && !/^[A-Za-z0-9_-]{43}$/.test(options.reopenInstallationKey)) throw invalid('--reopen-installation-key takes the installation key ID from a sealed envelope or private retired custody.');
98
+ if(verb==='deploy'&&options.demo&&(options.site||['platform','image','bindAddress','httpPort','httpsPort','envFile','host','setSecret','unsetSecret','rotateSecret','reopenInstallationKey'].some(key=>options[key]!==undefined)))throw invalid('--demo takes only --environment, --dry-run and --remove --yes: the hosted demo is its own Worker on demo.<domain>.');
98
99
  if(verb==='deploy'&&options.demo&&options.remove&&(options.dryRun||!options.yes))throw invalid(options.dryRun?'Use --remove and --dry-run on separate runs.':'deploy --demo --remove deletes the hosted demo\'s Worker, its demo.<domain> Custom Domain. Add --yes to confirm.');
99
- if ((options.remove || options.setSecret || options.unsetSecret || options.rotateSecret) && options.site) throw invalid('--remove, --set-secret, --unset-secret and --rotate-secret act on the application Worker, not the run site.');
100
+ if ((options.remove || options.setSecret || options.unsetSecret || options.rotateSecret || options.reopenInstallationKey) && options.site) throw invalid('--remove, --set-secret, --unset-secret, --rotate-secret and --reopen-installation-key act on the application Worker, not the run site.');
100
101
  if (options.origin !== undefined) {
101
102
  let url; try { url = new URL(options.origin); } catch { throw invalid('Provide a valid credential-free origin.'); }
102
103
  if (!['http:', 'https:'].includes(url.protocol) || url.username || url.password || url.search || url.hash || url.pathname !== '/') throw invalid('Provide a credential-free HTTP origin without a path.');
@@ -21,7 +21,7 @@ export async function runtimeFrontDoor({ host, port, activity, door, devKey, ori
21
21
  // ports to every other socket (the runtime's own listeners, outbound requests),
22
22
  // so the runtime's bind could find it taken. Choose a free port the OS never
23
23
  // assigns on its own instead.
24
- async function runtimeLoopbackPort(publicPort) {
24
+ export async function runtimeLoopbackPort(publicPort) {
25
25
  const [first, last] = await ephemeralRange();
26
26
  const candidates = [[10000, first - 1], [last + 1, 65535]].filter(([low, high]) => low <= high);
27
27
  if (!candidates.length) throw Error(`The OS assigns every local port from 10000 (ephemeral range ${first}-${last}); leave part of that space outside the range for the local runtime.`);
@@ -1,5 +1,11 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.2.77
4
+
5
+ - **Dependency signing keys are sealed at rest with a rotatable installation key (#367, #382).** Each interface's private signing key is stored as an AES-256-GCM envelope under a key derived from the generated `INSTALLATION_KEY` setting, which setup and hosted deploys keep beside `SESSION_SECRET` and archives never carry. Legacy plaintext keys upgrade once. `rer deploy --rotate-secret INSTALLATION_KEY` re-seals every row and retires the previous binding; `rer deploy --reopen-installation-key KID` reopens a D1 restore from before a rotation with retained private custody, reporting the D1 key history first. Missing or wrong keys fail closed with `installation_key_missing` or `installation_key_unavailable`.
6
+ - **The Run page keeps its install command whole at the shell pipe.** At phone widths the command wraps before the URL, or after its last slash, never beside `| sh`; Copy still copies the exact command.
7
+ - **The misbound-port startup check no longer races the app's own sockets.** Its test picks the wrong port the way rer picks its internal one, outside the OS ephemeral range, so the app's Miniflare sockets cannot take it before Vite binds.
8
+
3
9
  ## 0.2.76
4
10
 
5
11
  - **Patch the maintained TanStack Start security closure (#386).** The default seed and foundation carry the patched Start and server-core dependencies for GHSA-qx66-fv34-fjm8.
@@ -32,7 +32,77 @@ adapter adds OIDC discovery, sessions, domain policy and owner claims.
32
32
  same-origin `paths` as absolute URLs, and a per-interface `jwks_uri`.
33
33
  `GET /.well-known/rer-link/jwks/INTERFACE` publishes an ES256 public JWK only.
34
34
  The unqualified JWKS URL selects the identity interface. The application retains
35
- its private key in the server database. Sector/install identity survives re-link,
35
+ its private key in the server database as an AES-256-GCM envelope
36
+ `{version:1,kid,iv,ciphertext}`. The 96-bit random IV and 128-bit tag authenticate the
37
+ AAD `rer-at-rest-v1|rer_dependency_keys|<interface>|1|<kid>`, binding the table,
38
+ interface, envelope version and installation key ID. HKDF-SHA-256 derives a
39
+ dedicated encryption key from
40
+ `INSTALLATION_KEY` with the `rer-at-rest-v1:dependency-key` domain. The envelope's
41
+ `kid` identifies that installation secret; it is separate from the signing JWK's ID.
42
+ `INSTALLATION_KEY` requires the generated 256-bit key's 64 lowercase hex
43
+ characters; passphrases and other formats are refused. `rer setup` generates the
44
+ secret in the private settings file; hosted deploys
45
+ keep their own generated secret in `.rer/deploy/<environment>.secrets.env`
46
+ (mode 0600), exactly like `SESSION_SECRET`. Neither secret enters archives.
47
+ Pass both installation bindings to `createDependencies` and `AuthConfig`.
48
+
49
+ Legacy plaintext is accepted only before the installation records sealed
50
+ custody; a read upgrades the requested interface, and full rekey upgrades every
51
+ row in one D1 batch. After the last legacy key is upgraded, the durable
52
+ `keys_sealed` marker prevents plaintext from being reintroduced. The non-secret
53
+ `key_ids` history distinguishes retired versions from damaged envelopes. An
54
+ optional `INSTALLATION_KEY_PREVIOUS` permits reads across rotation; old rows
55
+ are re-sealed under the current key. Missing keys, malformed envelopes, wrong
56
+ keys and changed interface AAD fail closed with `installation_key_missing` or
57
+ `installation_key_unavailable` (503), without treating ciphertext as plaintext.
58
+ Rotate hosted custody with `rer deploy --rotate-secret INSTALLATION_KEY`:
59
+ rer retains both values privately, publishes both bindings in one Worker version,
60
+ re-seals every row, checks that every row opens with only the current key, then
61
+ retires the previous Worker binding. Routine rotation uses only the current/previous
62
+ pair; older retired keys require explicit reopen. By default, every retired
63
+ private value stays in the same 0600, Git-ignored file as `SESSION_SECRET`, in
64
+ `INSTALLATION_KEY_RETIRED=<kid>:<value>[,<kid>:<value>...]`; none is routinely
65
+ bound to the Worker. An interrupted operation resumes with the same pair. Back
66
+ up this private custody securely and retain it when moving checkouts.
67
+
68
+ Retain each retired key until no D1 Time Travel recovery point or exported backup
69
+ predates the completed rotation that retired it or otherwise needs that key.
70
+ After any rotation or reopen has finished, edit
71
+ `.rer/deploy/<environment>.secrets.env` and remove only its `<kid>:<value>` entry
72
+ from `INSTALLATION_KEY_RETIRED`, keeping valid comma separators; remove the
73
+ assignment if no entries remain. Preserve the current key, all other entries
74
+ and the file's owned 0600 permissions. There is no per-key removal command;
75
+ reopening a removed ID refuses before provider writes unless its custody is restored.
76
+
77
+ Restoring D1 backups or Time Travel from before a rotation may require an older
78
+ key. `rer deploy --reopen-installation-key KID` explicitly publishes the current
79
+ key and that retained retired key as `INSTALLATION_KEY_PREVIOUS`, re-seals and
80
+ verifies every row under the current key, then removes the previous binding.
81
+ CLI-side reopen rekey uses every validated retired key in private custody, so a
82
+ mid-rotation snapshot containing rows under multiple retired keys can be reopened
83
+ with either retained ID. Only the selected pair is published to the Worker.
84
+ Reopen/rekey reports the D1 `key_ids` tail and whether each history ID is in
85
+ custody before opening rows, including when the tail check refuses the restore.
86
+ It retains retired custody and resumes the same pair after interruption. Missing
87
+ retired custody refuses with `installation_key_unavailable`; recover the private
88
+ file before reopening. A whole pre-rotation D1 restore also restores `key_ids`:
89
+ if its tail is absent from configured custody, reads refuse with
90
+ `installation_key_unavailable` before inspecting envelopes. When that custody
91
+ check succeeds, a historically known envelope key ID whose key is no longer
92
+ configured yields `installation_key_version_unknown` (for example, a row-only
93
+ restore that retains the current installation history);
94
+ wrong configuration, malformed ciphertext and unrecognised key IDs yield
95
+ `installation_key_unavailable`. Neither failure generates a replacement key.
96
+
97
+ Base before #367 cannot open sealed keys. Keep sealing-capable code or roll
98
+ forward after restoring D1. Current Base refuses sealed envelopes on its
99
+ plaintext signing path with `installation_key_sealed_rollback`; old binaries
100
+ cannot acquire that check retroactively.
101
+ Session rotation never changes this key.
102
+
103
+ This protects signing keys in a D1 dump or backup obtained without the Worker
104
+ secret. It does not protect them from a compromised Worker or someone holding
105
+ both the database and the installation secret. Sector/install identity survives re-link,
36
106
  provider moves and export/import. Keys are isolated per interface.
37
107
 
38
108
  Provider origins and metadata endpoints require HTTPS. Under `rer dev` (the
@@ -10,17 +10,17 @@ export function linkedProviders(options) {
10
10
  if(config.dependencies && (staticProviders?.ids.includes('auth') || staticProviders?.callbackPaths?.['/auth/oidc/auth/callback'])) throw new Error('dependency_provider_conflict');
11
11
  async function current() {
12
12
  if (!config.dependencies) return staticProviders;
13
- const store=dependencyStore(db),link=await store.link();
13
+ const store=dependencyStore(db,config),link=await store.link();
14
14
  if(!link || link.needs_relink) return staticProviders;
15
- const row=await store.first("SELECT private_key FROM rer_dependency_keys WHERE interface='oidc-provider@1'");
16
- if(!row?.private_key) return null;
15
+ const row=await store.readKey();
16
+ if(!row) return null;
17
17
  const unclaimed=native?()=>native.unclaimed():async()=>!await db.prepare('SELECT 1 FROM oa_operators LIMIT 1').first();
18
18
  return createOidcProviders({...options, enabled:async()=>await options.enabled() || await unclaimed(), claim:async(request,token,expectedPin)=>{
19
19
  if(!await unclaimed())return null;
20
20
  if(native)return native.claimOwner?native.claimOwner({request,token,expectedPin}):null;
21
21
  return createIdpOwnerClaimHandler({expectedPin,db,authConfig:config,clientIp:()=>options.clientIp(request),clock:options.clock,fetch:options.fetch})(new Request(config.origin+'/auth/owner-claim',{method:'POST',headers:{Host:new URL(config.origin).host,Origin:config.origin,'Content-Type':'application/json'},body:JSON.stringify({token})}));
22
22
  }, claimScope: unclaimed, config:{origin:config.origin,local:config.local,signInPath:config.branding.signInPath,transactionSecret:config.OIDC_TRANSACTION_SECRET ?? config.SESSION_SECRET+'-oidc',providers:[{
23
- id:'auth',preset:'auth',issuer:link.issuer,clientId:link.client_id,privateKey:JSON.parse(row.private_key),
23
+ id:'auth',preset:'auth',issuer:link.issuer,clientId:link.client_id,privateKey:row.key,
24
24
  }]}});
25
25
  }
26
26
  if(!config.dependencies) return staticProviders;
@@ -1,11 +1,16 @@
1
+ import { AuthError } from '../operator-auth/errors.mjs';
1
2
  const encode = bytes => btoa(String.fromCharCode(...bytes)).replaceAll('+','-').replaceAll('/','_').replace(/=+$/,'');
2
3
  const json = value => encode(new TextEncoder().encode(JSON.stringify(value)));
3
4
  export async function keyPair() {
4
5
  const pair = await crypto.subtle.generateKey({name:'ECDSA',namedCurve:'P-256'},true,['sign','verify']);
5
6
  return {...await crypto.subtle.exportKey('jwk',pair.privateKey),kid:crypto.randomUUID(),alg:'ES256',use:'sig'};
6
7
  }
7
- export function publicKey(key) { return {kty:key.kty,crv:key.crv,x:key.x,y:key.y,kid:key.kid,alg:'ES256',use:'sig',key_ops:['verify']}; }
8
+ function requirePlaintextKey(key) {
9
+ if (key && ['version','iv','ciphertext'].some(field => Object.hasOwn(key,field))) throw new AuthError('installation_key_sealed_rollback',503);
10
+ }
11
+ export function publicKey(key) { requirePlaintextKey(key);return {kty:key.kty,crv:key.crv,x:key.x,y:key.y,kid:key.kid,alg:'ES256',use:'sig',key_ops:['verify']}; }
8
12
  export async function assertion(key, claims) {
13
+ requirePlaintextKey(key);
9
14
  const encoded = `${json({alg:'ES256',typ:'JWT',kid:key.kid})}.${json(claims)}`;
10
15
  const imported = await crypto.subtle.importKey('jwk',{...key,key_ops:['sign']},{name:'ECDSA',namedCurve:'P-256'},false,['sign']);
11
16
  return `${encoded}.${encode(new Uint8Array(await crypto.subtle.sign({name:'ECDSA',hash:'SHA-256'},imported,new TextEncoder().encode(encoded))))}`;
@@ -0,0 +1,16 @@
1
+ import { installationKeyId } from './sealing.mjs';
2
+ import { AuthError } from '../operator-auth/errors.mjs';
3
+
4
+ /** Private CLI custody only; never a Worker binding or an archive field. */
5
+ export async function retiredInstallationKeys(value) {
6
+ const retired = new Map();
7
+ if (!value) return retired;
8
+ try {
9
+ for (const entry of value.split(',')) {
10
+ const [kid, secret, extra] = entry.split(':');
11
+ if (extra !== undefined || !kid || retired.has(kid) || await installationKeyId(secret) !== kid) throw new Error('invalid-retired-custody');
12
+ retired.set(kid, secret);
13
+ }
14
+ } catch { throw new AuthError('installation_key_unavailable', 503); }
15
+ return retired;
16
+ }
@@ -1,5 +1,5 @@
1
1
  import type { Database, OperatorAuth } from '../operator-auth/index.mjs';
2
- export function createDependencies<R extends string>(options: { db: Database; origin: string; name: string; provider?: string; local?: boolean; auth: OperatorAuth<R>; claimOwner?:(token:string)=>Promise<Response|null>; clock?: () => number; fetch?: typeof fetch; provides?:string[]; interfaces?: {interface:string;optional?:boolean;provider?:string;paths:string[]}[] }): {document():Promise<unknown>;handle(request:Request):Promise<Response|null>};
2
+ export function createDependencies<R extends string>(options: { db: Database; INSTALLATION_KEY?: string; INSTALLATION_KEY_PREVIOUS?: string; origin: string; name: string; provider?: string; local?: boolean; auth: OperatorAuth<R>; claimOwner?:(token:string)=>Promise<Response|null>; clock?: () => number; fetch?: typeof fetch; provides?:string[]; interfaces?: {interface:string;optional?:boolean;provider?:string;paths:string[]}[] }): {document():Promise<unknown>;handle(request:Request):Promise<Response|null>};
3
3
  export const INTERFACE:string;
4
4
  export const CALLBACK:string;
5
5
  export const PATHS:string[];
@@ -1,6 +1,7 @@
1
1
  import { nativeDependencyAuthority } from './native.mjs';
2
2
  import { approveSetup, approveOwner, approvalFence, callbacksFor } from './approval.mjs';
3
3
  import { dependencyStore } from './store.mjs';
4
+ import { openDependencyKey } from './sealing.mjs';
4
5
  import { publicKey, assertion, digest } from './crypto.mjs';
5
6
  import { isLoopbackHost } from '../operator-auth/loopback.mjs';
6
7
  import { CALLBACK, INTERFACE, PATHS, NETWORK, insist, originOf, providerMetadata } from './protocol.mjs';
@@ -8,17 +9,17 @@ import { readJson } from '../operator-auth/identity/oidc/network.mjs';
8
9
  import { readInput } from '../operator-auth/input.mjs';
9
10
  import { ownerFence, pinStatement } from './authority.mjs';
10
11
  export { INTERFACE, CALLBACK, PATHS } from './protocol.mjs';
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}) {
12
+ export function createDependencies({db,origin,name,provider,interfaces=[{interface:INTERFACE,provider,paths:PATHS}],provides=[],local=false,INSTALLATION_KEY,INSTALLATION_KEY_PREVIOUS,auth,claimOwner,clock=Date.now,fetch:fetcher=globalThis.fetch}) {
12
13
  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)));
13
14
  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('//'))));
14
- const store=dependencyStore(db);
15
+ const store=dependencyStore(db,{INSTALLATION_KEY,INSTALLATION_KEY_PREVIOUS});
15
16
  const native=auth?.native?nativeDependencyAuthority(auth.accounts.dependencies):null;
16
17
  async function owner(request,action) {
17
18
  const actor=await auth.requireStepUp(request,action), current=await auth.accounts.owner();
18
19
  insist(actor.operator.id===current?.id,'owner_required',403);return actor;
19
20
  }
20
21
  async function document() {
21
- const installation=await store.installation(interfaces[0]?.interface??INTERFACE);
22
+ const installation=await store.identity();
22
23
  const linked=await Promise.all(interfaces.map(d=>store.link(d.interface)));
23
24
  return {name,version:1,origin,sector_id:installation.sector_id,dependencies:interfaces.map((d,i)=>({provider:linked[i]?.issuer??d.provider??null,interface:d.interface,optional:d.optional??true,cardinality:1,paths:d.paths.map(p=>origin+p),jwks_uri:origin+'/.well-known/rer-link/jwks/'+d.interface})),provides,
24
25
  claim:interfaces.some(d=>d.interface===INTERFACE) && (native?await native.unclaimed():!await db.prepare('SELECT 1 FROM oa_operators LIMIT 1').first()),callback:origin+CALLBACK,jwks_uri:origin+'/.well-known/rer-link/jwks'};
@@ -48,7 +49,7 @@ export function createDependencies({db,origin,name,provider,interfaces=[{interfa
48
49
  const unchanged=old?{sql:'EXISTS(SELECT 1 FROM rer_dependency_link WHERE interface=? AND issuer=? AND client_id=? AND metadata=? AND needs_relink=? AND linked_at=?)',args:[contract,old.issuer,old.client_id,JSON.stringify(old.metadata),old.needs_relink,old.linked_at]}:{sql:'NOT EXISTS(SELECT 1 FROM rer_dependency_link WHERE interface=?)',args:[contract]};
49
50
  const approval=await approvalFence(pending,contract,expected,callbacks,clock(),pendingPin,native);
50
51
  await db.batch([
51
- db.prepare(`UPDATE rer_dependency_codes SET created_at=CASE WHEN EXISTS(SELECT 1 FROM rer_dependency_keys WHERE interface=? AND json_extract(private_key,'$.kid')=?) AND ${unchanged.sql} AND ${approval.sql} THEN created_at ELSE -1 END WHERE digest=?`).bind(contract,installation.key.kid,...unchanged.args,...approval.args,codeDigest),
52
+ db.prepare(`UPDATE rer_dependency_codes SET created_at=CASE WHEN EXISTS(SELECT 1 FROM rer_dependency_keys WHERE interface=? AND private_key=?) AND ${unchanged.sql} AND ${approval.sql} THEN created_at ELSE -1 END WHERE digest=?`).bind(contract,installation.sealedKey,...unchanged.args,...approval.args,codeDigest),
52
53
  db.prepare(`INSERT INTO rer_dependency_link(interface,issuer,client_id,metadata,needs_relink,linked_at) VALUES(?,?,?,?,0,?) ON CONFLICT(interface) DO UPDATE SET issuer=excluded.issuer,client_id=excluded.client_id,metadata=excluded.metadata,needs_relink=0,linked_at=MAX(rer_dependency_link.linked_at+1,excluded.linked_at)`).bind(contract,expected,result.client_id,JSON.stringify(metadata),clock()),
53
54
  ...(native?await native.linkedStatements({pending,contract,old,issuer:expected,now:clock()}):[
54
55
  ...(contract===INTERFACE?[db.prepare("INSERT INTO oa_auth_audit(id,actor_id,action,value,created_at) SELECT ?,claim_id,'idpSignIn','true',? FROM oa_bootstrap WHERE EXISTS(SELECT 1 FROM oa_auth_settings WHERE singleton=1 AND first_setup=1 AND idp_sign_in=0) AND EXISTS(SELECT 1 FROM oa_setup_links WHERE interface='oidc-provider@1' AND attempt_id=? AND completed=0 AND owner_id=claim_id)").bind(crypto.randomUUID(),clock(),pending.attempt_id)]:[]),
@@ -85,7 +86,7 @@ export function createDependencies({db,origin,name,provider,interfaces=[{interfa
85
86
  db.prepare("INSERT INTO oa_auth_audit VALUES(?,?,'provider:unlink',?,?)").bind(crypto.randomUUID(),actor.operator.id,contract,clock())]:[]),
86
87
  ]);
87
88
  // Local removal is already complete. The provider may be offline.
88
- if(link && key) {try {await readJson(fetcher,link.metadata.link.deregister,NETWORK,{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({client_id:link.client_id,origin,interface:contract,client_assertion_type:'urn:ietf:params:oauth:client-assertion-type:jwt-bearer',client_assertion:await assertion(JSON.parse(key.private_key),{iss:link.client_id,sub:link.client_id,aud:link.metadata.link.deregister,iat:Math.floor(clock()/1000),exp:Math.floor(clock()/1000)+60,jti:crypto.randomUUID()})})});}catch{}}
89
+ if(link && key) {try {await readJson(fetcher,link.metadata.link.deregister,NETWORK,{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({client_id:link.client_id,origin,interface:contract,client_assertion_type:'urn:ietf:params:oauth:client-assertion-type:jwt-bearer',client_assertion:await assertion((await openDependencyKey({INSTALLATION_KEY,INSTALLATION_KEY_PREVIOUS},contract,key.private_key)).key,{iss:link.client_id,sub:link.client_id,aud:link.metadata.link.deregister,iat:Math.floor(clock()/1000),exp:Math.floor(clock()/1000)+60,jti:crypto.randomUUID()})})});}catch{}}
89
90
  return Response.json({unlinked:true});
90
91
  }
91
92
  return {document,async handle(request) {
@@ -0,0 +1,4 @@
1
+ ALTER TABLE rer_dependency_installation ADD COLUMN keys_sealed INTEGER NOT NULL DEFAULT 0 CHECK(keys_sealed IN (0,1));
2
+ -- Nonsecret version history lets restored rows name an unavailable retired key
3
+ -- without confusing ciphertext tampering or a wrong current secret with restore.
4
+ ALTER TABLE rer_dependency_installation ADD COLUMN key_ids TEXT NOT NULL DEFAULT '[]' CHECK(json_valid(key_ids) AND json_type(key_ids)='array');
@@ -0,0 +1,55 @@
1
+ import { utf8, encode, encryptJson, decryptJson } from '../operator-auth/identity/oidc/aes-gcm.mjs';
2
+ import { AuthError } from '../operator-auth/errors.mjs';
3
+ const DOMAIN = 'rer-at-rest-v1:dependency-key';
4
+ const fail = () => { throw new AuthError('installation_key_unavailable', 503); };
5
+ function validSecret(secret) { return typeof secret === 'string' && /^[a-f0-9]{64}$/.test(secret); }
6
+ export function requireInstallationKey(config) {
7
+ if (!validSecret(config.INSTALLATION_KEY)) throw new AuthError('installation_key_missing', 503);
8
+ }
9
+ export async function installationKeyId(secret) {
10
+ requireInstallationKey({ INSTALLATION_KEY: secret });
11
+ return encode(await crypto.subtle.digest('SHA-256', utf8.encode(`${DOMAIN}:key-id\0${secret}`)));
12
+ }
13
+ const aad = (contract, kid) => `rer-at-rest-v1|rer_dependency_keys|${contract}|1|${kid}`;
14
+ async function material(secret) {
15
+ const root = await crypto.subtle.importKey('raw', utf8.encode(secret), 'HKDF', false, ['deriveKey']);
16
+ const key = await crypto.subtle.deriveKey({ name: 'HKDF', hash: 'SHA-256', salt: utf8.encode('rer-at-rest-v1'), info: utf8.encode(DOMAIN) }, root, { name: 'AES-GCM', length: 256 }, false, ['encrypt', 'decrypt']);
17
+ const kid = await installationKeyId(secret);
18
+ return { key, kid };
19
+ }
20
+ function privateJwk(value) {
21
+ return value && value.kty === 'EC' && value.crv === 'P-256' && ['x','y','d'].every(k => typeof value[k] === 'string' && /^[A-Za-z0-9_-]{43}$/.test(value[k])) && typeof value.kid === 'string' && value.kid.length > 0;
22
+ }
23
+ export async function sealDependencyKey(config, contract, value) {
24
+ requireInstallationKey(config);
25
+ if (!privateJwk(value)) fail();
26
+ const { key, kid } = await material(config.INSTALLATION_KEY);
27
+ return JSON.stringify({ version: 1, kid, ...await encryptJson(key, aad(contract, kid), value) });
28
+ }
29
+ export async function openDependencyKey(config, contract, raw, { currentOnly = false, allowPlaintext = false, knownKeyIds, retiredKeys = [] } = {}) {
30
+ requireInstallationKey(config);
31
+ let value;try { value = JSON.parse(raw); } catch { fail(); }
32
+ // Only a complete legacy private JWK is upgradeable. An envelope, even a
33
+ // malformed/unknown one, can never take the legacy plaintext branch.
34
+ if (value && !['version','iv','ciphertext'].some(k => Object.hasOwn(value,k)) && privateJwk(value)) {
35
+ if (currentOnly || !allowPlaintext) fail();
36
+ return { key: value, reseal: true };
37
+ }
38
+ if (!value || value.version !== 1 || typeof value.kid !== 'string' || typeof value.iv !== 'string' || typeof value.ciphertext !== 'string' || Object.keys(value).sort().join(',') !== 'ciphertext,iv,kid,version') fail();
39
+ const secrets = [config.INSTALLATION_KEY, ...(!currentOnly ? [...(validSecret(config.INSTALLATION_KEY_PREVIOUS) ? [config.INSTALLATION_KEY_PREVIOUS] : []), ...retiredKeys] : [])];
40
+ let matched = false;
41
+ for (let i = 0; i < secrets.length; i++) {
42
+ try {
43
+ const { key, kid } = await material(secrets[i]);
44
+ if (kid !== value.kid) continue;
45
+ matched = true;
46
+ const jwk = await decryptJson(key, aad(contract, kid), value);
47
+ if (!privateJwk(jwk)) continue;
48
+ return { key: jwk, reseal: i > 0 };
49
+ } catch { /* Try the remaining explicitly supplied custody, then refuse. */ }
50
+ }
51
+ // Known version IDs contain no key material. They distinguish a missing
52
+ // retired version from tampering or a wrong supplied installation secret.
53
+ if (!matched && (!knownKeyIds || knownKeyIds.includes(value.kid))) throw new AuthError('installation_key_version_unknown', 503);
54
+ fail();
55
+ }
@@ -1,18 +1,71 @@
1
1
  import { keyPair } from './crypto.mjs';
2
- export function dependencyStore(db) {
2
+ import { requireInstallationKey, installationKeyId, sealDependencyKey, openDependencyKey } from './sealing.mjs';
3
+ import { AuthError } from '../operator-auth/errors.mjs';
4
+
5
+ async function sealingState(db, config, row, { retiredKeys = [], report } = {}) {
6
+ requireInstallationKey(config);
7
+ const state = row ?? await db.prepare('SELECT keys_sealed,key_ids FROM rer_dependency_installation WHERE singleton=1').first();
8
+ const ids = JSON.parse(state?.key_ids ?? '[]'), current = await installationKeyId(config.INSTALLATION_KEY);
9
+ const previous = config.INSTALLATION_KEY_PREVIOUS ? await installationKeyId(config.INSTALLATION_KEY_PREVIOUS) : null;
10
+ const available = [current, previous, ...await Promise.all(retiredKeys.map(installationKeyId))];
11
+ report?.({keyIds:ids, tail:ids.at(-1) ?? null, custody:ids.map(kid => ({kid, available:available.includes(kid)}))});
12
+ if (ids.length && !available.includes(ids.at(-1))) throw new AuthError('installation_key_unavailable', 503);
13
+ return { current, ids, options: { allowPlaintext: !state?.keys_sealed, knownKeyIds: ids.length ? ids : undefined, retiredKeys } };
14
+ }
15
+ // Closing the legacy branch is atomic with the last per-row upgrade. This SQL
16
+ // checks envelope shape only; reads never decrypt a sibling interface's key.
17
+ const finishUpgrade = (db, current) => db.prepare(`UPDATE rer_dependency_installation SET keys_sealed=1,key_ids=CASE WHEN json_array_length(key_ids)=0 THEN ? ELSE key_ids END WHERE singleton=1 AND NOT EXISTS(SELECT 1 FROM rer_dependency_keys WHERE (CASE WHEN json_valid(private_key) THEN json_extract(private_key,'$.version')=1 AND json_type(private_key,'$.kid')='text' AND json_type(private_key,'$.iv')='text' AND json_type(private_key,'$.ciphertext')='text' ELSE 0 END) IS NOT 1)`).bind(JSON.stringify([current]));
18
+
19
+ // Rekey alone opens the entire table, then checks the complete current set
20
+ // (including concurrent replacements) before authorizing key retirement.
21
+ export async function resealDependencyKeys(db, config = {}, custody = {}) {
22
+ const state = await sealingState(db, config, undefined, custody);
23
+ const rows = (await db.prepare('SELECT interface,private_key FROM rer_dependency_keys').all()).results;
24
+ const updates = [];
25
+ for (const row of rows) {
26
+ const value = await openDependencyKey(config, row.interface, row.private_key, state.options);
27
+ if (value.reseal) updates.push(db.prepare('UPDATE rer_dependency_keys SET private_key=? WHERE interface=? AND private_key=?').bind(await sealDependencyKey(config, row.interface, value.key), row.interface, row.private_key));
28
+ }
29
+ // Keep all historical IDs, with the current ID last, including a reopen.
30
+ const ids = [...state.ids.filter(id => id !== state.current), state.current];
31
+ await db.batch([...updates, db.prepare('UPDATE rer_dependency_installation SET keys_sealed=1,key_ids=? WHERE singleton=1').bind(JSON.stringify(ids))]);
32
+ for (const row of (await db.prepare('SELECT interface,private_key FROM rer_dependency_keys').all()).results) await openDependencyKey(config, row.interface, row.private_key, { currentOnly: true, knownKeyIds: ids });
33
+ return { resealed: updates.length };
34
+ }
35
+ export function dependencyStore(db, config = {}) {
3
36
  const first=(sql,...args)=>db.prepare(sql).bind(...args).first();
4
37
  const run=(sql,...args)=>db.prepare(sql).bind(...args).run();
38
+ async function identity() {
39
+ requireInstallationKey(config);
40
+ const ids = JSON.stringify([await installationKeyId(config.INSTALLATION_KEY)]);
41
+ await run('INSERT INTO rer_dependency_installation(singleton,sector_id,keys_sealed,key_ids) VALUES(1,?,1,?) ON CONFLICT DO NOTHING',crypto.randomUUID(),ids);
42
+ // An archive retains the sector but omits signing keys. A fresh relink can
43
+ // establish destination custody only while no private row needs an old key.
44
+ await run('UPDATE rer_dependency_installation SET keys_sealed=1,key_ids=? WHERE singleton=1 AND NOT EXISTS(SELECT 1 FROM rer_dependency_keys)',ids);
45
+ return first('SELECT * FROM rer_dependency_installation WHERE singleton=1');
46
+ }
47
+ async function readKey(contract = 'oidc-provider@1') {
48
+ requireInstallationKey(config);
49
+ const row = await first('SELECT k.private_key,i.keys_sealed,i.key_ids FROM rer_dependency_keys k LEFT JOIN rer_dependency_installation i ON i.singleton=1 WHERE k.interface=?',contract);
50
+ if (!row) return null;
51
+ const state = await sealingState(db, config, row);
52
+ const value = await openDependencyKey(config, contract, row.private_key, state.options);
53
+ if (!value.reseal) return { key: value.key, sealedKey: row.private_key };
54
+ await db.batch([
55
+ db.prepare('UPDATE rer_dependency_keys SET private_key=? WHERE interface=? AND private_key=?').bind(await sealDependencyKey(config, contract, value.key), contract, row.private_key),
56
+ finishUpgrade(db, state.current),
57
+ ]);
58
+ // Use the persisted winner if unlink/replacement raced our CAS.
59
+ return readKey(contract);
60
+ }
5
61
  return {
6
- first,run,
62
+ first,run,readKey,identity,
7
63
  async installation(contract = 'oidc-provider@1') {
8
- await run('INSERT INTO rer_dependency_installation(singleton,sector_id) VALUES(1,?) ON CONFLICT DO NOTHING',crypto.randomUUID());
9
- const row=await first('SELECT * FROM rer_dependency_installation WHERE singleton=1');
10
- let key=await first('SELECT private_key FROM rer_dependency_keys WHERE interface=?',contract);
11
- if(!key) {
12
- await run('INSERT INTO rer_dependency_keys(interface,private_key) VALUES(?,?) ON CONFLICT DO NOTHING',contract,JSON.stringify(await keyPair()));
13
- key=await first('SELECT private_key FROM rer_dependency_keys WHERE interface=?',contract);
64
+ const row=await identity();
65
+ if(!await first('SELECT 1 FROM rer_dependency_keys WHERE interface=?',contract)) {
66
+ await run('INSERT INTO rer_dependency_keys(interface,private_key) VALUES(?,?) ON CONFLICT DO NOTHING',contract,await sealDependencyKey(config,contract,await keyPair()));
14
67
  }
15
- return {...row,key:JSON.parse(key.private_key)};
68
+ return {...row,...await readKey(contract)};
16
69
  },
17
70
  async link(contract = 'oidc-provider@1') { const row=await first("SELECT * FROM rer_dependency_link WHERE interface=?",contract);return row?{...row,metadata:JSON.parse(row.metadata)}:null; },
18
71
  };
@@ -123,6 +123,7 @@ A transport failure carries `providerTransport`: the operation, sanitized endpoi
123
123
  - **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.
124
124
  - **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.
125
125
  - **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.
126
+ - **Installation key custody.** The setup manifest generates `INSTALLATION_KEY` independently of `SESSION_SECRET`. Hosted deployment keeps it in the same private, Git-ignored `.rer/deploy/<environment>.secrets.env`, before its first upload; `INSTALLATION_KEY_PREVIOUS` is optional and never generated by setup. `rer deploy --rotate-secret INSTALLATION_KEY` first saves a new/current and old/previous pair there, publishes both bindings in one Worker version, then reseals every dependency-key row through the recorded D1 database and verifies that every row opens with the current key. Only then does it remove the previous Worker binding. Routine rotation uses only the current/previous pair; older retired keys require explicit reopen. By default, every retired key remains in the same private file as `SESSION_SECRET`, in `INSTALLATION_KEY_RETIRED=<kid>:<value>[,<kid>:<value>...]`; retired keys never enter routine Worker bindings or archives. Resealing uses the [D1 transactional batch API](https://developers.cloudflare.com/api/resources/d1/subresources/database/methods/query/). Worker receipt and D1 identity checks precede database access. Any failure retains both saved values; rerun the same rotation command to resume with that exact pair. A D1 backup or Time Travel restore older than a rotation needs the corresponding retired key: `rer deploy --reopen-installation-key KID` publishes current plus only that retired key as previous, reseals and verifies every row through the same recorded D1, then removes the previous binding while retaining all retired custody. CLI-side reopen rekey uses every validated retired key in private custody to open mixed mid-rotation snapshots; only the selected pair is published to the Worker. Before opening rows, rekey reports the D1 `key_ids` tail and custody availability for every history ID. A whole pre-rotation restore with an unavailable tail reports `installation_key_unavailable`; a known row ID without its key reports `installation_key_version_unknown` only after the tail custody check succeeds. Failures retain the reopen marker and exact pair; repeat that command to finish. Missing retired custody refuses with `installation_key_unavailable` before provider writes: recover the private file before reopening. Back up private custody securely for as long as older database recovery points exist. Retain each retired key until no D1 Time Travel recovery point or exported backup predates the completed rotation that retired it or otherwise needs that key. After any rotation or reopen has finished, edit `.rer/deploy/<environment>.secrets.env` and remove only its `<kid>:<value>` entry from `INSTALLATION_KEY_RETIRED`, keeping valid comma separators; remove the assignment if no entries remain. Preserve the current key, all other entries and the file's owned 0600 permissions. There is no per-key removal command; reopening a removed ID refuses before provider writes unless its custody is restored. Base before #367 cannot open sealed keys; roll forward to sealing-capable code. The CLI has neither a Base-version capability receipt nor a code rollback operation, so out-of-band provider rollbacks cannot be checked here; current Base rejects sealed envelopes passed to plaintext signing with `installation_key_sealed_rollback`. Other deployment changes wait for completion. Manual installation-key set/unset, a conflicting supplied current key and a supplied previous key are refused. Without the current private key, restore custody from the deploying checkout before rotating. Neither keys nor database ciphertext appear in output.
126
127
  - **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).
127
128
 
128
129
  R2 removal requires a saved `created` identity (the bucket's creation date). Pending buckets or buckets missing that identity are refused as `uncertain-resource-create`, and same-named replacements as `owned-resource-replaced`, even if empty. For a confirmed bucket, removal automatically lists and deletes its objects before deleting the bucket, checking its identity again before every object delete and the bucket delete. Serialize outside bucket deletion and recreation with removal: the provider cannot make a delete conditional on that identity.
@@ -13,11 +13,12 @@ import { activeWorker, secretBindings } from './worker.mjs';
13
13
  import { ownerSecret } from './owner-secret.mjs';
14
14
  import { ownerRemove } from './owner-remove.mjs';
15
15
  import { ownerSignin } from './owner-signin.mjs';
16
+ import { ownerRekey } from './owner-rekey.mjs';
16
17
  import { refuseLocalModels } from './local-only.mjs';
17
18
  import { publicOrigin } from './public-origin.mjs';
18
19
 
19
20
  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|dry-run|health|remove|inspect|record-owner|signin --declaration <file> --environment <name> [--product <dir>] [--state <file>] [--outcome claimed|kept] | secret ... --set NAME [--set NAME]|--unset NAME [--unset NAME]';
21
+ const usage = 'usage: owner-cli.mjs deploy|dry-run|health|remove|inspect|record-owner|signin|rekey --declaration <file> --environment <name> [--product <dir>] [--state <file>] [--outcome claimed|kept] | secret ... --set NAME [--set NAME]|--unset NAME [--unset NAME]';
21
22
 
22
23
  /** The owner's committed source and existing local build. Run the seed's build first. */
23
24
  async function ownerArtifact(root, product) {
@@ -33,7 +34,7 @@ export async function main(argv = process.argv.slice(2), env = process.env, {fet
33
34
  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
35
  catch { throw new Error('usage'); }
35
36
  const {positionals:[command,...rest],values} = parsed;
36
- if (!['deploy','dry-run','health','secret','remove','inspect','record-owner','signin'].includes(command) || rest.length || !values.declaration || !values.environment) throw new Error('usage');
37
+ if (!['deploy','dry-run','health','secret','remove','inspect','record-owner','signin','rekey'].includes(command) || rest.length || !values.declaration || !values.environment) throw new Error('usage');
37
38
  if ((command === 'secret') !== (values.set !== undefined || values.unset !== undefined) || values.set !== undefined && values.unset !== undefined) throw new Error('usage');
38
39
  if (values.outcome !== undefined && command !== 'record-owner' || command === 'record-owner' && !['claimed','kept'].includes(values.outcome)) throw new Error('usage');
39
40
  await refuseLocalModels(resolve(cwd));
@@ -71,6 +72,7 @@ export async function main(argv = process.argv.slice(2), env = process.env, {fet
71
72
  : await ownerTarget(api,{project:declaration.project,environment:values.environment});
72
73
  const statePath = values.state ? resolve(root,values.state) : join(root,'.rer','deploy',`${target.environment}.json`);
73
74
  if (command === 'remove') return {ok:true,...await ownerRemove({api,target,statePath}).catch(error => { throw api.annotateFailure(error,'remove'); })};
75
+ if (command === 'rekey') return ownerRekey({api,target,statePath,declaration,env,notice});
74
76
  if (command === 'secret') {
75
77
  // Every named secret is changed in one Worker version, or none is.
76
78
  const named = [...new Set(values.set ?? values.unset)], declared = Array.isArray(declaration.secrets) ? declaration.secrets : [];
@@ -0,0 +1,69 @@
1
+ import { assert, uuid } from './validation.mjs';
2
+ import { activeWorker } from './worker.mjs';
3
+ import { checkResourceIdentity, readOwnerState, sameDeployment, withStateLock, ownerResourceName } from './owner.mjs';
4
+ import { retiredInstallationKeys } from '../dependencies/custody.mjs';
5
+
6
+ /** The D1 REST batch is one transaction, matching the Worker's db.batch contract.
7
+ * Nothing from query responses/errors is allowed into deployment diagnostics. */
8
+ function database(api, id) {
9
+ const execute = async body => {
10
+ try {
11
+ const rows = await api.request(`/d1/database/${id}/query`, { method: 'POST', body });
12
+ assert(Array.isArray(rows) && rows.every(row => row?.success === true && Array.isArray(row.results)), 'dependency-rekey-invalid-result');
13
+ return rows;
14
+ } catch { throw new Error('dependency-rekey-query-failed'); }
15
+ };
16
+ const prepare = (sql, params = []) => ({
17
+ sql, params,
18
+ bind(...values) { return prepare(sql, values); },
19
+ async all() { return (await execute({sql, params}))[0]; },
20
+ async first() { return (await this.all()).results[0] ?? null; },
21
+ async run() { return (await execute({sql, params}))[0]; },
22
+ });
23
+ return { prepare, batch: statements => statements.length ? execute({batch:statements.map(({sql,params}) => ({sql,params}))}) : Promise.resolve([]) };
24
+ }
25
+
26
+ /** Reseal the dependency rows in the declared DB only while the receipt still
27
+ * proves both the Worker and its recorded D1 resource belong to this deployment. */
28
+ export async function ownerRekey({ api, target, statePath, declaration, env, notice = line => console.error(line) }) {
29
+ return withStateLock(statePath, async () => {
30
+ const state = await readOwnerState(statePath, target);
31
+ assert(state.receipt && !state.pendingUpload && !state.pendingSecret, 'missing-owner-receipt');
32
+ const owned = async () => {
33
+ const live = await activeWorker(api, target.worker);
34
+ assert(live && sameDeployment(live, state.receipt.provider), 'owned-resource-replaced');
35
+ return live;
36
+ };
37
+ const live = await owned();
38
+ const binding = declaration.d1?.find(item => item.binding === 'DB');
39
+ assert(binding, 'dependency-rekey-missing-database');
40
+ const name = ownerResourceName(target.worker, binding.binding), entry = state.owned.d1[name];
41
+ assert(entry?.status === 'created' && uuid(entry.id), 'dependency-rekey-missing-database');
42
+ const resource = await api.request(`/d1/database/${entry.id}`);
43
+ checkResourceIdentity('d1', name, resource, entry);
44
+ assert(resource?.name === name, 'owned-resource-replaced');
45
+ assert(live.settings?.bindings?.some(item => item.name === binding.binding && item.type === 'd1' && item.id === entry.id), 'dependency-rekey-database-mismatch');
46
+ const config = {};
47
+ for (const key of ['INSTALLATION_KEY', 'INSTALLATION_KEY_PREVIOUS']) {
48
+ const secret = declaration.secrets?.find(item => item.binding === key);
49
+ assert(secret && typeof env[secret.environment] === 'string' && env[secret.environment].trim(), 'dependency-rekey-missing-key');
50
+ config[key] = env[secret.environment];
51
+ assert(live.settings?.bindings?.some(item => item.name === key && item.type === 'secret_text'), 'dependency-rekey-missing-key');
52
+ }
53
+ let result;
54
+ try {
55
+ const { resealDependencyKeys } = await import('../dependencies/store.mjs');
56
+ const retired = await retiredInstallationKeys(env.INSTALLATION_KEY_RETIRED);
57
+ result = await resealDependencyKeys(database(api, entry.id), config, {
58
+ retiredKeys:[...retired.values()],
59
+ report: status => {
60
+ // D1 is untrusted: only well-formed public key IDs enter diagnostics.
61
+ const publicId = kid => /^[A-Za-z0-9_-]{43}$/.test(kid) ? kid : '(invalid key ID)';
62
+ notice(`D1 key_ids tail: ${status.tail === null ? '(empty)' : publicId(status.tail)}; custody: ${status.custody.map(({kid,available}) => `${publicId(kid)}=${available ? 'in custody' : 'unavailable'}`).join(', ') || '(empty)'}`);
63
+ },
64
+ });
65
+ } catch { throw new Error('dependency-rekey-failed'); }
66
+ await owned();
67
+ return { ok: true, resealed: result.resealed };
68
+ });
69
+ }
@@ -208,7 +208,10 @@ trust/configuration change also changes the transaction fingerprint.
208
208
 
209
209
  Apply **only** `identity/oidc/schema/oidc.sql` for shared identity storage, and
210
210
  `modules/dependencies/schema/dependencies.sql` followed by
211
- `modules/dependencies/schema/approval-attempt.sql` if dependency linking is enabled.
211
+ `modules/dependencies/schema/approval-attempt.sql` and
212
+ `modules/dependencies/schema/keys-sealed.sql` if dependency linking is enabled.
213
+ Existing adopters append `keys-sealed.sql` as a new numbered migration; it
214
+ records completion of legacy sealing and nonsecret installation key versions.
212
215
  Existing native adopters add `approval-attempt.sql` as a new numbered migration;
213
216
  it invalidates old approvals, which must be renewed through local owner proof.
214
217
  Their `oa_oidc_*`, `oa_identity_providers` and provider-health names are identity
@@ -0,0 +1,21 @@
1
+ import { check } from './errors.mjs';
2
+ export const utf8 = new TextEncoder();
3
+ export function encode(bytes) { return btoa(String.fromCharCode(...new Uint8Array(bytes))).replaceAll('+', '-').replaceAll('/', '_').replaceAll('=', ''); }
4
+ export function decode(value) {
5
+ check(typeof value === 'string' && /^[A-Za-z0-9_-]+$/.test(value));
6
+ const bytes = Uint8Array.from(atob(value.replaceAll('-', '+').replaceAll('_', '/')), c => c.charCodeAt(0));
7
+ check(encode(bytes) === value);
8
+ return bytes;
9
+ }
10
+ // Both short-lived OIDC transactions and installation data use these primitives.
11
+ // Callers own key derivation and the storage envelope, preserving the OIDC format.
12
+ export async function encryptJson(key, aad, value) {
13
+ const iv = crypto.getRandomValues(new Uint8Array(12));
14
+ const ciphertext = await crypto.subtle.encrypt({ name: 'AES-GCM', iv, additionalData: utf8.encode(aad), tagLength: 128 }, key, utf8.encode(JSON.stringify(value)));
15
+ return { iv: encode(iv), ciphertext: encode(ciphertext) };
16
+ }
17
+ export async function decryptJson(key, aad, value) {
18
+ const iv = decode(value.iv);
19
+ check(iv.length === 12);
20
+ return JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(await crypto.subtle.decrypt({ name: 'AES-GCM', iv, additionalData: utf8.encode(aad), tagLength: 128 }, key, decode(value.ciphertext))));
21
+ }
@@ -1,12 +1,6 @@
1
1
  import { check } from './errors.mjs';
2
- export const utf8 = new TextEncoder();
3
- export function encode(bytes) { return btoa(String.fromCharCode(...new Uint8Array(bytes))).replaceAll('+', '-').replaceAll('/', '_').replaceAll('=', ''); }
4
- export function decode(value) {
5
- check(typeof value === 'string' && /^[A-Za-z0-9_-]+$/.test(value));
6
- const bytes = Uint8Array.from(atob(value.replaceAll('-', '+').replaceAll('_', '/')), c => c.charCodeAt(0));
7
- check(encode(bytes) === value);
8
- return bytes;
9
- }
2
+ import { utf8, encode, encryptJson, decryptJson } from './aes-gcm.mjs';
3
+ export { utf8, encode, decode } from './aes-gcm.mjs';
10
4
  export function random() { return encode(crypto.getRandomValues(new Uint8Array(32))); }
11
5
  export function isRandom(value) { return typeof value === 'string' && /^[A-Za-z0-9_-]{43}$/.test(value); }
12
6
  export async function digest(value) { return encode(await crypto.subtle.digest('SHA-256', utf8.encode(value))); }
@@ -18,12 +12,11 @@ async function encryptionKey(secret) {
18
12
  return crypto.subtle.importKey('raw', await crypto.subtle.digest('SHA-256', utf8.encode(`oidc-v1:encryption\0${secret}`)), 'AES-GCM', false, ['encrypt', 'decrypt']);
19
13
  }
20
14
  export async function seal(secret, stateHash, value) {
21
- const iv = crypto.getRandomValues(new Uint8Array(12));
22
- const ciphertext = await crypto.subtle.encrypt({ name: 'AES-GCM', iv, additionalData: utf8.encode(stateHash) }, await encryptionKey(secret), utf8.encode(JSON.stringify(value)));
23
- return `${encode(iv)}.${encode(ciphertext)}`;
15
+ const { iv, ciphertext } = await encryptJson(await encryptionKey(secret), stateHash, value);
16
+ return `${iv}.${ciphertext}`;
24
17
  }
25
18
  export async function unseal(secret, stateHash, value) {
26
19
  const [iv, ciphertext, extra] = value.split('.');
27
20
  check(!extra);
28
- return JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(await crypto.subtle.decrypt({ name: 'AES-GCM', iv: decode(iv), additionalData: utf8.encode(stateHash) }, await encryptionKey(secret), decode(ciphertext))));
21
+ return decryptJson(await encryptionKey(secret), stateHash, { iv, ciphertext });
29
22
  }
@@ -43,7 +43,7 @@ export interface AuthConfig {
43
43
  dependencies?: boolean;
44
44
  /** Name: 1-80 characters; accent: #rrggbb; signInPath: same-origin absolute path. */
45
45
  branding?: AuthBranding;
46
- origin: string; OWNER_EMAIL: string; SESSION_SECRET: string; SETUP_TOKEN?: string; MAIL_FROM?: string;
46
+ origin: string; OWNER_EMAIL: string; SESSION_SECRET: string; INSTALLATION_KEY?: string; INSTALLATION_KEY_PREVIOUS?: string; SETUP_TOKEN?: string; MAIL_FROM?: string;
47
47
  /** Local HTTP is allowed only for literal localhost, 127.0.0.1 or [::1] with matching Host. */
48
48
  local?: boolean; allowList?: string[]; sessionSeconds?: number; linkSeconds?: number;
49
49
  /** Invitation lifetime in seconds, up to seven days (the default); independent of sign-in/step-up links. */
@@ -13,7 +13,7 @@ export function localVariables(text) {
13
13
 
14
14
  // Inherited application bindings never reach a build or migration command.
15
15
  // The default names are the Base operator-auth and mail bindings.
16
- export const applicationBindings = /^(SESSION_SECRET|SETUP_TOKEN|OWNER_EMAIL|AUTH_|MAIL_|OIDC_|AI_|MODELS_|RER_MODELS_)/
16
+ export const applicationBindings = /^(SESSION_SECRET|INSTALLATION_KEY(?:_PREVIOUS)?$|SETUP_TOKEN|OWNER_EMAIL|AUTH_|MAIL_|OIDC_|AI_|MODELS_|RER_MODELS_)/
17
17
 
18
18
  export function buildEnvironment(bindings = applicationBindings, inherited = process.env) {
19
19
  const env = { ...inherited, CLOUDFLARE_LOAD_DEV_VARS_FROM_DOT_ENV: 'false', CLOUDFLARE_INCLUDE_PROCESS_ENV: 'false', WRANGLER_SEND_METRICS: 'false' }
@@ -23,7 +23,7 @@ export function buildEnvironment(bindings = applicationBindings, inherited = pro
23
23
  }
24
24
 
25
25
  // Values printed by a child are redacted when their name marks a credential.
26
- export const secretValues = (vars) => Object.entries(vars).filter(([key]) => /SECRET|TOKEN|API_KEY/.test(key)).map(([, value]) => value).filter(Boolean)
26
+ export const secretValues = (vars) => Object.entries(vars).filter(([key]) => /SECRET|TOKEN|API_KEY|^INSTALLATION_KEY(?:_PREVIOUS)?$/.test(key)).map(([, value]) => value).filter(Boolean)
27
27
 
28
28
  export function localOrigin(vars) {
29
29
  let url
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@runeditrun/rer",
3
- "version": "0.2.76",
3
+ "version": "0.2.77",
4
4
  "description": "The rer command: install, set up, run and launch Run Edit Run checkouts.",
5
5
  "license": "MIT",
6
6
  "type": "module",