diff --git a/docs/PROJECT_PLAN.md b/docs/PROJECT_PLAN.md index c704ecd..bbf38b8 100644 --- a/docs/PROJECT_PLAN.md +++ b/docs/PROJECT_PLAN.md @@ -10,11 +10,11 @@ workflow, while PRs validate without receiving production credentials. Identity consumer now composes the exact public Identity, Authorization adapter, Sessions, Mail, rate-limit, and storage packages. Worker version -`0a9956e6-01c6-4a9a-953f-4e71d94d0055` is live on `pegma.dev/api/*`; production +`f627b1ee-7675-47b2-a72b-6b26210f3bb3` is live on `pegma.dev/api/*`; production health, capabilities, unauthenticated account, and cross-origin rejection -smoke tests pass. Email-code activation is a separate gate: provider-domain -setup, its managed secret, an audited operator workflow, and an end-to-end -delivery smoke test. +smoke tests pass. Resend email-code delivery was activated on 2026-07-28 after +the sender domain and managed secret were installed; the scheduled durable +outbox delivered its provider smoke test successfully. **Hosting decision:** Cloudflare (Pages for the static site; Workers when a dynamic slice exists). Deliberate: the reference application @@ -209,19 +209,22 @@ Azure. `@pegma/rate-limit@0.1.0`, and the D1/storage `0.4.0` packages. It exposes a secure account API/browser boundary for issuer `https://pegma.dev` and RP ID `pegma.dev`, uses four durable abuse limits, and schedules cursor-persisted -maintenance. Email jobs commit atomically in Identity storage; a fail-closed -Resend adapter provides idempotent send and reconciliation but remains -disabled until the free-tier provider account, sender domain, managed secrets, -delivery smoke test, and audited operator acknowledgement workflow are -complete. No paid email service is assumed. +maintenance. Its generic `GET /api/secure` proof resolves the opaque cookie +through Sessions and revalidates the Identity/Authorization claims before +returning the issuer and subject. Email jobs commit atomically in Identity +storage; a fail-closed +Resend adapter provides idempotent send and reconciliation. The free-tier +provider account, verified sender domain, managed secrets, activation gate, +and provider delivery smoke test were completed on 2026-07-28. No paid email +service is assumed. **Logging precursor (2026-07-27):** Worker `pegma-dev-api` is deployed with `@pegma/logger-tee` → `@pegma/logger-cloudflare` + `@pegma/logger-datadog`. Workers Logs (Cloudflare’s log store) is enabled via Wrangler `observability.logs`. Datadog is optional until `DATADOG_API_KEY` is set. The Phase 4 account consumer now uses the published D1 adapter, Sessions, -Identity, and Authorization adapter; its email entry points remain fail closed -until the provider activation gate is complete. +Identity, and Authorization adapter; its Resend email-code entry points are +live behind their fail-closed capability checks. ### Phase 5 — dogfood support @@ -253,8 +256,10 @@ with a source link where not. Decide in Phase 3. 2. Configure the Resend free-tier account, verify the `pegma.dev` sender, install its managed provider secret, and smoke-test idempotent delivery behind an authenticated, audited terminal-mail acknowledgement workflow - before enabling email-code entry points. The stable HMAC secret is already - installed in Cloudflare's managed secret store. + before enabling email-code entry points. **Done 2026-07-28:** the stable + HMAC and provider secrets are in Cloudflare's managed secret store, live + health and capabilities expose delivery, and Resend reported the scheduled + durable-outbox test message as delivered. 3. Route same-origin `/api/*` traffic to `pegma-dev-api`, deploy, and verify the D1-backed account flow without changing the Pages-hosted static architecture. - **Done 2026-07-28; email activation remains separately gated.** + **Done 2026-07-28, including email activation.** diff --git a/public/account.js b/public/account.js index 56c1480..f8ae53f 100644 --- a/public/account.js +++ b/public/account.js @@ -8,6 +8,7 @@ const emailAvailability = document.querySelector('#email-availability'); const accountEmail = document.querySelector('#account-email-display'); const passkeyList = document.querySelector('#passkey-list'); const addPasskey = document.querySelector('#add-passkey'); +const testSecureApi = document.querySelector('#test-secure-api'); const signOut = document.querySelector('#sign-out'); let csrfToken = ''; @@ -303,6 +304,17 @@ addPasskey.addEventListener('submit', async (event) => { } }); +testSecureApi.addEventListener('click', async () => { + try { + const result = await api('/api/secure'); + showStatus( + `Backend session validated for ${result.subject} through ${result.session}.`, + ); + } catch (error) { + showStatus(`Backend session validation failed: ${error.message}`, true); + } +}); + signOut.addEventListener('click', async () => { try { await api('/api/identity/logout', { method: 'POST', body: '{}' }); diff --git a/src/pages/account.astro b/src/pages/account.astro index edecf42..3a30cd1 100644 --- a/src/pages/account.astro +++ b/src/pages/account.astro @@ -63,6 +63,10 @@ import Base from '../layouts/Base.astro'; +

Backend session

+

Call a protected Worker endpoint that resolves this browser session through @pegma/sessions.

+ +

Passkeys

