@runeditrun/rer 0.2.28 → 0.2.29

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/contract.mjs CHANGED
@@ -6,7 +6,7 @@ export const commonFlags = ['--help', '--cwd', '--non-interactive', '--json'];
6
6
  const definitions = {
7
7
  install: [[], 'Frozen dependency installation; no setup or global tool changes.'],
8
8
  setup: [['--owner-email', '--owner-name', '--port', '--host', '--answers', '--door'], 'Build, migrate, prepare private settings and first owner; stop the temporary app. --door sets a fresh checkout up at its front-door origin http://NAME.localhost:PORT (after rer door enable).'],
9
- dev: [['--port', '--host', '--idle-timeout', '--stop', '--detach', '--foreground', '--as', '--login', '--models', '--models-service', '--door', '--direct', '--demo'], 'Development with assets, HMR and the declared scheduled triggers run locally on their schedule. --detach returns once ready; --foreground keeps this command serving. With devIdentity it opens signed in as the owner; --as PERSONA picks another start. The legacy --login flag is accepted and uses the same automatic sign-in. --door moves this checkout to its front-door origin http://NAME.localhost:PORT, keeping its data; --direct moves it back; --port and --host serve directly. --demo (or rer demo) serves a throwaway demo: fresh data in .rer/demo/START (deleted when it stops: --stop, Ctrl-C or its end, one hour by default or --idle-timeout), the saved owner signed in, the seed\'s demo data, Demo in the app name and title, real public reads/checks and simulated external writes (RER_DEMO=1; the checkout\'s own data is never touched).'],
9
+ dev: [['--port', '--host', '--idle-timeout', '--stop', '--detach', '--foreground', '--as', '--login', '--models', '--models-service', '--door', '--direct', '--demo'], 'Development with assets, HMR and the declared scheduled triggers run locally on their schedule. --detach returns once ready; --foreground keeps this command serving. With devIdentity it opens signed in as the owner; --as PERSONA or --as EMAIL picks a persona or an invited/active person. The legacy --login flag is accepted and uses the same automatic sign-in. --door moves this checkout to its front-door origin http://NAME.localhost:PORT, keeping its data; --direct moves it back; --port and --host serve directly. --demo (or rer demo) serves a throwaway demo: fresh data in .rer/demo/START (deleted when it stops: --stop, Ctrl-C or its end, one hour by default or --idle-timeout), the saved owner signed in, the seed\'s demo data, Demo in the app name and title, real public reads/checks and simulated external writes (RER_DEMO=1; the checkout\'s own data is never touched).'],
10
10
  preview: [['--port', '--host', '--idle-timeout', '--stop', '--detach', '--foreground'], 'Production output; --detach returns once ready, --foreground keeps this command serving. Reuse intact build, refresh changed assets, preserve owner/state, idle timeout and explicit stop.'],
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.'],
@@ -26,5 +26,5 @@ export const demoVerb = Object.freeze({ flags: [...commonFlags, '--port', '--hos
26
26
  // sign the owner in to, so no seed declares it and check does not ask for it.
27
27
  export const signinVerb = Object.freeze({ flags: [...commonFlags, '--environment', '--env-file'], effects: 'A one-time sign-in link for the hosted owner, without mail. Uses the Cloudflare credentials that deployed --environment (default production; from the environment or --env-file) to write a single-use grant for the recorded owner into that deployment\'s auth database, then prints the link once to this terminal; it is never saved. The link works once, only for that owner, expires within 15 minutes, and its use is recorded in the owner\'s audit log. Signed in this way, the owner can correct a wrong email in settings.' });
28
28
  export const aliases = Object.fromEntries([...Object.keys(verbs).filter(v => v !== 'install'), 'release', 'deps', 'rer'].map(name => [name, name === 'deps' ? 'install' : name === 'rer' ? null : name]));
29
- export const releaseFlags = ['--repo', '--project', '--repository', '--output', '--ref', '--public-base', '--dry-run', '--local-verify', '--tag', '--clean-history', '--onto', '--env-file', '--no-queue'];
29
+ export const releaseFlags = ['--repo', '--project', '--repository', '--output', '--ref', '--public-base', '--dry-run', '--local-verify', '--tag', '--clean-history', '--onto', '--env-file', '--allow-placeholder-mark', '--no-queue'];
30
30
  export const requiredHooks = ['preview', 'dependencies', 'build', 'migrate', 'start', 'health', 'owner', 'signIn', 'verify', 'deploy', 'portability', 'state', 'settings', 'input'];
package/cli/inspect.mjs CHANGED
@@ -21,6 +21,7 @@ import { doorProtocol } from './door.mjs';
21
21
  import { savedOrigin } from './door-mode.mjs';
22
22
  import { probePnpm } from './pnpm-probe.mjs';
23
23
  import { deliveryDeclarationClauses } from './delivery-declarations.mjs';
24
+ import { checkoutPlaceholderMarks } from './placeholder-mark.mjs';
24
25
 
25
26
  // cliVersion: the rer version of the code answering (absent for a vendored copy
26
27
  // too old to record one). defaults: what a server start applies when the person
@@ -73,6 +74,8 @@ async function localState(project) {
73
74
 
74
75
  export async function check(project, explicitProfile) {
75
76
  const clauses = [], add = (id, ok, message) => clauses.push({ id, ok: Boolean(ok), ...(!ok ? { message } : {}) });
77
+ // A warning, never a failing clause: live run sites redeploy while seeds keep Base's mark.
78
+ let placeholderMarks = [];
76
79
  clauses.push(...await deliveryDeclarationClauses(project.root));
77
80
  for (const command of project.commands) add('SC-10.inputs.' + command.name, command.available, `Restore the declared inputs for ${command.name}.`);
78
81
  for (const loop of project.descriptor.loops ?? []) add('SC-10.loop.' + loop.id, !loop.required || loop.enabled, `Enable the required ${loop.id} loop or correct its declaration.`);
@@ -126,9 +129,10 @@ export async function check(project, explicitProfile) {
126
129
  add('SC-08.portability', typeof adapter?.portability?.export === 'function' && typeof adapter?.portability?.import === 'function', 'Adopt the reviewed mainline complete local portability API; archive support remains unavailable until then.');
127
130
  if (adapter?.devIdentity) for (const [id, ok, message] of await devIdentityClauses(project.root, adapter)) add(id, ok, message);
128
131
  for (const [id, ok, message] of await authCopyClauses(project.root)) add(id, ok, message);
132
+ placeholderMarks = await checkoutPlaceholderMarks(project.root, project.descriptor.project);
129
133
  }
130
134
  for(const issue of await localAiDiagnostics(project,process.env))add('AI.'+issue.feature,false,issue.code+': '+issue.message);
131
- return { clauses, ok: clauses.every(clause => clause.ok) };
135
+ return { clauses, ok: clauses.every(clause => clause.ok), placeholderMarks };
132
136
  }
133
137
 
134
138
  // Package mode: the exact pin, its lockfile entry, no vendored copy and no
package/cli/main.mjs CHANGED
@@ -31,6 +31,7 @@ export async function main(argv = process.argv.slice(2)) {
31
31
  if (options.verb === 'describe') { const result = await describe(project); out.human(options.json ? JSON.stringify(result) : JSON.stringify(result, null, 2)); return 0; }
32
32
  if (options.verb === 'check') {
33
33
  const result = await check(project, options.profile);
34
+ (await import('./placeholder-mark.mjs')).warnPlaceholderMarks(out, options, result.placeholderMarks);
34
35
  if (!options.json) for (const clause of result.clauses.filter(c => !c.ok)) out.human(`${clause.id}: ${clause.message}`);
35
36
  out.result(result.ok, result.ok ? 0 : 1, { clauses: result.clauses }); return result.ok ? 0 : 1;
36
37
  }
@@ -42,7 +43,11 @@ export async function main(argv = process.argv.slice(2)) {
42
43
  // The owner link is printed once to this terminal: never through the logged lifecycle.
43
44
  if (options.verb === 'signin') { out.result(true, 0, await (await import('./signin.mjs')).signinCommand(project, options, out)); return 0; }
44
45
  // A checkout without a declared run site refuses --site before any effect.
45
- if (options.site) (await import('./site.mjs')).declaredSite(project);
46
+ if (options.site) {
47
+ const { checkoutPlaceholderMarks, warnPlaceholderMarks } = await import('./placeholder-mark.mjs');
48
+ warnPlaceholderMarks(out, options, await checkoutPlaceholderMarks(project.root, project.descriptor.project));
49
+ (await import('./site.mjs')).declaredSite(project);
50
+ }
46
51
  if (options.verb === 'deploy' && !options.site && !options.demo && !options.remove && !options.setSecret && !options.unsetSecret) {
47
52
  const { deliveryDeclarationClauses } = await import('./delivery-declarations.mjs');
48
53
  const failures = (await deliveryDeclarationClauses(project.root)).filter(clause => !clause.ok);
package/cli/parse.mjs CHANGED
@@ -2,6 +2,7 @@ import { resolve } from 'node:path';
2
2
  import { commonFlags, serverDefaults, signinVerb, verbs } from './contract.mjs';
3
3
  import { invalid, refuse } from './errors.mjs';
4
4
  import { isLoopbackHost } from '../modules/operator-auth/loopback.mjs';
5
+ import { normalizeEmail } from '../modules/operator-auth/policy.mjs';
5
6
  const booleans = new Set(['--help', '--json', '--non-interactive', '--yes', '--dry-run', '--stop', '--detach', '--foreground', '--no-queue', '--login', '--legacy-v1', '--acknowledge-unverified-metadata', '--door', '--direct', '--site', '--remove', '--demo']);
6
7
  export const mailbox = value => typeof value === 'string' && value.length <= 254 && /^[a-zA-Z0-9.!+_%\-]+@[a-zA-Z0-9\-]+(?:\.[a-zA-Z0-9\-]+)+$/.test(value);
7
8
  // A loopback host: the shared predicate (including `*.localhost` door names),
@@ -54,7 +55,13 @@ export function parse(argv, cwd = process.cwd(), { independent = false, deferTai
54
55
  if(options.door&&['--port','--host'].some(flag=>options.supplied.has(flag)))throw invalid('--door cannot be combined with --port or --host, which always serve directly.');
55
56
  if(options.models!==undefined && !['fake','live'].includes(options.models))throw invalid('--models takes fake or live.');
56
57
  if(options.modelsService!==undefined && options.models!=='live')throw invalid('--models-service requires --models live.');
57
- if(options.as!==undefined && !/^[a-z][a-z0-9-]{0,39}$/.test(options.as))throw invalid('--as takes a persona name such as owner, signed-out or admin.');
58
+ if(options.as!==undefined) {
59
+ if(options.as.includes('@')) {
60
+ try { options.as=normalizeEmail(options.as); }
61
+ catch { throw invalid('--as takes a persona name or an invited person\'s email.'); }
62
+ }
63
+ else if(!/^[a-z][a-z0-9-]{0,39}$/.test(options.as))throw invalid('--as takes a persona name or an invited person\'s email.');
64
+ }
58
65
  if(options.demo&&['--door','--direct','--as','--models','--models-service'].some(flag=>options.supplied.has(flag)))throw invalid('A demo opens signed in as the owner on its own data: --demo takes only --port, --host, --idle-timeout, --stop, --detach and --foreground.');
59
66
  if(['dev','preview'].includes(verb) && !options.stop){
60
67
  // A demo ends one hour after it starts unless --idle-timeout says otherwise.
@@ -0,0 +1,46 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { readdir, readFile } from 'node:fs/promises';
3
+ import { join } from 'node:path';
4
+
5
+ // Base's placeholder mark: the "F" every new foundation edition starts with
6
+ // (foundation/template/public/brand/mark.svg). `rer check` and run site builds
7
+ // warn while a seed carries it (a live run site's redeploy never breaks over
8
+ // it); `rer release` refuses it unless --allow-placeholder-mark is given. Base's
9
+ // own projects (the foundation template and the default seed) are exempt.
10
+ const placeholder = new Set(['c2c2a7325e51067c043bbd8a945e830ba6caeea4ca298615e310a931a58a181d']);
11
+ const baseProjects = new Set(['example/foundation', 'runeditrun/default-seed-reference']);
12
+ const image = /\.(svg|ico|png|webp|jpe?g|gif)$/i;
13
+ const skipped = new Set(['node_modules', '.git', '.wrangler', '.rer', '.seed', '.cache', 'dist', 'scripts/base-cli', 'scripts/base-onboarding']);
14
+
15
+ const sha256 = bytes => createHash('sha256').update(bytes).digest('hex');
16
+ export const placeholderMessage = files => `Base's placeholder mark is still in ${files.join(', ')}; replace with the seed's own mark.`;
17
+
18
+ /** One plain warning line (a JSON warning event under --json); never a failure. */
19
+ export function warnPlaceholderMarks(out, options, files) {
20
+ if (!files.length) return;
21
+ if (options.json) out.event('warning', { code: 'placeholder_mark', files, message: placeholderMessage(files) });
22
+ else out.progress(`Warning: ${placeholderMessage(files)}\n`);
23
+ }
24
+
25
+ /** The image paths whose bytes are Base's placeholder mark, unless the project is Base's own. */
26
+ export async function placeholderMarks(project, paths, read) {
27
+ if (baseProjects.has(project)) return [];
28
+ const found = [];
29
+ for (const path of paths) if (image.test(path) && placeholder.has(sha256(await read(path)))) found.push(path);
30
+ return found.sort();
31
+ }
32
+
33
+ /** The checkout's own logo, favicon and app mark files carrying the placeholder. */
34
+ export async function checkoutPlaceholderMarks(root, project) {
35
+ const paths = [];
36
+ async function walk(path) {
37
+ for (const entry of await readdir(join(root, path), { withFileTypes: true })) {
38
+ const name = path ? `${path}/${entry.name}` : entry.name;
39
+ if (skipped.has(entry.name) || skipped.has(name)) continue;
40
+ if (entry.isDirectory()) await walk(name);
41
+ else if (entry.isFile()) paths.push(name);
42
+ }
43
+ }
44
+ await walk('');
45
+ return placeholderMarks(project, paths, path => readFile(join(root, path)));
46
+ }
package/cli/release.mjs CHANGED
@@ -24,6 +24,9 @@ Without --tag, write a preview. This command never pushes, uploads or deploys.
24
24
  Prepare a public child of the destination's current branch;
25
25
  cannot be combined with --clean-history.
26
26
  --env-file FILE Credential file for publication inspection.
27
+ --allow-placeholder-mark
28
+ Release while the seed still carries Base's placeholder
29
+ mark; the receipt records the files.
27
30
  --no-queue Bypass the job queue only in the original CI environment.
28
31
  --help Print this help without performing release work.
29
32
 
@@ -48,6 +51,7 @@ export async function dispatchRelease(args) {
48
51
  else if (args[index] === '--tag') options.tag = args[index + 1]?.startsWith('v') ? args[++index] : true;
49
52
  else if (args[index] === '--clean-history') options.cleanHistory = true;
50
53
  else if (args[index] === '--dry-run') options.dryRun = true;
54
+ else if (args[index] === '--allow-placeholder-mark') options.allowPlaceholderMark = true;
51
55
  else if (args[index] === '--local-verify') options.localVerify = true;
52
56
  else if (['--repo', '--project', '--repository', '--output', '--ref', '--env-file', '--onto', '--public-base'].includes(args[index]) && args[index + 1] && !args[index + 1].startsWith('--'))
53
57
  options[args[index] === '--env-file' ? 'envFile' : args[index] === '--public-base' ? 'publicBase' : args[index].slice(2)] = args[++index];
@@ -59,8 +63,8 @@ export async function dispatchRelease(args) {
59
63
  const receipt = await release(options);
60
64
  console.log(JSON.stringify(receipt, null, 2));
61
65
  return receipt.status === 'BLOCKED' ? 1 : 0;
62
- } catch {
63
- console.error('Release failed during argument, source or artifact validation. No release completed.');
66
+ } catch (error) {
67
+ console.error(error?.code === 'placeholder_mark' ? error.message : 'Release failed during argument, source or artifact validation. No release completed.');
64
68
  return 2;
65
69
  }
66
70
  }
@@ -1,5 +1,19 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.2.29
4
+
5
+ - **Placeholder mark (SC-14).** While a seed's logo, favicon or app mark is byte-equal to Base's placeholder mark, `rer check --profile first-party`, `rer build --site` and `rer deploy --site` print one warning naming the files (a `placeholder_mark` warning event under `--json`) and still succeed. `rer release` refuses the placeholder unless `--allow-placeholder-mark` is given; the receipt then records `placeholderMark: { allowed: true, files }`. Base's own projects are exempt.
6
+ - **Readable actors and evidence.** `foundation/runtime/actor.ts` (seeds: `src/base/actor.ts`): `actorLine` renders "<display name> · <time in the business time zone>", with "Former member" for an unknown actor. `evidenceHtml`/`evidenceFields` render evidence or details as labelled fields, never raw JSON or `[object Object]`. `EditionIdentity` gains an optional `timeZone`.
7
+ - **Refresh-safe forms.** `foundation/runtime/command-receipts.ts` and `.sql`: create forms carry a command key, and `runOnce` returns the first result for a replayed POST (409 while it is in flight). `seeOther` answers 303 to a GET. One-time secrets are read from the receipt once. Archives never carry `rer_command_receipts`; new foundations get `0015_command_receipts.sql`. In the default seed, `/app/people` is server-rendered and `POST /api/people` honours `Idempotency-Key` (migration `0025_command_receipts.sql`).
8
+ - **Invited people sign in with one click in dev and demo.** Invited and active people get the owner's **Sign in as <name>** action at `/signin` and beside their operator record. `rer dev --as EMAIL` prints their one-click entry. Mail stays suppressed and there is no outbox. Invitation expiry, cancellation, role, allow-list and inviter-authority checks still apply. Production keeps email sign-in and refuses the one-click route.
9
+ - **Mail threading.** The `rer` mail adapter sends an optional `messageKey` (1–200 characters of `[A-Za-z0-9._:-]`, validated before any request) and returns the relay's Message-ID as `providerMessageId`, so a follow-up can set In-Reply-To/References. Other providers refuse `messageKey`.
10
+ - **Browser-free agent check.** The default seed and foundation template declare `verify:agent` (build, typecheck, offline `source:check`, `verify:base-source`). Platform runs it ahead of `verify:fast`; full `rer verify` stays in CI.
11
+
12
+ ### Upgrade notes
13
+
14
+ - Update the exact rer package pin, or refresh vendored operating commands, to receive these changes. Seeds adopt the runtime files (`src/base/actor.ts`, `src/base/command-receipts.ts` and the receipts migration) on their next Base refresh; see "Seed mark, readable actors and refresh-safe forms" in SEED-COMMAND-CONTRACT.md.
15
+ - A seed still carrying Base's placeholder mark now needs `rer release --allow-placeholder-mark` until it has its own mark.
16
+
3
17
  ## 0.2.28
4
18
 
5
19
  - `rer release` of a GitHub source uses the exact source commit's completed successful **Verify** run instead of re-running the seed's full verification locally. Only a `push` or `workflow_dispatch` run on the default branch, or on the version's release tag when that tag resolves remotely to the same commit, qualifies; PR runs, other SHAs, repositories, branches and unsuccessful runs do not. The receipt and site provenance record the repository, commit, workflow, run id and URL. The producer still installs frozen dependencies, runs the committed `build` script, scans publication history and packages locally; a local install or build failure still blocks. A missing green Verify, or a GitHub API or authentication failure, blocks and names the exact SHA.
@@ -177,10 +177,23 @@ accepts 1–20 such IDs separated by ASCII spaces, without leading/trailing
177
177
  spaces, tabs or commas. Invalid values fail locally with `invalid_list_id`,
178
178
  `invalid_list_archive`, `invalid_list_help`, `invalid_in_reply_to` or
179
179
  `invalid_references`. Values are preserved; raw headers are never forwarded.
180
- Other recipients, attachments, reply-to and every other header are unsupported
181
- and fail before dispatch.
182
-
183
- HTTP 202 returns `accepted` with no provider message ID. HTTP 400, 401, 402,
180
+ Other recipients, attachments, reply-to and every other header, including
181
+ `Message-ID`, are unsupported and fail before dispatch.
182
+
183
+ An optional `messageKey` asks the relay to assign the Message-ID: 1–200 ASCII
184
+ characters from `A-Z a-z 0-9 . _ : -`, matching platform's relay validation at
185
+ `c1e3ade` (`src/managed-mail/headers.ts:22`); anything else fails locally with
186
+ `invalid_message_key`. The relay derives the same ID for the same installation
187
+ and key, so use one key per message (for example `incident:7:opened`, then
188
+ `incident:7:update-1`). Keys assign identity, not duplicate suppression. To
189
+ thread updates, keep the first notice's returned `providerMessageId` and send
190
+ each later update with its own key and `In-Reply-To`/`References` set to it.
191
+ Only `rer` (and `development`, which accepts what `rer` accepts) takes
192
+ `messageKey`; other providers refuse it with `unsupported_provider_setting`.
193
+
194
+ HTTP 202 returns `accepted` with the relay's assigned Message-ID (for example
195
+ `<ABCD…@mail.example.com>`) as `providerMessageId`, or null when the relay's
196
+ body carries no valid one. HTTP 400, 401, 402,
184
197
  403 and 413 return `rejected`, and so does any 3xx (`provider_redirected`);
185
198
  429 returns `rate_limited`; 502 and 503 return `uncertain`. Network failures
186
199
  are also `uncertain`.
@@ -191,7 +204,7 @@ adapter makes no retries and never reads or logs provider error bodies.
191
204
 
192
205
  Required fields: `deliveryId` (nonempty, at most 512 characters), `from`, nonempty `to: string[]`, `subject: string` (SendGrid requires nonempty; other providers allow empty), and at least one nonempty `text` or `html`. Addresses accept a mailbox or `Display Name <mailbox>`; the conservative mailbox grammar rejects controls, multiple addresses inside one string and malformed domains. Use arrays for recipients.
193
206
 
194
- Optional `cc`, `bcc`, `replyTo`, and string-valued `headers` preserve envelope and threading. `In-Reply-To` and ordered `References` can be supplied as headers. SendGrid and Resend also accept `Message-ID`; Cloudflare generates it and rejects a caller-supplied value. CR/LF/control characters, duplicate header names ignoring case, reserved envelope/MIME/security headers and invalid header names fail before a request. Provider-specific header restrictions are also enforced.
207
+ Optional `cc`, `bcc`, `replyTo`, and string-valued `headers` preserve envelope and threading. `In-Reply-To` and ordered `References` can be supplied as headers. SendGrid and Resend also accept `Message-ID`; Cloudflare generates it and rejects a caller-supplied value; `rer` rejects it and assigns one from an optional `messageKey`. CR/LF/control characters, duplicate header names ignoring case, reserved envelope/MIME/security headers and invalid header names fail before a request. Provider-specific header restrictions are also enforced.
195
208
 
196
209
  Attachments use `{filename, contentType, content: Uint8Array, disposition?: 'attachment'|'inline', contentId?}`. Content is raw bytes, never a base64 string at the public boundary. Inline attachments require a content ID. Unsupported attachment features fail explicitly. Provider size and count limits still apply.
197
210
 
@@ -5,6 +5,11 @@ import { rerListHeaderField } from './list-headers.mjs';
5
5
  const listEntries = /^[ \t]*<([^<>\s]+)>[ \t]*(?:,[ \t]*<([^<>\s]+)>[ \t]*)?$/;
6
6
  const relayMailbox = /^[^\s@]+@[^\s@]+\.[^\s@]{2,}$/;
7
7
 
8
+ // Match platform c1e3ade01eecd4d027a4f5ed0304d5f6bd7da6bb: src/managed-mail/headers.ts:22.
9
+ export function validateRerMessageKey(value) {
10
+ if (typeof value !== 'string' || value.length < 1 || value.length > 200 || /[^A-Za-z0-9._:-]/.test(value)) fail('invalid_message_key');
11
+ }
12
+
8
13
  export function validateRerConfig(config) {
9
14
  let url;
10
15
  try { url = new URL(config.relayUrl); } catch { fail('rer_relay_url_required'); }
@@ -2,6 +2,7 @@ import { validateConfig, validateMessage, parseAddress } from '../../core/valida
2
2
  import { fail } from '../../core/errors.mjs';
3
3
  import { requestProvider, redirected, classifyHttpStatus, sendResult } from '../../core/transport.mjs';
4
4
  import { rerHeaderFields } from './contract.mjs';
5
+ import { rerMessageId } from './list-headers.mjs';
5
6
 
6
7
  /** One Managed relay submission. RER owns the sender and installation identity. */
7
8
  export async function sendRer(config, message, dependencies = {}) {
@@ -13,6 +14,7 @@ export async function sendRer(config, message, dependencies = {}) {
13
14
  subject: message.subject,
14
15
  text: message.text,
15
16
  ...(message.html ? { html: message.html } : {}),
17
+ ...(message.messageKey !== undefined ? { messageKey: message.messageKey } : {}),
16
18
  ...rerHeaderFields(message.headers),
17
19
  });
18
20
  if (new TextEncoder().encode(body).byteLength > 128 * 1024) fail('rer_message_too_large');
@@ -24,8 +26,8 @@ export async function sendRer(config, message, dependencies = {}) {
24
26
  }, dependencies);
25
27
  if (response === null) return sendResult('rer', 'uncertain', null, 'transport_uncertain');
26
28
  if (response === redirected) return sendResult('rer', 'rejected', null, 'provider_redirected');
27
- // Do not consume provider bodies: they may contain credentials or personal data.
28
- if (response.status === 202) return sendResult('rer', 'accepted');
29
+ // Read only the accepted body's Message-ID; error bodies may contain credentials or personal data.
30
+ if (response.status === 202) return sendResult('rer', 'accepted', rerMessageId(await response.json().then(body => body?.messageId, () => null)));
29
31
  const status = classifyHttpStatus(response.status) ?? 'uncertain';
30
32
  return sendResult('rer', status, null, {
31
33
  rejected: 'provider_rejected', rate_limited: 'provider_rate_limited', uncertain: 'provider_uncertain',
@@ -18,6 +18,11 @@ const fields = new Map([
18
18
  ['references', ['references', 'invalid_references']],
19
19
  ]);
20
20
 
21
+ /** The relay's Message-ID, when its 202 body carries one in the grammar it accepts back as In-Reply-To/References. */
22
+ export function rerMessageId(value) {
23
+ return typeof value === 'string' && value.length <= 2000 && messageIdPattern.test(value) ? value : null;
24
+ }
25
+
21
26
  /** Validate a supported list/thread header and return its relay field, or null. */
22
27
  export function rerListHeaderField(name, value) {
23
28
  const mapping = fields.get(name.toLowerCase());
@@ -1,11 +1,11 @@
1
1
  import { fail } from './errors.mjs';
2
2
  import { validateMessagingConfig, validateMessagingResult, identity, rfc3339 } from '../adapters/messaging/contract.mjs';
3
- import { validateRerConfig, validateRerMessage } from '../adapters/rer/contract.mjs';
3
+ import { validateRerConfig, validateRerMessage, validateRerMessageKey } from '../adapters/rer/contract.mjs';
4
4
  import { rerListHeaderField } from '../adapters/rer/list-headers.mjs';
5
5
 
6
6
  const providers = ['sendgrid', 'resend', 'cloudflare', 'rer', 'development', 'messaging'];
7
7
  const controls = /[\x00-\x1f\x7f]/;
8
- const fields = new Set(['deliveryId', 'from', 'to', 'subject', 'text', 'html', 'cc', 'bcc', 'replyTo', 'headers', 'attachments', 'unsubscribe', 'customArgs', 'asmGroupId', 'subscriptionTracking', 'kind', 'expiresAt']);
8
+ const fields = new Set(['deliveryId', 'from', 'to', 'subject', 'text', 'html', 'cc', 'bcc', 'replyTo', 'headers', 'attachments', 'unsubscribe', 'customArgs', 'asmGroupId', 'subscriptionTracking', 'kind', 'expiresAt', 'messageKey']);
9
9
  const reservedHeaders = new Set(['x-sg-id', 'x-sg-eid', 'received', 'dkim-signature', 'content-type', 'content-transfer-encoding', 'mime-version', 'to', 'from', 'subject', 'reply-to', 'cc', 'bcc', 'return-path', 'sender']);
10
10
  const reservedArgs = new Set(['rer_delivery_id', 'email', 'event', 'timestamp', 'sg_event_id', 'sg_message_id']);
11
11
 
@@ -137,6 +137,11 @@ export function validateMessage(message, provider) {
137
137
  for (const attachment of message.attachments) validateAttachment(attachment);
138
138
  }
139
139
  if (message.unsubscribe !== undefined) validateUnsubscribe(message.unsubscribe);
140
+ if (message.messageKey !== undefined) {
141
+ // Only the rer relay assigns Message-IDs from keys; development accepts what rer accepts.
142
+ if (provider !== undefined && !['rer', 'development'].includes(provider)) fail('unsupported_provider_setting');
143
+ validateRerMessageKey(message.messageKey);
144
+ }
140
145
  if (provider === 'rer') validateRerMessage(message);
141
146
  const settings = ['customArgs', 'asmGroupId', 'subscriptionTracking'];
142
147
  if (provider && !['sendgrid', 'development'].includes(provider) && settings.some(key => message[key] !== undefined)) fail('unsupported_provider_setting');
@@ -13,6 +13,7 @@ export interface DevelopmentMessage {
13
13
  customArgs?: Record<string, string>;
14
14
  asmGroupId?: number;
15
15
  subscriptionTracking?: boolean;
16
+ messageKey?: string;
16
17
  }
17
18
  export interface DevelopmentCapture { id: string; createdAt: number; message: DevelopmentMessage }
18
19
  export type DevelopmentOutboxListMessage = Omit<DevelopmentMessage, 'attachments'>;
@@ -519,6 +519,17 @@ request URLs. `RER_DEV_IDENTITY=off` disables dev sign-in and personas. The
519
519
  layer answers 503 to every request when `RER_INSTALLATION_ID` is set beside a
520
520
  non-loopback `RER_MANAGEMENT_ORIGIN`.
521
521
 
522
+ In dev and isolated hosted demos, `/signin` lists **Sign in as <name>** for
523
+ active people and people with a live invitation. The default operator screen
524
+ gets `signInUrl` on those `/auth/operators` records and offers the same action.
525
+ `GET /auth/one-click?as=EMAIL&returnTo=/app` accepts the invitation with the
526
+ existing atomic issuer, expiry, version and cancellation checks. Local sessions
527
+ are always `dev` and require the checkout key on every request; hosted demo
528
+ sessions belong only to that visitor's database. Production answers 404. The
529
+ local persona list also includes invited/active people by email. Suppressed
530
+ email-link form requests direct the admitted visitor to this same one-click
531
+ entry rather than telling them to wait for mail.
532
+
522
533
  `dev/sign-in-as.mjs` is the test harness door: `signInAs({origin, key, as})`
523
534
  returns the cookies a test browser or fetch client installs, and
524
535
  `readDevKey(root)` reads the checkout's key.
@@ -0,0 +1,63 @@
1
+ import { demoEffectsEnabled } from '../../demo/effects.mjs';
2
+ import { devAdmitted } from '../dev-admission.mjs';
3
+ import { deny } from '../errors.mjs';
4
+ import { requireOrigin } from '../http.mjs';
5
+ import { safeReturnTo } from '../policy.mjs';
6
+ import { emailAllowed } from './roles.mjs';
7
+ import { operatorColumns } from './store.mjs';
8
+
9
+ export const oneClickHref = (email, returnTo = '/app') => `/auth/one-click?as=${encodeURIComponent(email)}&returnTo=${encodeURIComponent(safeReturnTo(returnTo))}`;
10
+
11
+ // Local entry needs the checkout's key on every request. Hosted demos live in
12
+ // the visitor's isolated database; only the installed demo effect guard enables
13
+ // this door. Ordinary production cannot enable it with a request header.
14
+ export function oneClickAccounts({ config, store, clock, sessions, authorizedLink, requireRoute, afterConfirm }) {
15
+ async function mode(request) {
16
+ if (config.local) return await devAdmitted(request) ? 'dev' : null;
17
+ return demoEffectsEnabled() ? 'native' : null;
18
+ }
19
+ async function invitation(request, operator) {
20
+ const token = await store.first(`SELECT token_hash AS digest FROM oa_tokens
21
+ WHERE operator_id=? AND kind='invite' AND consumed_at IS NULL AND revoked_at IS NULL
22
+ AND expires_at>? AND operator_version=? ORDER BY created_at DESC LIMIT 1`, [operator.id, clock(), operator.version]);
23
+ const approval = token && await authorizedLink(request, token.digest);
24
+ return approval ? { digest: token.digest, approval } : null;
25
+ }
26
+ async function eligible(request, operator) {
27
+ if (!operator || !emailAllowed(operator.email, config.allowList)) return false;
28
+ if (operator.status === 'invited') return !!await invitation(request, operator);
29
+ return operator.status === 'active';
30
+ }
31
+ return {
32
+ async people(request) {
33
+ if (!await mode(request)) return null;
34
+ requireOrigin(request, config);
35
+ const rows = (await store.statement(`SELECT ${operatorColumns} FROM oa_operators WHERE status IN ('active','invited') ORDER BY created_at,id`).all()).results;
36
+ const people = await Promise.all(rows.map(async operator => {
37
+ if (!await eligible(request, operator)) return null;
38
+ return { email: operator.email, displayName: operator.displayName, role: operator.role, href: oneClickHref(operator.email) };
39
+ }));
40
+ return people.filter(Boolean);
41
+ },
42
+ async enter(request, { as, returnTo }) {
43
+ const kind = await mode(request);
44
+ if (!kind) deny('not_found', 404);
45
+ requireOrigin(request, config);
46
+ if (request.method !== 'GET') deny('method_not_allowed', 405);
47
+ const operator = typeof as === 'string' ? await store.byEmail(as) : null;
48
+ if (!await eligible(request, operator)) deny('not_found', 404);
49
+ await requireRoute(operator);
50
+ const session = await sessions.newSession(kind);
51
+ let record;
52
+ if (operator.status === 'invited') {
53
+ const link = await invitation(request, operator);
54
+ if (!link) deny('invalid_or_expired', 400);
55
+ record = await store.consume(link.digest, clock(), session, config.allowList, link.approval.issuer, kind);
56
+ } else {
57
+ record = await store.issue({ operatorId: operator.id, expectedVersion: operator.version, session, now: clock(), kind });
58
+ }
59
+ const completed = sessions.completed(session, record, returnTo ?? record?.returnTo);
60
+ return afterConfirm(request, completed, 'email');
61
+ },
62
+ };
63
+ }
@@ -88,7 +88,7 @@ export class AuthStore {
88
88
  WHERE t.token_hash=? AND t.consumed_at IS NULL AND t.revoked_at IS NULL AND t.expires_at>? AND t.operator_version=o.version
89
89
  AND (o.status='active' OR (o.status='invited' AND t.kind='invite'))`, [hash, now]);
90
90
  }
91
- async consume(hash, now, session, allowedEmails, issuer) {
91
+ async consume(hash, now, session, allowedEmails, issuer, kind = null) {
92
92
  const allow = allowedEmails === undefined ? { sql: '1', args: [] } : { sql: `o.email IN (${allowedEmails.map(() => '?').join(',') || 'NULL'})`, args: allowedEmails };
93
93
  // JS evaluated the configured policy on this issuer snapshot. Bind that
94
94
  // approval to the invitation and repeat its authority check in the session
@@ -99,12 +99,12 @@ export class AuthStore {
99
99
  await this.batch([
100
100
  [`INSERT INTO oa_sessions(id,token_hash,operator_id,operator_version,kind,source_token_id,created_at,expires_at)
101
101
  SELECT ?,?,o.id,o.version+CASE WHEN o.status='invited' THEN 1 ELSE 0 END,
102
- CASE WHEN EXISTS(SELECT 1 FROM oa_dev_credentials d WHERE d.credential='oa_tokens' AND d.id=t.id) THEN 'dev' ELSE 'native' END,t.id,?,?
102
+ CASE WHEN ?='dev' OR EXISTS(SELECT 1 FROM oa_dev_credentials d WHERE d.credential='oa_tokens' AND d.id=t.id) THEN 'dev' ELSE 'native' END,t.id,?,?
103
103
  FROM oa_tokens t JOIN oa_operators o ON o.id=t.operator_id
104
104
  WHERE t.token_hash=? AND t.consumed_at IS NULL AND t.revoked_at IS NULL AND t.expires_at>? AND t.operator_version=o.version
105
105
  AND (o.status='active' OR (o.status='invited' AND t.kind='invite')) AND ${allow.sql}
106
106
  AND (t.kind='magic' OR (${authority.sql}))`,
107
- [session.id, session.hash, now, session.expiresAt, hash, now, ...allow.args, ...authority.args]],
107
+ [session.id, session.hash, kind, now, session.expiresAt, hash, now, ...allow.args, ...authority.args]],
108
108
  // Only the session just admitted by the full token/issuer/allow-list
109
109
  // predicate witnesses acceptance. Removing its cancellation guard and
110
110
  // activating the operator are atomic with that admission; failures roll
@@ -7,7 +7,7 @@ import { AuthStore } from '../accounts/store.mjs';
7
7
  import { createOperatorAuth } from '../service.mjs';
8
8
  import { AuthError } from '../errors.mjs';
9
9
  import { hashToken, opaqueToken } from '../crypto.mjs';
10
- import { readCookie, sessionCookie, isLoopbackHost, escapeHtml } from '../http.mjs';
10
+ import { readCookie, sessionCookie, isLoopbackHost } from '../http.mjs';
11
11
  import { safeReturnTo } from '../policy.mjs';
12
12
  import { isActiveOperator, defaultRolePolicy } from '../accounts/roles.mjs';
13
13
  import { devGate, devNotFound } from '../dev-gate.mjs';
@@ -15,7 +15,7 @@ import { registerDevAdmission } from '../dev-admission.mjs';
15
15
  import { definePersonas } from './personas.mjs';
16
16
  import { cliSession } from './cli-session.mjs';
17
17
  import { decorateLabel } from '../../demo/label.mjs';
18
- import { pageResponse } from '../page.mjs';
18
+ import { oneClickPage } from '../signin/one-click.mjs';
19
19
 
20
20
  export const DEV_LAYER_MARKER = 'rer-dev-layer:local-only-never-deploy';
21
21
  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 };
@@ -47,21 +47,24 @@ export function withDevIdentity(worker, { bindings = env => env, config: authCon
47
47
  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);
48
48
  }
49
49
  const gate = devGate({ key: env.RER_DEV_KEY, origin: env.AUTH_ORIGIN, local: env.AUTH_LOCAL === 'true' });
50
- registerDevAdmission(gate ? r => gate.admits(r) : null);
50
+ registerDevAdmission(gate && env.RER_DEV_IDENTITY !== 'off' ? r => gate.admits(r) : null);
51
51
  const path = new URL(request.url).pathname;
52
52
  if (path === '/__dev/key') return gate ? gate.exchange(request) : devNotFound();
53
- if (path === '/signin' && gate && env.RER_DEV_IDENTITY !== 'off' && request.method === 'GET') {
53
+ if (path === '/signin' && gate && env.RER_DEV_IDENTITY !== 'off' && ['GET', 'HEAD'].includes(request.method)) {
54
54
  if (!await gate.admits(request)) return new Response(null, { status: 303, headers: { ...headers, location: '/__dev/key' } });
55
- const { config } = identity(env, authConfig, declared);
55
+ const context = identity(env, authConfig, declared);
56
56
  const returnTo = safeReturnTo(new URL(request.url).searchParams.get('returnTo'));
57
- const href = `/auth/dev/enter?as=owner&returnTo=${encodeURIComponent(returnTo)}`;
58
- return decorateLabel(await pageResponse({ branding: config.branding, heading: 'Open your local app', content: `<a class="action" href="${escapeHtml(href)}">Continue as owner</a>` }), env.RER_DEMO === '1' ? 'Demo' : 'Dev');
57
+ const people = await Promise.all((await context.list(request)).filter(person => person.email).map(async person => ({
58
+ ...person, displayName: (await context.store.byEmail(person.email))?.displayName ?? declared.find(p => p.as === person.as)?.displayName ?? person.email,
59
+ href: `/auth/dev/enter?as=${encodeURIComponent(person.as)}&returnTo=${encodeURIComponent(returnTo)}`,
60
+ })));
61
+ return decorateLabel(await oneClickPage({ branding: context.config.branding, people, method: request.method }), env.RER_DEMO === '1' ? 'Demo' : 'Dev');
59
62
  }
60
63
  if (path === '/auth/dev/enter' || path === '/__dev/personas' || path === '/auth/local/cli-session') {
61
64
  if (!gate || env.RER_DEV_IDENTITY === 'off' || (path !== '/auth/local/cli-session' && !await gate.admits(request))) return rejectedResponse(request, devNotFound());
62
65
  const context = identity(env, authConfig, declared);
63
66
  try {
64
- const response = path === '/auth/local/cli-session' ? await cliSession(request, context, headers) : path === '/__dev/personas' ? Response.json(await context.list(), { headers }) : await enter(request, gate, context);
67
+ const response = path === '/auth/local/cli-session' ? await cliSession(request, context, headers) : path === '/__dev/personas' ? Response.json(await context.list(request), { headers }) : await enter(request, gate, context);
65
68
  return rejectedResponse(request, response);
66
69
  } catch (error) {
67
70
  if (error instanceof AuthError) return rejectedResponse(request, Response.json({ error: error.code }, { status: error.status, headers }));
@@ -78,6 +81,7 @@ export function withDevIdentity(worker, { bindings = env => env, config: authCon
78
81
  function identity(env, authConfig, declared) {
79
82
  const config = configure(authConfig(env)), store = new AuthStore(env.DB);
80
83
  const hash = token => hashToken(config.SESSION_SECRET, 'session', token);
84
+ const auth = createOperatorAuth({ db: env.DB, config: authConfig(env), clientIp: () => null });
81
85
  // The `owner` persona is the owner rer setup claimed while that owner is
82
86
  // active; after that owner has left, the earliest-created active owner; with
83
87
  // no active owner left, nobody (email null), so rer names who it signs in as.
@@ -95,20 +99,24 @@ function identity(env, authConfig, declared) {
95
99
  return session && isActiveOperator(session.operator, config.allowList) ? session : null;
96
100
  }
97
101
  return {
98
- config, store, hash, current, everyone,
102
+ config, store, hash, current, everyone, auth,
99
103
  async ownerProof(request) {
100
104
  // Reuse the same persisted app-local proof guard as the administration
101
105
  // routes. This read-only guard never needs a mail sender or an IP budget.
102
- const auth = createOperatorAuth({ db: env.DB, config: authConfig(env), clientIp: () => null });
103
106
  const actor = await auth.requireStepUp(request, 'owner:transfer');
104
107
  if (!defaultRolePolicy({ actor: actor.operator, action: 'operators:invite', role: 'owner' })) throw new AuthError('forbidden', 403);
105
108
  return { ...actor, hash: await hash(readCookie(request, config)) };
106
109
  },
107
- list: async () => [...(await everyone()).map(({ as, email, role }) => ({ as, email, ...(role ? { role } : {}) })), { as: 'signed-out' }],
110
+ async list(request) {
111
+ const personas = (await everyone()).map(({ as, email, role }) => ({ as, email, ...(role ? { role } : {}) }));
112
+ const people = await auth.oneClick.people(request);
113
+ return [...personas, ...(people ?? []).filter(person => !personas.some(p => p.email === person.email))
114
+ .map(person => ({ as: person.email, email: person.email, role: person.role })), { as: 'signed-out' }];
115
+ },
108
116
  };
109
117
  }
110
118
 
111
- async function enter(request, gate, { config, store, hash, current, everyone, ownerProof }) {
119
+ async function enter(request, gate, { config, store, hash, current, everyone, ownerProof, auth }) {
112
120
  if (request.method !== 'GET') return text(405, 'Method not allowed');
113
121
  const url = new URL(request.url), as = url.searchParams.get('as') ?? 'owner';
114
122
  const reply = new Headers(headers);
@@ -123,7 +131,12 @@ async function enter(request, gate, { config, store, hash, current, everyone, ow
123
131
  return new Response(null, { status: 303, headers: reply });
124
132
  }
125
133
  const persona = (await everyone()).find(p => p.as === as);
126
- if (!persona) return devNotFound();
134
+ if (!persona) {
135
+ const value = await auth.oneClick.enter(request, { as, returnTo: url.searchParams.get('returnTo') ?? '/app' });
136
+ reply.append('set-cookie', value.cookie);
137
+ reply.set('location', value.returnTo);
138
+ return new Response(null, { status: 303, headers: reply });
139
+ }
127
140
  if (!persona.email) return text(409, 'No active owner remains in this app. Sign in another way, or run rer reset --yes and rer setup for a new owner.');
128
141
  let operator = await store.byEmail(persona.email);
129
142
  // Personas are real operators, created only here, in local dev.
@@ -142,6 +142,11 @@ export interface IdentityProviders {
142
142
  }
143
143
  export interface DomainRule { domain: string; providerId: string; createdAt: number }
144
144
  export interface OperatorAuth<R extends string = Role> {
145
+ /** Key-gated local development or an isolated hosted demo; unavailable in production. */
146
+ readonly oneClick?: {
147
+ people(request: Request): Promise<Array<{ email: string; displayName: string; role: R; href: string }> | null>;
148
+ enter(request: Request, input: { as?: string; returnTo?: string }): Promise<CompletedSession<R>>;
149
+ };
145
150
  mintCredential(request:Request,input?:{expiresInSeconds?:number}):Promise<{id:string;token:string;expiresAt:number}>;
146
151
  authenticateCredential(request:Request):Promise<{id:string;personId:string;fence:number;kind:SessionKind}|null>;
147
152
  authorizeDependencySetup(request: Request, input: { token?: string }): Promise<boolean>;
@@ -30,6 +30,10 @@ export function createAuthHandler(auth) {
30
30
  const providerResponse = await oidc?.(request);
31
31
  if (providerResponse) return providerResponse;
32
32
  if (!path.startsWith('/auth/')) return null;
33
+ if (path === '/auth/one-click' && auth.oneClick) {
34
+ const value = await auth.oneClick.enter(request, readParameters(url.searchParams));
35
+ return seeOther(value.returnTo, value.cookie);
36
+ }
33
37
  if (path.startsWith('/auth/oidc/')) return json({ error: 'not_found' }, 404);
34
38
  if (path === '/auth/review-session') requireLoopback(request);
35
39
  if (path === '/auth/confirm' && ['GET', 'HEAD'].includes(request.method)) {
@@ -48,7 +52,14 @@ export function createAuthHandler(auth) {
48
52
  const session = await auth.getSession(request);
49
53
  return session ? json(session) : json({ error: 'unauthenticated' }, 401);
50
54
  }
51
- if (path === '/auth/operators' && request.method === 'GET') return json(await auth.listOperators(request));
55
+ if (path === '/auth/operators' && request.method === 'GET') {
56
+ const operators = await auth.listOperators(request);
57
+ const people = await auth.oneClick?.people(request);
58
+ return json(operators.map(operator => {
59
+ const person = people?.find(person => person.email === operator.email);
60
+ return person ? { ...operator, signInUrl: person.href } : operator;
61
+ }));
62
+ }
52
63
  if (path === '/auth/sessions' && request.method === 'GET') return json(await auth.listSessions(request, readParameters(url.searchParams).operatorId));
53
64
  if (path === '/auth/domain-rules' && request.method === 'GET') return json(await auth.listDomainRules(request));
54
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);}
@@ -69,6 +80,14 @@ export function createAuthHandler(auth) {
69
80
  case '/auth/bootstrap': { const value = await auth.bootstrap(request, input); return seeOther(value.returnTo, value.cookie); }
70
81
  case '/auth/magic-link': {
71
82
  const result = await auth.requestMagicLink(request, input);
83
+ const people = await auth.oneClick?.people(request);
84
+ if (people) {
85
+ const person = people.find(person => person.email === String(input.email).trim().toLowerCase());
86
+ const signInUrl = person ? new URL(person.href, url.origin) : null;
87
+ if (signInUrl) signInUrl.searchParams.set('returnTo', safeReturnTo(input.returnTo));
88
+ return form ? seeOther(signInUrl ? signInUrl.pathname + signInUrl.search : auth.presentation.signInPath)
89
+ : json({ ...result, ...(signInUrl ? { signInUrl: signInUrl.pathname + signInUrl.search } : {}) }, 202);
90
+ }
72
91
  return form ? seeOther(notice(auth, 'sent', { returnTo: safeReturnTo(input.returnTo) === '/app' ? undefined : safeReturnTo(input.returnTo), provider: result.requiredProvider })) : json(result, 202);
73
92
  }
74
93
  case '/auth/confirm': { const value = await auth.confirmLink(request, input); return seeOther(value.returnTo, value.cookie); }
@@ -20,6 +20,7 @@ import { ownerSignIn } from './accounts/owner-signin.mjs';
20
20
  import { emailChange } from './accounts/email-change.mjs';
21
21
  import { isLocalCli } from './local-cli.mjs';
22
22
  import { devAdmitted } from './dev-admission.mjs';
23
+ import { oneClickAccounts } from './accounts/one-click.mjs';
23
24
 
24
25
  export { STEP_UP_ACTIONS, STEP_UP_SECONDS } from './identity/email-link/index.mjs';
25
26
  export function createOperatorAuth(options) {
@@ -79,6 +80,7 @@ export function createOperatorAuth(options) {
79
80
  ...ownerSignIn({ config, store, clock, sessions, limit }),
80
81
  ...emailChange({ config, store, clock, authenticate, requireFreshProof }),
81
82
  presentation: config.branding,
83
+ oneClick: oneClickAccounts({ config, store, clock, sessions, authorizedLink, requireRoute, afterConfirm: admission.afterConfirm }),
82
84
  emailSignInAvailable: Boolean(mailSender),
83
85
  /** Identity providers (null when none is configured): routes, the sign-in page's list and owner actions. */
84
86
  providers,
@@ -5,6 +5,7 @@
5
5
  import { escapeHtml } from '../http.mjs';
6
6
  import { normalizeEmail, safeReturnTo } from '../policy.mjs';
7
7
  import { pageResponse } from '../page.mjs';
8
+ import { oneClickPage } from './one-click.mjs';
8
9
 
9
10
  const NOTICES = {
10
11
  sent: ['status', 'If this address can sign in here, a sign-in link is on its way. Open it on this device and press Confirm.'],
@@ -50,6 +51,12 @@ export function createSignInHandler(auth, { setup, links, defaultReturnTo = '/ap
50
51
  const branding = auth.presentation;
51
52
  const returnTo = safeReturnTo(url.searchParams.get('returnTo'), defaultReturnTo);
52
53
  const hint = emailHint(url.searchParams.get('login_hint'));
54
+ const people = await auth.oneClick?.people(request);
55
+ if (people?.length) return oneClickPage({ branding, method: request.method, people: people.map(person => {
56
+ const href = new URL(person.href, url.origin);
57
+ href.searchParams.set('returnTo', returnTo);
58
+ return { ...person, href: href.pathname + href.search };
59
+ }) });
53
60
  const providers = auth.providers ? (await auth.providers.list()).filter(p => p.visible) : [];
54
61
  const parts = [];
55
62
  const emailAvailable = auth.emailSignInAvailable;
@@ -0,0 +1,7 @@
1
+ import { escapeHtml } from '../http.mjs';
2
+ import { pageResponse } from '../page.mjs';
3
+
4
+ export function oneClickPage({ branding, people, method = 'GET' }) {
5
+ const content = `<div class="stack">${people.map(person => `<a class="action" href="${escapeHtml(person.href)}">Sign in as ${escapeHtml(person.displayName || person.email)}</a>`).join('')}</div>`;
6
+ return pageResponse({ branding, heading: `Sign in to ${escapeHtml(branding.productName)}`, content, method });
7
+ }
@@ -1,10 +1,10 @@
1
1
  import { all, insist, quote } from './storage.mjs';
2
2
  import { canonicalJson, sha256, base64, unbase64, utf8 } from './hash.mjs';
3
3
  /** Tables no archive carries: SQLite/Cloudflare internals, migration ledgers,
4
- * portability bookkeeping, development outboxes, operator identity and dependency
5
- * secrets. Exact names, or prefixes ending in `%`. Seeds' own table inventories
4
+ * portability bookkeeping, development outboxes, operator identity, dependency
5
+ * secrets and refresh-safe command receipts. Exact names, or prefixes ending in `%`. Seeds' own table inventories
6
6
  * skip the same tables through `excludedTable`. */
7
- export const excludedTables=Object.freeze(['sqlite_%','_cf_%','d1_migrations','_rer_deploy_migrations','_rer_portability_migrations','rer_portability_%','rer_mail_development_outbox','rer_ai_development_outbox','oa_%','oc_%','rer_dependency_keys','rer_dependency_pending','rer_dependency_codes']);
7
+ export const excludedTables=Object.freeze(['sqlite_%','_cf_%','d1_migrations','_rer_deploy_migrations','_rer_portability_migrations','rer_portability_%','rer_mail_development_outbox','rer_ai_development_outbox','oa_%','oc_%','rer_dependency_keys','rer_dependency_pending','rer_dependency_codes','rer_command_receipts']);
8
8
  const fields=['product','excludeTables','includeTables','derivedTables','secretColumns','exportRow','replaceableTables','requiredConfiguration','validateStaged','acceptedSchemas','buckets','extraPayloads','partBytes'];
9
9
  const name=value=>typeof value==='string' && value.length>0 && value.length<=512 && !/[\x00-\x1f]/.test(value);
10
10
  const names=value=>Array.isArray(value) && value.every(name) && new Set(value).size===value.length;
@@ -9,17 +9,23 @@ import { publicationScan, validatePublicationDestination } from './publication-s
9
9
  import { publicDestination, requirePublicDestination, remotePublicHead, publicChild, assertPublicTree } from './public-child.mjs';
10
10
  import { writePublishHandoff } from './publish-handoff.mjs';
11
11
  import { releasePublicBase } from './public-base.mjs';
12
+ import { placeholderMarks, placeholderMessage } from '../../cli/placeholder-mark.mjs';
12
13
 
13
14
  // Failure output belongs to the private receipt, not the site preview.
14
15
  const withoutOutput = gates => JSON.parse(JSON.stringify(gates, (key, value) => key === 'output' ? undefined : value));
15
16
 
16
- export async function release({ repo, ref = 'HEAD', output, project, repository, dryRun = false, tag = false, cleanHistory: clean = false, envFile, onto, publicBase, localVerify = false }) {
17
+ export async function release({ repo, ref = 'HEAD', output, project, repository, dryRun = false, tag = false, cleanHistory: clean = false, envFile, onto, publicBase, localVerify = false, allowPlaceholderMark = false }) {
17
18
  if (!/^[\w.-]+\/[\w.-]+$/.test(project ?? '')) throw Error('--project must be publisher/name');
18
19
  if (!/^https:\/\/github\.com\/[\w.-]+\/[\w.-]+(?:\.git)?$/i.test(repository ?? '')) throw Error('--repository must be a credential-free GitHub repository URL');
19
20
  if (onto !== undefined && clean) throw Error('--onto and --clean-history are mutually exclusive');
20
21
  if (publicBase !== undefined && (onto !== undefined || clean)) throw Error('--public-base selects exact-source history; cannot combine with export history modes');
21
22
  const preview = dryRun || !tag;
22
23
  const source = inspectSource(repo, ref);
24
+ // A release refuses a seed still wearing Base's placeholder mark unless the
25
+ // caller allows it explicitly; the receipt records that allowance.
26
+ const files = [...source.entries].filter(([, entry]) => entry.type === 'blob' && ['100644', '100755'].includes(entry.mode)).map(([path]) => path);
27
+ const marks = await placeholderMarks(source.entries.has('OPERATIONS.json') ? JSON.parse(source.bytes('OPERATIONS.json')).project : project, files, source.bytes);
28
+ if (marks.length && !allowPlaceholderMark) throw Object.assign(Error(`${placeholderMessage(marks)} Release refused; pass --allow-placeholder-mark to release with it.`), { code: 'placeholder_mark' });
23
29
  validatePublicationDestination(source, project, repository);
24
30
  releaseMessage(source);
25
31
  if (typeof tag === 'string' && tag !== source.tag) throw Error('Requested tag must match the committed release version');
@@ -90,6 +96,7 @@ export async function release({ repo, ref = 'HEAD', output, project, repository,
90
96
  dryRun, tagRequested: Boolean(tag), source: { commit: source.commit, tree: source.tree }, tag: { name: source.tag, created: false, pushed: false }, gates,
91
97
  publicationHistory: destination ? 'public-child' : clean ? 'parentless-export' : 'source-history',
92
98
  ...(destination ? { publicParent, publicDestination: { repository: destination.url, branch: destination.branch } } : {}),
99
+ ...(marks.length ? { placeholderMark: { allowed: true, files: marks } } : {}),
93
100
  publicExport: null, siteRelease: null };
94
101
  // A blocked preview may prepare the site metadata/docs for local review.
95
102
  // Its provenance explicitly records blocked gates; it is never a release.
@@ -119,6 +119,10 @@ Reruns preserve an existing owner, data and exact settings bytes; setup does
119
119
  not create a second owner or rotate secrets. Dev and preview use the saved
120
120
  owner and canonical durable state. Dev opens through the local identity entry;
121
121
  application mail is silently suppressed in development and demo.
122
+ Invited people choose **Sign in as <name>** in operator access or at `/signin`
123
+ to open `/app` with their assigned roles. A fresh local browser profile first
124
+ opens `RER_OPEN` to receive the checkout's key cookie. The local persona list
125
+ also accepts an invited or active person's email through `rer dev --as EMAIL`.
122
126
 
123
127
  Adapters use the shared captured command store for child work. It redacts
124
128
  registered credential values from terminal output and private logs, records
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@runeditrun/rer",
3
- "version": "0.2.28",
3
+ "version": "0.2.29",
4
4
  "description": "The rer command: install, set up, run and launch Run Edit Run checkouts.",
5
5
  "license": "MIT",
6
6
  "type": "module",