@runeditrun/rer 0.2.18 → 0.2.19

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
@@ -23,6 +23,9 @@ export const verbs = Object.fromEntries(Object.entries(definitions).map(([name,
23
23
  // `rer demo` is `rer dev --demo`; describe lists it as a verb with the dev
24
24
  // flags a demo takes whenever the seed's dev takes --demo.
25
25
  export const demoVerb = Object.freeze({ flags: [...commonFlags, '--port', '--host', '--idle-timeout', '--stop', '--detach', '--foreground', '--no-queue'], effects: 'A throwaway demo of this seed (rer dev --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, a Demo bar, and nothing sent (RER_DEMO=1; the checkout\'s own data is never touched).' });
26
+ // `rer signin` is rer's own, not a seed operation: any seed rer deploys, it can
27
+ // sign the owner in to, so no seed declares it and check does not ask for it.
28
+ 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.' });
26
29
  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]));
27
30
  export const releaseFlags = ['--repo', '--project', '--repository', '--output', '--ref', '--dry-run', '--tag', '--clean-history', '--onto', '--env-file', '--no-queue'];
28
31
  export const requiredHooks = ['preview', 'dependencies', 'build', 'migrate', 'start', 'health', 'owner', 'signIn', 'verify', 'deploy', 'portability', 'state', 'settings', 'input'];
@@ -25,7 +25,7 @@ export function validateDeployOptions(options) {
25
25
 
26
26
  // An explicit adapter declaration wins. Older hooks use a conventional root
27
27
  // declaration; discover it by its schema, never by seed identity or hook source.
28
- async function declarationFor(root, adapter) {
28
+ export async function declarationFor(root, adapter) {
29
29
  const declared = adapter.deployDeclaration ?? adapter.deploy?.declaration;
30
30
  const paths = declared ? [declared] : (await readdir(root)).filter(path => path.endsWith('.json') && path !== adapter.site?.declaration);
31
31
  const matches = [];
package/cli/inspect.mjs CHANGED
@@ -3,7 +3,7 @@ import { inventory } from './export.mjs';
3
3
  import { lstat, readFile } from 'node:fs/promises';
4
4
  import { createHash } from 'node:crypto';
5
5
  import { delimiter, dirname, resolve } from 'node:path';
6
- import { aliases, demoVerb, pins, requiredHooks, serverDefaults, verbs, releaseFlags } from './contract.mjs';
6
+ import { aliases, demoVerb, pins, requiredHooks, serverDefaults, signinVerb, verbs, releaseFlags } from './contract.mjs';
7
7
  import { runningVersion } from './version.mjs';
8
8
  import { contained, readPackage } from './project.mjs';
9
9
  import { shared } from './shared.mjs';
@@ -41,7 +41,9 @@ export async function describe(project) {
41
41
  ? operationsEffects
42
42
  : verbs[verb]?.effects ?? 'Produce releases; keygen writes a public anchor and, on success, its private key to non-terminal stdout; sign writes a detached signature and prints (but does not execute) the GitHub upload command; receipt verifies against local anchors offline.';
43
43
  return [verb, { flags: (verbs[verb]?.flags ?? releaseFlags).filter(flag => capability.flags?.includes(flag)), effects }];
44
- }).concat(capabilities.dev?.flags?.includes('--demo') ? [['demo', { flags: demoVerb.flags.filter(flag => capabilities.dev.flags.includes(flag)), effects: demoVerb.effects }]] : [])),
44
+ }).concat(capabilities.dev?.flags?.includes('--demo') ? [['demo', { flags: demoVerb.flags.filter(flag => capabilities.dev.flags.includes(flag)), effects: demoVerb.effects }]] : [])
45
+ // rer signin is rer's own: any seed it can deploy, it can sign the owner in to.
46
+ .concat(capabilities.deploy ? [['signin', { flags: signinVerb.flags, effects: signinVerb.effects }]] : [])),
45
47
  aliases: Object.fromEntries(Object.entries(aliases).filter(([alias, verb]) => pkg.scripts?.[alias] === commandLine(verb, declaredPackage(pkg) !== undefined))),
46
48
  local: { state: project.adapter?.state, settings: project.adapter?.settings ?? [], installerState: '.seed/installer', outbox: '/__dev/outbox', ...await localState(project), origin: await savedOrigin(project), ...(project.adapter?.devIdentity ? { devIdentity: true, devKey: '.rer/local/dev-key.env' } : {}) },
47
49
  // This pin serves a checkout through the machine's front door (rer door).
package/cli/main.mjs CHANGED
@@ -39,6 +39,8 @@ export async function main(argv = process.argv.slice(2)) {
39
39
  if (!options.json) out.human(JSON.stringify(result, null, 2));
40
40
  out.result(result.ok, result.ok ? 0 : 3, { diagnostics: result }); return result.ok ? 0 : 3;
41
41
  }
42
+ // The owner link is printed once to this terminal: never through the logged lifecycle.
43
+ if (options.verb === 'signin') { out.result(true, 0, await (await import('./signin.mjs')).signinCommand(project, options, out)); return 0; }
42
44
  // A checkout without a declared run site refuses --site before any effect.
43
45
  if (options.site) (await import('./site.mjs')).declaredSite(project);
44
46
  const bounded=await (await import('./bounded.mjs')).boundedCommand(project,options,argv,out);
package/cli/parse.mjs CHANGED
@@ -1,5 +1,5 @@
1
1
  import { resolve } from 'node:path';
2
- import { commonFlags, serverDefaults, verbs } from './contract.mjs';
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
5
  const booleans = new Set(['--help', '--json', '--non-interactive', '--yes', '--dry-run', '--open', '--stop', '--detach', '--foreground', '--no-queue', '--login', '--legacy-v1', '--acknowledge-unverified-metadata', '--door', '--direct', '--site', '--remove', '--demo']);
