@runeditrun/rer 0.2.122 → 0.2.124

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 (76) hide show
  1. package/cli/README.md +8 -0
  2. package/cli/bounded.mjs +3 -3
  3. package/cli/business/agent-output.mjs +4 -2
  4. package/cli/business/agent-verbs.mjs +10 -4
  5. package/cli/business/api.mjs +12 -9
  6. package/cli/business/carry.mjs +3 -2
  7. package/cli/business/choices.mjs +4 -1
  8. package/cli/business/connect.mjs +2 -1
  9. package/cli/business/local-commands.mjs +4 -1
  10. package/cli/business/mcp-bridge.mjs +7 -2
  11. package/cli/business/questions.mjs +5 -4
  12. package/cli/business/refusal.mjs +47 -0
  13. package/cli/business/run-grant.mjs +15 -16
  14. package/cli/business/setup-command.mjs +7 -2
  15. package/cli/business/supervisor.mjs +4 -1
  16. package/cli/deploy.mjs +2 -1
  17. package/cli/dev-identity.mjs +7 -0
  18. package/cli/errors.mjs +45 -9
  19. package/cli/export.mjs +1 -0
  20. package/cli/inspect.mjs +2 -0
  21. package/cli/main.mjs +17 -3
  22. package/cli/managed-server.mjs +8 -4
  23. package/cli/portability-empty.mjs +4 -2
  24. package/cli/portability-evidence.mjs +9 -1
  25. package/cli/portability-migrations.mjs +30 -8
  26. package/cli/portability-owners.mjs +54 -0
  27. package/cli/portability-worker.mjs +13 -5
  28. package/cli/portability.mjs +6 -4
  29. package/cli/render-warmup.mjs +31 -0
  30. package/cli/setup-input.mjs +14 -2
  31. package/cli/site-private.mjs +9 -1
  32. package/cli/site.mjs +5 -5
  33. package/edition-authoring/cli.mjs +3 -0
  34. package/edition-authoring/project-hashes.mjs +58 -0
  35. package/global/CHANGELOG.md +45 -0
  36. package/global/launch/dev.mjs +2 -2
  37. package/global/launch/render.mjs +12 -1
  38. package/global/launch/state.mjs +11 -4
  39. package/global/launch/worker.mjs +22 -5
  40. package/modules/deploy-kit/owner-cli.mjs +5 -2
  41. package/modules/deploy-kit/owner-remove.mjs +23 -5
  42. package/modules/job-queue/identity.mjs +11 -6
  43. package/modules/job-queue/policy.mjs +16 -2
  44. package/modules/operator-auth/README.md +6 -0
  45. package/modules/operator-auth/accounts/oa.mjs +1 -1
  46. package/modules/operator-auth/dev/index.mjs +32 -14
  47. package/modules/operator-auth/dev/persona-entry.mjs +38 -0
  48. package/modules/operator-auth/dev/persona-grant.mjs +16 -0
  49. package/modules/operator-auth/dev-admission.d.mts +2 -2
  50. package/modules/operator-auth/dev-admission.mjs +2 -2
  51. package/modules/operator-auth/dev-gate-script.mjs +28 -0
  52. package/modules/operator-auth/dev-gate.mjs +7 -10
  53. package/modules/portability/README.md +7 -2
  54. package/modules/portability/bridge.mjs +25 -23
  55. package/modules/portability/checkout-history.mjs +7 -6
  56. package/modules/portability/export.mjs +6 -3
  57. package/modules/portability/format.mjs +2 -2
  58. package/modules/portability/http-errors.mjs +1 -1
  59. package/modules/portability/http.mjs +2 -2
  60. package/modules/portability/import.mjs +13 -11
  61. package/modules/portability/index.d.mts +4 -2
  62. package/modules/portability/index.mjs +2 -2
  63. package/modules/portability/ledgers.mjs +16 -3
  64. package/modules/portability/legacy-files.mjs +3 -3
  65. package/modules/portability/migration-history.mjs +4 -3
  66. package/modules/portability/owner-history.mjs +62 -0
  67. package/modules/portability/worker-history.d.mts +1 -0
  68. package/modules/portability/worker-history.mjs +4 -4
  69. package/modules/release/README.md +7 -0
  70. package/modules/release/produce.mjs +3 -0
  71. package/onboarding/adapter.mjs +9 -9
  72. package/onboarding/commands.mjs +15 -5
  73. package/onboarding/operator-installer.mjs +2 -2
  74. package/onboarding/operator-settings.mjs +10 -8
  75. package/onboarding/redaction.mjs +1 -1
  76. package/package.json +1 -1
@@ -6,6 +6,7 @@ import { readySummary } from '../../cli/ready-summary.mjs';
6
6
  import { launchSummary } from '../../cli/run-transfers.mjs';
7
7
  import { contained } from '../../cli/project.mjs';
8
8
  import { shared } from '../../cli/shared.mjs';
9
+ import { personaOpenUrl, requireDevKey } from '../../cli/dev-identity.mjs';
9
10
 
10
11
  const elapsed = ms => { const s = Math.round(ms / 1000); return s < 60 ? `${s}s` : `${Math.floor(s / 60)}m ${s % 60}s`; };
11
12
  const quiet = 20000;
