@runeditrun/rer 0.2.41 → 0.2.43

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 (40) hide show
  1. package/README.md +21 -15
  2. package/cli/browser-runtime.mjs +17 -8
  3. package/cli/contract.mjs +1 -1
  4. package/cli/deploy-command.mjs +12 -0
  5. package/cli/deployment-record.mjs +5 -4
  6. package/cli/dev-identity.mjs +6 -2
  7. package/cli/export-summary.mjs +5 -3
  8. package/cli/hosted-export.mjs +26 -0
  9. package/cli/hydration/browser.mjs +2 -2
  10. package/cli/lifecycle.mjs +18 -5
  11. package/cli/main.mjs +3 -0
  12. package/cli/port.mjs +3 -3
  13. package/cli/portability-worker.mjs +3 -1
  14. package/cli/portability.mjs +7 -3
  15. package/cli/production-mail.mjs +7 -4
  16. package/cli/sqlite-notice.mjs +11 -0
  17. package/cli/transfers.mjs +1 -1
  18. package/global/CHANGELOG.md +18 -0
  19. package/global/README.md +21 -15
  20. package/global/cli/install.mjs +9 -4
  21. package/global/cli/path-link.mjs +42 -9
  22. package/global/cli/repository.mjs +4 -1
  23. package/global/launch/facts.mjs +3 -3
  24. package/global/main.mjs +5 -1
  25. package/global/rer.mjs +1 -1
  26. package/global/run.mjs +64 -0
  27. package/global/update/command.mjs +1 -1
  28. package/install.sh +8 -7
  29. package/modules/operator-auth/README.md +5 -0
  30. package/modules/operator-auth/accounts/display-name.mjs +23 -0
  31. package/modules/operator-auth/index.d.mts +2 -0
  32. package/modules/operator-auth/routes.mjs +4 -3
  33. package/modules/operator-auth/service.mjs +2 -0
  34. package/modules/portability/README.md +13 -1
  35. package/modules/portability/import.mjs +19 -7
  36. package/modules/portability/legacy-safety.mjs +4 -20
  37. package/modules/portability/restore-safety.mjs +23 -0
  38. package/onboarding/port-probe.mjs +4 -2
  39. package/onboarding/process-diagnostics.mjs +4 -1
  40. package/package.json +1 -1
@@ -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" "$@"
@@ -133,6 +133,7 @@ version), domain rules in `oa_domain_rules`. `auth.accounts` exposes it and
133
133
  | `/auth/owner-signin?token=…` | GET/HEAD | 200 owner sign-in confirmation for a live `rer signin` link, or 400 invalid/used/expired; **no writes** |
134
134
  | `/auth/owner-signin` | POST | token; consume once for the active owner it names, 303 with cookie; see "Owner sign-in without mail" |
135
135
  | `/auth/email` | POST | email; the signed-in operator's own sign-in email; fresh step-up proof; 409 `email_in_use` |
136
+ | `/auth/display-name` | POST | displayName; the signed-in operator's own name (1-120 characters); no step-up |
136
137
 
137
138
  Unknown `/auth/*` paths return 404. Unsupported methods return 405. Except for invalid/expired confirmation GET/HEAD documents, known public
138
139
  errors are JSON `{error:code}`: invalid input 400, unauthenticated 401, policy/host/
@@ -476,6 +477,10 @@ link). It revokes unused links sent to the old address and keeps sessions and
476
477
  provider bindings. An address another operator holds is refused with
477
478
  `email_in_use`. `STEP_UP_ACTIONS` gains `email:change`.
478
479
 
480
+ A name is corrected the same way, without a step-up: `POST /auth/display-name
481
+ {displayName}`. First-run `/setup` shows the owner's name as an editable field
482
+ that saves through it. Native accounts do not mount this route.
483
+
479
484
  ## Local dev identity and the key gate
480
485
 
481
486
  `dev-gate.mjs` (exported as `devGate`, production-safe) is the per-checkout key