@@ -22,7 +22,7 @@ export function parse(argv, cwd = process.cwd(), { independent = false, deferTai
22
22
  // Independent projects own verb names; only the common wrapper flags apply
23
23
  // to unknown names. Profile resolution rejects undeclared commands later.
24
24
  if (!/^[a-z][a-z0-9-]*$/.test(verb)) throw invalid('Unknown rer command. Run rer --help.');
25
- const allowed = new Set(independent ? [...commonFlags,...(['install','setup','build','verify','deploy','release','export','import','dev','preview'].includes(verb)?['--no-queue']:[])] : verbs[verb]?.flags ?? commonFlags), options = { verb, cwd: resolve(cwd), forwarded: [], supplied: new Set() };
25
+ const allowed = new Set(independent ? [...commonFlags,...(['install','setup','build','verify','deploy','release','export','import','dev','preview'].includes(verb)?['--no-queue']:[])] : (verbs[verb] ?? (verb === 'signin' ? signinVerb : undefined))?.flags ?? commonFlags), options = { verb, cwd: resolve(cwd), forwarded: [], supplied: new Set() };
26
26
  let separator = false;
27
27
  for (let i = 0; i < args.length; i++) {
28
28
  const flag = args[i];
@@ -89,8 +89,9 @@ export function parse(argv, cwd = process.cwd(), { independent = false, deferTai
89
89
  }
90
90
 
91
91
  export function help(verb) {
92
- if (!verb) return `Usage: rer VERB [FLAGS]\nCommands: ${Object.keys(verbs).join(', ')}, release\nRun rer VERB --help for flags.\n`;
93
- return `Usage: rer ${verb} [FLAGS]\nFlags: ${(verbs[verb]?.flags ?? commonFlags).join(', ')}\n${verbs[verb]?.effects ?? 'Execute the declared OPERATIONS v2 argv with explicit arguments after --.'}\n`;
92
+ if (!verb) return `Usage: rer VERB [FLAGS]\nCommands: ${Object.keys(verbs).join(', ')}, signin, release\nRun rer VERB --help for flags.\n`;
93
+ const known = verbs[verb] ?? (verb === 'signin' ? signinVerb : undefined);
94
+ return `Usage: rer ${verb} [FLAGS]\nFlags: ${(known?.flags ?? commonFlags).join(', ')}\n${known?.effects ?? 'Execute the declared OPERATIONS v2 argv with explicit arguments after --.'}\n`;
94
95
  }
95
96
 
96
97
  function distance(a,b){let row=Array.from({length:b.length+1},(_,i)=>i);for(let i=1;i<=a.length;i++){const next=[i];for(let j=1;j<=b.length;j++)next[j]=Math.min(next[j-1]+1,row[j]+1,row[j-1]+(a[i-1]===b[j-1]?0:1));row=next;}return row[b.length];}
package/cli/signin.mjs ADDED
@@ -0,0 +1,41 @@
1
+ import { declarationFor } from './deploy-command.mjs';
2
+ import { deployEnvironment, deployAgain } from './deploy-inputs.mjs';
3
+ import { hookState } from './deploy-hook-record.mjs';
4
+ import { missing, refuse, RerError } from './errors.mjs';
5
+ import { shared } from './shared.mjs';
6
+ import { main as owner } from '../modules/deploy-kit/owner-cli.mjs';
7
+ import { deployDiagnostic, providerRefusal } from '../modules/deploy-kit/diagnostics.mjs';
8
+
9
+ // rer signin: the owner's way into a hosted install without mail. With the same
10
+ // Cloudflare credentials that deployed it, rer writes a one-time grant (only its
11
+ // SHA-256) into the deployment's auth D1 and prints the link once to this terminal.
12
+ // It never reaches a log, receipt or the deploy record; the Worker admits it only
13
+ // for the recorded owner, once, within 15 minutes, and logs its use.
14
+ export async function signinCommand(project, options, out, { fetch } = {}) {
15
+ if (project.profile !== 'first-party' || typeof project.adapter?.deploy !== 'function') throw refuse('rer signin needs a seed with an owner-account deploy declaration.');
16
+ const root = project.root, environment = options.environment ?? 'production', again = deployAgain(options).replace(/^rer deploy/, 'rer signin');
17
+ const { path, value: declaration } = await declarationFor(root, project.adapter);
18
+ const { env } = await deployEnvironment({ root, options, declaration, localOnlyKeys: project.adapter.localOnlyKeys ?? [] });
19
+ if (['CLOUDFLARE_ACCOUNT_ID', 'CLOUDFLARE_API_TOKEN'].some(name => !env[name]?.trim())) throw missing('rer signin uses the Cloudflare credentials that deployed this environment: set CLOUDFLARE_ACCOUNT_ID and CLOUDFLARE_API_TOKEN in the environment or an --env-file, then run it again.');
20
+ const { createRedaction, credentialValues } = await shared('redaction.mjs');
21
+ const redaction = createRedaction();
22
+ redaction.addSecrets([...credentialValues(env), env.CLOUDFLARE_ACCOUNT_ID]);
23
+ const state = await hookState(root, environment);
24
+ let result;
25
+ try { result = await owner(['signin', '--declaration', path, '--environment', environment, ...(state ? ['--state', state] : [])], env, { cwd: root, localOnlyKeys: project.adapter.localOnlyKeys ?? [], ...(fetch ? { fetch } : {}) }); }
26
+ catch (error) { throw failure(error, { environment, again, redact: redaction.redact }); }
27
+ const minutes = Math.round((result.expiresAt - Date.now()) / 60000);
28
+ if (!options.json) out.human(`One-time sign-in link for the owner ${result.email}. It works once, only for that owner, and expires in ${minutes} minutes. rer does not save it; open it now:\n${result.link}`);
29
+ return { owner: result.email, expiresAt: result.expiresAt, ...(options.json ? { link: result.link } : {}) };
30
+ }
31
+
32
+ function failure(error, { environment, again, redact }) {
33
+ const code = deployDiagnostic(error, redact)?.code ?? error.message;
34
+ if (code === 'missing-owner-receipt') return refuse(`This checkout has no completed rer deployment of the ${environment} environment. Run rer signin from the checkout that deployed it (rer deploy --environment ${environment}).`);
35
+ if (code === 'owned-resource-replaced') return refuse(`The ${environment} Worker is no longer the one this checkout deployed, so rer will not sign anyone in to it. Run rer deploy --environment ${environment} first.`);
36
+ if (code === 'owner-signin-unsupported') return refuse(`The ${environment} deployment's database has no owner sign-in table. Update the seed to a rer that includes operator-auth's accounts/schema/owner-signin.sql migration, run rer deploy --environment ${environment}, then ${again}.`);
37
+ if (code === 'owner-signin-ambiguous') return refuse(`More than one D1 database of the ${environment} deployment holds an owner sign-in table, so rer cannot tell which one signs in the owner. Nothing was written.`);
38
+ if (code === 'owner-not-claimed') return refuse(`No owner has claimed the ${environment} deployment yet. Run rer deploy --environment ${environment}: it claims the owner. Nothing was written.`);
39
+ const refusal = providerRefusal(error, redact);
40
+ return new RerError('command_failed', `rer signin failed: ${/^[a-zA-Z0-9_-]{1,120}$/.test(code) ? redact(code) : 'signin-failed'}${refusal ? ` (${refusal})` : ''}. No sign-in link was issued; run ${again} again.`, 1);
41
+ }
@@ -1,5 +1,14 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.2.19
4
+
5
+ - `rer signin [--environment NAME]` uses the credentials that deployed a seed to print a one-time owner sign-in link, valid for 15 minutes. It requires no email delivery, refuses non-owners and used or expired links, and records successful use in the auth audit log.
6
+ - A freshly signed-in owner can correct their sign-in email in Operator access. The global command installs the checkout's pinned rer package before running `signin`.
7
+
8
+ ### Upgrade notes
9
+
10
+ - Update the exact rer package pin or refresh vendored commands and operator-auth. Apply `modules/operator-auth/accounts/schema/owner-signin.sql` as a new numbered migration, then redeploy. The reference seed includes the migration and README instructions. Run `rer signin` from the checkout that deployed the environment with its Cloudflare credentials.
11
+
3
12
  ## 0.2.17
4
13
 
5
14
  - Container builds check the app's reachable runtime imports from Wrangler main and fresh server output. Dormant source files and ordinary calls containing cloudflare-looking strings no longer fail the boundary; reachable Node-engine restrictions remain.
package/global/main.mjs CHANGED
@@ -30,13 +30,13 @@ pins (installed first by any verb when node_modules holds another), else its ven
30
30
  Run COMMAND once this computer's job queue admits it (heavy package scripts
31
31
  of a checkout that pins the rer package use it).
32
32
 
33
- Checkout verbs: install, setup, dev, demo, preview, build, verify, reset, deploy, export, import,
34
- outbox, doctor, describe, check, release. Run rer VERB --help in a checkout for its flags.
33
+ Checkout verbs: install, setup, dev, demo, preview, build, verify, reset, deploy, signin, export,
34
+ import, outbox, doctor, describe, check, release. Run rer VERB --help in a checkout for its flags.
35
35
  `;
36
36
 
37
37
  // The checkout verbs that install the pinned package before they run when
38
38
  // node_modules holds another version or none (dev installs it in its launch).
39
- const installsFirst = new Set([...Object.keys(verbs), 'release'].filter(verb => verb !== 'dev'));
39
+ const installsFirst = new Set([...Object.keys(verbs), 'signin', 'release'].filter(verb => verb !== 'dev'));
40
40
 
41
41
  export async function main(argv) {
42
42
  handleBrokenPipes();
@@ -122,6 +122,8 @@ A refused provider call also carries `providerRefusal` on the thrown error: the
122
122
 
123
123
  Removal reads back that no recorded resource remains before deleting the state file. On partial failure, the state file retains the remaining resources so a later `--remove --yes` can finish. Resources rer did not create are never touched.
124
124
 
125
+ - **Owner sign-in without mail.** `rer signin [--environment NAME] [--env-file FILE]` (owner CLI `signin`) needs only `CLOUDFLARE_ACCOUNT_ID` and `CLOUDFLARE_API_TOKEN` (with D1 edit). It refuses unless the state file holds a completed deploy and the live Worker is the one it recorded. It finds the one recorded D1 that holds `oa_owner_signins` and writes a single-use grant for the claimed owner there: the token's SHA-256, never the token. It returns the link once, to the terminal only. The state file is not changed. See operator-auth's "Owner sign-in without mail".
126
+
125
127
  ### If the state file is lost
126
128
 
127
129
  A fresh clone or CI runner has no `.rer/` directory, so the kit can no longer tell its own resources from anyone else's and refuses every later deploy as `resource-name-collision`. It is correct to refuse: the kit never adopts what it cannot prove it created. To recover, do one of these.
@@ -12,10 +12,11 @@ import { ownerTarget, ownerPlan, ownerDeploy, ownerHealth, settleOwnerState, sam
12
12
  import { activeWorker } from './worker.mjs';
13
13
  import { ownerSecret } from './owner-secret.mjs';
14
14
  import { ownerRemove } from './owner-remove.mjs';
15
+ import { ownerSignin } from './owner-signin.mjs';
15
16
  import { refuseLocalModels } from './local-only.mjs';
16
17
 
17
18
  export const cronNotice = 'This Worker has a Cron Trigger. Cloudflare may take up to about two hours to start its first scheduled run on some accounts.';
18
- const usage = 'usage: owner-cli.mjs deploy|health|remove|inspect|record-owner --declaration <file> --environment <name> [--product <dir>] [--state <file>] [--outcome claimed|kept] | secret ... --set NAME|--unset NAME';
19
+ const usage = 'usage: owner-cli.mjs deploy|health|remove|inspect|record-owner|signin --declaration <file> --environment <name> [--product <dir>] [--state <file>] [--outcome claimed|kept] | secret ... --set NAME|--unset NAME';
19
20
 
20
21
  /** The owner's committed source and existing local build. Run the seed's build first. */
21
22
  async function ownerArtifact(root, product) {
@@ -31,7 +32,7 @@ export async function main(argv = process.argv.slice(2), env = process.env, {fet
31
32
  try { parsed = parseArgs({args:argv,allowPositionals:true,strict:true,options:{declaration:{type:'string'},environment:{type:'string'},product:{type:'string',default:''},state:{type:'string'},set:{type:'string'},unset:{type:'string'},outcome:{type:'string'}}}); }
32
33
  catch { throw new Error('usage'); }
33
34
  const {positionals:[command,...rest],values} = parsed;
34
- if (!['deploy','health','secret','remove','inspect','record-owner'].includes(command) || rest.length || !values.declaration || !values.environment) throw new Error('usage');
35
+ if (!['deploy','health','secret','remove','inspect','record-owner','signin'].includes(command) || rest.length || !values.declaration || !values.environment) throw new Error('usage');
35
36
  if ((command === 'secret') !== (values.set !== undefined || values.unset !== undefined) || values.set !== undefined && values.unset !== undefined) throw new Error('usage');
36
37
  if (values.outcome !== undefined && command !== 'record-owner' || command === 'record-owner' && !['claimed','kept'].includes(values.outcome)) throw new Error('usage');
37
38
  await refuseLocalModels(resolve(cwd));
@@ -76,6 +77,8 @@ export async function main(argv = process.argv.slice(2), env = process.env, {fet
76
77
  await writeOwnerState(statePath, current);
77
78
  return {ok:true, owner:values.outcome};
78
79
  });
80
+ // The link is a credential: returned to the caller once, never written to the state file.
81
+ if (command === 'signin') return {ok:true,...await ownerSignin({api,target,statePath}).catch(error => { throw api.annotateFailure(error,'signin'); })};
79
82
  if (command === 'inspect') {
80
83
  assert(!localOnlyBinding(declaration, localOnlyKeys), 'local-only-binding');
81
84
  assert(state.receipt && !state.pendingUpload && !state.pendingSecret, 'missing-owner-receipt');
@@ -0,0 +1,34 @@
1
+ import { randomBytes, randomUUID } from 'node:crypto';
2
+ import { assert } from './validation.mjs';
3
+ import { query } from './migrations.mjs';
4
+ import { literal } from './migration-ledger.mjs';
5
+ import { readOwnerState, sameDeployment } from './owner.mjs';
6
+ import { activeWorker } from './worker.mjs';
7
+ import { OWNER_SIGNIN_PATH, OWNER_SIGNIN_SECONDS, ownerSigninDigest } from '../operator-auth/owner-signin-grant.mjs';
8
+
9
+ /** `rer signin`: with the same Cloudflare credentials that deployed this Worker, write a
10
+ * one-time grant for the claimed owner into the deployment's own auth D1 and return the
11
+ * link. Only the token's SHA-256 reaches the database; the token itself exists only in
12
+ * the returned link. Refuses unless the live Worker is the one this record deployed. */
13
+ export async function ownerSignin({ api, target, statePath, clock = Date.now }) {
14
+ const state = await readOwnerState(statePath, target);
15
+ assert(state.receipt && !state.pendingUpload && !state.pendingSecret, 'missing-owner-receipt');
16
+ const live = await activeWorker(api, target.worker);
17
+ assert(live && sameDeployment(live, state.receipt.provider), 'owned-resource-replaced');
18
+ const ids = Object.values(state.owned.d1).filter(entry => entry.status === 'created' && entry.id).map(entry => entry.id);
19
+ const holding = [];
20
+ for (const id of ids) if ((await query(api, id, "SELECT name FROM sqlite_master WHERE type='table' AND name='oa_owner_signins'"))[0].results.length) holding.push(id);
21
+ assert(holding.length > 0, 'owner-signin-unsupported');
22
+ assert(holding.length === 1, 'owner-signin-ambiguous');
23
+ const token = randomBytes(32).toString('base64url'), id = randomUUID(), now = clock();
24
+ // The recorded owner: the claimed (bootstrap) owner first, as operator-auth's own owner() reads it.
25
+ await query(api, holding[0], `INSERT INTO oa_owner_signins(id,token_hash,operator_id,operator_version,created_at,expires_at)
26
+ SELECT ${literal(id)},${literal(await ownerSigninDigest(token))},o.id,o.version,${now},${now + OWNER_SIGNIN_SECONDS * 1000}
27
+ FROM oa_operators o LEFT JOIN oa_bootstrap b ON b.claim_id=o.id WHERE o.role='owner' AND o.status='active'
28
+ ORDER BY b.claim_id IS NULL, o.created_at, o.id LIMIT 1`);
29
+ const [owner] = (await query(api, holding[0], `SELECT o.email FROM oa_owner_signins g JOIN oa_operators o ON o.id=g.operator_id WHERE g.id=${literal(id)}`))[0].results;
30
+ assert(owner, 'owner-not-claimed');
31
+ const link = new URL(OWNER_SIGNIN_PATH, target.origin);
32
+ link.searchParams.set('token', token);
33
+ return { link: link.href, email: owner.email, expiresAt: now + OWNER_SIGNIN_SECONDS * 1000 };
34
+ }
@@ -41,6 +41,8 @@ modules/mail/src/adapters/resend/serialize.mjs
41
41
  modules/mail/src/adapters/resend/size.mjs
42
42
  modules/mail/src/adapters/sendgrid/index.mjs
43
43
  modules/mail/src/adapters/sendgrid/serialize.mjs
44
+ modules/mail/src/adapters/rer/contract.mjs
45
+ modules/mail/src/adapters/rer/index.mjs
44
46
  modules/mail/src/adapters/messaging/contract.mjs
45
47
  modules/mail/src/adapters/messaging/event-schema.mjs
46
48
  modules/mail/src/adapters/messaging/index.mjs
@@ -116,10 +118,50 @@ These are for developing the module itself or documentation. A seed may keep any
116
118
  - `modules/mail/package.json`, `modules/mail/pnpm-lock.yaml`, `modules/mail/.gitignore`
117
119
  - `modules/mail/README.md` and every `README.md` under `modules/mail/src/`
118
120
 
119
- The provider is explicit: `sendgrid`, `resend`, `cloudflare`, or `development`.
121
+ The provider is explicit: `sendgrid`, `resend`, `cloudflare`, `rer`, `messaging`, or `development`.
120
122
  `mode` is required (`production`, `development`, or `test`). Remote providers require `apiKey`; Cloudflare additionally requires a 32-hex `accountId`. A remote provider in test/development mode still makes a real provider request unless the caller explicitly supplies a test fetch. Missing credentials, validation errors, or provider failure never select another provider. Config and messages reject unknown fields so requested features cannot silently disappear.
121
123
 
122
- `createMailSender(config, dependencies?)` returns `{send(message)}`. Dependencies are optional standard `fetch`, an explicit asynchronous `outbox.put(message)`, `clock: () => epochMilliseconds`, and `timeoutMilliseconds` (a positive safe integer bounding each remote attempt; the default is 15,000). Production normally uses global fetch. No configurable provider endpoint, retry, or automatic replay exists. The sender snapshots configuration at construction and the message at submission.
124
+ `createMailSender(config, dependencies?)` returns `{send(message)}`. Dependencies are optional standard `fetch`, an explicit asynchronous `outbox.put(message)`, `clock: () => epochMilliseconds`, and `timeoutMilliseconds` (a positive safe integer bounding each remote attempt; the default is 15,000). Production normally uses global fetch. Direct provider endpoints are fixed; `rer` uses its assigned relay URL. No retry or automatic replay exists. The sender snapshots configuration at construction and the message at submission.
125
+
126
+ ### Managed mail through RER
127
+
128
+ Seeds opt into Managed mail with `mail: {providers: ["rer"]}` in their candidate
129
+ deployment spec. The [delivery producer](../delivery-producer/README.md#managed-mail)
130
+ can generate the matching setup fields. RER assigns public `MAIL_PROVIDER`,
131
+ `MAIL_FROM`, `MAIL_RELAY_URL` and private `MAIL_API_KEY`; Managed owners do not
132
+ enter them. Wire those settings into the shared sender:
133
+
134
+ ```js
135
+ const sender = createMailSender({
136
+ provider: env.MAIL_PROVIDER, // rer
137
+ mode: 'production',
138
+ apiKey: env.MAIL_API_KEY,
139
+ relayUrl: env.MAIL_RELAY_URL,
140
+ });
141
+ await sender.send({
142
+ deliveryId: durableCommand.id,
143
+ from: env.MAIL_FROM,
144
+ to: ['recipient@example.net'],
145
+ subject: 'Your requested sign-in link',
146
+ text: 'Open the link you requested.',
147
+ });
148
+ ```
149
+
150
+ Pass `relayUrl` only for `rer`. It must be the assigned HTTPS URL, without URL
151
+ credentials, query or fragment. The adapter sends one POST with Bearer
152
+ authentication and `redirect: 'error'`. Its JSON contains one mailbox `to`,
153
+ `subject`, `text` and optional nonempty `html`. RER owns the sender and
154
+ installation identity; `from` and `deliveryId` are not transmitted. Subjects
155
+ must be nonempty, without newlines and at most 200 characters. Plain text is
156
+ required; each body is limited to 65,536 characters and the JSON to 128 KiB.
157
+ Other recipients, attachments, reply-to, headers and unsubscribe features are
158
+ unsupported and fail before dispatch.
159
+
160
+ HTTP 202 returns `accepted` with no provider message ID. HTTP 400, 401, 402,
161
+ 403 and 413 return `rejected`; 429 returns `rate_limited`; 502 and 503 return
162
+ `uncertain`. Network failures and refused redirects are also `uncertain`.
163
+ The usual application delivery policy decides whether to retry or stop; the
164
+ adapter makes no retries and never reads or logs provider error bodies.
123
165
 
124
166
  ## Message and results
125
167
 
@@ -0,0 +1,22 @@
1
+ import { fail } from '../../core/errors.mjs';
2
+
3
+ export function validateRerConfig(config) {
4
+ let url;
5
+ try { url = new URL(config.relayUrl); } catch { fail('rer_relay_url_required'); }
6
+ if (typeof config.relayUrl !== 'string' || url.protocol !== 'https:' ||
7
+ url.username || url.password || config.relayUrl.includes('?') || config.relayUrl.includes('#') ||
8
+ url.href !== config.relayUrl) fail('invalid_rer_relay_url');
9
+ }
10
+
11
+ export function validateRerMessage(message) {
12
+ if (message.to.length !== 1) fail('rer_one_recipient_required');
13
+ // The relay cannot preserve these features. Refuse them rather than silently
14
+ // dropping recipients, attachments, threading or unsubscribe instructions.
15
+ if (['cc', 'bcc', 'replyTo', 'attachments', 'unsubscribe'].some(field => message[field] !== undefined) ||
16
+ (message.headers !== undefined && Reflect.ownKeys(message.headers).length > 0)) {
17
+ fail('unsupported_provider_setting');
18
+ }
19
+ if (!message.subject.trim() || message.subject.length > 200) fail('invalid_subject');
20
+ if (!message.text?.trim() || message.text.length > 65_536 ||
21
+ (message.html !== undefined && message.html.length > 65_536)) fail('invalid_body');
22
+ }
@@ -0,0 +1,30 @@
1
+ import { validateConfig, validateMessage, parseAddress } from '../../core/validation.mjs';
2
+ import { fail } from '../../core/errors.mjs';
3
+ import { requestProvider, classifyHttpStatus, sendResult } from '../../core/transport.mjs';
4
+
5
+ /** One Managed relay submission. RER owns the sender and installation identity. */
6
+ export async function sendRer(config, message, dependencies = {}) {
7
+ validateConfig(config, dependencies);
8
+ if (config.provider !== 'rer') fail('rer_provider_required');
9
+ validateMessage(message, 'rer');
10
+ const body = JSON.stringify({
11
+ to: parseAddress(message.to[0]).email,
12
+ subject: message.subject,
13
+ text: message.text,
14
+ ...(message.html ? { html: message.html } : {}),
15
+ });
16
+ if (new TextEncoder().encode(body).byteLength > 128 * 1024) fail('rer_message_too_large');
17
+ const response = await requestProvider(config.relayUrl, {
18
+ method: 'POST',
19
+ redirect: 'error',
20
+ headers: { Authorization: `Bearer ${config.apiKey}`, 'Content-Type': 'application/json' },
21
+ body,
22
+ }, dependencies);
23
+ if (response === null) return sendResult('rer', 'uncertain', null, 'transport_uncertain');
24
+ // Do not consume provider bodies: they may contain credentials or personal data.
25
+ if (response.status === 202) return sendResult('rer', 'accepted');
26
+ const status = classifyHttpStatus(response.status) ?? 'uncertain';
27
+ return sendResult('rer', status, null, {
28
+ rejected: 'provider_rejected', rate_limited: 'provider_rate_limited', uncertain: 'provider_uncertain',
29
+ }[status]);
30
+ }
@@ -8,7 +8,7 @@ export async function requestProvider(url, init, dependencies = {}) {
8
8
  const deadline = new Promise(resolve => { timer = setTimeout(() => resolve(null), timeout); });
9
9
  return await Promise.race([
10
10
  Promise.resolve().then(() => (dependencies.fetch ?? globalThis.fetch)(url, {
11
- ...init, redirect: 'manual', signal: AbortSignal.timeout(timeout),
11
+ ...init, redirect: init.redirect === 'error' ? 'error' : 'manual', signal: AbortSignal.timeout(timeout),
12
12
  })).then(response => response instanceof Response ? response : null, () => null),
13
13
  deadline,
14
14
  ]);
@@ -1,7 +1,8 @@
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
4
 
4
- const providers = ['sendgrid', 'resend', 'cloudflare', 'development', 'messaging'];
5
+ const providers = ['sendgrid', 'resend', 'cloudflare', 'rer', 'development', 'messaging'];
5
6
  const controls = /[\x00-\x1f\x7f]/;
6
7
  const fields = new Set(['deliveryId', 'from', 'to', 'subject', 'text', 'html', 'cc', 'bcc', 'replyTo', 'headers', 'attachments', 'unsubscribe', 'customArgs', 'asmGroupId', 'subscriptionTracking', 'kind', 'expiresAt']);
7
8
  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']);
@@ -20,7 +21,7 @@ function bounded(value, limit, code, empty = false) {
20
21
  }
21
22
 
22
23
  export function validateConfig(config, dependencies = {}) {
23
- keys(config, new Set(['provider', 'mode', 'apiKey', 'accountId', 'serviceOrigin', 'installId', 'kid', 'signingKey']), 'invalid_config');
24
+ keys(config, new Set(['provider', 'mode', 'apiKey', 'accountId', 'relayUrl', 'serviceOrigin', 'installId', 'kid', 'signingKey']), 'invalid_config');
24
25
  record(dependencies, 'invalid_dependencies');
25
26
  if (!providers.includes(config.provider)) fail('invalid_provider');
26
27
  if (!['production', 'development', 'test'].includes(config.mode)) fail('invalid_mode');
@@ -28,6 +29,8 @@ export function validateConfig(config, dependencies = {}) {
28
29
  if (dependencies.clock !== undefined && typeof dependencies.clock !== 'function') fail('invalid_clock');
29
30
  if (dependencies.timeoutMilliseconds !== undefined &&
30
31
  (!Number.isSafeInteger(dependencies.timeoutMilliseconds) || dependencies.timeoutMilliseconds <= 0)) fail('invalid_timeout');
32
+ if (config.provider === 'rer') validateRerConfig(config);
33
+ else if (config.relayUrl !== undefined) fail('unsupported_provider_setting');
31
34
  if (config.provider === 'messaging') return validateMessagingConfig(config, dependencies) ?? config;
32
35
  if (['serviceOrigin', 'installId', 'kid', 'signingKey'].some(field => config[field] !== undefined) || dependencies.serviceBinding !== undefined) fail('unsupported_provider_setting');
33
36
  if (config.provider === 'development') {
@@ -132,6 +135,7 @@ export function validateMessage(message, provider) {
132
135
  for (const attachment of message.attachments) validateAttachment(attachment);
133
136
  }
134
137
  if (message.unsubscribe !== undefined) validateUnsubscribe(message.unsubscribe);
138
+ if (provider === 'rer') validateRerMessage(message);
135
139
  const settings = ['customArgs', 'asmGroupId', 'subscriptionTracking'];
136
140
  if (provider && !['sendgrid', 'development'].includes(provider) && settings.some(key => message[key] !== undefined)) fail('unsupported_provider_setting');
137
141
  if (message.asmGroupId !== undefined && (!Number.isSafeInteger(message.asmGroupId) || message.asmGroupId <= 0)) fail('invalid_asm_group');
@@ -3,11 +3,12 @@ import { fail } from './core/errors.mjs';
3
3
  import { sendSendGrid } from './adapters/sendgrid/index.mjs';
4
4
  import { sendResend } from './adapters/resend/index.mjs';
5
5
  import { sendCloudflare } from './adapters/cloudflare/index.mjs';
6
+ import { sendRer } from './adapters/rer/index.mjs';
6
7
  import { sendMessaging, reconcileMessaging, eraseMessaging } from './adapters/messaging/index.mjs';
7
8
  import { sendDevelopment } from './development/index.mjs';
8
9
  import { applyUnsubscribeHeaders } from './unsubscribe/index.mjs';
9
10
 
10
- const transports = { sendgrid: sendSendGrid, resend: sendResend, cloudflare: sendCloudflare, development: sendDevelopment, messaging: sendMessaging };
11
+ const transports = { sendgrid: sendSendGrid, resend: sendResend, cloudflare: sendCloudflare, rer: sendRer, development: sendDevelopment, messaging: sendMessaging };
11
12
 
12
13
  /** Explicit configuration; a missing/failed provider never selects another path. */
13
14
  export function createMailSender(config, dependencies = {}) {
@@ -130,6 +130,9 @@ version), domain rules in `oa_domain_rules`. `auth.accounts` exposes it and
130
130
  | `/auth/providers` | GET | the pinned provider links; owner only |
131
131
  | `/auth/providers/unlink`, `/auth/providers/relink` | POST | provider; owner only, step-up |
132
132
  | `/auth/oidc/<id>/start`, `/auth/oidc/<id>/callback` | POST / GET | each provider's own routes (see [identity/oidc](identity/oidc/README.md)) |
133
+ | `/auth/owner-signin?token=…` | GET/HEAD | 200 owner sign-in confirmation for a live `rer signin` link, or 400 invalid/used/expired; **no writes** |
134
+ | `/auth/owner-signin` | POST | token; consume once for the active owner it names, 303 with cookie; see "Owner sign-in without mail" |
135
+ | `/auth/email` | POST | email; the signed-in operator's own sign-in email; fresh step-up proof; 409 `email_in_use` |
133
136
 
134
137
  Unknown `/auth/*` paths return 404. Unsupported methods return 405. Except for invalid/expired confirmation GET/HEAD documents, known public
135
138
  errors are JSON `{error:code}`: invalid input 400, unauthenticated 401, policy/host/
@@ -426,6 +429,40 @@ Creating a server-declared owner dev persona also requires the signed-in owner's
426
429
  fresh local proof in addition to the checkout key. Its creation repeats the actor
427
430
  session/version fence in the database write.
428
431
 
432
+ ## Owner sign-in without mail (`rer signin`)
433
+
434
+ An owner whose mail does not work yet, or whose `OWNER_EMAIL` was mistyped, gets
435
+ in with `rer signin [--environment NAME]`. rer uses only the Cloudflare
436
+ credentials that deployed that environment: it checks that the live Worker is
437
+ the one its deploy record names, writes one row into `oa_owner_signins` in the
438
+ deployment's own D1 through the D1 API, and prints the link
439
+ `/auth/owner-signin?token=…` once to the terminal. The row holds the SHA-256 of
440
+ the 256-bit token (`owner-signin-grant.mjs`), the claimed owner's id and
441
+ version, and an expiry 15 minutes ahead; the token itself is never stored, and
442
+ rer writes it to no log, receipt or deploy record.
443
+
444
+ GET only shows a confirmation page (link scanners cannot use it). POST consumes
445
+ the grant in one transaction with the session it opens, and only while the
446
+ grant is unused, unexpired, at most 15 minutes from the Worker's own clock
447
+ (whatever clock minted it), and names the operator that is still the active
448
+ owner at the same version (a role or status change voids it). The same
449
+ transaction records `owner:signin-link` in `oa_auth_audit` for that owner and
450
+ counts as a fresh step-up proof. The route uses the confirmation rate limit,
451
+ the exact Origin and the secure cookie of every other sign-in.
452
+
453
+ Why it is safe: writing that table needs the same Cloudflare token that can
454
+ already replace the Worker or read and write its database, so the link adds no
455
+ authority beyond the deploy credentials. It works once, only for the recorded
456
+ owner, within 15 minutes, and its use is logged. Production email-link sign-in
457
+ is unchanged. Native accounts (`createNativeAuth`) do not mount this route.
458
+
459
+ A wrong sign-in email is corrected in the app: `POST /auth/email {email}`
460
+ changes the signed-in operator's own address after a fresh proof (a step-up
461
+ link to the current address, a recent email-link sign-in, or a `rer signin`
462
+ link). It revokes unused links sent to the old address and keeps sessions and
463
+ provider bindings. An address another operator holds is refused with
464
+ `email_in_use`. `STEP_UP_ACTIONS` gains `email:change`.
465
+
429
466
  ## Local dev identity and the key gate
430
467
 
431
468
  `dev-gate.mjs` (exported as `devGate`, production-safe) is the per-checkout key
@@ -593,6 +630,12 @@ requesting email links. The reference applies them as
593
630
  (`createOidcClient`) is replaced by `config.providers`; its existing bindings keep
594
631
  signing in once the same issuer is configured as a provider.
595
632
 
633
+ **Owner sign-in links.** `rer signin` needs `oa_owner_signins`: apply
634
+ `accounts/schema/owner-signin.sql` as a new numbered migration (additive, safe
635
+ after the fresh schema; the reference applies it as
636
+ `migrations/core/0024_owner_signin.sql`). Only the owner-signin route reads it;
637
+ until it exists, `rer signin` refuses before writing anything.
638
+
596
639
  Seeds copy this module at different revisions, and an older copy lacks the
597
640
  cancellation migration and the optional OIDC and conformance files. Check each
598
641
  seed's present source and applied migrations before adopting. A seed owns its
@@ -0,0 +1,34 @@
1
+ // A signed-in operator changes their own sign-in email. It needs a fresh proof
2
+ // (a step-up, the email-link sign-in that opened this session, or a `rer signin`
3
+ // owner link) and fences the change to this session and operator version. Links
4
+ // already sent to the old address stop working; sessions and bindings stay.
5
+ import { deny } from '../errors.mjs';
6
+ import { requirePost } from '../http.mjs';
7
+ import { normalizeEmail } from '../policy.mjs';
8
+ import { emailAllowed } from './roles.mjs';
9
+
10
+ export function emailChange({ config, store, clock, authenticate, requireFreshProof }) {
11
+ return {
12
+ async changeEmail(request, input) {
13
+ requirePost(request, config);
14
+ const actor = await authenticate(request);
15
+ if (!actor) deny('unauthenticated', 401);
16
+ const email = normalizeEmail(input?.email);
17
+ if (!emailAllowed(email, config.allowList)) deny('email_not_allowed');
18
+ await requireFreshProof(actor);
19
+ if (email !== actor.operator.email) {
20
+ const now = clock(), fence = store.actorFence(actor, now);
21
+ let changed;
22
+ try {
23
+ [changed] = await store.batch([
24
+ [`UPDATE oa_operators SET email=? WHERE id=? AND version=? AND ${fence.sql}`, [email, actor.operator.id, actor.operator.version, ...fence.args]],
25
+ ['UPDATE oa_tokens SET revoked_at=? WHERE operator_id=? AND consumed_at IS NULL AND revoked_at IS NULL AND EXISTS(SELECT 1 FROM oa_operators WHERE id=? AND email=?)',
26
+ [now, actor.operator.id, actor.operator.id, email]],
27
+ ]);
28
+ } catch (error) { if (/UNIQUE/.test(String(error))) deny('email_in_use', 409); throw error; }
29
+ if (changed.meta.changes !== 1) deny('authority_changed', 409);
30
+ }
31
+ return store.operator(actor.operator.id);
32
+ },
33
+ };
34
+ }
@@ -0,0 +1,50 @@
1
+ // The owner's way in without mail: a one-time link `rer signin` minted with the
2
+ // deployment's own Cloudflare credentials (see ../owner-signin-grant.mjs). The
3
+ // grant names the owner and its version; it admits only that operator while it
4
+ // is still the active owner, once, before it expires, and never longer than
5
+ // OWNER_SIGNIN_SECONDS from now whatever the minting clock said. The session it
6
+ // opens counts as a fresh step-up proof, so the owner can correct a wrong email.
7
+ import { deny } from '../errors.mjs';
8
+ import { validToken } from '../crypto.mjs';
9
+ import { requireOrigin, requirePost } from '../http.mjs';
10
+ import { safeReturnTo } from '../policy.mjs';
11
+ import { OWNER_SIGNIN_SECONDS, ownerSigninDigest } from '../owner-signin-grant.mjs';
12
+
13
+ export function ownerSignIn({ config, store, clock, sessions, limit }) {
14
+ const live = `g.token_hash=? AND g.consumed_at IS NULL AND g.expires_at>? AND g.expires_at<=? AND g.operator_version=o.version
15
+ AND o.role='owner' AND o.status='active'`;
16
+ const allowed = () => config.allowList === undefined ? { sql: '1', args: [] } : { sql: `o.email IN (${config.allowList.map(() => '?').join(',') || 'NULL'})`, args: config.allowList };
17
+ return {
18
+ async previewOwnerSignIn(request, token) {
19
+ requireOrigin(request, config);
20
+ if (!validToken(token)) return null;
21
+ const now = clock(), allow = allowed();
22
+ const grant = await store.first(`SELECT g.expires_at AS expiresAt FROM oa_owner_signins g JOIN oa_operators o ON o.id=g.operator_id WHERE ${live} AND ${allow.sql}`,
23
+ [await ownerSigninDigest(token), now, now + OWNER_SIGNIN_SECONDS * 1000, ...allow.args]);
24
+ return grant ? { kind: 'owner', expiresInMinutes: Math.max(1, Math.ceil((grant.expiresAt - now) / 60000)) } : null;
25
+ },
26
+ async confirmOwnerSignIn(request, { token }) {
27
+ requirePost(request, config);
28
+ // Keyed per token like /auth/confirm: bad guesses cannot spend the owner's own attempts.
29
+ await limit(request, typeof token === 'string' ? `owner-signin:${token.slice(0, 128)}` : '', 'confirmation');
30
+ if (!validToken(token)) deny('invalid_or_expired', 400);
31
+ const digest = await ownerSigninDigest(token), now = clock(), allow = allowed();
32
+ const session = await sessions.newSession();
33
+ // One transaction: the session, the grant's consumption, the owner's audit
34
+ // record and the step-up proof stand or fall together.
35
+ await store.batch([
36
+ [`INSERT INTO oa_sessions(id,token_hash,operator_id,operator_version,kind,created_at,expires_at)
37
+ SELECT ?,?,o.id,o.version,'native',?,? FROM oa_owner_signins g JOIN oa_operators o ON o.id=g.operator_id WHERE ${live} AND ${allow.sql}`,
38
+ [session.id, session.hash, now, session.expiresAt, digest, now, now + OWNER_SIGNIN_SECONDS * 1000, ...allow.args]],
39
+ ['UPDATE oa_owner_signins SET consumed_at=? WHERE token_hash=? AND consumed_at IS NULL AND EXISTS(SELECT 1 FROM oa_sessions WHERE id=?)', [now, digest, session.id]],
40
+ [`INSERT INTO oa_auth_audit(id,actor_id,action,value,created_at) SELECT ?,s.operator_id,'owner:signin-link',g.id,? FROM oa_sessions s
41
+ JOIN oa_owner_signins g ON g.token_hash=? AND g.consumed_at=? WHERE s.id=?`, [crypto.randomUUID(), now, digest, now, session.id]],
42
+ [`INSERT INTO oa_step_up_challenges(id,token_hash,session_id,operator_id,operator_version,action,return_to,created_at,expires_at,consumed_at)
43
+ SELECT ?,?,id,operator_id,operator_version,'owner:signin-link','/',?,?,? FROM oa_sessions WHERE id=?`, [crypto.randomUUID(), `owner-signin:${session.id}`, now, now, now, session.id]],
44
+ ]);
45
+ const record = await store.session(session.hash, now);
46
+ if (!record) deny('invalid_or_expired', 400);
47
+ return sessions.completed(session, record, safeReturnTo(undefined));
48
+ },
49
+ };
50
+ }
@@ -0,0 +1,10 @@
1
+ -- One-time owner sign-in links minted by `rer signin` with the deployment's own
2
+ -- Cloudflare credentials, written straight into this table through the D1 API.
3
+ -- Apply as a NEW numbered migration under the seed's next unused number; never
4
+ -- rewrite an applied migration. Additive only. token_hash is the SHA-256 of the
5
+ -- link token (owner-signin-grant.mjs); the token itself is never stored.
6
+ CREATE TABLE IF NOT EXISTS oa_owner_signins (
7
+ id TEXT PRIMARY KEY, token_hash TEXT NOT NULL UNIQUE,
8
+ operator_id TEXT NOT NULL REFERENCES oa_operators(id), operator_version INTEGER NOT NULL,
9
+ created_at INTEGER NOT NULL, expires_at INTEGER NOT NULL, consumed_at INTEGER
10
+ );
@@ -1,13 +1,13 @@
1
1
  import { escapeHtml } from '../../http.mjs';
2
2
  import { pageResponse } from '../../page.mjs';
3
3
 
4
- const HEADINGS = { invite: 'Accept your invitation to', magic: 'Confirm sign-in to', step_up: "Confirm it's you in" };
4
+ const HEADINGS = { invite: 'Accept your invitation to', magic: 'Confirm sign-in to', step_up: "Confirm it's you in", owner: 'Sign in as the owner of' };
5
5
 
6
- export async function confirmationResponse({ branding, preview, token, method }) {
6
+ export async function confirmationResponse({ branding, preview, token, method, action = '/auth/confirm' }) {
7
7
  const product = escapeHtml(branding.productName);
8
8
  const heading = preview ? `${HEADINGS[preview.kind]} ${product}` : 'This link is invalid or expired';
9
9
  const content = preview
10
- ? `<p>This link works once and expires in ${preview.expiresInMinutes} ${preview.expiresInMinutes === 1 ? 'minute' : 'minutes'}.</p><form method="post" action="/auth/confirm"><input type="hidden" name="token" value="${escapeHtml(token)}"><button type="submit">Confirm</button></form>`
10
+ ? `<p>This link works once and expires in ${preview.expiresInMinutes} ${preview.expiresInMinutes === 1 ? 'minute' : 'minutes'}.</p><form method="post" action="${escapeHtml(action)}"><input type="hidden" name="token" value="${escapeHtml(token)}"><button type="submit">Confirm</button></form>`
11
11
  : `<p>This link may have expired or already been used. Request a new link to continue.</p><a class="action" href="${escapeHtml(branding.signInPath)}">Request a new link</a>`;
12
12
  // Native form POSTs need their Origin; never disclose the token path/query.
13
13
  return pageResponse({ branding, heading, content, status: preview ? 200 : 400, method, referrer: preview ? 'strict-origin' : undefined });
@@ -7,7 +7,7 @@ import { isActiveOperator } from '../../accounts/roles.mjs';
7
7
  import { isLocalCli } from '../../local-cli.mjs';
8
8
  import { linkMessage } from './message.mjs';
9
9
  import { completionHook } from '../after-confirm.mjs';
10
- export const STEP_UP_ACTIONS = Object.freeze(['providers:unlink', 'providers:relink', 'domains:change', 'owner:transfer', 'export', 'delete', 'credentials:mint']);
10
+ export const STEP_UP_ACTIONS = Object.freeze(['providers:unlink', 'providers:relink', 'domains:change', 'owner:transfer', 'export', 'delete', 'credentials:mint', 'email:change']);
11
11
  export const STEP_UP_SECONDS = 600;
12
12
 
13
13
  // Persistence owns the atomic authority check, proof consumption and session
@@ -7,10 +7,10 @@ export interface MailMessage { deliveryId: string; from: string; to: string[]; s
7
7
  export interface MailSender { send(message: MailMessage): Promise<{ status: 'accepted' | 'rejected' | 'rate_limited' | 'uncertain' | 'development'; provider: string; providerMessageId: string | null; code?: string }> }
8
8
  export interface AuthBranding { productName?: string; accentColor?: string; signInPath?: string; /** Same-origin path of the seed's served rer-theme.css. */ theme?: string }
9
9
  export interface AuthPresentation { readonly productName: string; readonly accentColor: string; readonly signInPath: string; readonly theme?: string }
10
- export interface LinkPreview { kind: 'magic' | 'invite' | 'step_up'; expiresInMinutes: number }
10
+ export interface LinkPreview { kind: 'magic' | 'invite' | 'step_up' | 'owner'; expiresInMinutes: number }
11
11
  /** A step-up confirmation proves the session's operator again; it issues no new session. */
12
12
  export interface StepUpConfirmed { stepUp: StepUpAction; returnTo: string; cookie?: undefined }
13
- export type StepUpAction = 'providers:unlink' | 'providers:relink' | 'domains:change' | 'owner:transfer' | 'export' | 'delete' | 'credentials:mint';
13
+ export type StepUpAction = 'providers:unlink' | 'providers:relink' | 'domains:change' | 'owner:transfer' | 'export' | 'delete' | 'credentials:mint' | 'email:change';
14
14
  export const STEP_UP_ACTIONS: readonly StepUpAction[];
15
15
  export type ProviderPreset = 'auth' | 'google' | 'microsoft' | 'okta' | 'legacy-rs256';
16
16
  /** One identity provider. Secrets and the private key are server bindings, never source text. */
@@ -183,6 +183,12 @@ export interface OperatorAuth<R extends string = Role> {
183
183
  requestStepUp(request: Request, input: { action: StepUpAction; returnTo?: string }): Promise<{ status: 'accepted' }>;
184
184
  /** Refuse unless this session holds a fresh (10-minute) app-local email-link proof. Provider sessions never do by themselves. */
185
185
  requireStepUp(request: Request, action: StepUpAction): Promise<Session<R>>;
186
+ /** The `rer signin` owner link (GET /auth/owner-signin): its preview, or null when invalid, used, expired or not the active owner's. Absent with native accounts. */
187
+ previewOwnerSignIn?(request: Request, token: string | null): Promise<LinkPreview | null>;
188
+ /** Consume the owner link once; records 'owner:signin-link' in oa_auth_audit and counts as a fresh step-up. */
189
+ confirmOwnerSignIn?(request: Request, input: { token: string }): Promise<CompletedSession<R>>;
190
+ /** The signed-in operator's own sign-in email; needs a fresh step-up proof. */
191
+ changeEmail?(request: Request, input: { email: string }): Promise<Operator<R>>;
186
192
  listDomainRules(request: Request): Promise<DomainRule[]>;
187
193
  /** provider null lifts the rule. Needs a fresh step-up proof. */
188
194
  setDomainRule(request: Request, input: { domain: string; provider: string | null }): Promise<DomainRule[]>;
@@ -0,0 +1,10 @@
1
+ // The one-time owner sign-in link that `rer signin` mints with the deployment's
2
+ // own Cloudflare credentials. rer writes the grant straight into the auth D1
3
+ // (accounts/schema/owner-signin.sql) and prints the link once; the Worker
4
+ // consumes it (accounts/owner-signin.mjs). Only this digest is stored.
5
+ export const OWNER_SIGNIN_SECONDS = 900;
6
+ export const OWNER_SIGNIN_PATH = '/auth/owner-signin';
7
+ export async function ownerSigninDigest(token) {
8
+ const bytes = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(`owner-signin\0${token}`));
9
+ return Array.from(new Uint8Array(bytes), (b) => b.toString(16).padStart(2, '0')).join('');
10
+ }
@@ -6,6 +6,7 @@ import { AuthError } from './errors.mjs';
6
6
  import { securityHeaders, requireLoopback } from './http.mjs';
7
7
  import { safeReturnTo } from './policy.mjs';
8
8
  import { readInput, readParameters } from './input.mjs';
9
+ import { OWNER_SIGNIN_PATH } from './owner-signin-grant.mjs';
9
10
  function json(value, status = 200) { return Response.json(value, { status, headers: securityHeaders() }); }
10
11
  function seeOther(location, cookie) { return new Response(null, { status: 303, headers: { ...securityHeaders(), ...(cookie ? { 'Set-Cookie': cookie } : {}), Location: location } }); }
11
12
  // A native HTML form (the sign-in page before any script) gets a page back; an
@@ -36,6 +37,13 @@ export function createAuthHandler(auth) {
36
37
  const preview = await auth.previewLink(request, token);
37
38
  return await confirmationResponse({ branding: auth.presentation, preview, token, method: request.method });
38
39
  }
40
+ // Composition without the owner link or email change (native accounts) does not own these paths.
41
+ if ((path === OWNER_SIGNIN_PATH && !auth.confirmOwnerSignIn) || (path === '/auth/email' && !auth.changeEmail)) return json({ error: 'not_found' }, 404);
42
+ if (path === OWNER_SIGNIN_PATH && ['GET', 'HEAD'].includes(request.method)) {
43
+ const token = readParameters(url.searchParams).token ?? null;
44
+ const preview = await auth.previewOwnerSignIn(request, token);
45
+ return await confirmationResponse({ branding: auth.presentation, preview, token, method: request.method, action: OWNER_SIGNIN_PATH });
46
+ }
39
47
  if (path === '/auth/session' && request.method === 'GET') {
40
48
  const session = await auth.getSession(request);
41
49
  return session ? json(session) : json({ error: 'unauthenticated' }, 401);
@@ -46,7 +54,7 @@ export function createAuthHandler(auth) {
46
54
  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);}
47
55
  if (path === '/auth/providers' && request.method === 'GET') return json(await auth.listProviders(request));
48
56
  const posts = new Set(['/auth/bootstrap', '/auth/magic-link', '/auth/confirm', '/auth/signout', '/auth/invite', '/auth/invite/cancel', '/auth/review-session',
49
- '/auth/operator/status', '/auth/operator/role', '/auth/session/revoke', '/auth/step-up', '/auth/domain-rules', '/auth/providers/unlink', '/auth/providers/relink', '/auth/settings/identity', '/auth/setup-complete']);
57
+ '/auth/operator/status', '/auth/operator/role', '/auth/session/revoke', '/auth/step-up', '/auth/domain-rules', '/auth/providers/unlink', '/auth/providers/relink', '/auth/settings/identity', '/auth/setup-complete', OWNER_SIGNIN_PATH, '/auth/email']);
50
58
  if (!posts.has(path)) return json({ error: 'not_found' }, 404);