@@ -28,8 +29,18 @@ export function printer({ json, stopHint, keyless = false, root }) {
28
29
  heartbeat() { if (Date.now() - last >= quiet) progress('waiting', `still ${current} (${elapsed(Date.now() - phaseStarted)}). Allow up to 10 minutes; if this command is stopped, run ~/.local/bin/rer dev again to reattach.`); },
29
30
  // The dispatcher's ready event, as its own human ready lines.
30
31
  async ready(ready, { log, pid }) {
32
+ const link = ready.openUrl ? new URL(ready.openUrl) : null;
33
+ const fragment = new URLSearchParams(link?.hash.slice(1));
31
34
  if (keyless) { const { openUrl, ...rest } = ready; ready = rest; }
32
- else if (root && ready.openUrl && new URLSearchParams(new URL(ready.openUrl).hash.slice(1)).get('rer-dev') === '[REDACTED]') {
35
+ else if (root && fragment.get('rer-persona') === '[REDACTED]') {
36
+ // The journal carries only the grant's public fields. Recreate the
37
+ // signature for this invocation without reading or replacing the owner link.
38
+ const openUrl = await personaOpenUrl(link.origin, await requireDevKey(root), {
39
+ as: fragment.get('as'), email: fragment.get('email'),
40
+ }, Number(fragment.get('expires')));
41
+ ready = { ...ready, openUrl };
42
+ }
43
+ else if (root && fragment.get('rer-dev') === '[REDACTED]') {
33
44
  // The journal never transports the credential. Only the caller's final
34
45
  // handoff reads the private link the dispatcher saved inside .rer/local.
35
46
  const { readPrivateFile } = await shared('private-files.mjs');
@@ -9,7 +9,7 @@
9
9
  // server.json that server's PID and start time, and the process rer spawned
10
10
  // stop.json when rer dev --stop last ran: a launch requested before it stops
11
11
  // pin-install.json the process installing the checkout's pinned rer package
12
- import { appendFile, link, mkdir, readFile, readdir, realpath, rm, writeFile } from 'node:fs/promises';
12
+ import { appendFile, link, mkdir, readFile, readdir, realpath, rm, stat, writeFile } from 'node:fs/promises';
13
13
  import { join } from 'node:path';
14
14
  import { processInfo } from '../../modules/job-queue/processes.mjs';
15
15
  import { serversDirectory } from '../registry.mjs';
@@ -97,12 +97,19 @@ export async function settledPinInstall(checkout, { env = process.env, signal, o
97
97
 
98
98
  // The worker claims the checkout's launch; a second worker started at the
99
99
  // same moment finds the first and leaves.
100
- export async function claimLaunch(directory, token) {
100
+ export async function claimLaunch(directory, token, persona) {
101
101
  const path = join(directory, 'worker.json');
102
102
  for (let attempt = 0; attempt < 3; attempt++) {
103
103
  const { start, title: command } = await processInfo(process.pid), checkout = await realpath(process.cwd());
104
- if (await linkClaim(path, { token, pid: process.pid, start, command, checkout, startedAt: Date.now(), events: `events-${token}.jsonl` })) {
105
- for (const entry of await readdir(directory)) if (/^events-.*\.jsonl$/.test(entry) && entry !== `events-${token}.jsonl`) await rm(join(directory, entry), { force: true });
104
+ if (await linkClaim(path, { token, persona, pid: process.pid, start, command, checkout, startedAt: Date.now(), events: `events-${token}.jsonl` })) {
105
+ // A previous caller can still be reading its ready event when a different
106
+ // persona takes the launch claim. Keep recent journals for those callers.
107
+ const cutoff = Date.now() - 15 * 60_000;
108
+ for (const entry of await readdir(directory)) {
109
+ if (!/^events-.*\.jsonl$/.test(entry)) continue;
110
+ const journal = join(directory, entry);
111
+ if ((await stat(journal)).mtimeMs < cutoff) await rm(journal, { force: true });
112
+ }
106
113
  return true;
107
114
  }
108
115
  if (await liveWorker(directory)) return false;
@@ -9,9 +9,10 @@
9
9
  import { realpath } from 'node:fs/promises';
10
10
  import { join } from 'node:path';
11
11
  import { processInfo } from '../../modules/job-queue/processes.mjs';
12
+ import { setTimeout as delay } from 'node:timers/promises';
12
13
  import { liveServers } from '../registry.mjs';
13
14
  import { LaunchFailure, workerFailure } from './failure.mjs';
14
- import { prepare } from './prepare.mjs';
15
+ import { flagValue, prepare } from './prepare.mjs';
15
16
  import { claimLaunch, eventLog, launchDirectory, liveWorker, releaseLaunch, serverRecord, stopRequest } from './state.mjs';
16
17
  import { startServer } from './steps.mjs';
17
18
  import { captureFile } from './capture.mjs';
@@ -23,10 +24,8 @@ const children = new Set(), stopping = new AbortController();
23
24
  const stop = () => { stopping.abort(); for (const child of children) child.kill('SIGTERM'); };
24
25
  for (const signal of ['SIGTERM', 'SIGINT']) process.on(signal, stop);
25
26
  process.on('SIGHUP', () => {});
26
- if (!await claimLaunch(directory, token)) {
27
- const holder = await liveWorker(directory);
28
- await events.write({ event: 'redirect', token: holder?.token });
29
- } else {
27
+ const persona = flagValue(args, '--as');
28
+ if (await claim()) {
30
29
  const logFile = await captureFile(root, join(directory, 'launch.log'));
31
30
  const log = text => logFile.write(text + '\n');
32
31
  let started;
@@ -63,3 +62,21 @@ if (!await claimLaunch(directory, token)) {
63
62
  // the registered server exits. Repeated launches can prepare independently.
64
63
  await started?.closed;
65
64
  }
65
+
66
+ async function claim() {
67
+ for (;;) {
68
+ if (stopping.signal.aborted || await stopRequest.covers(directory, requestedAt)) {
69
+ await events.write({ event: 'failed', exitCode: 1, message: 'The launch stopped before the app was ready.' });
70
+ return false;
71
+ }
72
+ if (await claimLaunch(directory, token, persona)) return true;
73
+ const holder = await liveWorker(directory);
74
+ if (holder && holder.persona === persona) {
75
+ await events.write({ event: 'redirect', token: holder.token });
76
+ return false;
77
+ }
78
+ // A different persona can share the running server after it is ready. It
79
+ // needs its own handoff, so wait for the current preparation claim to end.
80
+ await delay(200);
81
+ }
82
+ }
@@ -213,10 +213,13 @@ export async function main(argv = process.argv.slice(2), env = process.env, {fet
213
213
  /** Prints refusal codes and resource names only; never inputs, tokens or provider bodies. */
214
214
  export function report(error) {
215
215
  const diagnostic = deployDiagnostic(error);
216
- if (diagnostic) return {ok:false,...diagnostic,...(error.missingSecrets ? {missingSecrets:error.missingSecrets} : {})};
216
+ const names = values => Array.isArray(values) ? values.filter(value => typeof value === 'string' && /^(?:worker|d1|r2|kv|queues|durable-object):[a-zA-Z0-9_.-]{1,128}$/.test(value)) : [];
217
+ const remaining = names(error.remaining), removed = names(error.removed);
218
+ const removal = Array.isArray(error.remaining) ? {removed,remaining,message:`Removed ${removed.join(', ') || 'nothing'}; ${remaining.length} resources remain or could not be verified absent (${remaining.join(', ') || 'none named'}). Keep the deployment record and run the removal again after correcting the cause.`} : {};
219
+ if (diagnostic) return {ok:false,...diagnostic,...removal,...(error.missingSecrets ? {missingSecrets:error.missingSecrets} : {})};
217
220
  if (error.message === 'missing-input') return {ok:false,code:'missing-input',inputs:error.inputs};
218
221
  if (error.message === 'usage') return {ok:false,code:'usage',usage};
219
- return {ok:false,code:/^[a-zA-Z0-9_-]{1,120}$/.test(error.message) ? error.message : 'owner-deploy-failed',...(error.resource ? {resource:error.resource} : {}),...(error.missingSecrets ? {missingSecrets:error.missingSecrets} : {})};
222
+ return {ok:false,code:/^[a-zA-Z0-9_-]{1,120}$/.test(error.message) ? error.message : 'owner-deploy-failed',...removal,...(error.resource ? {resource:error.resource} : {}),...(error.missingSecrets ? {missingSecrets:error.missingSecrets} : {})};
220
223
  }
221
224
  if (process.argv[1] && import.meta.url === pathToFileURL(resolve(process.argv[1])).href) {
222
225
  try { console.log(JSON.stringify(await main())); }
@@ -5,6 +5,7 @@ import { assert, hexId } from './validation.mjs';
5
5
  import { resourceKinds, findResource } from './resources.mjs';
6
6
  import { activeWorker } from './worker.mjs';
7
7
  import { deleteWorker } from './teardown.mjs';
8
+ import { recordDeployFailure } from './diagnostics.mjs';
8
9
  import { query } from './migrations.mjs';
9
10
  import { KINDS, readOwnerState, writeOwnerState, withStateLock, withScopeHints, withSettledLists, workerSettings, sameDeployment, resourceId, checkResourceIdentity, refuse, settlePendingSecret } from './owner.mjs';
10
11
 
@@ -81,15 +82,24 @@ export async function ownerRemove({api: provider, target, statePath, clock, slee
81
82
  await api.request(`/queues/${queue.id}/consumers/${consumer.consumer_id}`, {method:'DELETE'});
82
83
  }
83
84
  }
84
- if (worker) { await deleteWorker({api, worker, signal, ...(clock ? {clock} : {}), ...(sleep ? {sleep} : {})}); removed.push(`worker:${worker}`); }
85
- for (const item of doomed) {
85
+ let workerGone = true;
86
+ if (worker) {
87
+ try { await deleteWorker({api, worker, signal, ...(clock ? {clock} : {}), ...(sleep ? {sleep} : {})}); }
88
+ catch (error) {
89
+ failed.push({resource:`worker:${worker}`, code:error.message, error});
90
+ // Keep a surviving Worker's data. An applied delete with a failed
91
+ // acknowledgement may proceed only after a successful absence read.
92
+ workerGone = false;
93
+ try { workerGone = await workerSettings(api, target.worker) === null; } catch { /* Final readback below retains unverified resources. */ }
94
+ }
95
+ }
96
+ for (const item of workerGone ? doomed : []) {
86
97
  try {
87
98
  if (item.kind === 'r2') await removeBucket(api, item);
88
99
  else {
89
100
  await remove[item.kind](api, item.id, item.name);
90
101
  if (item.kind === 'queues') await waitForQueueRemoval(api,item,{clock,sleep,signal});
91
102
  }
92
- removed.push(`${item.kind}:${item.name}`);
93
103
  }
94
104
  catch (error) { failed.push({resource:`${item.kind}:${item.name}`, code:error.message, error}); }
95
105
  }
@@ -119,6 +129,11 @@ export async function ownerRemove({api: provider, target, statePath, clock, slee
119
129
  }
120
130
  });
121
131
  }
132
+ // A failed response can follow an applied delete or an ancillary cleanup
133
+ // refusal. Only the independent readback decides what was removed.
134
+ for (const resource of [ ...(worker ? [`worker:${worker}`] : []), ...doomed.map(({kind,name}) => `${kind}:${name}`) ]) {
135
+ if (!remaining.has(resource)) removed.push(resource);
136
+ }
122
137
  if (remaining.size || readFailure) {
123
138
  // Keep proof for every survivor or resource whose absence is unverified.
124
139
  for (const kind of KINDS) for (const name of Object.keys(state.owned[kind])) if (!remaining.has(`${kind}:${name}`)) delete state.owned[kind][name];
@@ -127,13 +142,16 @@ export async function ownerRemove({api: provider, target, statePath, clock, slee
127
142
  delete state.ownerClaim; delete state.retiredSecrets;
128
143
  }
129
144
  await writeOwnerState(statePath, state);
130
- throw readFailure ?? new Error('remove-incomplete');
145
+ if (readFailure) throw readFailure;
146
+ const workerFailure = failed.find(item => item.resource === `worker:${target.worker}` && remaining.has(item.resource));
147
+ if (workerFailure) throw workerFailure.error;
148
+ throw recordDeployFailure(new Error(`Removed ${removed.join(', ') || 'nothing'}; ${remaining.size} resources remain (${[...remaining].join(', ')}). Run the same removal command again after correcting the cause.`), {code:'remove-incomplete',step:'remove'});
131
149
  }
132
150
  await rm(statePath, {force:true});
133
151
  return {worker:target.worker, removed, remaining:[]};
134
152
  } catch (error) {
135
153
  error.remaining = [...remaining];
136
- error.failed = failed;
154
+ error.failed = failed.filter(item => remaining.has(item.resource));
137
155
  error.removed = removed.filter(resource => !remaining.has(resource));
138
156
  throw error;
139
157
  }
@@ -14,14 +14,19 @@ export async function identity() {
14
14
  // A prober that timed out or exited may close before the answer is written;
15
15
  // the prober reports that itself, so the answer's EPIPE or ECONNRESET is dropped.
16
16
  const server = createServer(client => { client.on('error', () => {}); client.end(token); });
17
- await new Promise((resolve, reject) => { server.once('error', reject); server.listen(path, resolve); });
18
- await chmod(path, 0o600);
19
- const { title, ...processIdentity } = await processInfo(process.pid);
20
- const info = { ...processIdentity, token, socket: path };
21
- return { info, async close() {
17
+ const close = async () => {
22
18
  await new Promise(resolve => server.close(resolve));
23
19
  await unlink(path).catch(error => { if (error.code !== 'ENOENT') throw error; });
24
- } };
20
+ };
21
+ await new Promise((resolve, reject) => { server.once('error', reject); server.listen(path, resolve); });
22
+ try {
23
+ await chmod(path, 0o600);
24
+ const { title, ...processIdentity } = await processInfo(process.pid);
25
+ return { info: { ...processIdentity, token, socket: path }, close };
26
+ } catch (error) {
27
+ await close().catch(() => {});
28
+ throw error;
29
+ }
25
30
  }
26
31
 
27
32
  export async function alive(owner) {
@@ -25,6 +25,20 @@ export async function callerPolicy(env=process.env) {
25
25
  const ci=!value&&env.CI==='true';
26
26
  // As with identity: a prober that closed first reports that itself.
27
27
  const server=createServer(socket=>{socket.on('error',()=>{});socket.end(JSON.stringify({token,ci}));});
28
- await new Promise((resolve,reject)=>{server.once('error',reject);server.listen(path,resolve);});await chmod(path,0o600);
29
- return {ci,environment:{RER_JOB_POLICY:JSON.stringify({path,token,owner:lifetime.info})},async close(){await new Promise(resolve=>server.close(resolve));await unlink(path).catch(error=>{if(error.code!=='ENOENT')throw error;});await lifetime.close();}};
28
+ const close=async()=>{
29
+ try {
30
+ if(server.listening){
31
+ await new Promise(resolve=>server.close(resolve));
32
+ await unlink(path).catch(error=>{if(error.code!=='ENOENT')throw error;});
33
+ }
34
+ }finally{await lifetime.close();}
35
+ };
36
+ try {
37
+ await new Promise((resolve,reject)=>{server.once('error',reject);server.listen(path,resolve);});
38
+ await chmod(path,0o600);
39
+ return {ci,environment:{RER_JOB_POLICY:JSON.stringify({path,token,owner:lifetime.info})},close};
40
+ }catch(error){
41
+ await close().catch(()=>{});
42
+ throw error;
43
+ }
30
44
  }
@@ -575,6 +575,12 @@ app shows the explicit mark, or the `--rer-logo` its theme declares, as an
575
575
  `<img>` with the product name as its alt text. With neither mark declaration,
576
576
  it shows the product name as text alone.
577
577
 
578
+ Explicit `rer dev --as PERSONA` links carry a 15-minute grant signed with the
579
+ checkout's key and bound to the origin and selected account. The same POST
580
+ exchanges the grant for a dev session and a cookie that admits that session
581
+ only. Persona switching and dev-minted credentials still require the
582
+ checkout-wide gate. Reset invalidates both forms of local entry.
583
+
578
584
  `dev/` is the dev layer: **server-only and local-only**. Import it only from a
579
585
  local-only Worker entry (a Vite-serve or local `wrangler dev` entry), never
580
586
  from the deployed main; its `DEV_LAYER_MARKER` lets `rer build` refuse any output
@@ -27,7 +27,7 @@ export function oaSessions({ config, store, clock }) {
27
27
  const session = await store.session(digest, clock());
28
28
  if (!session || !isActiveOperator(session.operator, config.allowList)) return null;
29
29
  // A dev session counts only behind the local key gate, on every request.
30
- if (session.kind === 'dev' && !await devAdmitted(request)) return null;
30
+ if (session.kind === 'dev' && !await devAdmitted(request, session.id)) return null;
31
31
  if (session.kind === 'review') {
32
32
  requireLoopback(request);
33
33
  if (config.review?.enabled !== true || session.operator.email !== normalizeEmail(config.review.operatorEmail)) return null;
@@ -11,7 +11,7 @@ import { hashToken, opaqueToken } from '../crypto.mjs';
11
11
  import { readCookie, sessionCookie, isLoopbackHost } from '../http.mjs';
12
12
  import { safeReturnTo } from '../policy.mjs';
13
13
  import { isActiveOperator, emailAllowed, defaultRolePolicy } from '../accounts/roles.mjs';
14
- import { devGate, devNotFound } from '../dev-gate.mjs';
14
+ import { DEV_KEY_HEADER, devGate, devNotFound } from '../dev-gate.mjs';
15
15
  import { registerDevAdmission } from '../dev-admission.mjs';
16
16
  import { definePersonas } from './personas.mjs';
17
17
  import { cliSession } from './cli-session.mjs';
@@ -20,6 +20,7 @@ import { representation } from '../representation.mjs';
20
20
  import { decorateLabel } from '../../demo/label.mjs';
21
21
  import { oneClickPage } from '../signin/one-click.mjs';
22
22
  import { hasInvitedPeople } from './invited.mjs';
23
+ import { personaSessions, redeemPersona } from './persona-entry.mjs';
23
24
 
24
25
  export const DEV_LAYER_MARKER = 'rer-dev-layer:local-only-never-deploy';
25
26
  const headers = { 'cache-control': 'no-store', 'referrer-policy': 'no-referrer', 'x-content-type-options': 'nosniff', 'x-robots-tag': 'noindex, nofollow', 'x-rer-dev-layer': DEV_LAYER_MARKER };
@@ -51,13 +52,21 @@ export function withDevIdentity(worker, { bindings = env => env, config: authCon
51
52
  return new URL(request.url).pathname === '/auth/dev/enter' || new URL(request.url).pathname === '/__dev/personas' || new URL(request.url).pathname === '/auth/local/cli-session' ? rejectedResponse(request, devNotFound()) : worker.fetch(request, original, execution);
52
53
  }
53
54
  const gate = devGate({ key: env.RER_DEV_KEY, origin: env.AUTH_ORIGIN, local: env.AUTH_LOCAL === 'true' });
54
- registerDevAdmission(gate && env.RER_DEV_IDENTITY !== 'off' ? r => gate.admitsSession(r) : null);
55
+ const scoped = gate && env.RER_DEV_IDENTITY !== 'off' ? personaSessions(env.RER_DEV_KEY, env.AUTH_ORIGIN) : null;
56
+ registerDevAdmission(scoped ? async (r, id) => await gate.admitsSession(r) ||
57
+ (typeof id === 'string' && !r.headers.has(DEV_KEY_HEADER) && await scoped.admits(r, id)) : null);
55
58
  const path = new URL(request.url).pathname;
56
59
  if (path === '/__dev/key') {
57
60
  if (!gate) return devNotFound();
58
61
  // The guidance names `rer dev --as <email>` only when the app has someone to take.
59
62
  const context = request.method === 'GET' || request.method === 'HEAD' ? identity(env, authConfig, declared) : null;
60
- return gate.exchange(request, authConfig(env).branding, { invited: context ? await hasInvitedPeople({ store: context.store, config: context.config, declared }) : false });
63
+ return gate.exchange(request, authConfig(env).branding, {
64
+ invited: context ? await hasInvitedPeople({ store: context.store, config: context.config, declared }) : false,
65
+ redeemPersona: scoped ? grant => redeemPersona(request, grant, {
66
+ key: env.RER_DEV_KEY, origin: env.AUTH_ORIGIN, context: () => identity(env, authConfig, declared),
67
+ enter: context => enter(request, gate, context, { grant, scoped, key: env.RER_DEV_KEY }),
68
+ }) : undefined,
69
+ });
61
70
  }
62
71
  if (path === '/signin' && gate && env.RER_DEV_IDENTITY !== 'off' && ['GET', 'HEAD'].includes(request.method)) {
63
72
  if (!await gate.admits(request)) return new Response(null, { status: 303, headers: { ...headers, location: '/__dev/key' } });
@@ -139,27 +148,35 @@ function identity(env, authConfig, declared) {
139
148
  };
140
149
  }
141
150
 
142
- async function enter(request, gate, { config, store, hash, current, everyone, ownerProof, auth }) {
143
- if (request.method !== 'GET') return text(405, 'Method not allowed');
144
- const url = new URL(request.url), as = url.searchParams.get('as') ?? 'owner';
151
+ async function enter(request, gate, { config, store, hash, current, everyone, ownerProof, auth }, scope) {
152
+ if (!scope && request.method !== 'GET') return text(405, 'Method not allowed');
153
+ const url = new URL(request.url), as = scope?.grant.as ?? url.searchParams.get('as') ?? 'owner';
154
+ const returnTo = scope ? '/app' : url.searchParams.get('returnTo');
145
155
  const reply = new Headers(headers);
146
156
  // A harness presenting the key header also receives the browser cookie.
147
- if (!(request.headers.get('cookie') ?? '').includes(`${gate.cookieName}=`)) reply.append('set-cookie', await gate.setCookie());
157
+ if (!scope && !(request.headers.get('cookie') ?? '').includes(`${gate.cookieName}=`)) reply.append('set-cookie', await gate.setCookie());
158
+ const complete = async (location, sessionId) => {
159
+ if (scope && sessionId) reply.append('set-cookie', await scope.scoped.cookie(sessionId, config.sessionSeconds));
160
+ reply.set('location', location);
161
+ return new Response(null, { status: 303, headers: reply });
162
+ };
148
163
  const existing = await current(request);
149
164
  if (as === 'signed-out') {
150
165
  const token = readCookie(request, config);
151
166
  if (token) await store.run('UPDATE oa_sessions SET revoked_at=COALESCE(revoked_at,?) WHERE token_hash=?', [Date.now(), await hash(token)]);
152
167
  reply.append('set-cookie', sessionCookie('', config, 0));
153
- reply.set('location', '/');
154
- return new Response(null, { status: 303, headers: reply });
168
+ return complete('/');
155
169
  }
156
170
  const oneClick = async email => {
157
- const value = await auth.oneClick.enter(request, { as: email, returnTo: url.searchParams.get('returnTo') ?? '/app' });
171
+ // The grant has already selected this exact account. Use the internal key
172
+ // to run the ordinary one-click checks and invitation acceptance for it.
173
+ const entry = scope ? new Request(url, { headers: { host: url.host, [DEV_KEY_HEADER]: scope.key } }) : request;
174
+ const value = await auth.oneClick.enter(entry, { as: email, returnTo: returnTo ?? '/app' });
158
175
  reply.append('set-cookie', value.cookie);
159
- reply.set('location', value.returnTo);
160
- return new Response(null, { status: 303, headers: reply });
176
+ return complete(value.returnTo, value.session.id);
161
177
  };
162
178
  const persona = (await everyone()).find(p => p.as === as);
179
+ if (scope && scope.grant.email !== (persona ? persona.email : as)) return devNotFound();
163
180
  if (!persona) return oneClick(as);
164
181
  if (!persona.email) return text(409, 'No active owner remains in this app. Sign in another way, or run ~/.local/bin/rer reset --yes and ~/.local/bin/rer setup for a new owner.' + ' ' + terminalHelp);
165
182
  let operator = await store.byEmail(persona.email);
@@ -187,12 +204,13 @@ async function enter(request, gate, { config, store, hash, current, everyone, ow
187
204
  });
188
205
  const domain = operator.email.slice(operator.email.lastIndexOf('@') + 1);
189
206
  if (operator.role !== 'owner' && await store.domainRule(domain)) return text(403, 'Sign-in refused');
207
+ let sessionId = existing?.id;
190
208
  if (existing?.kind !== 'dev' || existing.operator.id !== operator.id) {
191
209
  const token = opaqueToken(), session = { id: crypto.randomUUID(), hash: await hash(token), expiresAt: Date.now() + config.sessionSeconds * 1000 };
192
210
  const issued = await store.issue({ operatorId: operator.id, expectedVersion: operator.version, session, now: Date.now(), kind: 'dev' });
193
211
  if (!issued) return text(409, 'The operator changed while signing in. Try again.');
194
212
  reply.append('set-cookie', sessionCookie(token, config, config.sessionSeconds));
213
+ sessionId = session.id;
195
214
  }
196
- reply.set('location', safeReturnTo(url.searchParams.get('returnTo')));
197
- return new Response(null, { status: 303, headers: reply });
215
+ return complete(safeReturnTo(returnTo), sessionId);
198
216
  }
@@ -0,0 +1,38 @@
1
+ import { AuthError } from '../errors.mjs';
2
+ import { constantEqual, hashToken } from '../crypto.mjs';
3
+ import { devNotFound, readGateCookie } from '../dev-gate.mjs';
4
+ import { localCookieName, requirePost, sessionCookie } from '../http.mjs';
5
+ import { verifyPersonaGrant } from './persona-grant.mjs';
6
+
7
+ // This second cookie admits only the OA session created by this exchange. The
8
+ // checkout-wide gate still guards persona switching and dev-minted credentials.
9
+ export function personaSessions(key, origin) {
10
+ const cookieName = localCookieName('rer_dev_persona', origin);
11
+ const config = { cookieName, secure: new URL(origin).protocol === 'https:' };
12
+ const signature = id => hashToken(key, 'rer-dev-persona-session', JSON.stringify([origin, id]));
13
+ return {
14
+ async admits(request, id) {
15
+ const presented = readGateCookie(request, cookieName);
16
+ return presented !== null && constantEqual(presented, await signature(id));
17
+ },
18
+ async cookie(id, seconds) {
19
+ return sessionCookie(await signature(id), config, seconds);
20
+ },
21
+ };
22
+ }
23
+
24
+ export async function redeemPersona(request, grant, { key, origin, context, enter }) {
25
+ try {
26
+ if (!await verifyPersonaGrant(key, origin, grant)) return devNotFound();
27
+ const identity = context();
28
+ requirePost(request, identity.config);
29
+ const response = await enter(identity);
30
+ if (response.status !== 303) return response;
31
+ const headers = new Headers(response.headers), location = headers.get('location');
32
+ headers.delete('location');
33
+ return Response.json({ location }, { headers });
34
+ } catch (error) {
35
+ if (error instanceof AuthError) return devNotFound();
36
+ throw error;
37
+ }
38
+ }
@@ -0,0 +1,16 @@
1
+ import { constantEqual, hashToken } from '../crypto.mjs';
2
+
3
+ export const PERSONA_LINK_SECONDS = 900;
4
+
5
+ export function signPersonaGrant(key, origin, { as, email, expires }) {
6
+ return hashToken(key, 'rer-dev-persona-link', JSON.stringify([origin, as, email, expires]));
7
+ }
8
+
9
+ export async function verifyPersonaGrant(key, origin, grant) {
10
+ const now = Math.floor(Date.now() / 1000);
11
+ if (!grant || typeof grant.as !== 'string' || !grant.as
12
+ || (grant.email !== null && typeof grant.email !== 'string')
13
+ || !Number.isSafeInteger(grant.expires) || grant.expires <= now || grant.expires > now + PERSONA_LINK_SECONDS
14
+ || typeof grant.signature !== 'string' || !/^[a-f0-9]{64}$/.test(grant.signature)) return false;
15
+ return constantEqual(grant.signature, await signPersonaGrant(key, origin, grant));
16
+ }
@@ -1,4 +1,4 @@
1
1
  /** Registers the local key gate's check. Only the local-only dev layer calls it; a non-function clears it. */
2
- export function registerDevAdmission(check: ((request: Request) => boolean | Promise<boolean>) | null | undefined): void;
2
+ export function registerDevAdmission(check: ((request: Request, sessionId?: string) => boolean | Promise<boolean>) | null | undefined): void;
3
3
  /** True only when a registered check returns exactly true for this request; false with none registered or when it throws. */
4
- export function devAdmitted(request: Request): Promise<boolean>;
4
+ export function devAdmitted(request: Request, sessionId?: string): Promise<boolean>;
@@ -4,7 +4,7 @@
4
4
  // every dev credential is refused there.
5
5
  let admission = null;
6
6
  export function registerDevAdmission(check) { admission = typeof check === 'function' ? check : null; }
7
- export async function devAdmitted(request) {
7
+ export async function devAdmitted(request, sessionId) {
8
8
  if (!admission) return false;
9
- try { return (await admission(request)) === true; } catch { return false; }
9
+ try { return (await admission(request, sessionId)) === true; } catch { return false; }
10
10
  }
@@ -0,0 +1,28 @@
1
+ import { terminalHelpHtml } from './terminal-guidance.mjs';
2
+
3
+ // Strip the fragment before exchanging either credential. Handle hash changes
4
+ // too, since a new link can target the already-open exchange page.
5
+ export const EXCHANGE_SCRIPT = `(() => {
6
+ async function exchange() {
7
+ const fragment = new URLSearchParams(location.hash.slice(1));
8
+ const key = fragment.get('rer-dev'), signature = fragment.get('rer-persona');
9
+ if (!key && !signature) return;
10
+ history.replaceState(null, '', location.pathname + location.search);
11
+ const as = fragment.get('as');
12
+ const body = signature
13
+ ? { persona: { signature, as, email: fragment.get('email'), expires: Number(fragment.get('expires')) } }
14
+ : { key };
15
+ const response = await fetch('/__dev/key', {
16
+ method: 'POST', credentials: 'same-origin', headers: { 'content-type': 'application/json' }, body: JSON.stringify(body)
17
+ });
18
+ if (!response.ok) {
19
+ document.body.insertAdjacentHTML('beforeend', ${JSON.stringify('<p role="alert">This link no longer opens the app. Run ~/.local/bin/rer dev again for a fresh one.</p>' + `<p>${terminalHelpHtml}</p>`)});
20
+ return;
21
+ }
22
+ const next = signature ? (await response.json()).location : fragment.get('next') ||
23
+ (as ? '/auth/dev/enter?as=' + encodeURIComponent(as) : location.pathname + location.search);
24
+ location.replace(next.startsWith('/') && !next.startsWith('//') && !next.includes('\\\\') ? next : '/');
25
+ }
26
+ addEventListener('hashchange', exchange);
27
+ exchange();
28
+ })()`;
@@ -4,6 +4,8 @@ import { rejectedResponse } from './rejected-response.mjs';
4
4
  import { constantEqual } from './crypto.mjs';
5
5
  import { escapeHtml, isLoopbackHost, localCookieName } from './http.mjs';
6
6
  import { configureBranding } from './branding.mjs';
7
+ import { EXCHANGE_SCRIPT } from './dev-gate-script.mjs';
8
+ export { EXCHANGE_SCRIPT } from './dev-gate-script.mjs';
7
9
 
8
10
  // The local key gate. `rer setup` writes a random RER_DEV_KEY per checkout and
9
11
  // the local runtimes receive it as a binding; a deployed Worker never has one
@@ -31,12 +33,6 @@ async function cookieValue(key) {
31
33
  return Array.from(new Uint8Array(bytes), b => b.toString(16).padStart(2, '0')).join('');
32
34
  }
33
35
 
34
- // Reads `#rer-dev=KEY` (with optional `as` or `next`), removes it from the
35
- // address bar first, then trades it through a same-origin POST. The fragment
36
- // never reaches a server; the key never appears in a query string. Listen for
37
- // fragment navigation too: an open gate page stays loaded when RER_OPEN points
38
- // to the same path with a fresh key fragment.
39
- export const EXCHANGE_SCRIPT = "(()=>{const exchange=()=>{const h=new URLSearchParams(location.hash.slice(1)),k=h.get('rer-dev');if(!k)return;history.replaceState(null,'',location.pathname+location.search);const a=h.get('as'),n=h.get('next')||(a?'/auth/dev/enter?as='+encodeURIComponent(a):location.pathname+location.search),to=n.startsWith('/')&&!n.startsWith('//')&&!n.includes('\\\\')?n:'/';fetch('" + DEV_KEY_PATH + "',{method:'POST',credentials:'same-origin',headers:{'content-type':'application/json'},body:JSON.stringify({key:k})}).then(r=>{if(r.ok)location.replace(to);else document.body.insertAdjacentHTML('beforeend','<p role=\"alert\">This link no longer opens the app. Run ~/.local/bin/rer dev again for a fresh one.</p>" + (`<p>${terminalHelpHtml}</p>`).replaceAll("'", "&#39;") + "')})};addEventListener('hashchange',exchange);exchange()})()";
40
36
  // The hand-off page wears the seed's own theme: the same rer-theme.css tokens and the
41
37
  // same --rer-logo mark the sign-in pages draw. The mark becomes a real <img> named by
42
38
  // the product and shown beside the wordmark text; a seed that declares no logo shows
@@ -58,7 +54,7 @@ export function devNotFound() {
58
54
  'content-security-policy': "default-src 'none'; script-src 'none'; style-src 'none'; base-uri 'none'; form-action 'none'; frame-ancestors 'none'; object-src 'none'" } });
59
55
  }
60
56
 
61
- function readGateCookie(request, name) {
57
+ export function readGateCookie(request, name) {
62
58
  const entries = (request.headers.get('cookie') || '').split(';').map(part => part.trim()).filter(part => part.startsWith(`${name}=`));
63
59
  return entries.length === 1 ? entries[0].slice(name.length + 1) : null;
64
60
  }
@@ -96,7 +92,7 @@ export function devGate({ key, origin, local }) {
96
92
  setCookie,
97
93
  // GET serves the exchange page with the seed's productName, mark and theme; POST trades the key for the cookie.
98
94
  // `invited` says whether the app has a person beyond the owner and its personas for `rer dev --as <email>` to take.
99
- async exchange(request, branding, { invited = false } = {}) {
95
+ async exchange(request, branding, { invited = false, redeemPersona } = {}) {
100
96
  if (new URL(request.url).pathname !== DEV_KEY_PATH) return null;
101
97
  if (request.method === 'GET' || request.method === 'HEAD') {
102
98
  const { script, logo, style } = await exchangeHashes();
@@ -111,8 +107,9 @@ export function devGate({ key, origin, local }) {
111
107
  }
112
108
  if (request.method !== 'POST' || request.headers.get('sec-fetch-site') === 'cross-site' || !request.headers.get('content-type')?.startsWith('application/json')) return rejectedResponse(request, devNotFound());
113
109
  const text = await request.text();
114
- let presented; try { presented = text.length <= 1024 ? JSON.parse(text)?.key : undefined; } catch {}
115
- if (typeof presented !== 'string' || !constantEqual(presented, key)) return devNotFound();
110
+ let presented; try { presented = text.length <= 1024 ? JSON.parse(text) : undefined; } catch {}
111
+ if (presented?.persona && redeemPersona) return redeemPersona(presented.persona);
112
+ if (typeof presented?.key !== 'string' || !constantEqual(presented.key, key)) return devNotFound();
116
113
  return new Response(null, { status: 204, headers: { ...privateHeaders, 'set-cookie': await setCookie() } });
117
114
  },
118
115
  });
@@ -682,8 +682,12 @@ them into a scratch database to find the archive's place in that history:
682
682
  ledger's own names are kept beside their hashes. Import resolves each entry
683
683
  by hash exactly as it does an archived ledger table (next item), so a
684
684
  Platform prefix needs no declaration and a changed file refuses. Platform's
685
- ledger is never imported as product tables. Native sources record no
686
- `migrationLedger`; their archives are unchanged, and v1 and earlier v2
685
+ ledger is never imported as product tables. Native sources with applied
686
+ owner migrations carry `{origin:'d1_migrations',entries:[{name,sha256}]}`
687
+ in the same field. The entries combine core names and prefixed owner names
688
+ in recorded application order. Restore checks those names and hashes against
689
+ the destination's applied history and keeps both ledgers in place. Core-only
690
+ native archives use `manifest.migrations` as before, and v1 and earlier v2
687
691
  archives remain importable.
688
692
  - Older archives that still carry their source's migration ledger as a table
689
693
  (`rer_migrations` and the other ledgers above, from before they became
@@ -1145,6 +1149,7 @@ modules/portability/restore-safety.mjs
1145
1149
  modules/portability/bridge.mjs
1146
1150
  modules/portability/library-history.mjs
1147
1151
  modules/portability/checkout-history.mjs
1152
+ modules/portability/owner-history.mjs
1148
1153
  modules/portability/migration-history.mjs
1149
1154
  modules/portability/ledgers.mjs
1150
1155
  modules/portability/migration-statements.mjs