@runeditrun/rer 0.2.18 → 0.2.20
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/README.md +7 -7
- package/cli/README.md +22 -21
- package/cli/adapter.mjs +5 -0
- package/cli/container.mjs +7 -2
- package/cli/contract.mjs +6 -4
- package/cli/delivery-declarations.mjs +36 -0
- package/cli/demo-host.mjs +2 -2
- package/cli/demo.mjs +16 -5
- package/cli/deploy-command.mjs +4 -1
- package/cli/deploy.mjs +4 -1
- package/cli/detached-server.mjs +2 -2
- package/cli/dev-identity.mjs +1 -1
- package/cli/export.mjs +1 -1
- package/cli/inspect.mjs +17 -15
- package/cli/lifecycle.mjs +16 -49
- package/cli/listen.mjs +31 -0
- package/cli/local.mjs +12 -18
- package/cli/main.mjs +7 -0
- package/cli/managed-server.mjs +26 -44
- package/cli/output.mjs +1 -1
- package/cli/parse.mjs +8 -7
- package/cli/port.mjs +20 -20
- package/cli/production-auth.mjs +38 -0
- package/cli/server-proxy.mjs +2 -6
- package/cli/server-registry.mjs +7 -2
- package/cli/setup-input.mjs +3 -0
- package/cli/signin.mjs +41 -0
- package/global/CHANGELOG.md +18 -0
- package/global/README.md +7 -7
- package/global/cli/install.mjs +4 -28
- package/global/cli/path-link.mjs +25 -21
- package/global/launch/dev.mjs +1 -1
- package/global/launch/facts.mjs +11 -14
- package/global/launch/failure.mjs +20 -0
- package/global/launch/render.mjs +2 -6
- package/global/launch/worker.mjs +3 -3
- package/global/main.mjs +3 -3
- package/modules/container/build.mjs +2 -2
- package/modules/container/demo-egress.mjs +35 -0
- package/modules/container/worker-engine.mjs +3 -3
- package/modules/d1-transport/index.d.mts +9 -0
- package/modules/d1-transport/index.mjs +124 -0
- package/modules/delivery-producer/bindings.mjs +140 -0
- package/modules/delivery-producer/declarations.mjs +49 -0
- package/modules/demo/README.md +34 -0
- package/modules/demo/effects.mjs +73 -0
- package/modules/demo/index.d.mts +15 -0
- package/modules/demo/index.mjs +63 -0
- package/modules/demo/label.d.mts +2 -0
- package/modules/demo/label.mjs +24 -0
- package/modules/demo/responses.mjs +26 -0
- package/modules/demo/sockets.mjs +13 -0
- package/modules/demo/vite.d.mts +2 -0
- package/modules/demo/vite.mjs +19 -0
- package/modules/demo-host/README.md +5 -1
- package/modules/demo-host/container.mjs +4 -4
- package/modules/demo-host/pages.mjs +1 -1
- package/modules/demo-host/worker.mjs +1 -1
- 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/deploy-kit/owner.mjs +2 -2
- package/modules/deploy-kit/r2-objects.mjs +8 -5
- package/modules/job-queue/storage.mjs +4 -1
- package/modules/mail/README.md +62 -87
- 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 -3
- package/modules/mail/src/development/index.d.mts +1 -6
- package/modules/mail/src/development/index.mjs +3 -16
- package/modules/mail/src/sender.mjs +2 -1
- package/modules/operator-auth/README.md +53 -9
- 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/csp.mjs +1 -2
- package/modules/operator-auth/dev/cli-session.mjs +32 -0
- package/modules/operator-auth/dev/index.mjs +18 -11
- package/modules/operator-auth/identity/email-link/confirmation.mjs +3 -3
- package/modules/operator-auth/identity/email-link/index.mjs +4 -1
- package/modules/operator-auth/index.d.mts +8 -2
- package/modules/operator-auth/owner-signin-grant.mjs +10 -0
- package/modules/operator-auth/page.mjs +1 -1
- package/modules/operator-auth/routes.mjs +11 -1
- package/modules/operator-auth/service.mjs +4 -0
- package/modules/operator-auth/signin/index.d.mts +1 -1
- package/modules/portability/README.md +6 -0
- package/modules/portability/catalogue.mjs +1 -1
- package/modules/portability/copies.mjs +17 -2
- package/modules/portability/index.mjs +2 -0
- package/modules/portability/provider-data.mjs +1 -1
- package/modules/portability/storage.mjs +5 -1
- package/onboarding/README.md +8 -11
- package/onboarding/adapter-auth.mjs +6 -38
- package/onboarding/adapter-labels.mjs +1 -1
- package/onboarding/adapter.mjs +8 -11
- package/onboarding/app-fetch.mjs +1 -1
- package/onboarding/dependency-approval.mjs +5 -15
- package/onboarding/dev-identity.mjs +1 -1
- package/onboarding/operator-install.mjs +6 -7
- package/onboarding/operator-installer.mjs +5 -5
- package/onboarding/operator-prerequisites.mjs +4 -5
- package/onboarding/port-probe.mjs +38 -0
- package/onboarding/process-diagnostics.mjs +36 -20
- package/onboarding/server.mjs +1 -1
- package/onboarding/ui/app.js +1 -1
- package/operations/README.md +3 -0
- package/package.json +4 -2
- package/scripts/publish-check/public_hygiene.py +31 -10
- package/modules/mail/src/development/viewer-html.mjs +0 -42
- package/modules/mail/src/development/viewer.mjs +0 -72
- package/modules/operator-auth/dev/badge.mjs +0 -44
|
@@ -6,9 +6,9 @@ import { finishStart } from './startup.mjs';
|
|
|
6
6
|
|
|
7
7
|
// One visitor's demo: a Durable Object (newUniqueId) and its container, the
|
|
8
8
|
// seed's image from `rer build --platform container` on the workerd engine.
|
|
9
|
-
// The container starts with
|
|
10
|
-
// engine
|
|
11
|
-
// through the existing signed owner claim. The demo ends at its hour or after
|
|
9
|
+
// The container starts with public internet in demo mode. withDemo simulates
|
|
10
|
+
// external effects; the engine also refuses direct mail/SMS transports. The
|
|
11
|
+
// front signs the owner in through the existing signed owner claim. The demo ends at its hour or after
|
|
12
12
|
// 15 idle minutes: the alarm destroys the container and deletes everything.
|
|
13
13
|
// The platform stops a container about two minutes after its Durable Object's
|
|
14
14
|
// last event, when the object is evicted, and the exit watcher goes with it.
|
|
@@ -76,7 +76,7 @@ export class DemoContainer extends DurableObject {
|
|
|
76
76
|
await this.ctx.storage.put({ ends, seen: now, correlation, started: this.started, startDeadline: deadline });
|
|
77
77
|
report(correlation, this.started, 'start');
|
|
78
78
|
if (this.stopped) throw new Error('container-stopped');
|
|
79
|
-
this.container.start({ enableInternet:
|
|
79
|
+
this.container.start({ enableInternet: true, env: { ...settings, RER_DEMO: '1', [originVar]: origin, RER_INGRESS_ORIGIN: origin,
|
|
80
80
|
SESSION_SECRET: random(), SETUP_TOKEN: random(), OWNER_EMAIL: OWNER, RER_OWNER_CLAIM_ISSUER: origin, RER_OWNER_CLAIM_INSTALLATION_ID: id,
|
|
81
81
|
RER_OWNER_CLAIM_PUBLIC_KEYS: JSON.stringify(keys.publicKeys), RER_DEMO_EXPIRES: endsLocal } });
|
|
82
82
|
// A container that stops by itself ends the demo too.
|
|
@@ -37,7 +37,7 @@ export function startPage(env, { status = 200, notice, pending = false, headers
|
|
|
37
37
|
const name = escape(env.DEMO_NAME);
|
|
38
38
|
return html(env, { page: 'start', title: `Try ${env.DEMO_NAME}`, status, headers, turnstile: true, refresh: pending, body: `<h1 id="title">Try ${name}</h1>
|
|
39
39
|
<p class="intro">Your own copy of ${name}, signed in as its owner, with sample data.</p>
|
|
40
|
-
<ul><li>
|
|
40
|
+
<ul><li>Public checks run live. Messages and account changes are simulated.</li><li>It ends after an hour, or 15 idle minutes.</li><li>Then it is deleted. Nobody else can see it.</li></ul>
|
|
41
41
|
<p class="notice" id="notice" role="alert"${notice ? '' : ' hidden'}>${notice ? escape(notice) : ''}</p><form id="start" method="post" action="/__demo/start" data-auto="${notice || pending ? '0' : '1'}"${pending ? ' data-resume="1" data-state="working"' : ''}><div class="cf-turnstile" data-sitekey="${escape(env.TURNSTILE_SITE_KEY)}" data-size="flexible" data-callback="rerDemoVerified" data-before-interactive-callback="rerDemoInteractive" data-after-interactive-callback="rerDemoChecking" data-expired-callback="rerDemoExpired" data-error-callback="rerDemoCheckFailed"></div>
|
|
42
42
|
<button class="button" type="submit"${pending ? ' disabled' : ''}><span class="spinner" aria-hidden="true"></span><span class="label">${pending ? 'Starting your demo…' : 'Start the demo'}</span></button>
|
|
43
43
|
<ol class="steps" aria-hidden="true"><li data-at="done">Checking you're human</li><li data-at="now">Starting a private copy</li><li data-at="next">Signing you in</li></ol>
|
|
@@ -22,7 +22,7 @@ function demoId(request, env) {
|
|
|
22
22
|
try { return env.DEMO.idFromString(value); } catch { return null; }
|
|
23
23
|
}
|
|
24
24
|
|
|
25
|
-
// The demo's end in the visitor's time zone,
|
|
25
|
+
// The demo's end in the visitor's time zone, retained in runtime settings.
|
|
26
26
|
function localTime(time, timeZone = 'UTC') {
|
|
27
27
|
const parts = Object.fromEntries(new Intl.DateTimeFormat('en-US', { timeZone, hourCycle: 'h23', year: 'numeric', month: '2-digit', day: '2-digit',
|
|
28
28
|
hour: '2-digit', minute: '2-digit', second: '2-digit', timeZoneName: 'longOffset' }).formatToParts(time).map(part => [part.type, part.value]));
|
|
@@ -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
|
+
}
|
|
@@ -101,8 +101,8 @@ function entries(declaration, key) {
|
|
|
101
101
|
assert(Array.isArray(list) && list.every(item => item && typeof item === 'object' && !Array.isArray(item) && Object.keys(item).every(k => ENTRY_KEYS[key].includes(k))), 'invalid-owner-declaration');
|
|
102
102
|
return list;
|
|
103
103
|
}
|
|
104
|
-
/* RER_DEV_KEY opens local dev identity and RER_DEMO turns on demo mode (
|
|
105
|
-
*
|
|
104
|
+
/* RER_DEV_KEY opens local dev identity and RER_DEMO turns on demo mode (mocked
|
|
105
|
+
* third-party effects, throwaway data); they and every key a seed adapter declares local-only
|
|
106
106
|
* never become a deployed binding, secret or secret source. */
|
|
107
107
|
export const LOCAL_ONLY_KEYS = Object.freeze(['RER_DEV_KEY', 'RER_DEMO', 'RER_MODELS_KEY', 'RER_MODELS_SERVICE', '.rer/local/models.json']);
|
|
108
108
|
export function localOnlyBinding(declaration, localOnlyKeys = []) {
|
|
@@ -22,15 +22,18 @@ export async function* r2ObjectPages(api, bucket) {
|
|
|
22
22
|
const data = await api.envelope(`/r2/buckets/${bucket}/objects?per_page=1000${cursor ? `&cursor=${encodeURIComponent(cursor)}` : ''}`);
|
|
23
23
|
const rows = data.result, info = data.result_info;
|
|
24
24
|
assert(Array.isArray(rows) && rows.length <= 1000 && rows.every(row => typeof row?.key === 'string' && row.key.length), 'invalid-r2-object-list');
|
|
25
|
-
// Empty object listings may omit pagination or return null. Only that
|
|
26
|
-
// shape proves completion without explicit pagination evidence.
|
|
27
|
-
if (rows.length === 0 && info == null) { yield rows; return; }
|
|
28
|
-
assert(info && typeof info.is_truncated === 'boolean' && (!info.delimited || Array.isArray(info.delimited) && !info.delimited.length), 'provider-incomplete-pagination');
|
|
29
25
|
assert(new Set(rows.map(row => row.key)).size === rows.length, 'invalid-r2-object-list');
|
|
26
|
+
// Cloudflare may omit pagination (or return null) on any terminal page
|
|
27
|
+
// shorter than the requested limit. A full page cannot prove completion.
|
|
28
|
+
if (info == null) {
|
|
29
|
+
assert(rows.length < 1000, 'provider-incomplete-pagination');
|
|
30
|
+
yield rows; return;
|
|
31
|
+
}
|
|
32
|
+
assert(typeof info.is_truncated === 'boolean' && (!info.delimited || Array.isArray(info.delimited) && !info.delimited.length), 'provider-incomplete-pagination');
|
|
30
33
|
if (info.is_truncated) {
|
|
31
34
|
assert(rows.length > 0 && typeof info.cursor === 'string' && info.cursor.length > 0 && info.cursor.length <= 4096 && !seen.has(info.cursor), 'provider-invalid-cursor');
|
|
32
35
|
cursor = info.cursor; seen.add(cursor);
|
|
33
|
-
}
|
|
36
|
+
} else assert(info.cursor == null || info.cursor === '', 'provider-invalid-cursor');
|
|
34
37
|
yield rows;
|
|
35
38
|
if (!info.is_truncated) return;
|
|
36
39
|
}
|
|
@@ -20,7 +20,7 @@ export async function readJson(path, fallback) {
|
|
|
20
20
|
// Lamport's bakery lock: publish choosing before reading tickets, then wait for
|
|
21
21
|
// every earlier (number,id). Unique records avoid the stale-unlink/new-lock race
|
|
22
22
|
// of a single reclaimable lock file. Every publication is atomic and complete.
|
|
23
|
-
export async function transaction(directory, owner, action) {
|
|
23
|
+
export async function transaction(directory, owner, action, { validateState } = {}) {
|
|
24
24
|
const locks = join(directory, 'locks');
|
|
25
25
|
await mkdir(locks, { recursive: true, mode: 0o700 });
|
|
26
26
|
const id = randomUUID(), path = join(locks, `${id}.json`);
|
|
@@ -55,6 +55,9 @@ export async function transaction(directory, owner, action) {
|
|
|
55
55
|
while ((await participants()).some(record => record.id !== id && (record.choosing
|
|
56
56
|
|| record.number < number || (record.number === number && record.id < id)))) await delay(20);
|
|
57
57
|
const statePath = join(directory, 'state.json');
|
|
58
|
+
// Registry custody checks must share the writer's lock and precede any
|
|
59
|
+
// state read, so an atomic replacement cannot invalidate their inode.
|
|
60
|
+
await validateState?.(statePath);
|
|
58
61
|
const state = await readJson(statePath, { version: 1, sequence: 0, queued: [], running: [] });
|
|
59
62
|
if (state.version !== 1 || !Array.isArray(state.queued) || !Array.isArray(state.running)) throw Error('Invalid job queue state');
|
|
60
63
|
const result = await action(state);
|
package/modules/mail/README.md
CHANGED
|
@@ -19,11 +19,11 @@ const result = await sender.send({
|
|
|
19
19
|
|
|
20
20
|
## Adopting
|
|
21
21
|
|
|
22
|
-
A seed copies this module's runtime files byte for byte, to the same paths under its root, and records them in its source lock. Every seed copies the same one module:
|
|
22
|
+
A seed copies this module's runtime files byte for byte, to the same paths under its root, and records them in its source lock. Every seed copies the same one module: the remote transports and an explicit development suppression path. The same facade also supports optional signed Messaging links.
|
|
23
23
|
|
|
24
24
|
### Mail
|
|
25
25
|
|
|
26
|
-
Every seed copies these files. `index.mjs` loads all of them, including the
|
|
26
|
+
Every seed copies these files. `index.mjs` loads all of them, including the development path below, so none can be left out.
|
|
27
27
|
|
|
28
28
|
```text
|
|
29
29
|
modules/mail/LICENSE
|
|
@@ -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
|
|
@@ -69,9 +71,9 @@ modules/mail/src/doctor/receive.mjs
|
|
|
69
71
|
modules/mail/src/doctor/records.mjs
|
|
70
72
|
```
|
|
71
73
|
|
|
72
|
-
###
|
|
74
|
+
### Development delivery
|
|
73
75
|
|
|
74
|
-
|
|
76
|
+
Copy the development entry with the facade. Its sender validates messages and silently suppresses them. Preserve the schema and storage reader when an installation has historical development mail.
|
|
75
77
|
|
|
76
78
|
```text
|
|
77
79
|
modules/mail/src/development/
|
|
@@ -93,11 +95,10 @@ Sign-in mail is the seed's own wiring around the two things above, not a copy of
|
|
|
93
95
|
|
|
94
96
|
```text
|
|
95
97
|
default-seed/src/core/platform/auth/mail.server.mjs
|
|
96
|
-
default-seed/src/core/platform/auth/outbox.server.mjs
|
|
97
98
|
default-seed/migrations/core/0004_development_outbox.sql
|
|
98
99
|
```
|
|
99
100
|
|
|
100
|
-
`mail.server.mjs` builds the production sender from `MAIL_PROVIDER` (`resend`, `sendgrid` or `cloudflare`)
|
|
101
|
+
`mail.server.mjs` builds the production sender from `MAIL_PROVIDER` (`resend`, `sendgrid` or `cloudflare`). Explicit development and demo configuration suppress mail before selecting any configured remote sender. The migration preserves historical local messages.
|
|
101
102
|
|
|
102
103
|
### Former sendgrid-email API
|
|
103
104
|
|
|
@@ -116,10 +117,50 @@ These are for developing the module itself or documentation. A seed may keep any
|
|
|
116
117
|
- `modules/mail/package.json`, `modules/mail/pnpm-lock.yaml`, `modules/mail/.gitignore`
|
|
117
118
|
- `modules/mail/README.md` and every `README.md` under `modules/mail/src/`
|
|
118
119
|
|
|
119
|
-
The provider is explicit: `sendgrid`, `resend`, `cloudflare`, or `development`.
|
|
120
|
+
The provider is explicit: `sendgrid`, `resend`, `cloudflare`, `rer`, `messaging`, or `development`.
|
|
120
121
|
`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
122
|
|
|
122
|
-
`createMailSender(config, dependencies?)` returns `{send(message)}`. Dependencies are optional standard `fetch`,
|
|
123
|
+
`createMailSender(config, dependencies?)` returns `{send(message)}`. Dependencies are optional standard `fetch`, `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.
|
|
124
|
+
|
|
125
|
+
### Managed mail through RER
|
|
126
|
+
|
|
127
|
+
Seeds opt into Managed mail with `mail: {providers: ["rer"]}` in their candidate
|
|
128
|
+
deployment spec. The [delivery producer](../delivery-producer/README.md#managed-mail)
|
|
129
|
+
can generate the matching setup fields. RER assigns public `MAIL_PROVIDER`,
|
|
130
|
+
`MAIL_FROM`, `MAIL_RELAY_URL` and private `MAIL_API_KEY`; Managed owners do not
|
|
131
|
+
enter them. Wire those settings into the shared sender:
|
|
132
|
+
|
|
133
|
+
```js
|
|
134
|
+
const sender = createMailSender({
|
|
135
|
+
provider: env.MAIL_PROVIDER, // rer
|
|
136
|
+
mode: 'production',
|
|
137
|
+
apiKey: env.MAIL_API_KEY,
|
|
138
|
+
relayUrl: env.MAIL_RELAY_URL,
|
|
139
|
+
});
|
|
140
|
+
await sender.send({
|
|
141
|
+
deliveryId: durableCommand.id,
|
|
142
|
+
from: env.MAIL_FROM,
|
|
143
|
+
to: ['recipient@example.net'],
|
|
144
|
+
subject: 'Your requested sign-in link',
|
|
145
|
+
text: 'Open the link you requested.',
|
|
146
|
+
});
|
|
147
|
+
```
|
|
148
|
+
|
|
149
|
+
Pass `relayUrl` only for `rer`. It must be the assigned HTTPS URL, without URL
|
|
150
|
+
credentials, query or fragment. The adapter sends one POST with Bearer
|
|
151
|
+
authentication and `redirect: 'error'`. Its JSON contains one mailbox `to`,
|
|
152
|
+
`subject`, `text` and optional nonempty `html`. RER owns the sender and
|
|
153
|
+
installation identity; `from` and `deliveryId` are not transmitted. Subjects
|
|
154
|
+
must be nonempty, without newlines and at most 200 characters. Plain text is
|
|
155
|
+
required; each body is limited to 65,536 characters and the JSON to 128 KiB.
|
|
156
|
+
Other recipients, attachments, reply-to, headers and unsubscribe features are
|
|
157
|
+
unsupported and fail before dispatch.
|
|
158
|
+
|
|
159
|
+
HTTP 202 returns `accepted` with no provider message ID. HTTP 400, 401, 402,
|
|
160
|
+
403 and 413 return `rejected`; 429 returns `rate_limited`; 502 and 503 return
|
|
161
|
+
`uncertain`. Network failures and refused redirects are also `uncertain`.
|
|
162
|
+
The usual application delivery policy decides whether to retry or stop; the
|
|
163
|
+
adapter makes no retries and never reads or logs provider error bodies.
|
|
123
164
|
|
|
124
165
|
## Message and results
|
|
125
166
|
|
|
@@ -133,7 +174,7 @@ Resend checks a conservative 40,000,000-byte total email budget before Base64 or
|
|
|
133
174
|
JSON encoding, including UTF-8 bodies, all recipients/headers, aggregate Base64
|
|
134
175
|
attachments and MIME overhead. Its final JSON request is capped at 39,000,000
|
|
135
176
|
UTF-8 bytes. Oversize input throws `MailValidationError` with fixed code
|
|
136
|
-
`resend_message_too_large` before
|
|
177
|
+
`resend_message_too_large` before dispatch. See the precise
|
|
137
178
|
[Resend size budget](src/adapters/resend/README.md#outbound-size-budget); it is a
|
|
138
179
|
local guard and may reject input below the provider's maximum.
|
|
139
180
|
|
|
@@ -149,58 +190,14 @@ Network loss, redirects, HTTP 408 and 5xx are conservatively `uncertain`; 429 is
|
|
|
149
190
|
|
|
150
191
|
## Development and unsubscribe
|
|
151
192
|
|
|
152
|
-
Development requires
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
The typed `src/development/index.mjs` subpath exports
|
|
157
|
-
`createD1DevelopmentOutbox({db,maxMessages?,maxAgeMs?,clock?})` and
|
|
158
|
-
`createDevelopmentOutboxHandler({local,origin,outbox,path?,theme?})`. The root facade's
|
|
159
|
-
exports remain stable. `theme` is the seed's served theme stylesheet, a
|
|
160
|
-
root-relative `.css` path such as `'/rer-theme.css'` (the same grammar as
|
|
161
|
-
operator-auth `branding.theme`; any other value throws when the handler is
|
|
162
|
-
created). With it the page links that file, reads its `--rer-*` tokens with
|
|
163
|
-
readable fallbacks and a visible 3px focus ring, and its policy allows
|
|
164
|
-
same-origin styles, fonts and images (still no script). Without it the page is
|
|
165
|
-
unchanged. Apply the additive [schema](src/development/schema.sql)
|
|
166
|
-
to your local D1 database during local setup, for example:
|
|
167
|
-
|
|
168
|
-
```sh
|
|
169
|
-
pnpm exec wrangler d1 execute DB --local --file=../modules/mail/src/development/schema.sql
|
|
170
|
-
```
|
|
171
|
-
|
|
172
|
-
Use the actual database binding and source path for your host. The table and
|
|
173
|
-
index are namespaced `rer_mail_development_outbox`; the schema is repeatable and
|
|
174
|
-
does not replace application tables. Keep the local D1 persistence directory
|
|
175
|
-
between restarts. No provider credentials are needed for local capture.
|
|
176
|
-
|
|
177
|
-
```js
|
|
178
|
-
import { createMailSender } from './modules/mail/index.mjs';
|
|
179
|
-
import {
|
|
180
|
-
createD1DevelopmentOutbox, createDevelopmentOutboxHandler,
|
|
181
|
-
} from './modules/mail/src/development/index.mjs';
|
|
182
|
-
|
|
183
|
-
// These values come from trusted, explicit local host configuration.
|
|
184
|
-
const outbox = createD1DevelopmentOutbox({ db: env.DB });
|
|
185
|
-
const sender = createMailSender(
|
|
186
|
-
{ provider: 'development', mode: 'development' }, { outbox },
|
|
187
|
-
);
|
|
188
|
-
const viewOutbox = createDevelopmentOutboxHandler({
|
|
189
|
-
local: localConfiguration.enabled === true,
|
|
190
|
-
origin: localConfiguration.origin, // e.g. 'http://localhost:8787'
|
|
191
|
-
outbox,
|
|
192
|
-
});
|
|
193
|
-
// In the host's request handler, before the application catch-all:
|
|
194
|
-
const response = await viewOutbox(request);
|
|
195
|
-
if (response) return response;
|
|
196
|
-
// Continue normal application routing otherwise.
|
|
197
|
-
```
|
|
193
|
+
Development requires `provider:'development'` and `mode:'development'`.
|
|
194
|
+
It validates the prepared message and silently suppresses delivery, returning
|
|
195
|
+
`development` without contacting a provider or storing the message. Production
|
|
196
|
+
must never select development mode after missing credentials or a send failure.
|
|
198
197
|
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
remote sender, and does not mount the development viewer. Missing provider
|
|
203
|
-
credentials or a delivery failure must never select development mode.
|
|
198
|
+
`createD1DevelopmentOutbox({db,maxMessages?,maxAgeMs?,clock?})` remains available
|
|
199
|
+
for reading and erasing mail retained by older local installations. There is no
|
|
200
|
+
outbox viewer or development sign-in mail flow. Keep applied migrations.
|
|
204
201
|
|
|
205
202
|
`put(preparedMessage)` resolves without a receipt; `list()` returns captures
|
|
206
203
|
newest first, and `get(id)` returns a capture or `null`. A capture is
|
|
@@ -213,31 +210,9 @@ D1 batch as the operation; a message expires exactly at `createdAt + maxAgeMs`.
|
|
|
213
210
|
Equal timestamps retain the most recently inserted captures first. A failing
|
|
214
211
|
batch fails the operation without a process-memory fallback.
|
|
215
212
|
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
its scheme and authority. `localhost`, canonical `127.x.x.x`, and `[::1]` are
|
|
220
|
-
supported. Trailing slashes, credentials, paths, queries, fragments, whitespace
|
|
221
|
-
and alternate URL spellings in the configured origin are refused. Host must
|
|
222
|
-
include the configured non-default port. Forwarded headers never grant access;
|
|
223
|
-
a different Origin or a cross-site fetch is also refused before any D1 read.
|
|
224
|
-
The host must bind its development listener to loopback; these request checks
|
|
225
|
-
do not replace that listener configuration.
|
|
226
|
-
|
|
227
|
-
The listing shows subject, recipient and received time. A message detail shows
|
|
228
|
-
escaped text (escaped source for HTML-only messages) and a large **Open this
|
|
229
|
-
link** action for the first valid HTTP(S) link. It never renders live email
|
|
230
|
-
HTML or attachment content. All viewer responses, including errors, carry
|
|
231
|
-
no-store, noindex, nosniff and a strict CSP with an exact static-style hash and
|
|
232
|
-
scripts disabled. The layout wraps long content on a 390px viewport.
|
|
233
|
-
|
|
234
|
-
First-party seeds route local setup through `rer setup` and
|
|
235
|
-
declare their actual mail, auth, database and migration behavior in the RER
|
|
236
|
-
adapter. Base's default seed is the reference for loopback development mail and
|
|
237
|
-
the private local outbox. Follow the runnable checkout's root
|
|
238
|
-
`RUN-LOCALLY.md` for current command and state requirements; the outbox module does not
|
|
239
|
-
replace a seed's owner setup, database bindings, migration directory or sign-in
|
|
240
|
-
policy.
|
|
213
|
+
First-party seeds route local setup through `rer setup` and declare their actual
|
|
214
|
+
mail, auth, database and migration behavior in the RER adapter. Follow the
|
|
215
|
+
runnable checkout's root `RUN-LOCALLY.md` for its command and state requirements.
|
|
241
216
|
|
|
242
217
|
`unsubscribe: {url, mailto?, oneClick?}` supplies an HTTPS unsubscribe URL and optional mailbox. One-click generates `List-Unsubscribe-Post: List-Unsubscribe=One-Click`. Insecure URLs, injection and contradictory custom unsubscribe headers fail before dispatch. `applyUnsubscribeHeaders(message)` returns a new prepared message with the `unsubscribe` request removed. Passing an already prepared message to the facade is safe. Direct adapters reject unconsumed requests before any effect; the facade performs assembly once before dispatch. Applications own unsubscribe authorization and processing. Confirm delivered headers and DKIM coverage with a real delivered message; local serialization is not one-click acceptance.
|
|
243
218
|
|
|
@@ -277,7 +252,7 @@ For a D1 application, copy `src/events/d1-schema.sql` into a **new** migration a
|
|
|
277
252
|
use [the D1 event constructor](src/events/README.md). No migration, linking,
|
|
278
253
|
provider switch or credential removal happens automatically. Self-hosted installs
|
|
279
254
|
stay unlinked until the owner configures them; local development still uses the
|
|
280
|
-
|
|
255
|
+
explicit development suppression without a Messaging service.
|
|
281
256
|
|
|
282
257
|
## The former sendgrid-email API
|
|
283
258
|
|
|
@@ -331,6 +306,6 @@ pnpm --dir modules/mail test:workerd
|
|
|
331
306
|
|
|
332
307
|
The root install is also required for the bundle regression, which uses the reference app's actual Vite dependency. The facade formerly re-exported the doctor while the doctor dynamically imported the facade, causing Vite's `INEFFECTIVE_DYNAMIC_IMPORT` warning. Both now import a private sender module; the existing facade exports and send behavior remain unchanged. `tests/development/bundle.test.mjs` builds the facade and doctor with Vite and fails on that warning.
|
|
333
308
|
|
|
334
|
-
The module-local lock pins the Miniflare/workerd test runtime; production source has no npm dependencies. Unit suites cover core validation, adapters, events, inbound parsing, development, unsubscribe and doctor behaviour. The Messaging HTTP/service-binding smoke and real D1 intake race/rollback/restart suite join the existing area smokes. They check core portability, remote adapters, inbound hydration, durable event intake,
|
|
309
|
+
The module-local lock pins the Miniflare/workerd test runtime; production source has no npm dependencies. Unit suites cover core validation, adapters, events, inbound parsing, development, unsubscribe and doctor behaviour. The Messaging HTTP/service-binding smoke and real D1 intake race/rollback/restart suite join the existing area smokes. They check core portability, remote adapters, inbound hydration, durable event intake, historical development storage and doctor/facade assembly. The storage smokes retain real transaction rollback, namespace isolation, restart and suppression coverage. `tests/all.test.ts` runs the nested suites serially through `pnpm verify:modules`; each worker is disposed after its run. Former SendGrid API tests remain while seed source still imports the deprecated module.
|
|
335
310
|
|
|
336
311
|
Local conformance does not establish provider configuration, DNS propagation, deployed webhook reachability, DKIM coverage or mailbox delivery. Live acceptance remains **PENDING** until an exact-SHA hosted run sends and receives on the owner's approved test domain with independently correlated mailbox evidence. Resend is the default test sender; SendGrid is selected where Inbound Parse is required. No live request is authorized by running local tests.
|
|
@@ -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,12 +29,13 @@ 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') {
|
|
34
37
|
if (config.mode !== 'development') fail('development_mode_required');
|
|
35
38
|
if (config.apiKey !== undefined || config.accountId !== undefined) fail('unsupported_development_config');
|
|
36
|
-
if (!dependencies.outbox || typeof dependencies.outbox.put !== 'function') fail('development_outbox_required');
|
|
37
39
|
} else {
|
|
38
40
|
if (typeof config.apiKey !== 'string' || !config.apiKey.trim()) fail('api_key_required');
|
|
39
41
|
bounded(config.apiKey, 4096, 'invalid_api_key');
|
|
@@ -132,6 +134,7 @@ export function validateMessage(message, provider) {
|
|
|
132
134
|
for (const attachment of message.attachments) validateAttachment(attachment);
|
|
133
135
|
}
|
|
134
136
|
if (message.unsubscribe !== undefined) validateUnsubscribe(message.unsubscribe);
|
|
137
|
+
if (provider === 'rer') validateRerMessage(message);
|
|
135
138
|
const settings = ['customArgs', 'asmGroupId', 'subscriptionTracking'];
|
|
136
139
|
if (provider && !['sendgrid', 'development'].includes(provider) && settings.some(key => message[key] !== undefined)) fail('unsupported_provider_setting');
|
|
137
140
|
if (message.asmGroupId !== undefined && (!Number.isSafeInteger(message.asmGroupId) || message.asmGroupId <= 0)) fail('invalid_asm_group');
|
|
@@ -34,10 +34,5 @@ export class DevelopmentOutboxError extends Error {
|
|
|
34
34
|
readonly retryable: true;
|
|
35
35
|
}
|
|
36
36
|
export function createD1DevelopmentOutbox(options: { db: DevelopmentD1Database; maxMessages?: number; maxAgeMs?: number; clock?: () => number }): DevelopmentOutbox;
|
|
37
|
-
export function createDevelopmentOutboxHandler(options: {
|
|
38
|
-
local: boolean; origin: string; outbox: Pick<DevelopmentOutbox, 'list' | 'get'>; path?: string;
|
|
39
|
-
/** The seed's served theme stylesheet, a root-relative `.css` path such as '/rer-theme.css'; other values throw. */
|
|
40
|
-
theme?: string;
|
|
41
|
-
}): (request: Request) => Promise<Response | null>;
|
|
42
37
|
export function sendDevelopment(config: { provider: 'development'; mode: 'development' }, message: DevelopmentMessage,
|
|
43
|
-
dependencies
|
|
38
|
+
dependencies?: { clock?: () => number }): Promise<{ provider: 'development'; status: 'development'; providerMessageId: null }>;
|
|
@@ -1,9 +1,9 @@
|
|
|
1
|
-
import { MailValidationError,
|
|
1
|
+
import { MailValidationError, fail } from '../core/errors.mjs';
|
|
2
2
|
import { validateConfig, validateMessage } from '../core/validation.mjs';
|
|
3
3
|
import { sendResult } from '../core/transport.mjs';
|
|
4
4
|
|
|
5
|
+
// Retained for reading and erasing messages saved by older local installations.
|
|
5
6
|
export { createD1DevelopmentOutbox } from './outbox.mjs';
|
|
6
|
-
export { createDevelopmentOutboxHandler } from './viewer.mjs';
|
|
7
7
|
export { DevelopmentOutboxError } from '../core/errors.mjs';
|
|
8
8
|
|
|
9
9
|
function validate(operation, errorCode) {
|
|
@@ -15,24 +15,11 @@ function validate(operation, errorCode) {
|
|
|
15
15
|
}
|
|
16
16
|
}
|
|
17
17
|
|
|
18
|
-
/**
|
|
18
|
+
/** Explicit development delivery validates the message and silently suppresses it. */
|
|
19
19
|
export async function sendDevelopment(config, message, dependencies = {}) {
|
|
20
20
|
validate(() => validateConfig(config, dependencies), 'invalid_config');
|
|
21
21
|
if (validate(() => config.provider, 'invalid_config') !== 'development') fail('development_provider_required');
|
|
22
|
-
|
|
23
22
|
validate(() => validateMessage(message, 'development'), 'invalid_message');
|
|
24
23
|
if (validate(() => message.unsubscribe, 'invalid_message') !== undefined) fail('unsubscribe_not_assembled');
|
|
25
|
-
|
|
26
|
-
const snapshot = validate(() => structuredClone(message), 'invalid_message');
|
|
27
|
-
validate(() => validateMessage(snapshot, 'development'), 'invalid_message');
|
|
28
|
-
|
|
29
|
-
try {
|
|
30
|
-
await dependencies.outbox.put(snapshot);
|
|
31
|
-
} catch (error) {
|
|
32
|
-
// Input the outbox itself refuses stays permanent; a storage failure is worth a retry.
|
|
33
|
-
if (error instanceof MailValidationError) throw error;
|
|
34
|
-
throw new DevelopmentOutboxError();
|
|
35
|
-
}
|
|
36
|
-
|
|
37
24
|
return sendResult('development', 'development', null);
|
|
38
25
|
}
|
|
@@ -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 = {}) {
|