Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
33 changes: 19 additions & 14 deletions docs/PROJECT_PLAN.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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

Expand Down Expand Up @@ -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.**
12 changes: 12 additions & 0 deletions public/account.js
Original file line number Diff line number Diff line change
Expand Up @@ -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 = '';
Expand Down Expand Up @@ -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: '{}' });
Expand Down
4 changes: 4 additions & 0 deletions src/pages/account.astro
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,10 @@ import Base from '../layouts/Base.astro';
<button id="sign-out" class="secondary-button" type="button">Sign out</button>
</div>

<h3>Backend session</h3>
<p>Call a protected Worker endpoint that resolves this browser session through @pegma/sessions.</p>
<button id="test-secure-api" class="secondary-button" type="button">Test secure API</button>

<h3>Passkeys</h3>
<ul id="passkey-list" class="passkey-list"></ul>
<form id="add-passkey" class="account-form">
Expand Down
61 changes: 60 additions & 1 deletion worker/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand All @@ -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
Expand Down Expand Up @@ -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 <identity@pegma.dev>` 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.
Expand Down
181 changes: 181 additions & 0 deletions worker/src/azure-acs-mail.test.ts
Original file line number Diff line number Diff line change
@@ -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<typeof fetch>();
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<typeof fetch>()),
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<typeof fetch>(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<typeof fetch>(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',
);
});
});
Loading