@@ -0,0 +1,23 @@
1
+ // A signed-in operator corrects the name shown for them: at first-run setup
2
+ // (/setup) and later from the app's settings. It is not a credential, so no
3
+ // fresh proof is needed; the change is fenced to this session and operator version.
4
+ import { deny } from '../errors.mjs';
5
+ import { requirePost } from '../http.mjs';
6
+ import { displayName } from './admin.mjs';
7
+
8
+ export function displayNameChange({ config, store, clock, authenticate }) {
9
+ return {
10
+ async changeDisplayName(request, input) {
11
+ requirePost(request, config);
12
+ const actor = await authenticate(request);
13
+ if (!actor) deny('unauthenticated', 401);
14
+ const name = displayName(input?.displayName);
15
+ if (name !== actor.operator.displayName) {
16
+ const fence = store.actorFence(actor, clock());
17
+ const [changed] = await store.batch([[`UPDATE oa_operators SET display_name=? WHERE id=? AND version=? AND ${fence.sql} RETURNING id`, [name, actor.operator.id, actor.operator.version, ...fence.args]]]);
18
+ if (!changed.results.some(row => row.id === actor.operator.id)) deny('authority_changed', 409);
19
+ }
20
+ return store.operator(actor.operator.id);
21
+ },
22
+ };
23
+ }
@@ -196,6 +196,8 @@ export interface OperatorAuth<R extends string = Role> {
196
196
  confirmOwnerSignIn?(request: Request, input: { token: string }): Promise<CompletedSession<R>>;
197
197
  /** The signed-in operator's own sign-in email; needs a fresh step-up proof. */
198
198
  changeEmail?(request: Request, input: { email: string }): Promise<Operator<R>>;
199
+ /** The signed-in operator's own display name (1-120 characters, trimmed). Absent with native accounts. */
200
+ changeDisplayName?(request: Request, input: { displayName: string }): Promise<Operator<R>>;
199
201
  listDomainRules(request: Request): Promise<DomainRule[]>;
200
202
  /** provider null lifts the rule. Needs a fresh step-up proof. */
201
203
  setDomainRule(request: Request, input: { domain: string; provider: string | null }): Promise<DomainRule[]>;
@@ -41,8 +41,8 @@ export function createAuthHandler(auth) {
41
41
  const preview = await auth.previewLink(request, token);
42
42
  return await confirmationResponse({ branding: auth.presentation, preview, token, method: request.method });
43
43
  }
44
- // Composition without the owner link or email change (native accounts) does not own these paths.
45
- if ((path === OWNER_SIGNIN_PATH && !auth.confirmOwnerSignIn) || (path === '/auth/email' && !auth.changeEmail)) return json({ error: 'not_found' }, 404);
44
+ // Composition without the owner link, email or name change (native accounts) does not own these paths.
45
+ if ((path === OWNER_SIGNIN_PATH && !auth.confirmOwnerSignIn) || (path === '/auth/email' && !auth.changeEmail) || (path === '/auth/display-name' && !auth.changeDisplayName)) return json({ error: 'not_found' }, 404);
46
46
  if (path === OWNER_SIGNIN_PATH && ['GET', 'HEAD'].includes(request.method)) {
47
47
  const token = readParameters(url.searchParams).token ?? null;
48
48
  const preview = await auth.previewOwnerSignIn(request, token);
@@ -65,7 +65,7 @@ export function createAuthHandler(auth) {
65
65
  if (path === '/auth/settings/identity' && request.method === 'GET') {const value=await auth.identitySettings(request);return /text\/html/.test(request.headers.get('accept')??'')?await identitySettingsPage(value,auth.presentation):json(value);}
66
66
  if (path === '/auth/providers' && request.method === 'GET') return json(await auth.listProviders(request));
67
67
  const posts = new Set(['/auth/bootstrap', '/auth/magic-link', '/auth/confirm', '/auth/signout', '/auth/invite', '/auth/invite/cancel', '/auth/review-session',
68
- '/auth/operator/status', '/auth/operator/role', '/auth/session/revoke', '/auth/step-up', '/auth/domain-rules', '/auth/providers/unlink', '/auth/providers/relink', '/auth/settings/identity', '/auth/setup-complete', OWNER_SIGNIN_PATH, '/auth/email']);
68
+ '/auth/operator/status', '/auth/operator/role', '/auth/session/revoke', '/auth/step-up', '/auth/domain-rules', '/auth/providers/unlink', '/auth/providers/relink', '/auth/settings/identity', '/auth/setup-complete', OWNER_SIGNIN_PATH, '/auth/email', '/auth/display-name']);
69
69
  if (!posts.has(path)) return json({ error: 'not_found' }, 404);
70
70
  if (request.method !== 'POST') return json({ error: 'method_not_allowed' }, 405);
71
71
  const query = readParameters(url.searchParams);
@@ -93,6 +93,7 @@ export function createAuthHandler(auth) {
93
93
  case '/auth/confirm': { const value = await auth.confirmLink(request, input); return seeOther(value.returnTo, value.cookie); }
94
94
  case OWNER_SIGNIN_PATH: { const value = await auth.confirmOwnerSignIn(request, input); return seeOther(value.returnTo, value.cookie); }
95
95
  case '/auth/email': return json(await auth.changeEmail(request, input));
96
+ case '/auth/display-name': return json(await auth.changeDisplayName(request, input));
96
97
  case '/auth/review-session': { const value = await auth.issueReviewSession(request, input); return seeOther(value.returnTo, value.cookie); }
97
98
  case '/auth/step-up': {
98
99
  const result = await auth.requestStepUp(request, input);
@@ -18,6 +18,7 @@ import { createAdmission, legacyAdmission } from './identity/admission.mjs';
18
18
  import { createOidcProviders } from './identity/oidc/index.mjs';
19
19
  import { ownerSignIn } from './accounts/owner-signin.mjs';
20
20
  import { emailChange } from './accounts/email-change.mjs';
21
+ import { displayNameChange } from './accounts/display-name.mjs';
21
22
  import { isLocalCli } from './local-cli.mjs';
22
23
  import { devAdmitted } from './dev-admission.mjs';
23
24
  import { oneClickAccounts } from './accounts/one-click.mjs';
@@ -79,6 +80,7 @@ export function createOperatorAuth(options) {
79
80
  ...fencedCredentials({store,authenticate,requireFreshProof,config,clock,hash}),
80
81
  ...ownerSignIn({ config, store, clock, sessions, limit }),
81
82
  ...emailChange({ config, store, clock, authenticate, requireFreshProof }),
83
+ ...displayNameChange({ config, store, clock, authenticate }),
82
84
  presentation: config.branding,
83
85
  oneClick: oneClickAccounts({ config, store, clock, sessions, authorizedLink, requireRoute, afterConfirm: admission.afterConfirm }),
84
86
  emailSignInAvailable: Boolean(mailSender),
@@ -24,7 +24,7 @@ schema at construction. Apply the bookkeeping migration first. Policy fields:
24
24
  | `derivedTables` | Virtual/FTS tables to regenerate; their shadow tables are excluded. |
25
25
  | `secretColumns` | Per-table nullable base columns omitted at export and written as NULL. Primary keys and generated columns cannot be secret. |
26
26
  | `exportRow(table,row)` | Pure, synchronous, idempotent transformation of encoded base cells. Restore writes its result verbatim; SQLite recomputes generated cells. |
27
- | `replaceableTables` | Bootstrap or migration-seeded rows replaced in the atomic restore batch. Populated excluded dependents reachable through modifying FK actions refuse replacement. |
27
+ | `replaceableTables` | Bootstrap rows replaced in the atomic restore batch. Rows the destination's own migrations insert need no entry where the runner passes `migrations` (see "Migration-seeded rows"). Populated excluded dependents reachable through modifying FK actions refuse replacement. |
28
28
  | `requiredConfiguration` | Setting names returned after restore for the owner to re-enter. |
29
29
  | `validateStaged({db,tables,read,manifest})` | Read-only product validation before any object write; false or a thrown error refuses restore. `tables` names the staging tables for bounded SQL queries; `read` is a convenience for small tables. |
30
30
  | `acceptedSchemas` | Map from an earlier full schema hash to `{upgradeRow(table,row)}`. Upgrade functions are pure and synchronous. No older schema is accepted by default. |
@@ -315,6 +315,18 @@ journal adoption and completion. FK cycles and self-references restore together.
315
315
  An unsuccessful commit removes only owned objects. A lost commit acknowledgement
316
316
  is resolved by reading durable completion before any cleanup.
317
317
 
318
+ ### Migration-seeded rows
319
+
320
+ A fresh destination already holds the rows its own migrations insert, such as a
321
+ seed's default settings. When the runner passes `migrations` (Node runners: a
322
+ scratch replay of the destination's applied migrations), finalize treats a target
323
+ table holding exactly those rows as empty: the archive's rows replace them in the
324
+ restore batch, or they stay when the archive predates the table (an additive
325
+ bridge). The batch repeats the check. Any other row refuses with
326
+ `target_not_empty:<table>`, which the CLI reports with the table's name and the
327
+ export, reset and import commands to run. A Worker import has no replay, so a
328
+ hosted restore still needs such tables in `replaceableTables`.
329
+
318
330
  An empty destination must be reserved for restore: pause destination writers and
319
331
  serialize finalize/abort calls. Product writes to source tables can continue.
320
332
  R2 has no compare-and-swap transaction covering bucket emptiness and writes.
@@ -8,7 +8,7 @@ import { checkManifest, checkPart, ContentVerifier, ArchiveVerifier } from './fo
8
8
  import { fence, mergeJournal, tombstone } from './journal.mjs';
9
9
  import { writeObject } from './payloads.mjs';
10
10
  import { createCopy,sidecar,readCopy,restoreCopy } from './copies.mjs';
11
- import { excludedDependentGuards } from './restore-safety.mjs';
11
+ import { excludedDependentGuards, migrationSeeded, seededCondition } from './restore-safety.mjs';
12
12
  import { additiveBridge, sameSchemaMigrations, appliedMigrations } from './bridge.mjs';
13
13
  import { legacyEmptyGuards, legacyAuditStatements, requireLegacyEmpty } from './legacy-safety.mjs';
14
14
  export async function createImport(context,manifest,actor='direct',legacyRecovery) {
@@ -105,8 +105,20 @@ async function bucketsEmpty(context,row) {
105
105
  }while(cursor);
106
106
  }
107
107
  }
108
- function emptyGuards(context,row) {
109
- return row.metadata.targets.filter(t=>!context.config.replaceableTables.includes(t.name)).map(t=>guard(context.db,`NOT EXISTS(SELECT 1 FROM ${quote(t.name)})`));
108
+ function emptyGuards(context,row,seeded) {
109
+ return row.metadata.targets.filter(t=>!context.config.replaceableTables.includes(t.name) && !seeded.some(s=>s.name===t.name)).map(t=>guard(context.db,`NOT EXISTS(SELECT 1 FROM ${quote(t.name)})`));
110
+ }
111
+ // A fresh installation already holds the rows its own migrations insert (settings and
112
+ // other seeded rows). A table holding exactly those, as a node runner's replay of the
113
+ // applied migrations shows, does not make it non-empty: the archive's rows replace
114
+ // them, or they stay when the archive predates the table. Any other row refuses.
115
+ async function destinationState(context,row) {
116
+ const {db,config}=context,filled=[];
117
+ for(const table of row.metadata.targets) if(!config.replaceableTables.includes(table.name) && await statement(db,`SELECT 1 FROM ${quote(table.name)} LIMIT 1`).first())filled.push(table.name);
118
+ const seeded=await migrationSeeded(db,filled,context.migrations);
119
+ for(const name of filled)insist(seeded.some(s=>s.name===name),'target_not_empty:'+name,409);
120
+ const archived=seeded.filter(s=>row.metadata.manifest.tables.some(t=>t.name===s.name)).map(s=>s.name);
121
+ return {seeded,replaced:[...config.replaceableTables,...archived]};
110
122
  }
111
123
  async function removeOwned(context,id) {
112
124
  const owned=await all(context.db,'SELECT bucket,key FROM rer_portability_owned WHERE job=?',id);
@@ -137,8 +149,8 @@ export async function finalizeImport(context,id,{contentHash,archiveHash,laterJo
137
149
  insist(archiveHash===archive.digest(),'archive_checksum',409);
138
150
  const checked=await fence(db,manifest,row.metadata.copies,laterJournal);
139
151
  if(row.metadata.legacyRecovery)await requireLegacyEmpty(context,row.metadata.legacyRecovery);
140
- for(const table of row.metadata.targets) if(!config.replaceableTables.includes(table.name))insist(!(await statement(db,`SELECT 1 FROM ${quote(table.name)} LIMIT 1`).first()),'target_not_empty:'+table.name,409);
141
- const dependentGuards=await excludedDependentGuards(db,row.metadata.targets,config.replaceableTables);
152
+ const {seeded,replaced}=await destinationState(context,row);
153
+ const dependentGuards=await excludedDependentGuards(db,row.metadata.targets,replaced);
142
154
  await bucketsEmpty(context,row);
143
155
  await refuseDevData(db,row.metadata.copies,row.metadata.targets);
144
156
  await refuseProviderData(db,row.metadata.copies,row.metadata.targets);
@@ -160,11 +172,11 @@ export async function finalizeImport(context,id,{contentHash,archiveHash,laterJo
160
172
  }
161
173
  for(const payload of manifest.payloads)await config.extraPayloads[payload.name].consume(binaryStream(context,id,payload,binaryIndexes),payload);
162
174
  row.phase='complete';row.metadata.contentHash=digest;
163
- await db.batch([db.prepare('PRAGMA defer_foreign_keys=ON'),...emptyGuards(context,row),...dependentGuards,...legacyEmptyGuards(db,row),
175
+ await db.batch([db.prepare('PRAGMA defer_foreign_keys=ON'),...emptyGuards(context,row,seeded),...seeded.map(t=>guard(db,...seededCondition(t))),...dependentGuards,...legacyEmptyGuards(db,row),
164
176
  guard(db,'NOT EXISTS(SELECT 1 FROM rer_portability_epochs WHERE source=? AND epoch>?) AND NOT EXISTS(SELECT 1 FROM rer_portability_state WHERE source_identity=? AND epoch>?)',manifest.sourceIdentity,checked.epoch,manifest.sourceIdentity,checked.epoch),
165
177
  ...row.metadata.targets.map(t=>guard(db,`NOT EXISTS(SELECT 1 FROM ${quote(sidecar(row.metadata.copies[t.name]))} s JOIN rer_portability_journal j ON j.source=? AND j.tombstone=s.rer_portability_tombstone)`,manifest.sourceIdentity)),
166
178
  ...row.metadata.triggers.map(t=>db.prepare(`DROP TRIGGER ${quote(t.name)}`)),
167
- ...config.replaceableTables.map(t=>db.prepare(`DELETE FROM ${quote(t)}`)),
179
+ ...replaced.map(t=>db.prepare(`DELETE FROM ${quote(t)}`)),
168
180
  ...row.metadata.targets.flatMap(t=>restoreCopy(db,t,row.metadata.copies[t.name])),
169
181
  ...row.metadata.triggers.map(t=>db.prepare(t.sql)),...mergeJournal(db,manifest,checked),...legacyAuditStatements(db,row),save(db,row),
170
182
  db.prepare('UPDATE rer_portability_state SET import_job=NULL,applying=0 WHERE id=1'),db.prepare('DELETE FROM rer_portability_guard')]);
@@ -1,5 +1,6 @@
1
1
  import { all, statement, guard, quote, insist } from './storage.mjs';
2
2
  import { canonicalJson } from './hash.mjs';
3
+ import { migrationSeeded, seededCondition } from './restore-safety.mjs';
3
4
 
4
5
  // Recovery requires a new installation, including excluded identity tables and
5
6
  // normally replaceable product rows. Only SQLite/migration/transfer bookkeeping,
@@ -18,34 +19,17 @@ function shadowTables(tables) {
18
19
  }
19
20
  return shadows;
20
21
  }
21
- const imageSql=(table,columns)=>`SELECT json_array(${columns.map(c=>`quote(${quote(c)})`).join(',')}) AS image FROM ${quote(table)}`;
22
- const MAX_SEED_ROWS=10000;
23
-
24
22
  /** What the destination must still hold when the restore commits: `emptyTables` stay empty and
25
- * each of `seededTables` keeps exactly the rows its migrations put there. A table with rows the
26
- * replay of the destination's applied migrations (migrations(), a node runner's scratch database)
27
- * does not produce is listed as to-be-empty, so the preflight refuses it. */
23
+ * each of `seededTables` keeps exactly the rows its migrations put there. A table with other rows
24
+ * is listed as to-be-empty, so the preflight refuses it. */
28
25
  export async function legacyTargetState(db,migrations) {
29
26
  const tables=await all(db,"SELECT name,sql FROM sqlite_master WHERE type='table' AND sql IS NOT NULL ORDER BY name"),shadows=shadowTables(tables);
30
27
  const names=tables.map(t=>t.name).filter(name=>!bookkeeping(name) && !shadows.has(name.toLowerCase()));
31
28
  const filled=[];
32
29
  for(const name of names)if(await statement(db,`SELECT 1 FROM ${quote(name)} LIMIT 1`).first())filled.push(name);
33
- const seeded=[];
34
- if(filled.length && migrations) {
35
- const requests=[];
36
- for(const name of filled)requests.push({name,columns:(await all(db,`SELECT name FROM pragma_table_info(?)`,name)).map(c=>c.name)});
37
- // Without a usable replay no seed is vouched for, so those rows count as the installation's own.
38
- const expected=await migrations().then(replay=>replay.rowImages(requests,MAX_SEED_ROWS),()=>new Map());
39
- for(const {name,columns} of requests) {
40
- const want=expected.get(name);
41
- if(!want || (await statement(db,`SELECT count(*) AS n FROM ${quote(name)}`).first()).n!==want.length)continue;
42
- const found=(await all(db,imageSql(name,columns))).map(r=>r.image).sort();
43
- if(canonicalJson(found)===canonicalJson(want))seeded.push({name,columns,images:found});
44
- }
45
- }
30
+ const seeded=await migrationSeeded(db,filled,migrations);
46
31
  return {emptyTables:names.filter(name=>!seeded.some(s=>s.name===name)),seededTables:seeded};
47
32
  }
48
- const seededCondition=table=>[`(SELECT count(*) FROM ${quote(table.name)})=? AND NOT EXISTS(SELECT 1 FROM (${imageSql(table.name,table.columns)}) WHERE image NOT IN (SELECT value FROM json_each(?)))`,table.images.length,JSON.stringify(table.images)];
49
33
  export async function requireLegacyEmpty({db,buckets},{emptyTables,seededTables=[]}) {
50
34
  for(const table of emptyTables)insist(!(await statement(db,`SELECT 1 FROM ${quote(table)} LIMIT 1`).first()),'legacy_target_not_empty:'+table,409);
51
35
  for(const table of seededTables){const [condition,...values]=seededCondition(table);insist((await statement(db,`SELECT CASE WHEN (${condition}) THEN 1 ELSE 0 END AS ok`,...values).first()).ok===1,'legacy_target_not_empty:'+table.name,409);}
@@ -1,4 +1,5 @@
1
1
  import { all,statement,guard,quote,insist } from './storage.mjs';
2
+ import { canonicalJson } from './hash.mjs';
2
3
  const identifier=value=>value.replace(/[A-Z]/g,c=>c.toLowerCase());
3
4
 
4
5
  export async function excludedDependentGuards(db,targets,replaceable) {
@@ -28,3 +29,25 @@ export async function excludedDependentGuards(db,targets,replaceable) {
28
29
  }
29
30
  return guards;
30
31
  }
32
+ const imageSql=(table,columns)=>`SELECT json_array(${columns.map(c=>`quote(${quote(c)})`).join(',')}) AS image FROM ${quote(table)}`;
33
+ const MAX_SEED_ROWS=10000;
34
+
35
+ /** Of the filled tables `names`, those holding exactly the rows the replay of the destination's
36
+ * applied migrations (migrations(), a node runner's scratch database) leaves there: the settings
37
+ * and other rows a fresh installation's own migrations seed. Without a usable replay none is. */
38
+ export async function migrationSeeded(db,names,migrations) {
39
+ if(!names.length || !migrations)return [];
40
+ const requests=[];
41
+ for(const name of names)requests.push({name,columns:(await all(db,`SELECT name FROM pragma_table_info(?)`,name)).map(c=>c.name)});
42
+ // Without a usable replay no seed is vouched for, so those rows count as the installation's own.
43
+ const expected=await migrations().then(replay=>replay.rowImages(requests,MAX_SEED_ROWS),()=>new Map()),seeded=[];
44
+ for(const {name,columns} of requests) {
45
+ const want=expected.get(name);
46
+ if(!want || (await statement(db,`SELECT count(*) AS n FROM ${quote(name)}`).first()).n!==want.length)continue;
47
+ const found=(await all(db,imageSql(name,columns))).map(r=>r.image).sort();
48
+ if(canonicalJson(found)===canonicalJson(want))seeded.push({name,columns,images:found});
49
+ }
50
+ return seeded;
51
+ }
52
+ /** The SQL condition (with its values) that `table` still holds exactly its seeded rows. */
53
+ export const seededCondition=table=>[`(SELECT count(*) FROM ${quote(table.name)})=? AND NOT EXISTS(SELECT 1 FROM (${imageSql(table.name,table.columns)}) WHERE image NOT IN (SELECT value FROM json_each(?)))`,table.images.length,JSON.stringify(table.images)];
@@ -16,13 +16,15 @@ async function bind(host, port) {
16
16
  // A failed diagnostic is unknown, never evidence of a foreign owner. A real
17
17
  // bind can still prove availability. If a bind loses a race but inspection
18
18
  // finds no listener, retry the bind within the same inspection deadline.
19
- export async function probePort(host, port, { context = inspectionContext({ port }), hosts = [host], anyAddress = false } = {}) {
19
+ // A free-port search (`searching`) only needs to move on from a port in use:
20
+ // it skips one on the failed bind alone, without the slow ownership check.
21
+ export async function probePort(host, port, { context = inspectionContext({ port }), hosts = [host], anyAddress = false, searching = false } = {}) {
20
22
  const bindings = async () => {
21
23
  for (const address of hosts) { const result = await bind(address, port); if (!result.available) return result; }
22
24
  return { available: true };
23
25
  };
24
26
  let bound = await bindings(), listener, unchecked;
25
- if (!bound.available && bound.code !== 'EADDRINUSE') return bound;
27
+ if (!bound.available && (bound.code !== 'EADDRINUSE' || searching)) return bound;
26
28
  try { listener = await portListener(port, anyAddress ? undefined : host, context); }
27
29
  catch (error) { if (!uncheckedInspection(error)) throw error; unchecked = error; }
28
30
  if (listener) return { available: false, listener };
@@ -2,7 +2,7 @@ import {execFile} from 'node:child_process';
2
2
  import {promisify} from 'node:util';
3
3
  import {lstat,realpath,readFile,readdir,readlink} from 'node:fs/promises';
4
4
  import {basename,join} from 'node:path';
5
- import {homedir} from 'node:os';
5
+ import {availableParallelism,homedir,loadavg} from 'node:os';
6
6
  import {isIP} from 'node:net';
7
7
  import {setTimeout as delay} from 'node:timers/promises';
8
8
  import {commandFailure,approvedFailure} from './failures.mjs';
@@ -13,6 +13,9 @@ const exec=promisify(execFile);
13
13
  const lsof=process.platform==='darwin'?'/usr/sbin/lsof':'lsof';
14
14
  // One monotonic budget covers every command in an ownership decision.
15
15
  export const inspectionContext=({budgetMs=15000,...details}={})=>({deadline:performance.now()+budgetMs,budgetMs,...details});
16
+ // A free-port search on a busy computer gets longer, still bounded: the budget
17
+ // grows with the 1-minute load per CPU, up to four times.
18
+ export const searchContext=(details={})=>inspectionContext({budgetMs:Math.round(15000*Math.min(4,Math.max(1,loadavg()[0]/availableParallelism()))),...details});
16
19
  export const uncheckedInspection=error=>approvedFailure(error)?.ownershipUnchecked===true;
17
20
  const run=async(command,args,context=inspectionContext(),{maxBuffer=1024*1024,noMatch=false,positiveResult}={})=>{
18
21
  const invocation=[command,...args].join(' ').replaceAll(homedir(),'~');
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@runeditrun/rer",
3
- "version": "0.2.41",
3
+ "version": "0.2.43",
4
4
  "description": "The rer command: install, set up, run and launch Run Edit Run checkouts.",
5
5
  "license": "MIT",
6
6
  "type": "module",