@runeditrun/rer 0.2.28 → 0.2.30
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 -3
- package/cli/demo-build.mjs +23 -0
- package/cli/demo-host.mjs +10 -70
- package/cli/demo-native.mjs +74 -0
- package/cli/inspect.mjs +5 -1
- package/cli/lifecycle.mjs +1 -1
- package/cli/main.mjs +6 -1
- package/cli/parse.mjs +9 -2
- package/cli/placeholder-mark.mjs +46 -0
- package/cli/release.mjs +6 -2
- package/global/CHANGELOG.md +27 -0
- package/modules/container/README.md +2 -15
- package/modules/container/host.mjs +1 -3
- package/modules/container/ingress.mjs +1 -15
- package/modules/container/worker-engine.mjs +2 -3
- package/modules/demo-host/README.md +23 -156
- package/modules/demo-host/build.mjs +49 -0
- package/modules/demo-host/capacity.mjs +8 -2
- package/modules/demo-host/claim.mjs +2 -2
- package/modules/demo-host/diagnostics.mjs +1 -18
- package/modules/demo-host/native/alarms.mjs +51 -0
- package/modules/demo-host/native/bindings.mjs +24 -0
- package/modules/demo-host/native/bridge.mjs +17 -0
- package/modules/demo-host/native/config.mjs +35 -0
- package/modules/demo-host/native/cron.mjs +31 -0
- package/modules/demo-host/native/d1.mjs +37 -0
- package/modules/demo-host/native/deploy-r2.mjs +43 -0
- package/modules/demo-host/native/isolate.mjs +36 -0
- package/modules/demo-host/native/loader.mjs +30 -0
- package/modules/demo-host/native/namespace.mjs +35 -0
- package/modules/demo-host/native/prepare.mjs +35 -0
- package/modules/demo-host/native/queues.mjs +62 -0
- package/modules/demo-host/native/r2-client.mjs +37 -0
- package/modules/demo-host/native/r2.mjs +43 -0
- package/modules/demo-host/native/resources.mjs +37 -0
- package/modules/demo-host/native/seed-object.mjs +22 -0
- package/modules/demo-host/native/sql.mjs +17 -0
- package/modules/demo-host/native/visitor.mjs +147 -0
- package/modules/demo-host/native/worker.mjs +22 -0
- package/modules/demo-host/pages.mjs +1 -1
- package/modules/demo-host/plan.mjs +9 -30
- package/modules/demo-host/remove.mjs +13 -23
- package/modules/demo-host/upgrade.mjs +41 -0
- package/modules/demo-host/worker.mjs +3 -4
- package/modules/mail/README.md +18 -5
- package/modules/mail/src/adapters/rer/contract.mjs +5 -0
- package/modules/mail/src/adapters/rer/index.mjs +4 -2
- package/modules/mail/src/adapters/rer/list-headers.mjs +5 -0
- package/modules/mail/src/core/validation.mjs +7 -2
- package/modules/mail/src/development/index.d.mts +1 -0
- package/modules/operator-auth/README.md +11 -0
- package/modules/operator-auth/accounts/one-click.mjs +63 -0
- package/modules/operator-auth/accounts/store.mjs +3 -3
- package/modules/operator-auth/dev/index.mjs +26 -13
- package/modules/operator-auth/index.d.mts +5 -0
- package/modules/operator-auth/routes.mjs +20 -1
- package/modules/operator-auth/service.mjs +2 -0
- package/modules/operator-auth/signin/index.mjs +7 -0
- package/modules/operator-auth/signin/one-click.mjs +7 -0
- package/modules/portability/catalogue.mjs +3 -3
- package/modules/release/produce.mjs +8 -1
- package/onboarding/README.md +4 -0
- package/package.json +1 -1
- package/modules/demo-host/container.mjs +0 -221
- package/modules/demo-host/entrypoint.sh +0 -9
- package/modules/demo-host/image.mjs +0 -18
- package/modules/demo-host/placement.mjs +0 -37
- package/modules/demo-host/prepare.mjs +0 -28
- package/modules/demo-host/startup.mjs +0 -27
- package/modules/demo-host/template.mjs +0 -71
|
@@ -1,35 +1,25 @@
|
|
|
1
|
+
import { ownedBucket, removeBucket } from './native/deploy-r2.mjs';
|
|
1
2
|
import { assert } from '../deploy-kit/validation.mjs';
|
|
2
3
|
import { workerSettings } from '../deploy-kit/owner.mjs';
|
|
3
4
|
import { servedVersion } from '../deploy-kit/site.mjs';
|
|
4
5
|
import { deleteWorker } from '../deploy-kit/teardown.mjs';
|
|
5
6
|
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
* deploy made: the front Worker (its Durable Object namespaces go with it), the
|
|
9
|
-
* Workers Custom Domains on the primary demo hostname and declared descendants
|
|
10
|
-
* (Cloudflare adds and removes their DNS records with them), and the Container application `wrangler deploy` created for
|
|
11
|
-
* the Worker's DemoContainer namespace. It makes no D1, KV, R2, queue or DNS
|
|
12
|
-
* record of its own: the domain's record is Cloudflare's, and goes with it.
|
|
13
|
-
*
|
|
14
|
-
* The Worker is the demo's own only while it serves the version carrying the
|
|
15
|
-
* demo's record (plan.mjs `demoRecord`). The domain is the demo's only while it
|
|
16
|
-
* routes to that Worker, the Container application only while it belongs to
|
|
17
|
-
* that Worker's DemoContainer namespace. Anything else of those names, or
|
|
18
|
-
* attached to that Worker, is refused before the first delete. The Worker goes
|
|
19
|
-
* last, so a run cut short leaves the record for the next one; once everything
|
|
20
|
-
* is gone a second run is a no-op. */
|
|
7
|
+
// Exact-id teardown and ownership inventory, shared by native upgrades.
|
|
8
|
+
// The Worker is deleted last so interrupted removal retains its ownership record.
|
|
21
9
|
|
|
22
10
|
function refuse(code, resource) { const error = new Error(code); error.resource = resource; return error; }
|
|
23
11
|
const rows = value => { assert(Array.isArray(value), 'provider-invalid-list'); return value; };
|
|
24
12
|
|
|
25
13
|
/** What exists of the demo now, each with its exact id; refuses whatever is not provably the demo's. */
|
|
26
|
-
async function
|
|
14
|
+
export async function demoInventory(api, plan) {
|
|
27
15
|
const named = (await Promise.all(plan.hostnames.map(async hostname =>
|
|
28
16
|
rows(await api.request(`/workers/domains?hostname=${hostname}`)).filter(row => row?.hostname === hostname)))).flat();
|
|
29
17
|
const attached = rows(await api.request(`/workers/domains?service=${plan.worker}`)).filter(row => row?.service === plan.worker);
|
|
30
|
-
const apps = rows(await api.request('/containers/applications')).filter(row => row?.name === plan.container);
|
|
31
18
|
const namespaces = rows(await api.list('/workers/durable_objects/namespaces')).filter(row => row?.script === plan.worker);
|
|
32
|
-
const
|
|
19
|
+
const settings = await workerSettings(api, plan.worker);
|
|
20
|
+
const worker = settings !== null;
|
|
21
|
+
const container = namespaces.find(row => row.class === 'DemoContainer')?.id;
|
|
22
|
+
const apps = container ? rows(await api.request('/containers/applications')).filter(row => row?.name === plan.container || row?.durable_objects?.namespace_id === container) : [];
|
|
33
23
|
for (const row of named) if (row.service !== plan.worker) throw refuse('resource-name-collision', `domain:${row.hostname}`);
|
|
34
24
|
if (worker) {
|
|
35
25
|
const served = await servedVersion(api, plan.worker);
|
|
@@ -40,13 +30,12 @@ async function inventory(api, plan) {
|
|
|
40
30
|
// Without the Worker nothing proves these are the demo's.
|
|
41
31
|
throw refuse('uncertain-resource-create', named[0] || attached[0] ? `domain:${(named[0] ?? attached[0]).hostname}` : `container:${plan.container}`);
|
|
42
32
|
}
|
|
43
|
-
const
|
|
44
|
-
|
|
45
|
-
return { worker, domains: named, apps };
|
|
33
|
+
for (const app of apps) if (app.name !== plan.container || !container || app.durable_objects?.namespace_id !== container) throw refuse('resource-name-collision', `container:${plan.container}`);
|
|
34
|
+
return { worker, settings, namespaces, domains: named, apps, bucket: worker ? await ownedBucket(api, plan, settings) : null };
|
|
46
35
|
}
|
|
47
36
|
|
|
48
37
|
export async function demoRemove({ api, plan, sleep }) {
|
|
49
|
-
const found = await
|
|
38
|
+
const found = await demoInventory(api, plan);
|
|
50
39
|
if (!found.worker) return { worker: plan.worker, removed: [], remaining: [], alreadyRemoved: true };
|
|
51
40
|
const removed = [];
|
|
52
41
|
for (const domain of found.domains) {
|
|
@@ -54,6 +43,7 @@ export async function demoRemove({ api, plan, sleep }) {
|
|
|
54
43
|
removed.push(`domain:${domain.hostname}`);
|
|
55
44
|
}
|
|
56
45
|
for (const app of found.apps) { await api.request(`/containers/applications/${app.id}`, { method: 'DELETE' }); removed.push(`container:${plan.container}`); }
|
|
46
|
+
if (found.bucket) { await removeBucket(api, found.bucket); removed.push(`r2:${found.bucket.name}`); }
|
|
57
47
|
await deleteWorker({ api, worker: plan.worker, ...sleep ? { sleep } : {} });
|
|
58
48
|
removed.push(`worker:${plan.worker}`);
|
|
59
49
|
// Read back: nothing of the demo is listed any more.
|
|
@@ -62,7 +52,7 @@ export async function demoRemove({ api, plan, sleep }) {
|
|
|
62
52
|
for (const row of rows(await api.list('/workers/durable_objects/namespaces'))) if (row?.script === plan.worker) remaining.push(`durable-object:${row.class}`);
|
|
63
53
|
const domains = await Promise.all(plan.hostnames.map(async hostname => ({ hostname, rows: rows(await api.request(`/workers/domains?hostname=${hostname}`)) })));
|
|
64
54
|
for (const { hostname, rows: listed } of domains) if (listed.some(row => row?.hostname === hostname)) remaining.push(`domain:${hostname}`);
|
|
65
|
-
const apps = rows(await api.request('/containers/applications'));
|
|
55
|
+
const apps = found.apps.length ? rows(await api.request('/containers/applications')) : [];
|
|
66
56
|
for (const app of found.apps) if (apps.some(row => row?.id === app.id)) remaining.push(`container:${plan.container}`);
|
|
67
57
|
if (remaining.length) { const error = new Error('remove-incomplete'); error.remaining = remaining; error.removed = removed.filter(item => !remaining.includes(item)); throw error; }
|
|
68
58
|
return { worker: plan.worker, removed, remaining: [] };
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
import { demoInventory } from './remove.mjs';
|
|
2
|
+
|
|
3
|
+
// Keep the Worker and custom domains throughout the transition. Container apps
|
|
4
|
+
// must go before deleting their backing class; Wrangler then applies the class
|
|
5
|
+
// migration atomically with the native code. A failed upload can be rerun.
|
|
6
|
+
export async function upgradeDemo({ api, plan }) {
|
|
7
|
+
const found = await demoInventory(api, plan);
|
|
8
|
+
const classes = found.namespaces.map(row => row.class);
|
|
9
|
+
const unknown = classes.filter(name => !['DemoContainer', 'NativeDemo', 'DemoCapacity'].includes(name));
|
|
10
|
+
if (unknown.length) throw new Error('demo-upgrade-unknown-class');
|
|
11
|
+
const service = found.worker ? await api.request(`/workers/services/${plan.worker}`) : null;
|
|
12
|
+
const tag = service?.default_environment?.script?.migration_tag;
|
|
13
|
+
if (found.worker && classes.length && !tag) throw new Error('demo-upgrade-missing-migration-tag');
|
|
14
|
+
const migration = { tag: 'native-v2' };
|
|
15
|
+
const added = ['NativeDemo', 'DemoCapacity'].filter(name => !classes.includes(name));
|
|
16
|
+
if (added.length) migration.new_sqlite_classes = added;
|
|
17
|
+
if (classes.includes('DemoContainer')) migration.deleted_classes = ['DemoContainer'];
|
|
18
|
+
if (tag === migration.tag && (added.length || migration.deleted_classes)) throw new Error('demo-upgrade-inconsistent-migration');
|
|
19
|
+
for (const app of found.apps) await api.request(`/containers/applications/${app.id}`, { method: 'DELETE' });
|
|
20
|
+
if (found.apps.length) {
|
|
21
|
+
const remaining = await api.request('/containers/applications');
|
|
22
|
+
if (remaining.some(row => found.apps.some(app => app.id === row.id))) throw new Error('demo-upgrade-container-remove-incomplete');
|
|
23
|
+
}
|
|
24
|
+
if (classes.includes('DemoContainer')) {
|
|
25
|
+
// The API checks the currently deployed bindings before class deletion.
|
|
26
|
+
// Detach the retired binding first; inherit every other value by name,
|
|
27
|
+
// including secrets, and retain the ownership annotation for a rerun.
|
|
28
|
+
const body = new FormData();
|
|
29
|
+
body.set('settings', new Blob([JSON.stringify({
|
|
30
|
+
annotations: { 'workers/message': plan.record },
|
|
31
|
+
bindings: found.settings.bindings.filter(binding => !(binding.type === 'durable_object_namespace' && binding.class_name === 'DemoContainer'))
|
|
32
|
+
.map(binding => ({ name: binding.name, type: 'inherit' })),
|
|
33
|
+
})], { type: 'application/json' }));
|
|
34
|
+
await api.request(`/workers/scripts/${plan.worker}/settings`, { method: 'PATCH', body });
|
|
35
|
+
}
|
|
36
|
+
// Wrangler validates the full declared history locally, even though only
|
|
37
|
+
// steps after the deployed tag are sent. Describe the existing classes in
|
|
38
|
+
// that historical step so a deletion resolves without shipping old code.
|
|
39
|
+
if (tag === migration.tag) return [{ tag, new_sqlite_classes: classes }];
|
|
40
|
+
return tag ? [{ tag, new_sqlite_classes: classes }, migration] : [migration];
|
|
41
|
+
}
|
|
@@ -1,16 +1,15 @@
|
|
|
1
1
|
// A seed's hosted demo at demo.<domain>, generated by `rer deploy --demo`.
|
|
2
2
|
// GET / shows the start page (a Turnstile managed widget that starts the demo by itself).
|
|
3
3
|
// POST /__demo/start checks the visitor's IP rate limit, Turnstile and capacity,
|
|
4
|
-
// then starts a
|
|
4
|
+
// then starts a native isolate of their own, signs its owner in and sets the
|
|
5
5
|
// rer_demo cookie. The page's script asks for JSON (Accept: application/json) to
|
|
6
6
|
// show its progress and failures; a plain form post gets the 303 or the page. Every request with that cookie goes to the visitor's
|
|
7
|
-
//
|
|
7
|
+
// isolate; nothing else on this host is reachable.
|
|
8
8
|
import { operatorPage } from './operator.mjs';
|
|
9
9
|
import { measured, testHost } from './measurement.mjs';
|
|
10
10
|
import { bounded, category, report } from './diagnostics.mjs';
|
|
11
11
|
import { startPage, demoCookie, clearCookie } from './pages.mjs';
|
|
12
12
|
|
|
13
|
-
export { DemoContainer } from './container.mjs';
|
|
14
13
|
export { DemoCapacity } from './capacity.mjs';
|
|
15
14
|
|
|
16
15
|
const HOUR = 60 * 60_000;
|
|
@@ -106,7 +105,7 @@ async function start(request, env, ctx) {
|
|
|
106
105
|
// Who holds the place: automated browsers pass Turnstile's testing keys.
|
|
107
106
|
report(correlation, started, 'admitted', { agent: (request.headers.get('user-agent') ?? '').slice(0, 160), network: request.cf?.asOrganization ?? null });
|
|
108
107
|
demo = env.DEMO.get(id);
|
|
109
|
-
const begun = 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) });
|
|
108
|
+
const begun = demo.begin({ correlation, clientIp: ip, origin: env.DEMO_ORIGIN, originVar: env.DEMO_ORIGIN_VAR, ends, endsLocal: localTime(ends, request.cf?.timezone), settings: JSON.parse(env.DEMO_SETTINGS) });
|
|
110
109
|
// A new object can take seconds to answer. That is a slow start, not a
|
|
111
110
|
// failed one: the page polls this copy, and a begin that later fails ends
|
|
112
111
|
// it and releases its place.
|
package/modules/mail/README.md
CHANGED
|
@@ -177,10 +177,23 @@ accepts 1–20 such IDs separated by ASCII spaces, without leading/trailing
|
|
|
177
177
|
spaces, tabs or commas. Invalid values fail locally with `invalid_list_id`,
|
|
178
178
|
`invalid_list_archive`, `invalid_list_help`, `invalid_in_reply_to` or
|
|
179
179
|
`invalid_references`. Values are preserved; raw headers are never forwarded.
|
|
180
|
-
Other recipients, attachments, reply-to and every other header
|
|
181
|
-
and fail before dispatch.
|
|
182
|
-
|
|
183
|
-
|
|
180
|
+
Other recipients, attachments, reply-to and every other header, including
|
|
181
|
+
`Message-ID`, are unsupported and fail before dispatch.
|
|
182
|
+
|
|
183
|
+
An optional `messageKey` asks the relay to assign the Message-ID: 1–200 ASCII
|
|
184
|
+
characters from `A-Z a-z 0-9 . _ : -`, matching platform's relay validation at
|
|
185
|
+
`c1e3ade` (`src/managed-mail/headers.ts:22`); anything else fails locally with
|
|
186
|
+
`invalid_message_key`. The relay derives the same ID for the same installation
|
|
187
|
+
and key, so use one key per message (for example `incident:7:opened`, then
|
|
188
|
+
`incident:7:update-1`). Keys assign identity, not duplicate suppression. To
|
|
189
|
+
thread updates, keep the first notice's returned `providerMessageId` and send
|
|
190
|
+
each later update with its own key and `In-Reply-To`/`References` set to it.
|
|
191
|
+
Only `rer` (and `development`, which accepts what `rer` accepts) takes
|
|
192
|
+
`messageKey`; other providers refuse it with `unsupported_provider_setting`.
|
|
193
|
+
|
|
194
|
+
HTTP 202 returns `accepted` with the relay's assigned Message-ID (for example
|
|
195
|
+
`<ABCD…@mail.example.com>`) as `providerMessageId`, or null when the relay's
|
|
196
|
+
body carries no valid one. HTTP 400, 401, 402,
|
|
184
197
|
403 and 413 return `rejected`, and so does any 3xx (`provider_redirected`);
|
|
185
198
|
429 returns `rate_limited`; 502 and 503 return `uncertain`. Network failures
|
|
186
199
|
are also `uncertain`.
|
|
@@ -191,7 +204,7 @@ adapter makes no retries and never reads or logs provider error bodies.
|
|
|
191
204
|
|
|
192
205
|
Required fields: `deliveryId` (nonempty, at most 512 characters), `from`, nonempty `to: string[]`, `subject: string` (SendGrid requires nonempty; other providers allow empty), and at least one nonempty `text` or `html`. Addresses accept a mailbox or `Display Name <mailbox>`; the conservative mailbox grammar rejects controls, multiple addresses inside one string and malformed domains. Use arrays for recipients.
|
|
193
206
|
|
|
194
|
-
Optional `cc`, `bcc`, `replyTo`, and string-valued `headers` preserve envelope and threading. `In-Reply-To` and ordered `References` can be supplied as headers. SendGrid and Resend also accept `Message-ID`; Cloudflare generates it and rejects a caller-supplied value
|
|
207
|
+
Optional `cc`, `bcc`, `replyTo`, and string-valued `headers` preserve envelope and threading. `In-Reply-To` and ordered `References` can be supplied as headers. SendGrid and Resend also accept `Message-ID`; Cloudflare generates it and rejects a caller-supplied value; `rer` rejects it and assigns one from an optional `messageKey`. CR/LF/control characters, duplicate header names ignoring case, reserved envelope/MIME/security headers and invalid header names fail before a request. Provider-specific header restrictions are also enforced.
|
|
195
208
|
|
|
196
209
|
Attachments use `{filename, contentType, content: Uint8Array, disposition?: 'attachment'|'inline', contentId?}`. Content is raw bytes, never a base64 string at the public boundary. Inline attachments require a content ID. Unsupported attachment features fail explicitly. Provider size and count limits still apply.
|
|
197
210
|
|
|
@@ -5,6 +5,11 @@ import { rerListHeaderField } from './list-headers.mjs';
|
|
|
5
5
|
const listEntries = /^[ \t]*<([^<>\s]+)>[ \t]*(?:,[ \t]*<([^<>\s]+)>[ \t]*)?$/;
|
|
6
6
|
const relayMailbox = /^[^\s@]+@[^\s@]+\.[^\s@]{2,}$/;
|
|
7
7
|
|
|
8
|
+
// Match platform c1e3ade01eecd4d027a4f5ed0304d5f6bd7da6bb: src/managed-mail/headers.ts:22.
|
|
9
|
+
export function validateRerMessageKey(value) {
|
|
10
|
+
if (typeof value !== 'string' || value.length < 1 || value.length > 200 || /[^A-Za-z0-9._:-]/.test(value)) fail('invalid_message_key');
|
|
11
|
+
}
|
|
12
|
+
|
|
8
13
|
export function validateRerConfig(config) {
|
|
9
14
|
let url;
|
|
10
15
|
try { url = new URL(config.relayUrl); } catch { fail('rer_relay_url_required'); }
|
|
@@ -2,6 +2,7 @@ import { validateConfig, validateMessage, parseAddress } from '../../core/valida
|
|
|
2
2
|
import { fail } from '../../core/errors.mjs';
|
|
3
3
|
import { requestProvider, redirected, classifyHttpStatus, sendResult } from '../../core/transport.mjs';
|
|
4
4
|
import { rerHeaderFields } from './contract.mjs';
|
|
5
|
+
import { rerMessageId } from './list-headers.mjs';
|
|
5
6
|
|
|
6
7
|
/** One Managed relay submission. RER owns the sender and installation identity. */
|
|
7
8
|
export async function sendRer(config, message, dependencies = {}) {
|
|
@@ -13,6 +14,7 @@ export async function sendRer(config, message, dependencies = {}) {
|
|
|
13
14
|
subject: message.subject,
|
|
14
15
|
text: message.text,
|
|
15
16
|
...(message.html ? { html: message.html } : {}),
|
|
17
|
+
...(message.messageKey !== undefined ? { messageKey: message.messageKey } : {}),
|
|
16
18
|
...rerHeaderFields(message.headers),
|
|
17
19
|
});
|
|
18
20
|
if (new TextEncoder().encode(body).byteLength > 128 * 1024) fail('rer_message_too_large');
|
|
@@ -24,8 +26,8 @@ export async function sendRer(config, message, dependencies = {}) {
|
|
|
24
26
|
}, dependencies);
|
|
25
27
|
if (response === null) return sendResult('rer', 'uncertain', null, 'transport_uncertain');
|
|
26
28
|
if (response === redirected) return sendResult('rer', 'rejected', null, 'provider_redirected');
|
|
27
|
-
//
|
|
28
|
-
if (response.status === 202) return sendResult('rer', 'accepted');
|
|
29
|
+
// Read only the accepted body's Message-ID; error bodies may contain credentials or personal data.
|
|
30
|
+
if (response.status === 202) return sendResult('rer', 'accepted', rerMessageId(await response.json().then(body => body?.messageId, () => null)));
|
|
29
31
|
const status = classifyHttpStatus(response.status) ?? 'uncertain';
|
|
30
32
|
return sendResult('rer', status, null, {
|
|
31
33
|
rejected: 'provider_rejected', rate_limited: 'provider_rate_limited', uncertain: 'provider_uncertain',
|
|
@@ -18,6 +18,11 @@ const fields = new Map([
|
|
|
18
18
|
['references', ['references', 'invalid_references']],
|
|
19
19
|
]);
|
|
20
20
|
|
|
21
|
+
/** The relay's Message-ID, when its 202 body carries one in the grammar it accepts back as In-Reply-To/References. */
|
|
22
|
+
export function rerMessageId(value) {
|
|
23
|
+
return typeof value === 'string' && value.length <= 2000 && messageIdPattern.test(value) ? value : null;
|
|
24
|
+
}
|
|
25
|
+
|
|
21
26
|
/** Validate a supported list/thread header and return its relay field, or null. */
|
|
22
27
|
export function rerListHeaderField(name, value) {
|
|
23
28
|
const mapping = fields.get(name.toLowerCase());
|
|
@@ -1,11 +1,11 @@
|
|
|
1
1
|
import { fail } from './errors.mjs';
|
|
2
2
|
import { validateMessagingConfig, validateMessagingResult, identity, rfc3339 } from '../adapters/messaging/contract.mjs';
|
|
3
|
-
import { validateRerConfig, validateRerMessage } from '../adapters/rer/contract.mjs';
|
|
3
|
+
import { validateRerConfig, validateRerMessage, validateRerMessageKey } from '../adapters/rer/contract.mjs';
|
|
4
4
|
import { rerListHeaderField } from '../adapters/rer/list-headers.mjs';
|
|
5
5
|
|
|
6
6
|
const providers = ['sendgrid', 'resend', 'cloudflare', 'rer', 'development', 'messaging'];
|
|
7
7
|
const controls = /[\x00-\x1f\x7f]/;
|
|
8
|
-
const fields = new Set(['deliveryId', 'from', 'to', 'subject', 'text', 'html', 'cc', 'bcc', 'replyTo', 'headers', 'attachments', 'unsubscribe', 'customArgs', 'asmGroupId', 'subscriptionTracking', 'kind', 'expiresAt']);
|
|
8
|
+
const fields = new Set(['deliveryId', 'from', 'to', 'subject', 'text', 'html', 'cc', 'bcc', 'replyTo', 'headers', 'attachments', 'unsubscribe', 'customArgs', 'asmGroupId', 'subscriptionTracking', 'kind', 'expiresAt', 'messageKey']);
|
|
9
9
|
const reservedHeaders = new Set(['x-sg-id', 'x-sg-eid', 'received', 'dkim-signature', 'content-type', 'content-transfer-encoding', 'mime-version', 'to', 'from', 'subject', 'reply-to', 'cc', 'bcc', 'return-path', 'sender']);
|
|
10
10
|
const reservedArgs = new Set(['rer_delivery_id', 'email', 'event', 'timestamp', 'sg_event_id', 'sg_message_id']);
|
|
11
11
|
|
|
@@ -137,6 +137,11 @@ export function validateMessage(message, provider) {
|
|
|
137
137
|
for (const attachment of message.attachments) validateAttachment(attachment);
|
|
138
138
|
}
|
|
139
139
|
if (message.unsubscribe !== undefined) validateUnsubscribe(message.unsubscribe);
|
|
140
|
+
if (message.messageKey !== undefined) {
|
|
141
|
+
// Only the rer relay assigns Message-IDs from keys; development accepts what rer accepts.
|
|
142
|
+
if (provider !== undefined && !['rer', 'development'].includes(provider)) fail('unsupported_provider_setting');
|
|
143
|
+
validateRerMessageKey(message.messageKey);
|
|
144
|
+
}
|
|
140
145
|
if (provider === 'rer') validateRerMessage(message);
|
|
141
146
|
const settings = ['customArgs', 'asmGroupId', 'subscriptionTracking'];
|
|
142
147
|
if (provider && !['sendgrid', 'development'].includes(provider) && settings.some(key => message[key] !== undefined)) fail('unsupported_provider_setting');
|
|
@@ -13,6 +13,7 @@ export interface DevelopmentMessage {
|
|
|
13
13
|
customArgs?: Record<string, string>;
|
|
14
14
|
asmGroupId?: number;
|
|
15
15
|
subscriptionTracking?: boolean;
|
|
16
|
+
messageKey?: string;
|
|
16
17
|
}
|
|
17
18
|
export interface DevelopmentCapture { id: string; createdAt: number; message: DevelopmentMessage }
|
|
18
19
|
export type DevelopmentOutboxListMessage = Omit<DevelopmentMessage, 'attachments'>;
|
|
@@ -519,6 +519,17 @@ request URLs. `RER_DEV_IDENTITY=off` disables dev sign-in and personas. The
|
|
|
519
519
|
layer answers 503 to every request when `RER_INSTALLATION_ID` is set beside a
|
|
520
520
|
non-loopback `RER_MANAGEMENT_ORIGIN`.
|
|
521
521
|
|
|
522
|
+
In dev and isolated hosted demos, `/signin` lists **Sign in as <name>** for
|
|
523
|
+
active people and people with a live invitation. The default operator screen
|
|
524
|
+
gets `signInUrl` on those `/auth/operators` records and offers the same action.
|
|
525
|
+
`GET /auth/one-click?as=EMAIL&returnTo=/app` accepts the invitation with the
|
|
526
|
+
existing atomic issuer, expiry, version and cancellation checks. Local sessions
|
|
527
|
+
are always `dev` and require the checkout key on every request; hosted demo
|
|
528
|
+
sessions belong only to that visitor's database. Production answers 404. The
|
|
529
|
+
local persona list also includes invited/active people by email. Suppressed
|
|
530
|
+
email-link form requests direct the admitted visitor to this same one-click
|
|
531
|
+
entry rather than telling them to wait for mail.
|
|
532
|
+
|
|
522
533
|
`dev/sign-in-as.mjs` is the test harness door: `signInAs({origin, key, as})`
|
|
523
534
|
returns the cookies a test browser or fetch client installs, and
|
|
524
535
|
`readDevKey(root)` reads the checkout's key.
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
import { demoEffectsEnabled } from '../../demo/effects.mjs';
|
|
2
|
+
import { devAdmitted } from '../dev-admission.mjs';
|
|
3
|
+
import { deny } from '../errors.mjs';
|
|
4
|
+
import { requireOrigin } from '../http.mjs';
|
|
5
|
+
import { safeReturnTo } from '../policy.mjs';
|
|
6
|
+
import { emailAllowed } from './roles.mjs';
|
|
7
|
+
import { operatorColumns } from './store.mjs';
|
|
8
|
+
|
|
9
|
+
export const oneClickHref = (email, returnTo = '/app') => `/auth/one-click?as=${encodeURIComponent(email)}&returnTo=${encodeURIComponent(safeReturnTo(returnTo))}`;
|
|
10
|
+
|
|
11
|
+
// Local entry needs the checkout's key on every request. Hosted demos live in
|
|
12
|
+
// the visitor's isolated database; only the installed demo effect guard enables
|
|
13
|
+
// this door. Ordinary production cannot enable it with a request header.
|
|
14
|
+
export function oneClickAccounts({ config, store, clock, sessions, authorizedLink, requireRoute, afterConfirm }) {
|
|
15
|
+
async function mode(request) {
|
|
16
|
+
if (config.local) return await devAdmitted(request) ? 'dev' : null;
|
|
17
|
+
return demoEffectsEnabled() ? 'native' : null;
|
|
18
|
+
}
|
|
19
|
+
async function invitation(request, operator) {
|
|
20
|
+
const token = await store.first(`SELECT token_hash AS digest FROM oa_tokens
|
|
21
|
+
WHERE operator_id=? AND kind='invite' AND consumed_at IS NULL AND revoked_at IS NULL
|
|
22
|
+
AND expires_at>? AND operator_version=? ORDER BY created_at DESC LIMIT 1`, [operator.id, clock(), operator.version]);
|
|
23
|
+
const approval = token && await authorizedLink(request, token.digest);
|
|
24
|
+
return approval ? { digest: token.digest, approval } : null;
|
|
25
|
+
}
|
|
26
|
+
async function eligible(request, operator) {
|
|
27
|
+
if (!operator || !emailAllowed(operator.email, config.allowList)) return false;
|
|
28
|
+
if (operator.status === 'invited') return !!await invitation(request, operator);
|
|
29
|
+
return operator.status === 'active';
|
|
30
|
+
}
|
|
31
|
+
return {
|
|
32
|
+
async people(request) {
|
|
33
|
+
if (!await mode(request)) return null;
|
|
34
|
+
requireOrigin(request, config);
|
|
35
|
+
const rows = (await store.statement(`SELECT ${operatorColumns} FROM oa_operators WHERE status IN ('active','invited') ORDER BY created_at,id`).all()).results;
|
|
36
|
+
const people = await Promise.all(rows.map(async operator => {
|
|
37
|
+
if (!await eligible(request, operator)) return null;
|
|
38
|
+
return { email: operator.email, displayName: operator.displayName, role: operator.role, href: oneClickHref(operator.email) };
|
|
39
|
+
}));
|
|
40
|
+
return people.filter(Boolean);
|
|
41
|
+
},
|
|
42
|
+
async enter(request, { as, returnTo }) {
|
|
43
|
+
const kind = await mode(request);
|
|
44
|
+
if (!kind) deny('not_found', 404);
|
|
45
|
+
requireOrigin(request, config);
|
|
46
|
+
if (request.method !== 'GET') deny('method_not_allowed', 405);
|
|
47
|
+
const operator = typeof as === 'string' ? await store.byEmail(as) : null;
|
|
48
|
+
if (!await eligible(request, operator)) deny('not_found', 404);
|
|
49
|
+
await requireRoute(operator);
|
|
50
|
+
const session = await sessions.newSession(kind);
|
|
51
|
+
let record;
|
|
52
|
+
if (operator.status === 'invited') {
|
|
53
|
+
const link = await invitation(request, operator);
|
|
54
|
+
if (!link) deny('invalid_or_expired', 400);
|
|
55
|
+
record = await store.consume(link.digest, clock(), session, config.allowList, link.approval.issuer, kind);
|
|
56
|
+
} else {
|
|
57
|
+
record = await store.issue({ operatorId: operator.id, expectedVersion: operator.version, session, now: clock(), kind });
|
|
58
|
+
}
|
|
59
|
+
const completed = sessions.completed(session, record, returnTo ?? record?.returnTo);
|
|
60
|
+
return afterConfirm(request, completed, 'email');
|
|
61
|
+
},
|
|
62
|
+
};
|
|
63
|
+
}
|
|
@@ -88,7 +88,7 @@ export class AuthStore {
|
|
|
88
88
|
WHERE t.token_hash=? AND t.consumed_at IS NULL AND t.revoked_at IS NULL AND t.expires_at>? AND t.operator_version=o.version
|
|
89
89
|
AND (o.status='active' OR (o.status='invited' AND t.kind='invite'))`, [hash, now]);
|
|
90
90
|
}
|
|
91
|
-
async consume(hash, now, session, allowedEmails, issuer) {
|
|
91
|
+
async consume(hash, now, session, allowedEmails, issuer, kind = null) {
|
|
92
92
|
const allow = allowedEmails === undefined ? { sql: '1', args: [] } : { sql: `o.email IN (${allowedEmails.map(() => '?').join(',') || 'NULL'})`, args: allowedEmails };
|
|
93
93
|
// JS evaluated the configured policy on this issuer snapshot. Bind that
|
|
94
94
|
// approval to the invitation and repeat its authority check in the session
|
|
@@ -99,12 +99,12 @@ export class AuthStore {
|
|
|
99
99
|
await this.batch([
|
|
100
100
|
[`INSERT INTO oa_sessions(id,token_hash,operator_id,operator_version,kind,source_token_id,created_at,expires_at)
|
|
101
101
|
SELECT ?,?,o.id,o.version+CASE WHEN o.status='invited' THEN 1 ELSE 0 END,
|
|
102
|
-
CASE WHEN EXISTS(SELECT 1 FROM oa_dev_credentials d WHERE d.credential='oa_tokens' AND d.id=t.id) THEN 'dev' ELSE 'native' END,t.id,?,?
|
|
102
|
+
CASE WHEN ?='dev' OR EXISTS(SELECT 1 FROM oa_dev_credentials d WHERE d.credential='oa_tokens' AND d.id=t.id) THEN 'dev' ELSE 'native' END,t.id,?,?
|
|
103
103
|
FROM oa_tokens t JOIN oa_operators o ON o.id=t.operator_id
|
|
104
104
|
WHERE t.token_hash=? AND t.consumed_at IS NULL AND t.revoked_at IS NULL AND t.expires_at>? AND t.operator_version=o.version
|
|
105
105
|
AND (o.status='active' OR (o.status='invited' AND t.kind='invite')) AND ${allow.sql}
|
|
106
106
|
AND (t.kind='magic' OR (${authority.sql}))`,
|
|
107
|
-
[session.id, session.hash, now, session.expiresAt, hash, now, ...allow.args, ...authority.args]],
|
|
107
|
+
[session.id, session.hash, kind, now, session.expiresAt, hash, now, ...allow.args, ...authority.args]],
|
|
108
108
|
// Only the session just admitted by the full token/issuer/allow-list
|
|
109
109
|
// predicate witnesses acceptance. Removing its cancellation guard and
|
|
110
110
|
// activating the operator are atomic with that admission; failures roll
|
|
@@ -7,7 +7,7 @@ import { AuthStore } from '../accounts/store.mjs';
|
|
|
7
7
|
import { createOperatorAuth } from '../service.mjs';
|
|
8
8
|
import { AuthError } from '../errors.mjs';
|
|
9
9
|
import { hashToken, opaqueToken } from '../crypto.mjs';
|
|
10
|
-
import { readCookie, sessionCookie, isLoopbackHost
|
|
10
|
+
import { readCookie, sessionCookie, isLoopbackHost } from '../http.mjs';
|
|
11
11
|
import { safeReturnTo } from '../policy.mjs';
|
|
12
12
|
import { isActiveOperator, defaultRolePolicy } from '../accounts/roles.mjs';
|
|
13
13
|
import { devGate, devNotFound } from '../dev-gate.mjs';
|
|
@@ -15,7 +15,7 @@ import { registerDevAdmission } from '../dev-admission.mjs';
|
|
|
15
15
|
import { definePersonas } from './personas.mjs';
|
|
16
16
|
import { cliSession } from './cli-session.mjs';
|
|
17
17
|
import { decorateLabel } from '../../demo/label.mjs';
|
|
18
|
-
import {
|
|
18
|
+
import { oneClickPage } from '../signin/one-click.mjs';
|
|
19
19
|
|
|
20
20
|
export const DEV_LAYER_MARKER = 'rer-dev-layer:local-only-never-deploy';
|
|
21
21
|
const headers = { 'cache-control': 'no-store', 'referrer-policy': 'no-referrer', 'x-content-type-options': 'nosniff', 'x-robots-tag': 'noindex, nofollow', 'x-rer-dev-layer': DEV_LAYER_MARKER };
|
|
@@ -47,21 +47,24 @@ export function withDevIdentity(worker, { bindings = env => env, config: authCon
|
|
|
47
47
|
return new URL(request.url).pathname === '/auth/dev/enter' || new URL(request.url).pathname === '/__dev/personas' || new URL(request.url).pathname === '/auth/local/cli-session' ? rejectedResponse(request, devNotFound()) : worker.fetch(request, original, execution);
|
|
48
48
|
}
|
|
49
49
|
const gate = devGate({ key: env.RER_DEV_KEY, origin: env.AUTH_ORIGIN, local: env.AUTH_LOCAL === 'true' });
|
|
50
|
-
registerDevAdmission(gate ? r => gate.admits(r) : null);
|
|
50
|
+
registerDevAdmission(gate && env.RER_DEV_IDENTITY !== 'off' ? r => gate.admits(r) : null);
|
|
51
51
|
const path = new URL(request.url).pathname;
|
|
52
52
|
if (path === '/__dev/key') return gate ? gate.exchange(request) : devNotFound();
|
|
53
|
-
if (path === '/signin' && gate && env.RER_DEV_IDENTITY !== 'off' && request.method
|
|
53
|
+
if (path === '/signin' && gate && env.RER_DEV_IDENTITY !== 'off' && ['GET', 'HEAD'].includes(request.method)) {
|
|
54
54
|
if (!await gate.admits(request)) return new Response(null, { status: 303, headers: { ...headers, location: '/__dev/key' } });
|
|
55
|
-
const
|
|
55
|
+
const context = identity(env, authConfig, declared);
|
|
56
56
|
const returnTo = safeReturnTo(new URL(request.url).searchParams.get('returnTo'));
|
|
57
|
-
const
|
|
58
|
-
|
|
57
|
+
const people = await Promise.all((await context.list(request)).filter(person => person.email).map(async person => ({
|
|
58
|
+
...person, displayName: (await context.store.byEmail(person.email))?.displayName ?? declared.find(p => p.as === person.as)?.displayName ?? person.email,
|
|
59
|
+
href: `/auth/dev/enter?as=${encodeURIComponent(person.as)}&returnTo=${encodeURIComponent(returnTo)}`,
|
|
60
|
+
})));
|
|
61
|
+
return decorateLabel(await oneClickPage({ branding: context.config.branding, people, method: request.method }), env.RER_DEMO === '1' ? 'Demo' : 'Dev');
|
|
59
62
|
}
|
|
60
63
|
if (path === '/auth/dev/enter' || path === '/__dev/personas' || path === '/auth/local/cli-session') {
|
|
61
64
|
if (!gate || env.RER_DEV_IDENTITY === 'off' || (path !== '/auth/local/cli-session' && !await gate.admits(request))) return rejectedResponse(request, devNotFound());
|
|
62
65
|
const context = identity(env, authConfig, declared);
|
|
63
66
|
try {
|
|
64
|
-
const response = path === '/auth/local/cli-session' ? await cliSession(request, context, headers) : path === '/__dev/personas' ? Response.json(await context.list(), { headers }) : await enter(request, gate, context);
|
|
67
|
+
const response = path === '/auth/local/cli-session' ? await cliSession(request, context, headers) : path === '/__dev/personas' ? Response.json(await context.list(request), { headers }) : await enter(request, gate, context);
|
|
65
68
|
return rejectedResponse(request, response);
|
|
66
69
|
} catch (error) {
|
|
67
70
|
if (error instanceof AuthError) return rejectedResponse(request, Response.json({ error: error.code }, { status: error.status, headers }));
|
|
@@ -78,6 +81,7 @@ export function withDevIdentity(worker, { bindings = env => env, config: authCon
|
|
|
78
81
|
function identity(env, authConfig, declared) {
|
|
79
82
|
const config = configure(authConfig(env)), store = new AuthStore(env.DB);
|
|
80
83
|
const hash = token => hashToken(config.SESSION_SECRET, 'session', token);
|
|
84
|
+
const auth = createOperatorAuth({ db: env.DB, config: authConfig(env), clientIp: () => null });
|
|
81
85
|
// The `owner` persona is the owner rer setup claimed while that owner is
|
|
82
86
|
// active; after that owner has left, the earliest-created active owner; with
|
|
83
87
|
// no active owner left, nobody (email null), so rer names who it signs in as.
|
|
@@ -95,20 +99,24 @@ function identity(env, authConfig, declared) {
|
|
|
95
99
|
return session && isActiveOperator(session.operator, config.allowList) ? session : null;
|
|
96
100
|
}
|
|
97
101
|
return {
|
|
98
|
-
config, store, hash, current, everyone,
|
|
102
|
+
config, store, hash, current, everyone, auth,
|
|
99
103
|
async ownerProof(request) {
|
|
100
104
|
// Reuse the same persisted app-local proof guard as the administration
|
|
101
105
|
// routes. This read-only guard never needs a mail sender or an IP budget.
|
|
102
|
-
const auth = createOperatorAuth({ db: env.DB, config: authConfig(env), clientIp: () => null });
|
|
103
106
|
const actor = await auth.requireStepUp(request, 'owner:transfer');
|
|
104
107
|
if (!defaultRolePolicy({ actor: actor.operator, action: 'operators:invite', role: 'owner' })) throw new AuthError('forbidden', 403);
|
|
105
108
|
return { ...actor, hash: await hash(readCookie(request, config)) };
|
|
106
109
|
},
|
|
107
|
-
|
|
110
|
+
async list(request) {
|
|
111
|
+
const personas = (await everyone()).map(({ as, email, role }) => ({ as, email, ...(role ? { role } : {}) }));
|
|
112
|
+
const people = await auth.oneClick.people(request);
|
|
113
|
+
return [...personas, ...(people ?? []).filter(person => !personas.some(p => p.email === person.email))
|
|
114
|
+
.map(person => ({ as: person.email, email: person.email, role: person.role })), { as: 'signed-out' }];
|
|
115
|
+
},
|
|
108
116
|
};
|
|
109
117
|
}
|
|
110
118
|
|
|
111
|
-
async function enter(request, gate, { config, store, hash, current, everyone, ownerProof }) {
|
|
119
|
+
async function enter(request, gate, { config, store, hash, current, everyone, ownerProof, auth }) {
|
|
112
120
|
if (request.method !== 'GET') return text(405, 'Method not allowed');
|
|
113
121
|
const url = new URL(request.url), as = url.searchParams.get('as') ?? 'owner';
|
|
114
122
|
const reply = new Headers(headers);
|
|
@@ -123,7 +131,12 @@ async function enter(request, gate, { config, store, hash, current, everyone, ow
|
|
|
123
131
|
return new Response(null, { status: 303, headers: reply });
|
|
124
132
|
}
|
|
125
133
|
const persona = (await everyone()).find(p => p.as === as);
|
|
126
|
-
if (!persona)
|
|
134
|
+
if (!persona) {
|
|
135
|
+
const value = await auth.oneClick.enter(request, { as, returnTo: url.searchParams.get('returnTo') ?? '/app' });
|
|
136
|
+
reply.append('set-cookie', value.cookie);
|
|
137
|
+
reply.set('location', value.returnTo);
|
|
138
|
+
return new Response(null, { status: 303, headers: reply });
|
|
139
|
+
}
|
|
127
140
|
if (!persona.email) return text(409, 'No active owner remains in this app. Sign in another way, or run rer reset --yes and rer setup for a new owner.');
|
|
128
141
|
let operator = await store.byEmail(persona.email);
|
|
129
142
|
// Personas are real operators, created only here, in local dev.
|
|
@@ -142,6 +142,11 @@ export interface IdentityProviders {
|
|
|
142
142
|
}
|
|
143
143
|
export interface DomainRule { domain: string; providerId: string; createdAt: number }
|
|
144
144
|
export interface OperatorAuth<R extends string = Role> {
|
|
145
|
+
/** Key-gated local development or an isolated hosted demo; unavailable in production. */
|
|
146
|
+
readonly oneClick?: {
|
|
147
|
+
people(request: Request): Promise<Array<{ email: string; displayName: string; role: R; href: string }> | null>;
|
|
148
|
+
enter(request: Request, input: { as?: string; returnTo?: string }): Promise<CompletedSession<R>>;
|
|
149
|
+
};
|
|
145
150
|
mintCredential(request:Request,input?:{expiresInSeconds?:number}):Promise<{id:string;token:string;expiresAt:number}>;
|
|
146
151
|
authenticateCredential(request:Request):Promise<{id:string;personId:string;fence:number;kind:SessionKind}|null>;
|
|
147
152
|
authorizeDependencySetup(request: Request, input: { token?: string }): Promise<boolean>;
|
|
@@ -30,6 +30,10 @@ export function createAuthHandler(auth) {
|
|
|
30
30
|
const providerResponse = await oidc?.(request);
|
|
31
31
|
if (providerResponse) return providerResponse;
|
|
32
32
|
if (!path.startsWith('/auth/')) return null;
|
|
33
|
+
if (path === '/auth/one-click' && auth.oneClick) {
|
|
34
|
+
const value = await auth.oneClick.enter(request, readParameters(url.searchParams));
|
|
35
|
+
return seeOther(value.returnTo, value.cookie);
|
|
36
|
+
}
|
|
33
37
|
if (path.startsWith('/auth/oidc/')) return json({ error: 'not_found' }, 404);
|
|
34
38
|
if (path === '/auth/review-session') requireLoopback(request);
|
|
35
39
|
if (path === '/auth/confirm' && ['GET', 'HEAD'].includes(request.method)) {
|
|
@@ -48,7 +52,14 @@ export function createAuthHandler(auth) {
|
|
|
48
52
|
const session = await auth.getSession(request);
|
|
49
53
|
return session ? json(session) : json({ error: 'unauthenticated' }, 401);
|
|
50
54
|
}
|
|
51
|
-
if (path === '/auth/operators' && request.method === 'GET')
|
|
55
|
+
if (path === '/auth/operators' && request.method === 'GET') {
|
|
56
|
+
const operators = await auth.listOperators(request);
|
|
57
|
+
const people = await auth.oneClick?.people(request);
|
|
58
|
+
return json(operators.map(operator => {
|
|
59
|
+
const person = people?.find(person => person.email === operator.email);
|
|
60
|
+
return person ? { ...operator, signInUrl: person.href } : operator;
|
|
61
|
+
}));
|
|
62
|
+
}
|
|
52
63
|
if (path === '/auth/sessions' && request.method === 'GET') return json(await auth.listSessions(request, readParameters(url.searchParams).operatorId));
|
|
53
64
|
if (path === '/auth/domain-rules' && request.method === 'GET') return json(await auth.listDomainRules(request));
|
|
54
65
|
if (path === '/auth/settings/identity' && request.method === 'GET') {const value=await auth.identitySettings(request);return /text\/html/.test(request.headers.get('accept')??'')?await identitySettingsPage(value,auth.presentation):json(value);}
|
|
@@ -69,6 +80,14 @@ export function createAuthHandler(auth) {
|
|
|
69
80
|
case '/auth/bootstrap': { const value = await auth.bootstrap(request, input); return seeOther(value.returnTo, value.cookie); }
|
|
70
81
|
case '/auth/magic-link': {
|
|
71
82
|
const result = await auth.requestMagicLink(request, input);
|
|
83
|
+
const people = await auth.oneClick?.people(request);
|
|
84
|
+
if (people) {
|
|
85
|
+
const person = people.find(person => person.email === String(input.email).trim().toLowerCase());
|
|
86
|
+
const signInUrl = person ? new URL(person.href, url.origin) : null;
|
|
87
|
+
if (signInUrl) signInUrl.searchParams.set('returnTo', safeReturnTo(input.returnTo));
|
|
88
|
+
return form ? seeOther(signInUrl ? signInUrl.pathname + signInUrl.search : auth.presentation.signInPath)
|
|
89
|
+
: json({ ...result, ...(signInUrl ? { signInUrl: signInUrl.pathname + signInUrl.search } : {}) }, 202);
|
|
90
|
+
}
|
|
72
91
|
return form ? seeOther(notice(auth, 'sent', { returnTo: safeReturnTo(input.returnTo) === '/app' ? undefined : safeReturnTo(input.returnTo), provider: result.requiredProvider })) : json(result, 202);
|
|
73
92
|
}
|
|
74
93
|
case '/auth/confirm': { const value = await auth.confirmLink(request, input); return seeOther(value.returnTo, value.cookie); }
|
|
@@ -20,6 +20,7 @@ import { ownerSignIn } from './accounts/owner-signin.mjs';
|
|
|
20
20
|
import { emailChange } from './accounts/email-change.mjs';
|
|
21
21
|
import { isLocalCli } from './local-cli.mjs';
|
|
22
22
|
import { devAdmitted } from './dev-admission.mjs';
|
|
23
|
+
import { oneClickAccounts } from './accounts/one-click.mjs';
|
|
23
24
|
|
|
24
25
|
export { STEP_UP_ACTIONS, STEP_UP_SECONDS } from './identity/email-link/index.mjs';
|
|
25
26
|
export function createOperatorAuth(options) {
|
|
@@ -79,6 +80,7 @@ export function createOperatorAuth(options) {
|
|
|
79
80
|
...ownerSignIn({ config, store, clock, sessions, limit }),
|
|
80
81
|
...emailChange({ config, store, clock, authenticate, requireFreshProof }),
|
|
81
82
|
presentation: config.branding,
|
|
83
|
+
oneClick: oneClickAccounts({ config, store, clock, sessions, authorizedLink, requireRoute, afterConfirm: admission.afterConfirm }),
|
|
82
84
|
emailSignInAvailable: Boolean(mailSender),
|
|
83
85
|
/** Identity providers (null when none is configured): routes, the sign-in page's list and owner actions. */
|
|
84
86
|
providers,
|
|
@@ -5,6 +5,7 @@
|
|
|
5
5
|
import { escapeHtml } from '../http.mjs';
|
|
6
6
|
import { normalizeEmail, safeReturnTo } from '../policy.mjs';
|
|
7
7
|
import { pageResponse } from '../page.mjs';
|
|
8
|
+
import { oneClickPage } from './one-click.mjs';
|
|
8
9
|
|
|
9
10
|
const NOTICES = {
|
|
10
11
|
sent: ['status', 'If this address can sign in here, a sign-in link is on its way. Open it on this device and press Confirm.'],
|
|
@@ -50,6 +51,12 @@ export function createSignInHandler(auth, { setup, links, defaultReturnTo = '/ap
|
|
|
50
51
|
const branding = auth.presentation;
|
|
51
52
|
const returnTo = safeReturnTo(url.searchParams.get('returnTo'), defaultReturnTo);
|
|
52
53
|
const hint = emailHint(url.searchParams.get('login_hint'));
|
|
54
|
+
const people = await auth.oneClick?.people(request);
|
|
55
|
+
if (people?.length) return oneClickPage({ branding, method: request.method, people: people.map(person => {
|
|
56
|
+
const href = new URL(person.href, url.origin);
|
|
57
|
+
href.searchParams.set('returnTo', returnTo);
|
|
58
|
+
return { ...person, href: href.pathname + href.search };
|
|
59
|
+
}) });
|
|
53
60
|
const providers = auth.providers ? (await auth.providers.list()).filter(p => p.visible) : [];
|
|
54
61
|
const parts = [];
|
|
55
62
|
const emailAvailable = auth.emailSignInAvailable;
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import { escapeHtml } from '../http.mjs';
|
|
2
|
+
import { pageResponse } from '../page.mjs';
|
|
3
|
+
|
|
4
|
+
export function oneClickPage({ branding, people, method = 'GET' }) {
|
|
5
|
+
const content = `<div class="stack">${people.map(person => `<a class="action" href="${escapeHtml(person.href)}">Sign in as ${escapeHtml(person.displayName || person.email)}</a>`).join('')}</div>`;
|
|
6
|
+
return pageResponse({ branding, heading: `Sign in to ${escapeHtml(branding.productName)}`, content, method });
|
|
7
|
+
}
|
|
@@ -1,10 +1,10 @@
|
|
|
1
1
|
import { all, insist, quote } from './storage.mjs';
|
|
2
2
|
import { canonicalJson, sha256, base64, unbase64, utf8 } from './hash.mjs';
|
|
3
3
|
/** Tables no archive carries: SQLite/Cloudflare internals, migration ledgers,
|
|
4
|
-
* portability bookkeeping, development outboxes, operator identity
|
|
5
|
-
* secrets. Exact names, or prefixes ending in `%`. Seeds' own table inventories
|
|
4
|
+
* portability bookkeeping, development outboxes, operator identity, dependency
|
|
5
|
+
* secrets and refresh-safe command receipts. Exact names, or prefixes ending in `%`. Seeds' own table inventories
|
|
6
6
|
* skip the same tables through `excludedTable`. */
|
|
7
|
-
export const excludedTables=Object.freeze(['sqlite_%','_cf_%','d1_migrations','_rer_deploy_migrations','_rer_portability_migrations','rer_portability_%','rer_mail_development_outbox','rer_ai_development_outbox','oa_%','oc_%','rer_dependency_keys','rer_dependency_pending','rer_dependency_codes']);
|
|
7
|
+
export const excludedTables=Object.freeze(['sqlite_%','_cf_%','d1_migrations','_rer_deploy_migrations','_rer_portability_migrations','rer_portability_%','rer_mail_development_outbox','rer_ai_development_outbox','oa_%','oc_%','rer_dependency_keys','rer_dependency_pending','rer_dependency_codes','rer_command_receipts']);
|
|
8
8
|
const fields=['product','excludeTables','includeTables','derivedTables','secretColumns','exportRow','replaceableTables','requiredConfiguration','validateStaged','acceptedSchemas','buckets','extraPayloads','partBytes'];
|
|
9
9
|
const name=value=>typeof value==='string' && value.length>0 && value.length<=512 && !/[\x00-\x1f]/.test(value);
|
|
10
10
|
const names=value=>Array.isArray(value) && value.every(name) && new Set(value).size===value.length;
|