51
59
  if (request.method !== 'POST') return json({ error: 'method_not_allowed' }, 405);
52
60
  const query = readParameters(url.searchParams);
@@ -64,6 +72,8 @@ export function createAuthHandler(auth) {
64
72
  return form ? seeOther(notice(auth, 'sent', { returnTo: safeReturnTo(input.returnTo) === '/app' ? undefined : safeReturnTo(input.returnTo), provider: result.requiredProvider })) : json(result, 202);
65
73
  }
66
74
  case '/auth/confirm': { const value = await auth.confirmLink(request, input); return seeOther(value.returnTo, value.cookie); }
75
+ case OWNER_SIGNIN_PATH: { const value = await auth.confirmOwnerSignIn(request, input); return seeOther(value.returnTo, value.cookie); }
76
+ case '/auth/email': return json(await auth.changeEmail(request, input));
67
77
  case '/auth/review-session': { const value = await auth.issueReviewSession(request, input); return seeOther(value.returnTo, value.cookie); }
68
78
  case '/auth/step-up': {
69
79
  const result = await auth.requestStepUp(request, input);
@@ -16,6 +16,8 @@ import { emailAllowed, isActiveOperator, defaultRolePolicy } from './accounts/ro
16
16
  import { oaSessions, createOaAccounts } from './accounts/oa.mjs';
17
17
  import { createAdmission, legacyAdmission } from './identity/admission.mjs';
18
18
  import { createOidcProviders } from './identity/oidc/index.mjs';
19
+ import { ownerSignIn } from './accounts/owner-signin.mjs';
20
+ import { emailChange } from './accounts/email-change.mjs';
19
21
  import { isLocalCli } from './local-cli.mjs';
20
22
  import { devAdmitted } from './dev-admission.mjs';
21
23
 
@@ -74,6 +76,8 @@ export function createOperatorAuth(options) {
74
76
  ...admin,
75
77
  ...providerControl({ store, accounts, authenticate, config, clock }),
76
78
  ...fencedCredentials({store,authenticate,requireFreshProof,config,clock,hash}),
79
+ ...ownerSignIn({ config, store, clock, sessions, limit }),
80
+ ...emailChange({ config, store, clock, authenticate, requireFreshProof }),
77
81
  presentation: config.branding,
78
82
  emailSignInAvailable: Boolean(mailSender),
79
83
  /** Identity providers (null when none is configured): routes, the sign-in page's list and owner actions. */
@@ -1,6 +1,6 @@
1
1
  import { all, quote, insist } from './storage.mjs';
2
2
  import { sidecar, copyRowid } from './copies.mjs';
3
- const TRANSIENT=['oa_setup_links','rer_dependency_keys','rer_dependency_pending','rer_dependency_codes','oa_provider_sessions','oa_provider_session_pins','oa_oidc_transactions','oa_step_up_challenges','oa_identity_provider_health'];
3
+ const TRANSIENT=['oa_setup_links','rer_dependency_keys','rer_dependency_pending','rer_dependency_codes','oa_provider_sessions','oa_provider_session_pins','oa_oidc_transactions','oa_step_up_challenges','oa_identity_provider_health','oa_owner_signins'];
4
4
  // Mandatory secret/session filtering even when a product explicitly includes a table.
5
5
  export async function dropProviderData(db,tables,copies) {
6
6
  const commands=[];
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@runeditrun/rer",
3
- "version": "0.2.18",
3
+ "version": "0.2.19",
4
4
  "description": "The rer command: install, set up, run and launch Run Edit Run checkouts.",
5
5
  "license": "MIT",
6
6
  "type": "module",