diff --git a/worker/README.md b/worker/README.md index dbcacf1..a39c39e 100644 --- a/worker/README.md +++ b/worker/README.md @@ -37,7 +37,7 @@ authenticated operator session with `npm run worker:deploy` until a separate, least-privileged credential has both Worker script and `pegma.dev` route authority. Do not substitute a broad personal OAuth token into GitHub. The production Worker was operator-deployed on 2026-07-28 as version -`0a9956e6-01c6-4a9a-953f-4e71d94d0055`. +`f627b1ee-7675-47b2-a72b-6b26210f3bb3`. ## Identity composition @@ -54,6 +54,12 @@ require a per-session synchronizer token. Request bodies are bounded before JSON parsing, and logs contain route/error classifications rather than contact data, credentials, codes, or session identifiers. +`GET /api/secure` is the generic backend-authentication proof. It resolves the +opaque `__Host-pegma_session` cookie through `@pegma/sessions`, revalidates the +stored principal against Identity and the Authorization claims adapter, and +returns only the issuer and subject. Missing, expired, revoked, malformed, or +account-invalid sessions receive `401`; every response is `no-store`. + The production composition pins `@pegma/identity@0.1.0` and `@pegma/authorization-identity@0.1.2`. Account creation and fallback sign-in commit the email-code operation and its `@pegma/mail@0.1.0` job atomically in @@ -83,6 +89,59 @@ and must remain stable while any email-code or Mail job is live. Verify the `pegma.dev` sender domain and smoke-test delivery before changing `IDENTITY_EMAIL_ENABLED` to `true`. +### Enabling Resend in production + +Production has both `IDENTITY_EMAIL_CODE_SECRET_BASE64` and `RESEND_API_KEY`. +Resend delivery was activated on 2026-07-28 after the `pegma.dev` domain was +verified. Live health reports `emailDelivery: true`, Identity advertises +`emailCode: true`, and an account-code job sent by the scheduled durable +outbox reached Resend's official delivered test sink. + +Use this activation sequence for a new environment or credential rotation: + +1. Create the Resend account and a sending API key. +2. Add `pegma.dev` as a Resend sending domain and install every DNS record + Resend supplies. Wait for the domain to show as verified. +3. Put the key directly into the Worker: + + ```sh + npx wrangler secret put RESEND_API_KEY -c worker/wrangler.jsonc + ``` + +4. Send a provider smoke test from `Pegma ` to a real + address controlled by the operator. +5. Change `IDENTITY_EMAIL_ENABLED` in `worker/wrangler.jsonc` to `true`, run + the complete gate, and deploy. +6. Confirm `/api/health` reports `emailDelivery: true`, then exercise account + creation. The scheduled worker drains the durable Mail job each minute. + +Do not reverse steps 2 and 5. Identity deliberately fails closed so it never +commits a verification-code operation that has no usable delivery path. + +### Additional provider adapters + +The host-owned adapters live beside the composition root: + +- `cloudflare-email-mail.ts` uses Cloudflare Email Service's native + `SendEmail` binding. Cloudflare does not currently document submission + idempotency, so construction requires the literal + `acceptDoubleSendRisk: true`. Authoritative delivery must be supplied from + Email Sending Queue events through the adapter's `deliveryStatus` port; the + included event parser normalizes those untrusted payloads. +- `azure-acs-mail.ts` signs the Azure Communication Services Email REST API + with an access key, derives a stable operation UUID from the Mail + idempotency key, and uses ACS repeatability headers. The host must durably + supply the original `firstSentAt` timestamp. The adapter refuses to resubmit + after ACS's five-minute repeatability window. Recipient delivery comes from + Event Grid through its `deliveryStatus` port; a successful send operation + alone is not reported as delivery. The included Event Grid parser produces + the receipt shape expected by a host-owned status store. + +`createIdentityRuntime` accepts either adapter through `mailDelivery`, so +Identity and the durable outbox remain provider-neutral. Production continues +to select Resend until the chosen alternative has its domain, credentials, +event receipt store, and callback correlation configured. + The D1 schema is deployment-managed by `migrations/0001_pegma_storage.sql`. The adapter runs with `createSchemaIfMissing: false`, so request traffic never performs DDL. diff --git a/worker/src/azure-acs-mail.test.ts b/worker/src/azure-acs-mail.test.ts new file mode 100644 index 0000000..9dc4369 --- /dev/null +++ b/worker/src/azure-acs-mail.test.ts @@ -0,0 +1,181 @@ +import { describe, expect, it, vi } from 'vitest'; +import { + AzureAcsMailError, + classifyAzureAcsFailure, + createAzureAcsMailPorts, + parseAzureAcsDeliveryEvent, +} from './azure-acs-mail'; + +const now = new Date('2026-07-28T16:00:00.000Z'); +const accessKey = btoa(String.fromCharCode(...new Uint8Array(32).fill(9))); + +function options(fetch: typeof globalThis.fetch) { + return { + endpoint: 'https://pegma.unitedstates.communication.azure.com', + accessKey, + senderAddress: 'identity@pegma.azurecomm.net', + firstSentAt: vi.fn(async () => now), + fetch, + now: () => new Date(now), + }; +} + +describe('Azure Communication Services Email Mail adapter', () => { + it('uses one deterministic operation and repeatability ID per Mail key', async () => { + const request = vi.fn(); + request.mockImplementation(async (_url, init) => { + const id = new Headers(init?.headers).get('Operation-Id')!; + return Response.json({ id, status: 'Running' }, { status: 202 }); + }); + const ports = createAzureAcsMailPorts(options(request)); + const input = { + idempotencyKey: 'pegma-mail:v1:partition:job:1', + mail: { + recipient: 'person@example.test', + subject: 'Verify', + text: 'Code 12345678', + }, + }; + + const first = await ports.provider.send(input); + const second = await ports.provider.send(input); + + expect(second).toEqual(first); + const headers = new Headers(request.mock.calls[0]![1]?.headers); + expect(headers.get('Operation-Id')).toBe(first.providerMessageRef); + expect(headers.get('Repeatability-Request-ID')).toBe( + first.providerMessageRef, + ); + expect(headers.get('Repeatability-First-Sent')).toBe(now.toUTCString()); + expect(headers.get('Authorization')).toMatch( + /^HMAC-SHA256 SignedHeaders=/u, + ); + }); + + it('fails closed after the ACS five-minute repeatability window', async () => { + const ports = createAzureAcsMailPorts({ + ...options(vi.fn()), + firstSentAt: async () => new Date(now.getTime() - 5 * 60_000 - 1), + }); + + await expect( + ports.provider.send({ + idempotencyKey: 'pegma-mail:v1:partition:job:1', + mail: { + recipient: 'person@example.test', + subject: 'Verify', + text: 'Code 12345678', + }, + }), + ).rejects.toMatchObject({ category: 'provider_idempotency_expired' }); + }); + + it('normalizes Event Grid delivery reports for a host receipt store', () => { + expect( + parseAzureAcsDeliveryEvent({ + eventType: 'Microsoft.Communication.EmailDeliveryReportReceived', + eventTime: '2026-07-28T16:00:01.000Z', + data: { + messageId: '8540c0de-899f-5cce-acb5-3ec493af3800', + status: 'Bounced', + deliveryAttemptTimeStamp: '2026-07-28T16:00:00.2855749Z', + }, + }), + ).toEqual({ + providerMessageRef: '8540c0de-899f-5cce-acb5-3ec493af3800', + status: 'Bounced', + occurredAt: '2026-07-28T16:00:00.285Z', + failureCategory: 'azure_bounced', + }); + }); + + it('does not invoke accessors in untrusted Event Grid reports', () => { + const getter = vi.fn(() => 'Delivered'); + const data = { + messageId: '8540c0de-899f-5cce-acb5-3ec493af3800', + deliveryAttemptTimeStamp: '2026-07-28T16:00:00.000Z', + }; + Object.defineProperty(data, 'status', { get: getter }); + + expect( + parseAzureAcsDeliveryEvent({ + eventType: 'Microsoft.Communication.EmailDeliveryReportReceived', + data, + }), + ).toBeNull(); + expect(getter).not.toHaveBeenCalled(); + }); + + it.each([ + ['Delivered', 'delivered'], + ['Bounced', 'failed'], + ['Suppressed', 'failed'], + ['FilteredSpam', 'failed'], + ] as const)('reconciles Event Grid %s as %s', async (status, expected) => { + const request = vi.fn(async (url, init) => { + const id = + new Headers(init?.headers).get('Operation-Id') ?? + new URL(String(url)).pathname.split('/').at(-1)!; + return Response.json( + { id, status: init?.method === 'POST' ? 'Running' : 'Succeeded' }, + { status: init?.method === 'POST' ? 202 : 200 }, + ); + }); + const ports = createAzureAcsMailPorts({ + ...options(request), + deliveryStatus: vi.fn(async () => ({ status })), + }); + const sent = await ports.provider.send({ + idempotencyKey: 'pegma-mail:v1:partition:job:1', + mail: { + recipient: 'person@example.test', + subject: 'Verify', + text: 'Code 12345678', + }, + }); + + await expect( + ports.reconciliation.reconcile({ + idempotencyKey: 'pegma-mail:v1:partition:job:1', + providerMessageRef: sent.providerMessageRef, + }), + ).resolves.toMatchObject({ status: expected }); + }); + + it('does not misreport a successful send operation as recipient delivery', async () => { + const request = vi.fn(async (url, init) => { + const id = + new Headers(init?.headers).get('Operation-Id') ?? + new URL(String(url)).pathname.split('/').at(-1)!; + return Response.json( + { id, status: init?.method === 'POST' ? 'Running' : 'Succeeded' }, + { status: init?.method === 'POST' ? 202 : 200 }, + ); + }); + const ports = createAzureAcsMailPorts(options(request)); + const sent = await ports.provider.send({ + idempotencyKey: 'pegma-mail:v1:partition:job:1', + mail: { + recipient: 'person@example.test', + subject: 'Verify', + text: 'Code 12345678', + }, + }); + + await expect( + ports.reconciliation.reconcile({ + idempotencyKey: 'pegma-mail:v1:partition:job:1', + providerMessageRef: sent.providerMessageRef, + }), + ).resolves.toEqual({ status: 'unknown' }); + }); + + it('classifies only adapter-owned failures', () => { + expect( + classifyAzureAcsFailure(new AzureAcsMailError('provider_retryable')), + ).toBe('provider_retryable'); + expect(classifyAzureAcsFailure(new Error('secret'))).toBe( + 'provider_unavailable', + ); + }); +}); diff --git a/worker/src/azure-acs-mail.ts b/worker/src/azure-acs-mail.ts new file mode 100644 index 0000000..5028de5 --- /dev/null +++ b/worker/src/azure-acs-mail.ts @@ -0,0 +1,510 @@ +import type { + MailProvider, + MailReconciliationPort, +} from '@pegma/identity'; +import type { MailReconciliationRequest, MailSendRequest } from '@pegma/mail'; + +const API_VERSION = '2025-09-01'; +const RESPONSE_LIMIT = 32 * 1024; +const PROVIDER_TIMEOUT_MS = 10_000; +const UUID = + /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu; + +export type AzureAcsDeliveryStatus = + | 'Delivered' + | 'Suppressed' + | 'Bounced' + | 'Quarantined' + | 'FilteredSpam' + | 'Expanded' + | 'Failed' + | 'Unknown'; + +export interface AzureAcsDeliveryResult { + readonly status: AzureAcsDeliveryStatus; + readonly failureCategory?: string; +} + +export interface AzureAcsDeliveryEvent extends AzureAcsDeliveryResult { + readonly providerMessageRef: string; + readonly occurredAt: string; +} + +export class AzureAcsMailError extends Error { + constructor(readonly category: string) { + super(category); + this.name = 'AzureAcsMailError'; + } +} + +function requireText(value: unknown, name: string, maximum: number): string { + if ( + typeof value !== 'string' || + value.trim().length === 0 || + value.length > maximum || + /[\u0000-\u001F\u007F-\u009F]/u.test(value) + ) { + throw new TypeError(`${name} is invalid`); + } + return value; +} + +function isObject(value: unknown): value is Record { + try { + return ( + typeof value === 'object' && + value !== null && + !Array.isArray(value) && + Object.getPrototypeOf(value) === Object.prototype + ); + } catch { + return false; + } +} + +function dataProperty(value: unknown, name: string): unknown { + if ( + (typeof value !== 'object' && typeof value !== 'function') || + value === null + ) { + return undefined; + } + try { + const property = Object.getOwnPropertyDescriptor(value, name); + return property !== undefined && Object.hasOwn(property, 'value') + ? property.value + : undefined; + } catch { + return undefined; + } +} + +function bytesToBase64(value: Uint8Array): string { + let binary = ''; + for (const byte of value) binary += String.fromCharCode(byte); + return btoa(binary); +} + +function base64ToBytes(value: string): Uint8Array { + if ( + value.length < 40 || + value.length > 512 || + !/^[A-Za-z0-9+/]+={0,2}$/u.test(value) + ) { + throw new TypeError('Azure ACS access key is invalid'); + } + let binary: string; + try { + binary = atob(value); + } catch { + throw new TypeError('Azure ACS access key is invalid'); + } + if (btoa(binary) !== value || binary.length < 32) { + throw new TypeError('Azure ACS access key is invalid'); + } + return Uint8Array.from(binary, (character) => character.charCodeAt(0)); +} + +async function boundedJson(response: Response): Promise { + const declared = response.headers.get('Content-Length'); + if ( + declared !== null && + (!/^\d+$/u.test(declared) || Number(declared) > RESPONSE_LIMIT) + ) { + throw new AzureAcsMailError('provider_response_invalid'); + } + if (response.body === null) { + throw new AzureAcsMailError('provider_response_invalid'); + } + const reader = response.body.getReader(); + const chunks: Uint8Array[] = []; + let length = 0; + try { + while (true) { + const chunk = await reader.read(); + if (chunk.done) break; + length += chunk.value.byteLength; + if (length > RESPONSE_LIMIT) { + await reader.cancel(); + throw new AzureAcsMailError('provider_response_invalid'); + } + chunks.push(chunk.value); + } + } finally { + reader.releaseLock(); + } + const bytes = new Uint8Array(length); + let offset = 0; + for (const chunk of chunks) { + bytes.set(chunk, offset); + offset += chunk.byteLength; + } + try { + return JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(bytes)); + } catch { + throw new AzureAcsMailError('provider_response_invalid'); + } +} + +function providerCategory(body: unknown, fallback: string): string { + const errorValue = dataProperty(body, 'error'); + const error = isObject(errorValue) ? errorValue : null; + const errorCode = dataProperty(error, 'code'); + const code = + error !== null && + typeof errorCode === 'string' && + /^[A-Za-z][A-Za-z0-9_.-]{0,63}$/u.test(errorCode) + ? errorCode.toLowerCase().replaceAll(/[^a-z0-9]+/gu, '_') + : null; + return code === null ? fallback : `azure_${code}`.slice(0, 64); +} + +async function operationId(idempotencyKey: string): Promise { + const digest = new Uint8Array( + await crypto.subtle.digest( + 'SHA-256', + new TextEncoder().encode(idempotencyKey), + ), + ); + digest[6] = (digest[6]! & 0x0f) | 0x40; + digest[8] = (digest[8]! & 0x3f) | 0x80; + const hex = [...digest.slice(0, 16)] + .map((value) => value.toString(16).padStart(2, '0')) + .join(''); + return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`; +} + +function repeatabilityDate(value: Date | string, now: Date): string { + const date = value instanceof Date ? new Date(value) : new Date(value); + const milliseconds = date.getTime(); + const distance = now.getTime() - milliseconds; + if ( + !Number.isFinite(milliseconds) || + distance < -30_000 || + distance > 5 * 60_000 + ) { + throw new AzureAcsMailError('provider_idempotency_expired'); + } + return date.toUTCString(); +} + +function operationStatus( + body: unknown, + expectedId: string, +): 'NotStarted' | 'Running' | 'Succeeded' | 'Failed' | null { + const id = dataProperty(body, 'id'); + if ( + !isObject(body) || + typeof id !== 'string' || + id.toLowerCase() !== expectedId.toLowerCase() + ) { + return null; + } + const status = dataProperty(body, 'status'); + return status === 'NotStarted' || + status === 'Running' || + status === 'Succeeded' || + status === 'Failed' + ? status + : null; +} + +function deliveryFailure( + result: AzureAcsDeliveryResult, +): string | undefined { + if ( + typeof result.failureCategory === 'string' && + /^[a-z][a-z0-9_]{0,63}$/u.test(result.failureCategory) + ) { + return result.failureCategory; + } + return result.status === 'Unknown' || + result.status === 'Delivered' || + result.status === 'Expanded' + ? undefined + : `azure_${result.status.toLowerCase()}`; +} + +export function parseAzureAcsDeliveryEvent( + value: unknown, +): AzureAcsDeliveryEvent | null { + const eventType = dataProperty(value, 'eventType'); + const data = dataProperty(value, 'data'); + if ( + eventType !== 'Microsoft.Communication.EmailDeliveryReportReceived' || + !isObject(data) + ) { + return null; + } + const messageId = dataProperty(data, 'messageId'); + const status = dataProperty(data, 'status'); + const deliveryTimestamp = dataProperty(data, 'deliveryAttemptTimeStamp'); + const timestamp = + typeof deliveryTimestamp === 'string' + ? deliveryTimestamp + : dataProperty(value, 'eventTime'); + if ( + typeof messageId !== 'string' || + !UUID.test(messageId) || + (status !== 'Delivered' && + status !== 'Suppressed' && + status !== 'Bounced' && + status !== 'Quarantined' && + status !== 'FilteredSpam' && + status !== 'Expanded' && + status !== 'Failed') || + typeof timestamp !== 'string' + ) { + return null; + } + let occurredAt: string; + try { + occurredAt = new Date(timestamp).toISOString(); + } catch { + return null; + } + const failureCategory = + status === 'Delivered' || status === 'Expanded' + ? undefined + : `azure_${status.toLowerCase()}`; + return Object.freeze({ + providerMessageRef: messageId, + status, + occurredAt, + ...(failureCategory === undefined ? {} : { failureCategory }), + }); +} + +/** + * REST adapter for Azure Communication Services Email. + * + * firstSentAt must return the same durable timestamp for every invocation of + * one Mail idempotency key. ACS retains repeatability records for five + * minutes; after that the adapter fails closed instead of risking a resend. + * Authoritative recipient delivery still comes from Event Grid, supplied + * through deliveryStatus. + */ +export function createAzureAcsMailPorts(options: { + readonly endpoint: string; + readonly accessKey: string; + readonly senderAddress: string; + readonly firstSentAt: ( + idempotencyKey: string, + ) => Promise | Date | string; + readonly deliveryStatus?: ( + providerMessageRef: string, + ) => Promise; + readonly fetch?: typeof fetch; + readonly now?: () => Date; +}): { + readonly provider: MailProvider; + readonly reconciliation: MailReconciliationPort; +} { + const endpoint = new URL(options.endpoint); + if ( + endpoint.protocol !== 'https:' || + endpoint.username !== '' || + endpoint.password !== '' || + endpoint.pathname !== '/' || + endpoint.search !== '' || + endpoint.hash !== '' + ) { + throw new TypeError('Azure ACS endpoint is invalid'); + } + const accessKey = base64ToBytes(options.accessKey); + const hmacKeyBytes = new Uint8Array(accessKey.byteLength); + hmacKeyBytes.set(accessKey); + const senderAddress = requireText( + options.senderAddress, + 'Azure ACS sender', + 320, + ); + const request = options.fetch ?? fetch; + const now = options.now ?? (() => new Date()); + + function currentDate(): Date { + const value = now(); + if (!(value instanceof Date) || !Number.isFinite(value.getTime())) { + throw new AzureAcsMailError('provider_clock_invalid'); + } + return value; + } + + async function signedCall( + method: 'GET' | 'POST', + pathAndQuery: string, + body: string, + headers: Readonly> = {}, + ): Promise<{ readonly response: Response; readonly body: unknown }> { + const requestUrl = new URL(pathAndQuery, endpoint); + const requestDate = currentDate().toUTCString(); + const contentHash = bytesToBase64( + new Uint8Array( + await crypto.subtle.digest( + 'SHA-256', + new TextEncoder().encode(body), + ), + ), + ); + const stringToSign = `${method}\n${requestUrl.pathname}${requestUrl.search}\n${requestDate};${requestUrl.host};${contentHash}`; + const key = await crypto.subtle.importKey( + 'raw', + hmacKeyBytes.buffer, + { name: 'HMAC', hash: 'SHA-256' }, + false, + ['sign'], + ); + const signature = bytesToBase64( + new Uint8Array( + await crypto.subtle.sign( + 'HMAC', + key, + new TextEncoder().encode(stringToSign), + ), + ), + ); + + let response: Response; + try { + response = await request(requestUrl, { + method, + headers: { + Authorization: `HMAC-SHA256 SignedHeaders=x-ms-date;host;x-ms-content-sha256&Signature=${signature}`, + 'x-ms-date': requestDate, + 'x-ms-content-sha256': contentHash, + ...headers, + }, + ...(method === 'POST' ? { body } : {}), + signal: AbortSignal.timeout(PROVIDER_TIMEOUT_MS), + }); + } catch { + throw new AzureAcsMailError('provider_timeout'); + } + const parsed = await boundedJson(response); + return { response, body: parsed }; + } + + async function getOperation(id: string): Promise<{ + readonly status: 'NotStarted' | 'Running' | 'Succeeded' | 'Failed'; + readonly body: unknown; + }> { + const result = await signedCall( + 'GET', + `/emails/operations/${encodeURIComponent(id)}?api-version=${API_VERSION}`, + '', + ); + if (!result.response.ok) { + throw new AzureAcsMailError( + result.response.status === 429 || result.response.status >= 500 + ? 'provider_retryable' + : providerCategory(result.body, 'provider_rejected'), + ); + } + const status = operationStatus(result.body, id); + if (status === null) { + throw new AzureAcsMailError('provider_response_invalid'); + } + return { status, body: result.body }; + } + + const provider: MailProvider = Object.freeze({ + async send(input: MailSendRequest) { + const id = await operationId(input.idempotencyKey); + const firstSent = repeatabilityDate( + await options.firstSentAt(input.idempotencyKey), + currentDate(), + ); + const body = JSON.stringify({ + senderAddress, + recipients: { to: [{ address: input.mail.recipient }] }, + content: { + subject: input.mail.subject, + plainText: input.mail.text, + ...(input.mail.html === undefined + ? {} + : { html: input.mail.html }), + }, + ...(input.mail.headers === undefined + ? {} + : { headers: input.mail.headers }), + }); + const result = await signedCall( + 'POST', + `/emails:send?api-version=${API_VERSION}`, + body, + { + 'Content-Type': 'application/json', + 'Operation-Id': id, + 'Repeatability-Request-ID': id, + 'Repeatability-First-Sent': firstSent, + }, + ); + + if (result.response.status === 409) { + await getOperation(id); + return { providerMessageRef: id }; + } + if (!result.response.ok) { + throw new AzureAcsMailError( + result.response.status === 412 + ? 'provider_idempotency_expired' + : result.response.status === 429 || result.response.status >= 500 + ? 'provider_retryable' + : providerCategory(result.body, 'provider_rejected'), + ); + } + if (operationStatus(result.body, id) === null) { + throw new AzureAcsMailError('provider_response_invalid'); + } + return { providerMessageRef: id }; + }, + }); + + const reconciliation: MailReconciliationPort = Object.freeze({ + async reconcile(input: MailReconciliationRequest) { + if (!UUID.test(input.providerMessageRef)) { + return { + status: 'failed' as const, + failureCategory: 'provider_reference_invalid', + }; + } + if (options.deliveryStatus !== undefined) { + const delivery = await options.deliveryStatus( + input.providerMessageRef, + ); + if (delivery.status === 'Delivered') { + return { status: 'delivered' as const }; + } + const failed = deliveryFailure(delivery); + if (failed !== undefined) { + return { + status: 'failed' as const, + failureCategory: failed, + }; + } + } + + const operation = await getOperation(input.providerMessageRef); + if (operation.status === 'Failed') { + return { + status: 'failed' as const, + failureCategory: providerCategory( + operation.body, + 'azure_send_failed', + ), + }; + } + // Succeeded means ACS processed the send operation, not that the + // recipient MTA accepted it. Event Grid remains authoritative. + return { status: 'unknown' as const }; + }, + }); + + return Object.freeze({ provider, reconciliation }); +} + +export function classifyAzureAcsFailure(error: unknown): string { + return error instanceof AzureAcsMailError + ? error.category + : 'provider_unavailable'; +} diff --git a/worker/src/cloudflare-email-mail.test.ts b/worker/src/cloudflare-email-mail.test.ts new file mode 100644 index 0000000..0896db2 --- /dev/null +++ b/worker/src/cloudflare-email-mail.test.ts @@ -0,0 +1,146 @@ +import { describe, expect, it, vi } from 'vitest'; +import { + classifyCloudflareEmailFailure, + CloudflareEmailMailError, + createCloudflareEmailMailPorts, + parseCloudflareEmailDeliveryEvent, +} from './cloudflare-email-mail'; + +function binding(messageId = 'cf-message-123'): SendEmail { + return { + send: vi.fn(async () => ({ messageId })), + } as unknown as SendEmail; +} + +describe('Cloudflare Email Service Mail adapter', () => { + it('requires an explicit acknowledgement of provider double-send risk', () => { + expect(() => + createCloudflareEmailMailPorts({ + binding: binding(), + from: 'identity@pegma.dev', + acceptDoubleSendRisk: false as true, + }), + ).toThrow(/double-send risk/u); + }); + + it('sends through the native binding and retains the Mail key as correlation', async () => { + const email = binding(); + const ports = createCloudflareEmailMailPorts({ + binding: email, + from: 'Pegma ', + acceptDoubleSendRisk: true, + }); + + await expect( + ports.provider.send({ + idempotencyKey: 'pegma-mail:v1:partition:job:1', + mail: { + recipient: 'person@example.test', + subject: 'Verify', + text: 'Code 12345678', + }, + }), + ).resolves.toEqual({ providerMessageRef: 'cf-message-123' }); + + expect(email.send).toHaveBeenCalledWith({ + to: 'person@example.test', + from: 'Pegma ', + subject: 'Verify', + text: 'Code 12345678', + headers: { + 'x-pegma-idempotency-key': 'pegma-mail:v1:partition:job:1', + }, + }); + }); + + it('normalizes Queue lifecycle events for a host receipt store', () => { + expect( + parseCloudflareEmailDeliveryEvent({ + type: 'cf.email.sending.message.bounced', + payload: { messageId: 'cf-message-123' }, + metadata: { eventTimestamp: '2026-07-28T16:00:00.000Z' }, + }), + ).toEqual({ + providerMessageRef: 'cf-message-123', + status: 'bounced', + occurredAt: '2026-07-28T16:00:00.000Z', + failureCategory: 'cloudflare_bounced', + }); + }); + + it('does not invoke accessors in untrusted Queue events', () => { + const getter = vi.fn(() => 'cf-message-123'); + const payload = {}; + Object.defineProperty(payload, 'messageId', { get: getter }); + + expect( + parseCloudflareEmailDeliveryEvent({ + type: 'cf.email.sending.message.delivered', + payload, + metadata: { eventTimestamp: '2026-07-28T16:00:00.000Z' }, + }), + ).toBeNull(); + expect(getter).not.toHaveBeenCalled(); + }); + + it.each([ + ['delivered', 'delivered'], + ['complained', 'delivered'], + ['bounced', 'failed'], + ['failed', 'failed'], + ['rejected', 'failed'], + ['deferred', 'unknown'], + ] as const)('reconciles %s as %s', async (status, expected) => { + const ports = createCloudflareEmailMailPorts({ + binding: binding(), + from: 'identity@pegma.dev', + acceptDoubleSendRisk: true, + deliveryStatus: vi.fn(async () => ({ status })), + }); + + await expect( + ports.reconciliation.reconcile({ + idempotencyKey: 'pegma-mail:v1:partition:job:1', + providerMessageRef: 'cf-message-123', + }), + ).resolves.toMatchObject({ status: expected }); + }); + + it('classifies only adapter-owned failures', () => { + expect( + classifyCloudflareEmailFailure( + new CloudflareEmailMailError('provider_retryable'), + ), + ).toBe('provider_retryable'); + expect(classifyCloudflareEmailFailure(new Error('secret'))).toBe( + 'provider_unavailable', + ); + }); + + it.each([ + ['SMTP.RATE-LIMIT/Exceeded', 'cloudflare_smtp_rate_limit_exceeded'], + ['---', 'provider_unavailable'], + ])('normalizes provider code %s as %s', async (code, expected) => { + const email = { + send: vi.fn(async () => { + throw { code }; + }), + } as unknown as SendEmail; + const ports = createCloudflareEmailMailPorts({ + binding: email, + from: 'identity@pegma.dev', + acceptDoubleSendRisk: true, + }); + + await expect( + ports.provider.send({ + idempotencyKey: 'pegma-mail:v1:partition:job:1', + mail: { + recipient: 'person@example.test', + subject: 'Verify', + text: 'Code 12345678', + }, + }), + ).rejects.toMatchObject({ category: expected }); + }); +}); diff --git a/worker/src/cloudflare-email-mail.ts b/worker/src/cloudflare-email-mail.ts new file mode 100644 index 0000000..d145a8d --- /dev/null +++ b/worker/src/cloudflare-email-mail.ts @@ -0,0 +1,250 @@ +import type { + MailProvider, + MailReconciliationPort, +} from '@pegma/identity'; +import type { MailReconciliationRequest, MailSendRequest } from '@pegma/mail'; + +const MESSAGE_REFERENCE = /^[A-Za-z0-9._:@+-]{1,512}$/u; + +export type CloudflareEmailDeliveryStatus = + | 'delivered' + | 'deferred' + | 'bounced' + | 'failed' + | 'rejected' + | 'complained' + | 'unknown'; + +export interface CloudflareEmailDeliveryResult { + readonly status: CloudflareEmailDeliveryStatus; + readonly failureCategory?: string; +} + +export interface CloudflareEmailDeliveryEvent + extends CloudflareEmailDeliveryResult { + readonly providerMessageRef: string; + readonly occurredAt: string; +} + +export class CloudflareEmailMailError extends Error { + constructor(readonly category: string) { + super(category); + this.name = 'CloudflareEmailMailError'; + } +} + +function requireText(value: unknown, name: string, maximum: number): string { + if ( + typeof value !== 'string' || + value.trim().length === 0 || + value.length > maximum || + /[\u0000-\u001F\u007F-\u009F]/u.test(value) + ) { + throw new TypeError(`${name} is invalid`); + } + return value; +} + +function failureCategory(value: unknown, fallback: string): string { + return typeof value === 'string' && /^[a-z][a-z0-9_]{0,63}$/u.test(value) + ? value + : fallback; +} + +function providerCodeCategory(code: string): string { + const normalized = code + .toLowerCase() + .replace(/[^a-z0-9]+/gu, '_') + .replace(/^_+|_+$/gu, ''); + return normalized === '' + ? 'provider_unavailable' + : `cloudflare_${normalized}`.slice(0, 64); +} + +function isObject(value: unknown): value is Record { + try { + return ( + typeof value === 'object' && + value !== null && + !Array.isArray(value) && + Object.getPrototypeOf(value) === Object.prototype + ); + } catch { + return false; + } +} + +function dataProperty(value: unknown, name: string): unknown { + if ( + (typeof value !== 'object' && typeof value !== 'function') || + value === null + ) { + return undefined; + } + try { + const property = Object.getOwnPropertyDescriptor(value, name); + return property !== undefined && Object.hasOwn(property, 'value') + ? property.value + : undefined; + } catch { + return undefined; + } +} + +export function parseCloudflareEmailDeliveryEvent( + value: unknown, +): CloudflareEmailDeliveryEvent | null { + const payload = dataProperty(value, 'payload'); + const metadata = dataProperty(value, 'metadata'); + if (!isObject(payload) || !isObject(metadata)) { + return null; + } + const type = dataProperty(value, 'type'); + const prefix = 'cf.email.sending.message.'; + const status = + typeof type === 'string' && type.startsWith(prefix) + ? type.slice(prefix.length) + : ''; + if ( + status !== 'delivered' && + status !== 'deferred' && + status !== 'bounced' && + status !== 'failed' && + status !== 'rejected' && + status !== 'complained' + ) { + return null; + } + const messageId = dataProperty(payload, 'messageId'); + const timestamp = dataProperty(metadata, 'eventTimestamp'); + if ( + typeof messageId !== 'string' || + !MESSAGE_REFERENCE.test(messageId) || + typeof timestamp !== 'string' + ) { + return null; + } + let occurredAt: string; + try { + occurredAt = new Date(timestamp).toISOString(); + } catch { + return null; + } + return Object.freeze({ + providerMessageRef: messageId, + status, + occurredAt, + ...(status === 'bounced' || + status === 'failed' || + status === 'rejected' + ? { failureCategory: `cloudflare_${status}` } + : {}), + }); +} + +/** + * Cloudflare Email Sending currently has no documented submission + * idempotency contract. The explicit opt-in keeps that double-send risk + * visible at every composition root that chooses this adapter. + */ +export function createCloudflareEmailMailPorts(options: { + readonly binding: SendEmail; + readonly from: string; + readonly acceptDoubleSendRisk: true; + readonly deliveryStatus?: ( + providerMessageRef: string, + ) => Promise; +}): { + readonly provider: MailProvider; + readonly reconciliation: MailReconciliationPort; +} { + if (options.acceptDoubleSendRisk !== true) { + throw new TypeError('Cloudflare Email double-send risk must be accepted'); + } + const from = requireText(options.from, 'Cloudflare Email sender', 512); + + const provider: MailProvider = Object.freeze({ + async send(input: MailSendRequest) { + try { + const result = await options.binding.send({ + to: input.mail.recipient, + from, + subject: input.mail.subject, + text: input.mail.text, + ...(input.mail.html === undefined ? {} : { html: input.mail.html }), + headers: { + ...input.mail.headers, + 'x-pegma-idempotency-key': input.idempotencyKey, + }, + }); + const resultMessageId = dataProperty(result, 'messageId'); + const messageId = + typeof resultMessageId === 'string' && + MESSAGE_REFERENCE.test(resultMessageId) + ? resultMessageId + : null; + if (messageId === null) { + throw new CloudflareEmailMailError('provider_response_invalid'); + } + return { providerMessageRef: messageId }; + } catch (error) { + if (error instanceof CloudflareEmailMailError) throw error; + const errorCode = dataProperty(error, 'code'); + const code = typeof errorCode === 'string' ? errorCode : ''; + if ( + code === 'E_RATE_LIMIT_EXCEEDED' || + code === 'E_DAILY_LIMIT_EXCEEDED' || + code === 'E_INTERNAL_SERVER_ERROR' + ) { + throw new CloudflareEmailMailError('provider_retryable'); + } + throw new CloudflareEmailMailError( + providerCodeCategory(code), + ); + } + }, + }); + + const reconciliation: MailReconciliationPort = Object.freeze({ + async reconcile(input: MailReconciliationRequest) { + if (!MESSAGE_REFERENCE.test(input.providerMessageRef)) { + return { + status: 'failed' as const, + failureCategory: 'provider_reference_invalid', + }; + } + if (options.deliveryStatus === undefined) { + return { status: 'unknown' as const }; + } + const result = await options.deliveryStatus(input.providerMessageRef); + if ( + result.status === 'delivered' || + result.status === 'complained' + ) { + return { status: 'delivered' as const }; + } + if ( + result.status === 'bounced' || + result.status === 'failed' || + result.status === 'rejected' + ) { + return { + status: 'failed' as const, + failureCategory: failureCategory( + result.failureCategory, + `cloudflare_${result.status}`, + ), + }; + } + return { status: 'unknown' as const }; + }, + }); + + return Object.freeze({ provider, reconciliation }); +} + +export function classifyCloudflareEmailFailure(error: unknown): string { + return error instanceof CloudflareEmailMailError + ? error.category + : 'provider_unavailable'; +} diff --git a/worker/src/identity-api.test.ts b/worker/src/identity-api.test.ts index a9ff46e..36c2859 100644 --- a/worker/src/identity-api.test.ts +++ b/worker/src/identity-api.test.ts @@ -312,6 +312,35 @@ describe('identity API security boundary', () => { expect(fixture.identityPort.claimsFor).toHaveBeenCalledWith(principalId); }); + it('protects the generic backend endpoint with the server-side session', async () => { + const fixture = createFixture(); + const anonymous = await fixture.api( + new Request(`${IDENTITY_ISSUER}/api/secure`), + ); + expect(anonymous.status).toBe(401); + expect(await anonymous.json()).toEqual({ + error: 'authentication_required', + }); + + const { cookie } = await signIn(fixture); + const authenticated = await fixture.api( + new Request(`${IDENTITY_ISSUER}/api/secure`, { + headers: { Cookie: cookie }, + }), + ); + + expect(authenticated.status).toBe(200); + expect(authenticated.headers.get('Cache-Control')).toBe('no-store'); + expect(authenticated.headers.get('Vary')).toBe('Cookie'); + expect(await authenticated.json()).toEqual({ + authenticated: true, + issuer: IDENTITY_ISSUER, + subject: principalId, + session: '@pegma/sessions', + }); + expect(fixture.identityPort.claimsFor).toHaveBeenCalledWith(principalId); + }); + it('requires the server-side synchronizer token for account mutation', async () => { const fixture = createFixture(); const { cookie } = await signIn(fixture); diff --git a/worker/src/identity-api.ts b/worker/src/identity-api.ts index 00de3db..8fc613e 100644 --- a/worker/src/identity-api.ts +++ b/worker/src/identity-api.ts @@ -530,6 +530,16 @@ export function createIdentityApi( }); } + if (request.method === 'GET' && path === '/api/secure') { + const authenticated = await requireAuthentication(request, options); + return json({ + authenticated: true, + issuer: authenticated.link.issuer, + subject: authenticated.link.subject, + session: '@pegma/sessions', + }); + } + if (request.method !== 'POST' && request.method !== 'DELETE') { throw new ApiError(404, 'not_found'); } diff --git a/worker/src/identity-runtime.test.ts b/worker/src/identity-runtime.test.ts index 458e37c..92b6556 100644 --- a/worker/src/identity-runtime.test.ts +++ b/worker/src/identity-runtime.test.ts @@ -1,6 +1,10 @@ import { createMemoryStore } from '@pegma/storage-core'; import type { Logger, PrincipalId } from '@pegma/spine'; import { describe, expect, it, vi } from 'vitest'; +import { + classifyCloudflareEmailFailure, + createCloudflareEmailMailPorts, +} from './cloudflare-email-mail'; import { createIdentityRuntime, type IdentityCompositionOptions, @@ -61,6 +65,11 @@ describe('published Identity composition', () => { headers: { Cookie: `__Host-pegma_session=${sessionId}` }, }), ); + const secure = await runtime.api( + new Request('https://pegma.dev/api/secure', { + headers: { Cookie: `__Host-pegma_session=${sessionId}` }, + }), + ); expect(await capabilities.json()).toMatchObject({ passkeys: true, @@ -74,6 +83,13 @@ describe('published Identity composition', () => { }, csrfToken, }); + expect(secure.status).toBe(200); + expect(await secure.json()).toEqual({ + authenticated: true, + issuer: 'https://pegma.dev', + subject: user.principalId, + session: '@pegma/sessions', + }); }); it('commits account-creation Mail before the scheduled provider call', async () => { @@ -109,6 +125,37 @@ describe('published Identity composition', () => { expect(provider).toHaveBeenCalledTimes(1); }); + it('accepts a host-selected provider adapter without changing Identity', async () => { + const send = vi.fn(async () => ({ messageId: 'cf-message-runtime' })); + const ports = createCloudflareEmailMailPorts({ + binding: { send } as unknown as SendEmail, + from: 'identity@pegma.dev', + acceptDoubleSendRisk: true, + }); + const runtime = createIdentityRuntime( + options({ + emailEnabled: true, + mailDelivery: { + ...ports, + classifyFailure: classifyCloudflareEmailFailure, + }, + }), + logger, + ); + + const started = await runtime.api( + mutation('/api/identity/email-code/account/options', { + email: 'cloudflare@example.test', + }), + ); + expect(started.status).toBe(200); + expect(send).not.toHaveBeenCalled(); + + const page = await runtime.mailWorker!.runSendPage({ limit: 100 }); + expect(page.results[0]).toMatchObject({ status: 'accepted' }); + expect(send).toHaveBeenCalledTimes(1); + }); + it('rejects noncanonical or undersized HMAC secrets', () => { expect(() => createIdentityRuntime( diff --git a/worker/src/identity-runtime.ts b/worker/src/identity-runtime.ts index 355249b..a337c5e 100644 --- a/worker/src/identity-runtime.ts +++ b/worker/src/identity-runtime.ts @@ -3,6 +3,8 @@ import { createHmacEmailCodeProtector, createIdentity, type Identity, + type MailProvider, + type MailReconciliationPort, type MailWorker, } from '@pegma/identity'; import { @@ -46,6 +48,11 @@ export interface IdentityCompositionOptions { readonly emailEnabled: boolean; readonly resendApiKey?: string; readonly fetch?: typeof fetch; + readonly mailDelivery?: { + readonly provider: MailProvider; + readonly reconciliation: MailReconciliationPort; + readonly classifyFailure: (error: unknown) => string; + }; } function emailCodeSecret(value: unknown): Uint8Array { @@ -160,30 +167,41 @@ export function createIdentityRuntime( }); const resendKey = - options.emailEnabled && typeof options.resendApiKey === 'string' && options.resendApiKey.length > 0 ? options.resendApiKey : null; + const delivery = + !options.emailEnabled + ? null + : options.mailDelivery ?? + (resendKey === null + ? null + : (() => { + const ports = createResendMailPorts({ + apiKey: resendKey, + from: options.emailFrom, + ...(options.fetch === undefined + ? {} + : { fetch: options.fetch }), + }); + return { + ...ports, + classifyFailure: classifyResendFailure, + }; + })()); const mailWorker = - resendKey === null + delivery === null ? null - : (() => { - const ports = createResendMailPorts({ - apiKey: resendKey, - from: options.emailFrom, - ...(options.fetch === undefined ? {} : { fetch: options.fetch }), - }); - return identity.createMailWorker({ - workerId: 'pegma-dev-identity-mail', - provider: ports.provider, - reconciliation: ports.reconciliation, - renderer: createIdentityMailRenderer(), - leaseMilliseconds: 30_000, - acceptedCallbackMilliseconds: 5 * 60_000, - classifyFailure: classifyResendFailure, - }); - })(); + : identity.createMailWorker({ + workerId: 'pegma-dev-identity-mail', + provider: delivery.provider, + reconciliation: delivery.reconciliation, + renderer: createIdentityMailRenderer(), + leaseMilliseconds: 30_000, + acceptedCallbackMilliseconds: 5 * 60_000, + classifyFailure: delivery.classifyFailure, + }); const emailCodeReady = mailWorker !== null; const sessions = createSessionStore(store, { logger }); const api = createIdentityApi({ diff --git a/worker/src/index.ts b/worker/src/index.ts index f2dd391..2d61b76 100644 --- a/worker/src/index.ts +++ b/worker/src/index.ts @@ -62,7 +62,7 @@ export default { return Response.json(body, { status }); } - if (path.startsWith('/api/identity/')) { + if (path === '/api/secure' || path.startsWith('/api/identity/')) { try { return createProductionIdentityRuntime(env, logger).api(request); } catch (error) { diff --git a/worker/worker-configuration.d.ts b/worker/worker-configuration.d.ts index 6338411..416f64c 100644 --- a/worker/worker-configuration.d.ts +++ b/worker/worker-configuration.d.ts @@ -1,10 +1,10 @@ /* eslint-disable */ -// Generated by Wrangler by running `wrangler types --config=worker/wrangler.jsonc worker/worker-configuration.d.ts` (hash: 21db54365523905c3ae1bbb8924401be) +// Generated by Wrangler by running `wrangler types --config=worker/wrangler.jsonc worker/worker-configuration.d.ts` (hash: 75d6aad1ee166f4faa6212c745e3d48e) // Runtime types generated with workerd@1.20260722.1 2026-07-28 nodejs_compat interface __BaseEnv_Env { IDENTITY_DB: D1Database; IDENTITY_EMAIL_FROM: "Pegma "; - IDENTITY_EMAIL_ENABLED: "false"; + IDENTITY_EMAIL_ENABLED: "true"; } declare namespace Cloudflare { interface GlobalProps { diff --git a/worker/wrangler.jsonc b/worker/wrangler.jsonc index 4b84c39..da8bbc3 100644 --- a/worker/wrangler.jsonc +++ b/worker/wrangler.jsonc @@ -14,7 +14,7 @@ ], "vars": { "IDENTITY_EMAIL_FROM": "Pegma ", - "IDENTITY_EMAIL_ENABLED": "false", + "IDENTITY_EMAIL_ENABLED": "true", }, "triggers": { "crons": ["* * * * *"],