@runeditrun/rer 0.2.17 → 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 +3 -0
- package/cli/demo-host.mjs +2 -0
- package/cli/deploy-command.mjs +1 -1
- package/cli/inspect.mjs +4 -2
- package/cli/main.mjs +2 -0
- package/cli/output.mjs +7 -3
- package/cli/parse.mjs +5 -4
- package/cli/signin.mjs +41 -0
- package/cli/stdio.mjs +12 -0
- package/global/CHANGELOG.md +9 -0
- package/global/main.mjs +3 -3
- package/global/output.mjs +1 -12
- package/modules/demo-host/README.md +25 -6
- package/modules/demo-host/capacity.mjs +27 -6
- package/modules/demo-host/container.mjs +37 -9
- package/modules/demo-host/entrypoint.sh +9 -0
- package/modules/demo-host/image.mjs +18 -0
- package/modules/demo-host/pages.mjs +7 -7
- package/modules/demo-host/plan.mjs +1 -1
- package/modules/demo-host/prepare.mjs +28 -0
- package/modules/demo-host/start-script.mjs +11 -4
- package/modules/demo-host/startup.mjs +25 -0
- package/modules/demo-host/template.mjs +71 -0
- package/modules/demo-host/worker.mjs +74 -31
- package/modules/deploy-kit/README.md +2 -0
- package/modules/deploy-kit/owner-cli.mjs +5 -2
- package/modules/deploy-kit/owner-signin.mjs +34 -0
- package/modules/mail/README.md +44 -2
- package/modules/mail/src/adapters/rer/contract.mjs +22 -0
- package/modules/mail/src/adapters/rer/index.mjs +30 -0
- package/modules/mail/src/core/transport.mjs +1 -1
- package/modules/mail/src/core/validation.mjs +6 -2
- package/modules/mail/src/sender.mjs +2 -1
- package/modules/operator-auth/README.md +43 -0
- package/modules/operator-auth/accounts/email-change.mjs +34 -0
- package/modules/operator-auth/accounts/owner-signin.mjs +50 -0
- package/modules/operator-auth/accounts/schema/owner-signin.sql +10 -0
- package/modules/operator-auth/identity/email-link/confirmation.mjs +3 -3
- package/modules/operator-auth/identity/email-link/index.mjs +1 -1
- package/modules/operator-auth/index.d.mts +8 -2
- package/modules/operator-auth/owner-signin-grant.mjs +10 -0
- package/modules/operator-auth/routes.mjs +11 -1
- package/modules/operator-auth/service.mjs +4 -0
- package/modules/portability/provider-data.mjs +1 -1
- package/package.json +1 -1
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
import { createHash } from 'node:crypto';
|
|
2
|
+
import { cp, lstat, mkdir, readdir, readFile, rename, writeFile } from 'node:fs/promises';
|
|
3
|
+
import { join } from 'node:path';
|
|
4
|
+
|
|
5
|
+
const descriptor = '.rer-demo-template.json';
|
|
6
|
+
const initialized = '.rer-demo-initialized.json';
|
|
7
|
+
const copying = '.rer-demo-initializing.json';
|
|
8
|
+
|
|
9
|
+
async function inventory(directory, prefix = '') {
|
|
10
|
+
const entries = [];
|
|
11
|
+
for (const entry of (await readdir(directory, { withFileTypes: true })).sort((a, b) => a.name.localeCompare(b.name))) {
|
|
12
|
+
if (!entry.isFile() && !entry.isDirectory()) throw new Error('demo-template-invalid-entry');
|
|
13
|
+
const path = prefix + entry.name;
|
|
14
|
+
entries.push({ path, directory: entry.isDirectory() });
|
|
15
|
+
if (entry.isDirectory()) entries.push(...await inventory(join(directory, entry.name), path + '/'));
|
|
16
|
+
}
|
|
17
|
+
return entries;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
/** Called only after the engine has closed its database and persistence files. */
|
|
21
|
+
export async function sealTemplate(template, manifest) {
|
|
22
|
+
const entries = await inventory(template);
|
|
23
|
+
if (entries.some(entry => ['host.lock', descriptor, initialized, copying].includes(entry.path))) throw new Error('demo-template-not-fresh');
|
|
24
|
+
const marker = { version: 1, manifest: createHash('sha256').update(JSON.stringify(manifest)).digest('hex'), entries };
|
|
25
|
+
await writeFile(join(template, descriptor), JSON.stringify(marker) + '\n', { flag: 'wx', mode: 0o600 });
|
|
26
|
+
return marker;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
async function present(directory, entries) {
|
|
30
|
+
for (const entry of entries) {
|
|
31
|
+
let stat;
|
|
32
|
+
try { stat = await lstat(join(directory, entry.path)); }
|
|
33
|
+
catch (error) { if (error.code === 'ENOENT') return false; throw error; }
|
|
34
|
+
if (entry.directory ? !stat.isDirectory() : !stat.isFile()) return false;
|
|
35
|
+
}
|
|
36
|
+
return true;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/** Caller holds data/host.lock until the host exits. Never overlays live data. */
|
|
40
|
+
export async function copyTemplate(template, data) {
|
|
41
|
+
const raw = await readFile(join(template, descriptor), 'utf8'), marker = JSON.parse(raw);
|
|
42
|
+
if (marker.version !== 1 || !/^[a-f0-9]{64}$/.test(marker.manifest ?? '') || !Array.isArray(marker.entries)
|
|
43
|
+
|| marker.entries.some(entry => typeof entry.path !== 'string' || !entry.path || entry.path.startsWith('/')
|
|
44
|
+
|| entry.path.split('/').some(part => ['', '.', '..'].includes(part)) || typeof entry.directory !== 'boolean'
|
|
45
|
+
|| [descriptor, initialized, copying, 'host.lock'].includes(entry.path))) throw new Error('demo-template-invalid');
|
|
46
|
+
await mkdir(data, { recursive: true, mode: 0o700 });
|
|
47
|
+
const existing = await readdir(data);
|
|
48
|
+
if (existing.includes('host.lock') && !(await lstat(join(data, 'host.lock'))).isFile()) throw new Error('demo-volume-invalid-lock');
|
|
49
|
+
if (existing.includes(copying)) throw new Error('demo-volume-incomplete');
|
|
50
|
+
if (existing.includes(initialized)) {
|
|
51
|
+
if (!(await lstat(join(data, initialized))).isFile()) throw new Error('demo-volume-incomplete');
|
|
52
|
+
if (await readFile(join(data, initialized), 'utf8') !== raw) throw new Error('demo-volume-template-mismatch');
|
|
53
|
+
// SQLite may remove its transient WAL/SHM files after a later clean close.
|
|
54
|
+
if (!await present(data, marker.entries.filter(entry => !/-(wal|shm)$/.test(entry.path)))) throw new Error('demo-volume-incomplete');
|
|
55
|
+
return { copied: false };
|
|
56
|
+
}
|
|
57
|
+
if (existing.some(name => name !== 'host.lock')) throw new Error('demo-volume-not-fresh');
|
|
58
|
+
if (!await present(template, marker.entries)) throw new Error('demo-template-incomplete');
|
|
59
|
+
await writeFile(join(data, copying), raw, { flag: 'wx', mode: 0o600 });
|
|
60
|
+
for (const entry of marker.entries.filter(entry => !entry.path.includes('/'))) {
|
|
61
|
+
await cp(join(template, entry.path), join(data, entry.path), { recursive: true, force: false, errorOnExist: true });
|
|
62
|
+
}
|
|
63
|
+
if (!await present(data, marker.entries)) throw new Error('demo-volume-incomplete');
|
|
64
|
+
await rename(join(data, copying), join(data, initialized));
|
|
65
|
+
return { copied: true };
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
if (process.argv[1] === import.meta.filename) {
|
|
69
|
+
try { await copyTemplate(process.argv[2] ?? '/template', process.argv[3] ?? '/data'); }
|
|
70
|
+
catch (error) { console.error('Demo volume initialization failed:', error.message); process.exitCode = 1; }
|
|
71
|
+
}
|
|
@@ -7,7 +7,7 @@
|
|
|
7
7
|
// container; nothing else on this host is reachable.
|
|
8
8
|
import { operatorPage } from './operator.mjs';
|
|
9
9
|
import { bounded, category, report } from './diagnostics.mjs';
|
|
10
|
-
import { startPage, demoCookie } from './pages.mjs';
|
|
10
|
+
import { startPage, demoCookie, clearCookie } from './pages.mjs';
|
|
11
11
|
|
|
12
12
|
export { DemoContainer } from './container.mjs';
|
|
13
13
|
export { DemoCapacity } from './capacity.mjs';
|
|
@@ -33,51 +33,94 @@ async function human(env, token, ip) {
|
|
|
33
33
|
if (typeof token !== 'string' || !token || token.length > 2048) return false;
|
|
34
34
|
const body = new URLSearchParams({ secret: env.TURNSTILE_SECRET_KEY, response: token });
|
|
35
35
|
if (ip) body.set('remoteip', ip);
|
|
36
|
-
const response = await fetch('https://challenges.cloudflare.com/turnstile/v0/siteverify', { method: 'POST', body });
|
|
36
|
+
const response = await fetch('https://challenges.cloudflare.com/turnstile/v0/siteverify', { method: 'POST', body, signal: AbortSignal.timeout(5000) });
|
|
37
37
|
const result = response.ok ? await response.json() : {};
|
|
38
38
|
if (result.success !== true) console.error('Turnstile refused a start:', response.status, JSON.stringify(result['error-codes'] ?? []));
|
|
39
39
|
return result.success === true;
|
|
40
40
|
}
|
|
41
41
|
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
const
|
|
49
|
-
if (
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
42
|
+
const wantsJSON = request => request.headers.get('accept') === 'application/json';
|
|
43
|
+
function refusal(request, env, status, notice, headers = {}) {
|
|
44
|
+
return wantsJSON(request) ? Response.json({ notice }, { status, headers: { 'cache-control': 'no-store', ...headers } }) : startPage(env, { status, notice, headers });
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
function progress(request, env, id, state) {
|
|
48
|
+
const headers = new Headers({ 'cache-control': 'no-store' });
|
|
49
|
+
if (state.correlation) headers.set('x-rer-demo-correlation', state.correlation);
|
|
50
|
+
if (state.phase === 'failed') return refusal(request, env, 502, 'The demo did not start. Try again.', { ...Object.fromEntries(headers), 'set-cookie': clearCookie(env) });
|
|
51
|
+
headers.append('set-cookie', demoCookie(env, id.toString()));
|
|
52
|
+
if (state.phase === 'starting') {
|
|
53
|
+
headers.set('retry-after', '1');
|
|
54
|
+
if (wantsJSON(request)) return Response.json({ pending: true }, { status: 202, headers });
|
|
55
|
+
// A plain form keeps the same visitor reservation while the copy starts.
|
|
56
|
+
return startPage(env, { status: 202, pending: true, headers: Object.fromEntries(headers) });
|
|
53
57
|
}
|
|
54
|
-
const
|
|
58
|
+
for (const cookie of state.cookies) headers.append('set-cookie', cookie);
|
|
59
|
+
if (wantsJSON(request)) return Response.json({ location: state.location }, { headers });
|
|
60
|
+
headers.set('location', state.location);
|
|
61
|
+
return new Response(null, { status: 303, headers });
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
async function status(request, env) {
|
|
65
|
+
const id = demoId(request, env);
|
|
66
|
+
if (!id) return refusal(request, env, 410, 'This demo has ended. Start a new demo.');
|
|
67
|
+
try { return progress(request, env, id, await bounded(env.DEMO.get(id).status(), 2000)); }
|
|
68
|
+
catch { return refusal(request, env, 503, 'The demo could not be reached. Try again.'); }
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
async function start(request, env, ctx) {
|
|
72
|
+
const refuse = (status, notice, headers = {}) => refusal(request, env, status, notice, headers);
|
|
73
|
+
if (request.headers.get('origin') !== env.DEMO_ORIGIN) return refuse(403, 'Start the demo from this page.');
|
|
74
|
+
let demo, correlation;
|
|
75
|
+
const started = Date.now();
|
|
55
76
|
try {
|
|
56
|
-
const
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
if (
|
|
60
|
-
|
|
61
|
-
|
|
77
|
+
const ip = request.headers.get('cf-connecting-ip') ?? '';
|
|
78
|
+
if (!(await bounded(env.STARTS.limit({ key: ip }), 1000)).success) return refuse(429, 'Too many demos started from your network. Try again in a minute.');
|
|
79
|
+
const form = await bounded(request.formData(), 1000);
|
|
80
|
+
if (!await bounded(human(env, form.get('cf-turnstile-response'), ip), 5000)) return refuse(403, 'The check did not pass. Try again.');
|
|
81
|
+
// A retry while the original start is pending resumes that copy, not a
|
|
82
|
+
// second reservation that the visitor can never use.
|
|
83
|
+
const prior = demoId(request, env);
|
|
84
|
+
if (prior) {
|
|
85
|
+
const state = await bounded(env.DEMO.get(prior).status(), 1000);
|
|
86
|
+
if (state.phase === 'starting') return progress(request, env, prior, state);
|
|
87
|
+
}
|
|
88
|
+
const id = env.DEMO.newUniqueId(), ends = Date.now() + HOUR;
|
|
89
|
+
const capacity = env.CAPACITY.get(env.CAPACITY.idFromName('capacity'));
|
|
90
|
+
// A lost handoff occupies a place for at most a minute. The object extends
|
|
91
|
+
// it to the demo's end only after health and owner admission succeed.
|
|
92
|
+
if (!await bounded(capacity.acquire(id.toString(), Date.now() + 60_000, Number(env.DEMO_MAX_INSTANCES)), 2000)) {
|
|
93
|
+
return refuse(503, 'Every demo is in use right now. Try again in a few minutes.');
|
|
94
|
+
}
|
|
95
|
+
demo = env.DEMO.get(id); correlation = crypto.randomUUID();
|
|
96
|
+
const state = await bounded(demo.begin({ correlation, origin: env.DEMO_ORIGIN, originVar: env.DEMO_ORIGIN_VAR, ends, endsLocal: localTime(ends, request.cf?.timezone), settings: JSON.parse(env.DEMO_SETTINGS) }), 2000);
|
|
97
|
+
return progress(request, env, id, { ...state, correlation });
|
|
62
98
|
} catch (error) {
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
await bounded(env.CAPACITY.get(env.CAPACITY.idFromName('diagnostics')).record(correlation, diagnostic), 3000);
|
|
68
|
-
} catch (capture) { report(correlation, started, 'diagnostic', { error: category(capture) }); }
|
|
69
|
-
try { await bounded(demo.end(), 6000); } catch (cleanup) { report(correlation, started, 'cleanup', { error: category(cleanup) }); }
|
|
70
|
-
return refuse(502, 'The demo did not start. Try again.', { 'x-rer-demo-correlation': correlation });
|
|
99
|
+
report(correlation, started, 'failed', { error: category(error) });
|
|
100
|
+
// Cleanup runs independently of the response: retries never wait on it.
|
|
101
|
+
if (demo) ctx.waitUntil(bounded(demo.end(), 6000).catch(cleanup => report(correlation, started, 'cleanup', { error: category(cleanup) })));
|
|
102
|
+
return refuse(502, 'The demo did not start. Try again.', correlation ? { 'x-rer-demo-correlation': correlation } : {});
|
|
71
103
|
}
|
|
72
104
|
}
|
|
73
105
|
|
|
74
106
|
export default {
|
|
75
|
-
async fetch(request, env) {
|
|
107
|
+
async fetch(request, env, ctx) {
|
|
76
108
|
const url = new URL(request.url);
|
|
77
109
|
if (url.pathname.startsWith('/__demo/operator/')) return operatorPage(request, env, url.pathname.slice('/__demo/operator/'.length));
|
|
78
|
-
if (url.pathname === '/__demo/start') return request.method === 'POST' ? start(request, env) : home();
|
|
110
|
+
if (url.pathname === '/__demo/start') return request.method === 'POST' ? start(request, env, ctx) : home();
|
|
111
|
+
if (url.pathname === '/__demo/status') return request.method === 'GET' ? status(request, env) : home();
|
|
79
112
|
const id = demoId(request, env);
|
|
80
|
-
if (id)
|
|
113
|
+
if (id) {
|
|
114
|
+
// The JSON start leaves the browser on /. Reloading it must keep the
|
|
115
|
+
// pending copy on the progress page until health and owner claim finish.
|
|
116
|
+
if (url.pathname === '/' && ['GET', 'HEAD'].includes(request.method)) {
|
|
117
|
+
try {
|
|
118
|
+
const state = await bounded(env.DEMO.get(id).status(), 2000);
|
|
119
|
+
if (state.phase === 'starting') return progress(request, env, id, state);
|
|
120
|
+
} catch { return refusal(request, env, 503, 'The demo could not be reached. Try again.'); }
|
|
121
|
+
}
|
|
122
|
+
return env.DEMO.get(id).fetch(request);
|
|
123
|
+
}
|
|
81
124
|
if (!['GET', 'HEAD'].includes(request.method)) return new Response('Start a demo first.', { status: 403 });
|
|
82
125
|
if (url.pathname !== '/') return home();
|
|
83
126
|
return startPage(env);
|
|
@@ -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
|
+
}
|
package/modules/mail/README.md
CHANGED
|
@@ -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.
|
|
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
|
+
}
|