From dfcfaa25228df157a7b1d56b52599f3f38b38fa3 Mon Sep 17 00:00:00 2001 From: Daniel Naab Date: Fri, 4 Dec 2026 11:28:04 -0600 Subject: [PATCH 01/10] docs(story-142): design for access request contact details and approval email Pot-Run: 7979 --- notes/flight-board.md | 1 + .../design.md | 200 ++++++++++++++++++ 2 files changed, 201 insertions(+) create mode 100644 notes/story-142-access-request-contact-details/design.md diff --git a/notes/flight-board.md b/notes/flight-board.md index 2652bac7a..5b90ced19 100644 --- a/notes/flight-board.md +++ b/notes/flight-board.md @@ -6,6 +6,7 @@ |-------|--------|--------|----------|---------| | #9 Carlos completes complex sections through conversation | story-9/conversational-sections | in-progress | .worktrees/story-9-conversational-sections | 2026-04-18 | | #9 UX fixes (live field updates, loading, context) | story-9/ux-fixes | pr-open ([#83](https://github.com/flexion/forms-lab/pull/83)) | main repo checkout | 2026-04-19 | +| #142 Capture requester contact details and email approval notifications | story-142/access-request-contact-details | in-progress | .worktrees/story-142-access-request-contact-details | 2026-12-04 | ## Landed diff --git a/notes/story-142-access-request-contact-details/design.md b/notes/story-142-access-request-contact-details/design.md new file mode 100644 index 000000000..0fc50fed5 --- /dev/null +++ b/notes/story-142-access-request-contact-details/design.md @@ -0,0 +1,200 @@ +--- +status: working +--- + +# Story #142 — Capture requester contact details and email approval notifications + +Issue: https://github.com/flexion/forms-lab/issues/142 + +## Problem + +Outside users request access with one button. The app keeps only their GitHub +login, display name and avatar, and approving them notifies no one. The admin +has no way to reach a requester and the requester never learns they are in. + +## Decisions + +1. **Save what GitHub gives us at every sign-in, for every user.** The callback + already fetches `/user` and (for non-env users) `/user/emails`. We fetch + emails once, for all users, and persist both. Users who are not yet in the + table get their details on their next sign-in; no backfill. +2. **Allowlist profile fields; don't store the raw `/user` payload.** With the + `read:user` scope `/user` also returns account-internal data (plan, + 2FA status, disk usage, private repo counts) that is not contact + information. We store the public, person-describing fields only: + `id`, `name`, `company`, `location`, `blog`, `bio`, `email` (public email), + `twitter_username`, `html_url`, `created_at`. +3. **All emails, with their flags.** One row per address: `email`, `primary`, + `verified`, `visibility`. Replaced wholesale on each sign-in so removed + addresses disappear. +4. **One casual, optional free-text note** on the request-access page, + stored on the access request. Max 1000 characters (server truncates). +5. **Email is a separate service from Slack notifications.** Ops alerts go + through the notify server to Slack; mail to users is a different audience + and owner. New `src/services/email/` with an `EmailSender` interface. + **The AWS SES SDK (`@aws-sdk/client-sesv2`) is isolated** to one file in + that service (P2 dependency choice: isolate). +6. **Approval sends the email synchronously** in the approve request, then + records the outcome on the access entry, so the admin page can say + "email sent" or "not sent: ". A failed send never blocks approval. +7. **Unconfigured email is a normal state.** With no `EMAIL_FROM`, the app + uses a logging sender that sends nothing and reports `not configured`. + Dev, tests and branch deployments work without SES. +8. **Only `main` sends mail.** Branch deployments omit `EMAIL_FROM`. +9. **Slack text from users is escaped.** The note, name and company are + user-controlled; escape `&`, `<`, `>` in the Slack formatter so they can't + produce `` pings or disguised links. + +## Data model (auth service owns all of it — P3) + +`users` table — add nullable columns with an idempotent migration +(`ALTER TABLE ... ADD COLUMN` only when missing, checked via +`PRAGMA table_info`): + +| column | from GitHub | +|---|---| +| github_id INTEGER | `id` | +| company TEXT | `company` | +| location TEXT | `location` | +| blog TEXT | `blog` | +| bio TEXT | `bio` | +| public_email TEXT | `email` | +| twitter_username TEXT | `twitter_username` | +| html_url TEXT | `html_url` | +| github_created_at TEXT | `created_at` (ISO string) | + +New table `user_emails`: + +```sql +CREATE TABLE IF NOT EXISTS user_emails ( + login TEXT NOT NULL, + email TEXT NOT NULL, + is_primary INTEGER NOT NULL, + verified INTEGER NOT NULL, + visibility TEXT, + updated_at INTEGER NOT NULL, + PRIMARY KEY (login, email) +) +``` + +`user_access` — add nullable columns: `note TEXT`, +`approval_email_sent_at INTEGER`, `approval_email_error TEXT`. + +### Interfaces + +```ts +// services/auth +interface GitHubUser { login; name: string | null; avatar_url; id?; company?; location?; + blog?; bio?; email?; twitter_username?; html_url?; created_at? } // all extra fields nullable + +interface UserProfile { ...existing; githubId, company, location, blog, bio, publicEmail, + twitterUsername, htmlUrl, githubCreatedAt: string | number | null; emails: UserEmail[] } +interface UserEmail { email: string; primary: boolean; verified: boolean; visibility: string | null } + +interface UserStore { + upsert(user: {...existing}): void // unchanged, still used + saveGitHubProfile(ghUser: GitHubUser, emails: GitHubEmail[]): void // profile + replace emails + get(login): UserProfile | null // now includes details + emails + exists(login): boolean +} +/** Primary verified email, else first verified, else null. */ +function contactEmail(profile: UserProfile): string | null + +interface AccessEntry { ...existing; note: string | null; + approvalEmailSentAt: number | null; approvalEmailError: string | null } +interface AccessStore { ...existing; + requestAccess(login: string, note?: string | null): void + recordApprovalEmail(login: string, result: { sentAt: number } | { error: string }): void } + +// services/email +interface EmailMessage { to: string; subject: string; text: string; html: string } +type EmailResult = { ok: true } | { ok: false; error: string } +interface EmailSender { readonly configured: boolean; send(m: EmailMessage): Promise } +function createSesEmailSender(opts: { from: string; region: string }): EmailSender +function createLoggingEmailSender(): EmailSender // configured=false, ok:false 'email not configured' +function createEmailSenderFromEnv(env): EmailSender +function renderAccessApprovedEmail(input: { name: string; login: string; + deploymentUrl: string; deploymentName: string }): Omit +``` + +`notes/` on fields: `name` on GitHub can be null; keep falling back to login. + +## Flows + +**Sign-in (`/auth/callback`)**: fetch profile → fetch emails once (all users; +on failure `[]`) → existing three-layer authorization unchanged, but reusing +the fetched emails → `userStore.saveGitHubProfile(ghUser, emails)` wherever +`upsert` is called today (both the new-requester branch and the final +persist). + +**Request access (`POST /auth/request-access`)**: read optional `note` form +field, trim, cap 1000 chars, empty → null → `accessStore.requestAccess(login, +note)`. Slack `access.requested` details gain: contact email (or "no verified +email"), company if set, the note if set. + +**Request page copy** (casual, optional, encourages submitting): + +> **Tell us a little about yourself** (optional) +> Where you work, who sent you our way, what you'd like to try — whatever +> helps us say yes faster. + +Textarea `name="note"`, `maxlength="1000"`, properly labelled; button stays +"Request Access". + +**Approve (`POST /admin/users/approve`)**: approve → look up profile → +`contactEmail` → if none, record error `no verified email on file`; +otherwise render + send → record `sentAt` or `error`. Redirect as today. +Deployment URL = external origin + `resolveUrl('/')`; deployment name from +base path (same logic as the access-request notification). + +**Admin page**: pending and approved rows show the contact email +(as `mailto:`), other emails with primary/verified flags, company, +location, profile link, and the note. Approved rows show +"Approval email sent " or "Approval email not sent: ". +Presentation stays stateless (P4): the route computes display data. + +## Infrastructure + +- Pulumi: `aws.sesv2.EmailIdentity` for the domain (when `domain` is + configured) with the three DKIM CNAME records in the existing Route53 + zone; `RolePolicy` granting `ses:SendEmail` on that identity. +- SES sandbox exit is a manual AWS support request — documented, not + automated. Until then, mail only reaches verified recipients. +- `deploy.nix`: write `EMAIL_FROM="Forms Lab "` into + `.env` only when `BRANCH = main`. (Branch apps stay unconfigured.) +- `.env.example`: document `EMAIL_FROM`. + +## Security / threat model + +New section "Hono application to SES (outbound email)" and updates to +"Browser to Hono application (authentication)": + +- New personal data at rest (emails, profile, free-text note) in the + per-deployment SQLite DB. Retention for denied/revoked users is not yet + defined — residual risk, follow-up. +- Free text from unauthenticated-but-signed-in users: rendered via JSX + (auto-escaped) on the admin page; escaped for Slack mrkdwn; plain text + + escaped HTML in email (the note is never put in outbound mail). +- Email recipient is always the stored *verified* address, never a + form-supplied one, so the approve action can't be used to mail arbitrary + people. Content is a fixed template. +- IAM grant is scoped to the one SES identity. + +## Out of scope + +- Denial emails, digest/reminder emails, retention job, backfill of + existing users, editing the note after submission. + +## Testing + +- Unit: user-store migration on an old-schema DB, `saveGitHubProfile` + round-trip, email replacement, `contactEmail` precedence; access-store + note + approval-email recording + migration; email template; logging + sender; SES sender with injected client (no network); Slack escaping. +- Route: callback persists profile + emails for env, domain and requester + paths; request-access stores trimmed/capped note and includes details in + the notification; approve sends to the contact email, records success, + records failure without blocking approval, handles no-email. +- Admin page renders details, flags and email status. +- Architecture test passes (new `email` service imported only via its + `index.ts`). From cbeebbb5842307320259a19c96d30e22b4440659 Mon Sep 17 00:00:00 2001 From: Daniel Naab Date: Fri, 4 Dec 2026 11:33:19 -0600 Subject: [PATCH 02/10] feat(email): add email service with SES sender and access-approved template Isolates @aws-sdk/client-sesv2 to services/email/ses-sender.ts. Falls back to a logging sender when EMAIL_FROM is unset. Pulumi adds an SES domain identity with DKIM records and a send-only role policy; main's .env gets EMAIL_FROM. Refs #142 Pot-Run: 7979 --- .env.example | 6 + CLAUDE.md | 1 + bun.lock | 13 ++ catalog/architecture/deployment.md | 35 +++- catalog/architecture/software-architecture.md | 3 +- infrastructure/nixos/modules/deploy.nix | 6 + infrastructure/pulumi/index.ts | 46 +++++ package.json | 1 + src/services/email/access-approved-email.ts | 55 ++++++ src/services/email/from-env.ts | 20 ++ src/services/email/index.ts | 9 + src/services/email/logging-sender.ts | 17 ++ src/services/email/ses-sender.ts | 71 ++++++++ src/services/email/types.ts | 16 ++ .../email/access-approved-template.test.ts | 53 ++++++ test/services/email/senders.test.ts | 171 ++++++++++++++++++ 16 files changed, 520 insertions(+), 3 deletions(-) create mode 100644 src/services/email/access-approved-email.ts create mode 100644 src/services/email/from-env.ts create mode 100644 src/services/email/index.ts create mode 100644 src/services/email/logging-sender.ts create mode 100644 src/services/email/ses-sender.ts create mode 100644 src/services/email/types.ts create mode 100644 test/services/email/access-approved-template.test.ts create mode 100644 test/services/email/senders.test.ts diff --git a/.env.example b/.env.example index f4b337129..5d0efd293 100644 --- a/.env.example +++ b/.env.example @@ -11,3 +11,9 @@ AWS_BEDROCK_REGION=us-west-2 # Leaving both unset defaults to ALLOWED_USERS=danielnaab. ALLOWED_USERS=danielnaab ALLOWED_EMAIL_DOMAINS=flexion.us +# Outbound email to users (e.g. "your access was approved"), sent via +# Amazon SES using the default AWS credential chain and AWS_REGION. +# Leave unset in dev: emails are then logged (recipient + subject only), +# not sent, and the admin page reports "email not configured". +# Only the main deployment sets this on the server. +# EMAIL_FROM="Forms Lab " diff --git a/CLAUDE.md b/CLAUDE.md index 00054a039..737b591fc 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -249,6 +249,7 @@ Follows [meta-knowledge-base](https://github.com/danielnaab/meta-knowledge-base) - `src/services/auth/` — Authentication, sessions, user store (GitHub OAuth) - `src/services/deployment/` — Deploy orchestration and metadata - `src/services/notifications/` — Notification types and client +- `src/services/email/` — Outbound email to users (SES sender, logging fallback, templates) - `src/services/content/` — Content rendering (markdown, github-permalink, catalog types) - `src/services/storage/` — Persistence layer (SQLite project + cache stores) - `src/services/variant-preferences/` — Per-user variant selection diff --git a/bun.lock b/bun.lock index dc559dbb5..da836ccdf 100644 --- a/bun.lock +++ b/bun.lock @@ -6,6 +6,7 @@ "name": "forms-lab", "dependencies": { "@ai-sdk/amazon-bedrock": "^4.0.92", + "@aws-sdk/client-sesv2": "^3.1029.0", "@aws-sdk/credential-providers": "^3.1029.0", "@dagrejs/dagre": "^3.0.0", "ai": "^6.0.156", @@ -54,6 +55,8 @@ "@aws-sdk/client-cognito-identity": ["@aws-sdk/client-cognito-identity@3.1029.0", "", { "dependencies": { "@aws-crypto/sha256-browser": "5.2.0", "@aws-crypto/sha256-js": "5.2.0", "@aws-sdk/core": "^3.973.27", "@aws-sdk/credential-provider-node": "^3.972.30", "@aws-sdk/middleware-host-header": "^3.972.9", "@aws-sdk/middleware-logger": "^3.972.9", "@aws-sdk/middleware-recursion-detection": "^3.972.10", "@aws-sdk/middleware-user-agent": "^3.972.29", "@aws-sdk/region-config-resolver": "^3.972.11", "@aws-sdk/types": "^3.973.7", "@aws-sdk/util-endpoints": "^3.996.6", "@aws-sdk/util-user-agent-browser": "^3.972.9", "@aws-sdk/util-user-agent-node": "^3.973.15", "@smithy/config-resolver": "^4.4.14", "@smithy/core": "^3.23.14", "@smithy/fetch-http-handler": "^5.3.16", "@smithy/hash-node": "^4.2.13", "@smithy/invalid-dependency": "^4.2.13", "@smithy/middleware-content-length": "^4.2.13", "@smithy/middleware-endpoint": "^4.4.29", "@smithy/middleware-retry": "^4.5.0", "@smithy/middleware-serde": "^4.2.17", "@smithy/middleware-stack": "^4.2.13", "@smithy/node-config-provider": "^4.3.13", "@smithy/node-http-handler": "^4.5.2", "@smithy/protocol-http": "^5.3.13", "@smithy/smithy-client": "^4.12.9", "@smithy/types": "^4.14.0", "@smithy/url-parser": "^4.2.13", "@smithy/util-base64": "^4.3.2", "@smithy/util-body-length-browser": "^4.2.2", "@smithy/util-body-length-node": "^4.2.3", "@smithy/util-defaults-mode-browser": "^4.3.45", "@smithy/util-defaults-mode-node": "^4.2.49", "@smithy/util-endpoints": "^3.3.4", "@smithy/util-middleware": "^4.2.13", "@smithy/util-retry": "^4.3.0", "@smithy/util-utf8": "^4.2.2", "tslib": "^2.6.2" } }, "sha512-wmQpZI+DweZ8mKGvkGXZFLxgyR2PoSqsnSvS8wHEuq9U282eD91zfkFsTK+rgQZK+ZYuCKwlBTjHbKKlQiJEjw=="], + "@aws-sdk/client-sesv2": ["@aws-sdk/client-sesv2@3.1029.0", "", { "dependencies": { "@aws-crypto/sha256-browser": "5.2.0", "@aws-crypto/sha256-js": "5.2.0", "@aws-sdk/core": "^3.973.27", "@aws-sdk/credential-provider-node": "^3.972.30", "@aws-sdk/middleware-host-header": "^3.972.9", "@aws-sdk/middleware-logger": "^3.972.9", "@aws-sdk/middleware-recursion-detection": "^3.972.10", "@aws-sdk/middleware-user-agent": "^3.972.29", "@aws-sdk/region-config-resolver": "^3.972.11", "@aws-sdk/signature-v4-multi-region": "^3.996.16", "@aws-sdk/types": "^3.973.7", "@aws-sdk/util-endpoints": "^3.996.6", "@aws-sdk/util-user-agent-browser": "^3.972.9", "@aws-sdk/util-user-agent-node": "^3.973.15", "@smithy/config-resolver": "^4.4.14", "@smithy/core": "^3.23.14", "@smithy/fetch-http-handler": "^5.3.16", "@smithy/hash-node": "^4.2.13", "@smithy/invalid-dependency": "^4.2.13", "@smithy/middleware-content-length": "^4.2.13", "@smithy/middleware-endpoint": "^4.4.29", "@smithy/middleware-retry": "^4.5.0", "@smithy/middleware-serde": "^4.2.17", "@smithy/middleware-stack": "^4.2.13", "@smithy/node-config-provider": "^4.3.13", "@smithy/node-http-handler": "^4.5.2", "@smithy/protocol-http": "^5.3.13", "@smithy/smithy-client": "^4.12.9", "@smithy/types": "^4.14.0", "@smithy/url-parser": "^4.2.13", "@smithy/util-base64": "^4.3.2", "@smithy/util-body-length-browser": "^4.2.2", "@smithy/util-body-length-node": "^4.2.3", "@smithy/util-defaults-mode-browser": "^4.3.45", "@smithy/util-defaults-mode-node": "^4.2.49", "@smithy/util-endpoints": "^3.3.4", "@smithy/util-middleware": "^4.2.13", "@smithy/util-retry": "^4.3.0", "@smithy/util-utf8": "^4.2.2", "tslib": "^2.6.2" } }, "sha512-ZL2E13IaLQjevcL9nHqT7Jf8EeYfDhgwNyuOh1bp/2ECga+0BzJaHKiASZdvBCZHV+cCDqH3SiGKePUMOxakYA=="], + "@aws-sdk/core": ["@aws-sdk/core@3.973.27", "", { "dependencies": { "@aws-sdk/types": "^3.973.7", "@aws-sdk/xml-builder": "^3.972.17", "@smithy/core": "^3.23.14", "@smithy/node-config-provider": "^4.3.13", "@smithy/property-provider": "^4.2.13", "@smithy/protocol-http": "^5.3.13", "@smithy/signature-v4": "^5.3.13", "@smithy/smithy-client": "^4.12.9", "@smithy/types": "^4.14.0", "@smithy/util-base64": "^4.3.2", "@smithy/util-middleware": "^4.2.13", "@smithy/util-utf8": "^4.2.2", "tslib": "^2.6.2" } }, "sha512-CUZ5m8hwMCH6OYI4Li/WgMfIEx10Q2PLI9Y3XOUTPGZJ53aZ0007jCv+X/ywsaERyKPdw5MRZWk877roQksQ4A=="], "@aws-sdk/credential-provider-cognito-identity": ["@aws-sdk/credential-provider-cognito-identity@3.972.22", "", { "dependencies": { "@aws-sdk/nested-clients": "^3.996.19", "@aws-sdk/types": "^3.973.7", "@smithy/property-provider": "^4.2.13", "@smithy/types": "^4.14.0", "tslib": "^2.6.2" } }, "sha512-ih6ORpme4i2qJqGckOQ9Lt2iiZ+5tm3bnfsT5TwoPyFnuDURXv3OdhYa3Nr/m0iJr38biqKYKdGKb5GR1KB2hw=="], @@ -88,6 +91,8 @@ "@aws-sdk/region-config-resolver": ["@aws-sdk/region-config-resolver@3.972.11", "", { "dependencies": { "@aws-sdk/types": "^3.973.7", "@smithy/config-resolver": "^4.4.14", "@smithy/node-config-provider": "^4.3.13", "@smithy/types": "^4.14.0", "tslib": "^2.6.2" } }, "sha512-6Q8B1dcx6BBqUTY1Mc/eROKA0FImEEY5VPSd6AGPEUf0ErjExz4snVqa9kNJSoVDV1rKaNf3qrWojgcKW+SdDg=="], + "@aws-sdk/signature-v4-multi-region": ["@aws-sdk/signature-v4-multi-region@3.996.52", "", { "dependencies": { "@aws-sdk/types": "^3.975.1", "@smithy/signature-v4": "^5.7.5", "@smithy/types": "^4.20.0", "tslib": "^2.6.2" } }, "sha512-6W6SjGc8OXUhMzNxU1X922ghD+PP1XvzmCk5Scui0jaYsLezycMYR1RaLp5xTIOUrhTXyb4DnAbPr3fBgmdnzg=="], + "@aws-sdk/token-providers": ["@aws-sdk/token-providers@3.1026.0", "", { "dependencies": { "@aws-sdk/core": "^3.973.27", "@aws-sdk/nested-clients": "^3.996.19", "@aws-sdk/types": "^3.973.7", "@smithy/property-provider": "^4.2.13", "@smithy/shared-ini-file-loader": "^4.4.8", "@smithy/types": "^4.14.0", "tslib": "^2.6.2" } }, "sha512-Ieq/HiRrbEtrYP387Nes0XlR7H1pJiJOZKv+QyQzMYpvTiDs0VKy2ZB3E2Zf+aFovWmeE7lRE4lXyF7dYM6GgA=="], "@aws-sdk/types": ["@aws-sdk/types@3.973.7", "", { "dependencies": { "@smithy/types": "^4.14.0", "tslib": "^2.6.2" } }, "sha512-reXRwoJ6CfChoqAsBszUYajAF8Z2LRE+CRcKocvFSMpIiLOtYU3aJ9trmn6VVPAzbbY5LXF+FfmUslbXk1SYFg=="], @@ -562,6 +567,12 @@ "@aws-crypto/util/@smithy/util-utf8": ["@smithy/util-utf8@2.3.0", "", { "dependencies": { "@smithy/util-buffer-from": "^2.2.0", "tslib": "^2.6.2" } }, "sha512-R8Rdn8Hy72KKcebgLiv8jQcQkXoLMOGGv5uI1/k0l+snqkOzQ1R0ChUBCxWMlBsFMekWjq0wRudIweFs7sKT5A=="], + "@aws-sdk/signature-v4-multi-region/@aws-sdk/types": ["@aws-sdk/types@3.975.1", "", { "dependencies": { "@smithy/types": "^4.20.0", "tslib": "^2.6.2" } }, "sha512-7rGxUkCB2QPoQOeJmonmAICTN2zrH+fpmi1p4Iwu72lnxNaMhOgqcbpyddifnM1DBb19TWQ1u6z/XjkaFNEDWw=="], + + "@aws-sdk/signature-v4-multi-region/@smithy/signature-v4": ["@smithy/signature-v4@5.7.6", "", { "dependencies": { "@smithy/core": "^3.42.0", "@smithy/types": "^4.21.0", "tslib": "^2.6.2" } }, "sha512-pUD4rYByPT0JzealoFbIO5XkyeJxYjrXCjMAdKL16pOKH4aVIY3PnD3RUfWrHv0/NLxQDV4r/uS6RVDdB3sANw=="], + + "@aws-sdk/signature-v4-multi-region/@smithy/types": ["@smithy/types@4.21.0", "", { "dependencies": { "tslib": "^2.6.2" } }, "sha512-4zXqqxCPZFUQ5ByaqaCrMCiaKo2aJ7df05sVEy+hdWMtDzNXIkPoy8S0ZpgYZSrBAii/3YtLAAkfq92lNeEd0g=="], + "happy-dom/entities": ["entities@7.0.1", "", {}, "sha512-TWrgLOFUQTH994YUyl1yT4uyavY5nNB5muff+RtWaqNVCAK408b5ZnnbNAUEWLTCpum9w6arT70i1XdQ4UeOPA=="], "pdf-lib/tslib": ["tslib@1.14.1", "", {}, "sha512-Xni35NKzjgMrwevysHTCArtLDpPvye8zV/0E4EyYn43P7/7qvQwPh9BGkHewbMulVntbigmcT7rdX3BNo9wRJg=="], @@ -576,6 +587,8 @@ "@aws-crypto/util/@smithy/util-utf8/@smithy/util-buffer-from": ["@smithy/util-buffer-from@2.2.0", "", { "dependencies": { "@smithy/is-array-buffer": "^2.2.0", "tslib": "^2.6.2" } }, "sha512-IJdWBbTcMQ6DA0gdNhh/BwrLkDR+ADW5Kr1aZmd4k3DIF6ezMV4R2NIAmT08wQJ3yUK82thHWmC/TnK/wpMMIA=="], + "@aws-sdk/signature-v4-multi-region/@smithy/signature-v4/@smithy/core": ["@smithy/core@3.42.0", "", { "dependencies": { "@smithy/types": "^4.21.0", "tslib": "^2.6.2" } }, "sha512-qyh3zXvxCWOLWa6cyQEsyEDDIwUoBExz6cp5Aj2LOwbO3mgrFB8POL0wggbCXRrUt7gRDkgmVH3w2TP/UBiuFA=="], + "table/strip-ansi/ansi-regex": ["ansi-regex@5.0.1", "", {}, "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ=="], "@aws-crypto/sha256-browser/@smithy/util-utf8/@smithy/util-buffer-from/@smithy/is-array-buffer": ["@smithy/is-array-buffer@2.2.0", "", { "dependencies": { "tslib": "^2.6.2" } }, "sha512-GGP3O9QFD24uGeAXYUjwSTXARoqpZykHadOmA8G5vfJPK0/DC67qa//0qvqrJzL1xc8WQWX7/yc7fwudjPHPhA=="], diff --git a/catalog/architecture/deployment.md b/catalog/architecture/deployment.md index d372f431b..15db9782b 100644 --- a/catalog/architecture/deployment.md +++ b/catalog/architecture/deployment.md @@ -25,7 +25,7 @@ A single EC2 instance hosts all branch deployments. GitHub push webhooks trigger | Component | Location | Role | |-----------|----------|------| -| Pulumi project | `infrastructure/pulumi/` | Provisions EC2, EIP, security group | +| Pulumi project | `infrastructure/pulumi/` | Provisions EC2, EIP, security group, DNS, SES email identity | | NixOS config | `infrastructure/nixos/` | Declares entire server state | | Webhook listener | `src/webhook/` | Receives GitHub push events | | Deploy script | `infrastructure/nixos/modules/deploy.nix` | Builds and deploys branches | @@ -52,6 +52,37 @@ bun run cli nixos status # Check running services bun run cli webhook setup # GitHub webhook configuration ``` +## Outbound email + +The `main` deployment emails users when an admin approves their access +request (`src/services/email/`, Amazon SES). Branch deployments never send +mail: `deploy.nix` writes `EMAIL_FROM` into `.env` only for `main`, and +without it the app logs instead of sending. + +Pulumi provisions, when `domain` is configured: an SES domain identity, +the three Easy DKIM CNAME records in the hosted zone, and an instance-role +policy allowing `ses:SendEmail` on that identity only. + +Manual steps (not automated): + +1. **Check DKIM verification.** After `bun run cli infra up`, confirm the + records resolve and SES sees them: + ```bash + dig +short CNAME ._domainkey. # tokens: aws sesv2 get-email-identity --email-identity + aws sesv2 get-email-identity --email-identity \ + --query '{dkim: DkimAttributes.Status, sending: VerifiedForSendingStatus}' + ``` + Expect `dkim: SUCCESS` and `sending: true`. This can take up to 72 hours + after the records first resolve, and requires the domain's NS + delegation to point at the Pulumi hosted zone (`nameServers` output). +2. **Leave the SES sandbox.** New AWS accounts start in the SES sandbox, + where mail is delivered only to verified addresses and sends from the + app to anyone else fail (the admin page shows the error). Request + production access in the SES console (Account dashboard → Request + production access) for the region in `AWS_REGION`. Until AWS grants it, + treat approval emails as best-effort; check the account status with + `aws sesv2 get-account --query ProductionAccessEnabled`. + ## Sources - [EC2 with Pulumi](../decisions/infrastructure/ec2-with-pulumi.md) @@ -59,4 +90,4 @@ bun run cli webhook setup # GitHub webhook configuration - [GitHub webhook deploys](../decisions/infrastructure/github-webhook-deploys.md) - [Subpath routing](../decisions/infrastructure/subpath-routing.md) - [Nix-built processes](../decisions/infrastructure/nix-built-processes.md) -- Canonical code: `infrastructure/pulumi/`, `infrastructure/nixos/`, `src/webhook/` +- Canonical code: `src/services/email/`, `infrastructure/pulumi/`, `infrastructure/nixos/`, `src/webhook/` diff --git a/catalog/architecture/software-architecture.md b/catalog/architecture/software-architecture.md index 3feab02bd..8b35c0083 100644 --- a/catalog/architecture/software-architecture.md +++ b/catalog/architecture/software-architecture.md @@ -85,6 +85,7 @@ Core domain services. Each service directory has a `types.ts` (P3) and one or mo - **`deployment/`** — GitHub API client and deployment metadata (branch state, commit info, PR status). - **`forms/`** — Form resolution, validation, navigation, sessions, and submission. Internally contains sub-modules (`comparison/`, `filling-agent/`, `filling/`, `review/`, `shaping/`) that are implementation details; external callers see only the public interface at `services/forms/index.ts`. Shaping uses LLM-assisted commands with an atomic batch executor; each accepted batch produces one git commit plus a structured entry in the shaping log. See the [command-based shaping decision](../decisions/architecture/command-based-shaping.md). - **`form-documents/`** — PDF → structured spec extraction pipeline. Uses Bedrock (Claude) to parse PDFs into `DataCollectionSpec`s, plus AcroForm field mapping and filling. +- **`email/`** — Outbound email to users (e.g. "your access was approved"). `EmailSender` interface with an Amazon SES implementation and a logging stand-in used when `EMAIL_FROM` is unset. Separate from `notifications/`, which alerts operators via Slack. - **`evaluation/`** — Evaluation harness and LLM-as-judge kinds for scoring extraction and shaping output against fixtures. - **`extraction/`** — Pluggable PDF extractor registry, enabling variant selection for evaluation and deployment. - **`notifications/`** — Notification event types and Slack client used by the deploy pipeline. @@ -139,7 +140,7 @@ Neither choice is wrong. What matters is that the choice is explicit. Drifting i **Current state:** -- **Isolated:** USWDS (design-system only), Bedrock (`services/form-documents/`, `services/forms/shaping/`, `services/forms/filling-agent/`, `services/evaluation/` only), AI SDK tool-use (`services/form-documents/` and `services/forms/shaping/` only), `bun:sqlite` (`services/storage/`, `services/auth/user-store.ts` only), git CLI (`services/projects/form-project-repo.ts` only), `markdown-it` (`services/content/markdown.ts` only) +- **Isolated:** USWDS (design-system only), Bedrock (`services/form-documents/`, `services/forms/shaping/`, `services/forms/filling-agent/`, `services/evaluation/` only), AI SDK tool-use (`services/form-documents/` and `services/forms/shaping/` only), `bun:sqlite` (`services/storage/`, `services/auth/user-store.ts` only), git CLI (`services/projects/form-project-repo.ts` only), `markdown-it` (`services/content/markdown.ts` only), AWS SES SDK `@aws-sdk/client-sesv2` (`services/email/ses-sender.ts` only) - **Embraced:** `hono/jsx` (design-system components), Hono routing (entrypoints), Bun (runtime) When adding a new dependency, note the choice in the commit or ADR that introduces it. Future axes of change are cheaper to plan for when they're visible. diff --git a/infrastructure/nixos/modules/deploy.nix b/infrastructure/nixos/modules/deploy.nix index a21932672..ca0ce13bc 100644 --- a/infrastructure/nixos/modules/deploy.nix +++ b/infrastructure/nixos/modules/deploy.nix @@ -212,6 +212,12 @@ AWS_REGION=us-east-1 CACHE_DB_PATH=/srv/forms-lab/cache.sqlite REPOS_PATH=/srv/forms-lab/repos ENVEOF + # Only main sends email to users (SES identity for the hostname is + # provisioned by Pulumi). Branch apps leave EMAIL_FROM unset, so they + # use the logging sender and send nothing. + if [ "$BRANCH" = "main" ]; then + echo 'EMAIL_FROM="Forms Lab "' >> "$BRANCH_DIR/.env" + fi ${pkgs.coreutils}/bin/chmod 600 "$BRANCH_DIR/.env" # Start or restart the service (use full path to sudo wrapper with setuid bit) diff --git a/infrastructure/pulumi/index.ts b/infrastructure/pulumi/index.ts index 6cecdd513..40b7b3682 100644 --- a/infrastructure/pulumi/index.ts +++ b/infrastructure/pulumi/index.ts @@ -173,6 +173,49 @@ if (domain) { }) } +// Outbound email via SES (only when domain is configured). +// The app sends approval emails from noreply@ (see EMAIL_FROM in +// infrastructure/nixos/modules/deploy.nix). Easy DKIM: SES generates three +// tokens; each becomes a CNAME in the hosted zone. New accounts start in the +// SES sandbox — leaving it is a manual support request (see +// catalog/architecture/deployment.md, "Outbound email"). +let emailIdentity: aws.sesv2.EmailIdentity | undefined +if (domain && zone) { + const hostedZone = zone + emailIdentity = new aws.sesv2.EmailIdentity('forms-lab-email', { + emailIdentity: domain, + tags: { Name: 'forms-lab' }, + }) + + const dkimTokens = emailIdentity.dkimSigningAttributes.tokens + for (let i = 0; i < 3; i++) { + const token = dkimTokens.apply((tokens) => tokens[i]) + new aws.route53.Record(`forms-lab-dkim-${i}`, { + zoneId: hostedZone.zoneId, + name: pulumi.interpolate`${token}._domainkey.${domain}`, + type: 'CNAME', + ttl: 1800, + records: [pulumi.interpolate`${token}.dkim.amazonses.com`], + }) + } + + new aws.iam.RolePolicy('forms-lab-ses-send', { + role: role.id, + policy: emailIdentity.arn.apply((identityArn) => + JSON.stringify({ + Version: '2012-10-17', + Statement: [ + { + Effect: 'Allow', + Action: ['ses:SendEmail'], + Resource: [identityArn], + }, + ], + }), + ), + }) +} + // Outputs export const instanceId = instance.id export const publicIp = eip.publicIp @@ -180,3 +223,6 @@ export const hostname = eip.publicDns export const sshCommand = pulumi.interpolate`ssh root@${eip.publicDns}` export const nameServers = zone?.nameServers export const domainName = domain +export const emailIdentityArn = emailIdentity?.arn +export const emailSendingDomain = emailIdentity?.emailIdentity +export const emailDkimStatus = emailIdentity?.dkimSigningAttributes.status diff --git a/package.json b/package.json index a9828e56d..e462021e0 100644 --- a/package.json +++ b/package.json @@ -22,6 +22,7 @@ }, "dependencies": { "@ai-sdk/amazon-bedrock": "^4.0.92", + "@aws-sdk/client-sesv2": "^3.1029.0", "@aws-sdk/credential-providers": "^3.1029.0", "@dagrejs/dagre": "^3.0.0", "ai": "^6.0.156", diff --git a/src/services/email/access-approved-email.ts b/src/services/email/access-approved-email.ts new file mode 100644 index 000000000..d2fc80c2a --- /dev/null +++ b/src/services/email/access-approved-email.ts @@ -0,0 +1,55 @@ +import type { EmailMessage } from './types' + +export interface AccessApprovedEmailInput { + /** Display name; falls back to `login` when blank. */ + name: string + login: string + deploymentUrl: string + deploymentName: string +} + +/** Fixed template sent when an admin approves an access request. */ +export function renderAccessApprovedEmail( + input: AccessApprovedEmailInput, +): Omit { + const name = input.name.trim() || input.login + const subject = "You're in: Forms Lab access approved" + + const text = [ + `Hi ${name},`, + '', + `Good news: your request for access to Forms Lab has been approved. You can sign in to the ${input.deploymentName} deployment now:`, + '', + input.deploymentUrl, + '', + 'Sign in with the same GitHub account you used to request access.', + '', + 'Thanks for trying it out!', + 'The Forms Lab team', + '', + ].join('\n') + + const e = escapeHtml + const html = ` + + +

Hi ${e(name)},

+

Good news: your request for access to Forms Lab has been approved. You can sign in to the ${e(input.deploymentName)} deployment now:

+

${e(input.deploymentUrl)}

+

Sign in with the same GitHub account you used to request access.

+

Thanks for trying it out!
The Forms Lab team

+ + +` + + return { subject, text, html } +} + +function escapeHtml(value: string): string { + return value + .replaceAll('&', '&') + .replaceAll('<', '<') + .replaceAll('>', '>') + .replaceAll('"', '"') + .replaceAll("'", ''') +} diff --git a/src/services/email/from-env.ts b/src/services/email/from-env.ts new file mode 100644 index 000000000..e91bd8d9c --- /dev/null +++ b/src/services/email/from-env.ts @@ -0,0 +1,20 @@ +import { createLoggingEmailSender } from './logging-sender' +import { createSesEmailSender } from './ses-sender' +import type { EmailSender } from './types' + +const DEFAULT_REGION = 'us-east-1' + +/** + * `EMAIL_FROM` set → SES sender in `AWS_REGION`; otherwise the logging + * sender. Unconfigured email is a normal state (dev, tests, branch apps). + */ +export function createEmailSenderFromEnv( + env: Record = process.env, +): EmailSender { + const from = env.EMAIL_FROM?.trim() + if (!from) return createLoggingEmailSender() + return createSesEmailSender({ + from, + region: env.AWS_REGION?.trim() || DEFAULT_REGION, + }) +} diff --git a/src/services/email/index.ts b/src/services/email/index.ts new file mode 100644 index 000000000..e55ed64f6 --- /dev/null +++ b/src/services/email/index.ts @@ -0,0 +1,9 @@ +// Public interface for the email service (outbound mail to users). +// External imports (other services, entrypoints, design-system) MUST come +// through this file. Enforced by test/architecture/dependency-rule.test.ts. + +export { renderAccessApprovedEmail } from './access-approved-email' +export { createEmailSenderFromEnv } from './from-env' +export { createLoggingEmailSender } from './logging-sender' +export { createSesEmailSender } from './ses-sender' +export type { EmailMessage, EmailResult, EmailSender } from './types' diff --git a/src/services/email/logging-sender.ts b/src/services/email/logging-sender.ts new file mode 100644 index 000000000..d97d2e712 --- /dev/null +++ b/src/services/email/logging-sender.ts @@ -0,0 +1,17 @@ +import type { EmailMessage, EmailResult, EmailSender } from './types' + +/** + * Stand-in used when email isn't configured. Sends nothing and says so. + * Logs recipient and subject only — never the body. + */ +export function createLoggingEmailSender(): EmailSender { + return { + configured: false, + async send(message: EmailMessage): Promise { + console.log( + `[email] not configured; would have sent "${message.subject}" to ${message.to}`, + ) + return { ok: false, error: 'email not configured' } + }, + } +} diff --git a/src/services/email/ses-sender.ts b/src/services/email/ses-sender.ts new file mode 100644 index 000000000..55ccf7484 --- /dev/null +++ b/src/services/email/ses-sender.ts @@ -0,0 +1,71 @@ +// The only file that imports the AWS SES SDK (isolated dependency — see +// catalog/architecture/software-architecture.md, "Dependencies and externalities"). +import { SESv2Client, SendEmailCommand } from '@aws-sdk/client-sesv2' +import type { EmailMessage, EmailResult, EmailSender } from './types' + +const MAX_ERROR_LENGTH = 200 + +/** + * The slice of SESv2Client this sender uses. Injectable so tests never touch + * the network; production builds a real client lazily on first send. + */ +export interface SesSendClient { + send(command: SendEmailCommand): Promise +} + +export interface SesEmailSenderOptions { + /** RFC 5322 From value, e.g. `Forms Lab `. */ + from: string + region: string + client?: SesSendClient +} + +/** + * Sends mail through Amazon SES v2. Credentials come from the default AWS + * provider chain (the EC2 instance role in production). + */ +export function createSesEmailSender(opts: SesEmailSenderOptions): EmailSender { + let client = opts.client + return { + configured: true, + async send(message: EmailMessage): Promise { + try { + client ??= new SESv2Client({ region: opts.region }) + await client.send( + new SendEmailCommand({ + FromEmailAddress: opts.from, + Destination: { ToAddresses: [message.to] }, + Content: { + Simple: { + Subject: { Data: message.subject, Charset: 'UTF-8' }, + Body: { + Text: { Data: message.text, Charset: 'UTF-8' }, + Html: { Data: message.html, Charset: 'UTF-8' }, + }, + }, + }, + }), + ) + return { ok: true } + } catch (err) { + return { ok: false, error: shortError(err) } + } + }, + } +} + +function shortError(err: unknown): string { + let text: string + if (err instanceof Error) { + text = + err.name && err.name !== 'Error' + ? `${err.name}: ${err.message}` + : err.message + } else { + text = String(err) + } + text = text.trim() || 'unknown error' + return text.length > MAX_ERROR_LENGTH + ? `${text.slice(0, MAX_ERROR_LENGTH - 1)}…` + : text +} diff --git a/src/services/email/types.ts b/src/services/email/types.ts new file mode 100644 index 000000000..60edf6efc --- /dev/null +++ b/src/services/email/types.ts @@ -0,0 +1,16 @@ +/** One outbound email to one recipient. `text` and `html` carry the same content. */ +export interface EmailMessage { + to: string + subject: string + text: string + html: string +} + +/** Outcome of a send. Senders never throw; failures carry a short reason. */ +export type EmailResult = { ok: true } | { ok: false; error: string } + +export interface EmailSender { + /** False when the app has no way to deliver mail (dev, tests, branch deployments). */ + readonly configured: boolean + send(message: EmailMessage): Promise +} diff --git a/test/services/email/access-approved-template.test.ts b/test/services/email/access-approved-template.test.ts new file mode 100644 index 000000000..697c63102 --- /dev/null +++ b/test/services/email/access-approved-template.test.ts @@ -0,0 +1,53 @@ +import { describe, expect, it } from 'bun:test' +import { renderAccessApprovedEmail } from '../../../src/services/email' + +const input = { + name: 'Ada Lovelace', + login: 'ada', + deploymentUrl: 'https://forms.labs.flexion.us/main/', + deploymentName: 'main', +} + +describe('renderAccessApprovedEmail', () => { + it('has a subject naming Forms Lab', () => { + const msg = renderAccessApprovedEmail(input) + expect(msg.subject).toContain('Forms Lab') + }) + + it('greets by name and links the deployment in text and HTML', () => { + const msg = renderAccessApprovedEmail(input) + expect(msg.text).toContain('Hi Ada Lovelace') + expect(msg.text).toContain('https://forms.labs.flexion.us/main/') + expect(msg.text).toContain('main') + expect(msg.html).toContain('Hi Ada Lovelace') + expect(msg.html).toContain('href="https://forms.labs.flexion.us/main/"') + expect(msg.html).toContain('main') + }) + + it('falls back to the login when the name is blank', () => { + const msg = renderAccessApprovedEmail({ ...input, name: ' ' }) + expect(msg.text).toContain('Hi ada') + expect(msg.html).toContain('Hi ada') + }) + + it('HTML-escapes every interpolated value', () => { + const msg = renderAccessApprovedEmail({ + name: '', + login: 'x', + deploymentUrl: 'https://example.com/?a=1&b="2"', + deploymentName: 'dep', + }) + expect(msg.html).not.toContain('', + ) + + const html = await getAdminPage(app) + + expect(html).not.toContain('') + expect(html).toContain('<script>alert(1)</script>') + expect(html).toContain('line one\n') + }) + + it('does not link a blog URL with a non-http scheme', async () => { + const { app, accessStore, userStore } = buildApp() + userStore.saveGitHubProfile( + { + login: 'sneaky', + name: 'Sneaky', + avatar_url: 'https://e.com/a.png', + blog: 'javascript:alert(1)', + }, + [], + ) + accessStore.requestAccess('sneaky') + + const html = await getAdminPage(app) + + expect(html).not.toContain('href="javascript:') + expect(html).toContain('No verified email') + }) + + it('shows when the approval email was sent', async () => { + const { app, accessStore, userStore } = buildApp() + saveRequesterProfile(userStore) + accessStore.requestAccess('pendinguser') + accessStore.approve('pendinguser', 'adminuser') + accessStore.recordApprovalEmail('pendinguser', { + sentAt: Date.UTC(2026, 11, 4, 12) / 1000, + }) + + const html = await getAdminPage(app) + + expect(html).toContain('Approval email sent') + expect(html).toContain('2026') + }) + + it('shows why the approval email was not sent', async () => { + const { app, accessStore, userStore } = buildApp() + saveRequesterProfile(userStore) + accessStore.requestAccess('pendinguser') + accessStore.approve('pendinguser', 'adminuser') + accessStore.recordApprovalEmail('pendinguser', { + error: 'email not configured', + }) + + const html = await getAdminPage(app) + + expect(html).toContain('Approval email not sent: email not configured') + }) + }) }) diff --git a/test/base-path.test.ts b/test/base-path.test.ts index d32dfbcdf..2209d6de8 100644 --- a/test/base-path.test.ts +++ b/test/base-path.test.ts @@ -1,5 +1,9 @@ import { afterEach, describe, expect, it } from 'bun:test' -import { getBasePath, resolveUrl } from '../src/shared/base-path' +import { + getBasePath, + getDeploymentName, + resolveUrl, +} from '../src/shared/base-path' describe('getBasePath', () => { const originalEnv = process.env.BASE_PATH @@ -92,3 +96,22 @@ describe('resolveUrl', () => { ) }) }) + +describe('getDeploymentName', () => { + const originalEnv = process.env.BASE_PATH + + afterEach(() => { + if (originalEnv === undefined) delete process.env.BASE_PATH + else process.env.BASE_PATH = originalEnv + }) + + it('returns "root" when there is no base path', () => { + delete process.env.BASE_PATH + expect(getDeploymentName()).toBe('root') + }) + + it('returns the base path without slashes', () => { + process.env.BASE_PATH = '/story-142/' + expect(getDeploymentName()).toBe('story-142') + }) +}) diff --git a/test/shared/external-origin.test.ts b/test/shared/external-origin.test.ts new file mode 100644 index 000000000..8a2f462ee --- /dev/null +++ b/test/shared/external-origin.test.ts @@ -0,0 +1,37 @@ +import { describe, expect, it } from 'bun:test' +import { getExternalOrigin } from '../../src/shared/external-origin' + +function req(url: string, headers: Record = {}) { + return { + url, + header: (name: string) => headers[name.toLowerCase()], + } +} + +describe('getExternalOrigin', () => { + it('uses the request URL when no proxy headers are present', () => { + expect(getExternalOrigin(req('http://localhost:3000/x'))).toBe( + 'http://localhost:3000', + ) + }) + + it('prefers forwarded proto and host from the reverse proxy', () => { + expect( + getExternalOrigin( + req('http://localhost:3000/x', { + 'x-forwarded-proto': 'https', + 'x-forwarded-host': 'forms.example.com', + host: 'localhost:3000', + }), + ), + ).toBe('https://forms.example.com') + }) + + it('falls back to the Host header', () => { + expect( + getExternalOrigin( + req('http://localhost:3000/x', { host: 'forms.example.com' }), + ), + ).toBe('http://forms.example.com') + }) +}) From 7f415d43191a8b6df8b6b61573b1c71a62d8273d Mon Sep 17 00:00:00 2001 From: Daniel Naab Date: Fri, 4 Dec 2026 11:43:46 -0600 Subject: [PATCH 05/10] fix(auth): refresh pending requesters' contact details at sign-in Requests made before contact capture would otherwise never get emails stored, so their approval email could not be sent. Refs #142 Pot-Run: 7979 --- src/entrypoints/app/routes/auth/index.tsx | 3 +++ test/auth-routes.test.ts | 33 +++++++++++++++++++++++ 2 files changed, 36 insertions(+) diff --git a/src/entrypoints/app/routes/auth/index.tsx b/src/entrypoints/app/routes/auth/index.tsx index 68cfd68d0..0c7d17047 100644 --- a/src/entrypoints/app/routes/auth/index.tsx +++ b/src/entrypoints/app/routes/auth/index.tsx @@ -186,6 +186,9 @@ export function createAuthRoutes( } if (entry.status === 'pending') { + // Keep contact details current while the request waits, so + // requests made before details were captured get them too. + userStore.saveGitHubProfile(ghUser, emails) return c.redirect(resolveUrl('/auth/access-pending')) } diff --git a/test/auth-routes.test.ts b/test/auth-routes.test.ts index 4b7e26e3d..47e9e0d8c 100644 --- a/test/auth-routes.test.ts +++ b/test/auth-routes.test.ts @@ -340,6 +340,39 @@ describe('Auth Routes', () => { ) }) + it('pending requesters: refreshes profile and emails at sign-in', async () => { + // Requests made before this story have no emails on file; the next + // sign-in must fill them in so approval can email the requester. + process.env.ALLOWED_USERS = 'someoneelse' + const outsideEmails: GitHubEmail[] = [ + { + email: 'person@example.com', + primary: true, + verified: true, + visibility: null, + }, + ] + mockAccessStore.get = mock(() => ({ + login: 'person', + status: 'pending', + source: 'request', + requestedAt: 1, + decidedAt: null, + decidedBy: null, + note: null, + approvalEmailSentAt: null, + approvalEmailError: null, + })) as unknown as AccessStore['get'] + mockGitHub(fullUser, outsideEmails) + const res = await signIn() + expect(res.headers.get('Location')).toBe('/auth/access-pending') + expect(mockAccessStore.setApproved).not.toHaveBeenCalled() + expect(mockUserStore.saveGitHubProfile).toHaveBeenCalledWith( + fullUser, + outsideEmails, + ) + }) + it('saves with empty emails when the emails fetch fails', async () => { process.env.ALLOWED_USERS = 'person' mockGitHub(fullUser, emails) From a6ac6778d462276d2b2fac9d5f240f0d41311398 Mon Sep 17 00:00:00 2001 From: Daniel Naab Date: Fri, 4 Dec 2026 11:44:33 -0600 Subject: [PATCH 06/10] feat(admin): show requester bio, public email and social handle Links are only built for plain email addresses and valid X handles. Refs #142 Pot-Run: 7979 --- .../app/routes/admin/components.tsx | 41 +++++++++++++++++++ .../app/routes/admin/view-model.ts | 26 ++++++++++++ test/admin-routes.test.ts | 9 ++-- 3 files changed, 73 insertions(+), 3 deletions(-) diff --git a/src/entrypoints/app/routes/admin/components.tsx b/src/entrypoints/app/routes/admin/components.tsx index cb5dee4ea..c62acab26 100644 --- a/src/entrypoints/app/routes/admin/components.tsx +++ b/src/entrypoints/app/routes/admin/components.tsx @@ -23,6 +23,10 @@ export interface AdminUserRow { decidedBy: string | null contactEmail: AdminEmailView | null otherEmails: AdminEmailView[] + bio: string | null + /** `href` is null when the value isn't safe to link; shown as text. */ + publicEmail: { label: string; href: string | null } | null + socialHandle: { label: string; href: string | null } | null company: string | null location: string | null /** `href` is null when the value isn't a safe http(s) URL; shown as text. */ @@ -97,6 +101,43 @@ const ContactDetails: FC<{ user: AdminUserRow }> = ({ user: u }) => ( )} + {u.bio && ( + <> +
Bio
+
{u.bio}
+ + )} + {u.publicEmail && ( + <> +
Public email
+
+ {u.publicEmail.href ? ( + + {u.publicEmail.label} + + ) : ( + u.publicEmail.label + )} +
+ + )} + {u.socialHandle && ( + <> +
X / Twitter
+
+ {u.socialHandle.href ? ( + + {u.socialHandle.label} + + ) : ( + u.socialHandle.label + )} +
+ + )} {u.company && ( <>
Company
diff --git a/src/entrypoints/app/routes/admin/view-model.ts b/src/entrypoints/app/routes/admin/view-model.ts index 13681fa75..094b74aa9 100644 --- a/src/entrypoints/app/routes/admin/view-model.ts +++ b/src/entrypoints/app/routes/admin/view-model.ts @@ -82,6 +82,9 @@ export function toAdminUserRow( otherEmails: (profile?.emails ?? []) .filter((e) => e.email !== contact) .map(emailView), + bio: profile?.bio?.trim() || null, + publicEmail: linkableEmail(profile?.publicEmail ?? null), + socialHandle: socialHandleView(profile?.twitterUsername ?? null), company: profile?.company || null, location: profile?.location || null, blog: blog ? { label: blog, href: safeWebUrl(blog) } : null, @@ -91,3 +94,26 @@ export function toAdminUserRow( approvalEmail: approvalEmailStatus(entry), } } + +/** + * GitHub's public profile email, linked as mailto only when it is a plain + * address (no spaces or query characters that could add mailto headers). + */ +function linkableEmail( + email: string | null, +): { label: string; href: string | null } | null { + const value = email?.trim() + if (!value) return null + const plain = /^[^\s@?&#]+@[^\s@?&#]+$/.test(value) + return { label: value, href: plain ? `mailto:${value}` : null } +} + +/** GitHub's `twitter_username`, linked only when it is a valid X handle. */ +function socialHandleView( + handle: string | null, +): { label: string; href: string | null } | null { + const value = handle?.trim().replace(/^@/, '') + if (!value) return null + const valid = /^[A-Za-z0-9_]{1,15}$/.test(value) + return { label: `@${value}`, href: valid ? `https://x.com/${value}` : null } +} diff --git a/test/admin-routes.test.ts b/test/admin-routes.test.ts index 3c9719f19..55ece62b1 100644 --- a/test/admin-routes.test.ts +++ b/test/admin-routes.test.ts @@ -91,9 +91,9 @@ function saveRequesterProfile( company: 'Acme Agency', location: 'Springfield', blog: 'pat.example.org', - bio: null, - email: null, - twitter_username: null, + bio: 'Product designer for public benefits.', + email: 'pat.public@example.com', + twitter_username: 'pat_designs', html_url: `https://github.com/${login}`, created_at: '2015-06-01T00:00:00Z', }, @@ -375,6 +375,9 @@ describe('Admin Routes', () => { expect(html).toContain('href="https://pat.example.org"') expect(html).toContain('href="https://github.com/pendinguser"') expect(html).toContain('2015') + expect(html).toContain('Product designer for public benefits.') + expect(html).toContain('href="mailto:pat.public@example.com"') + expect(html).toContain('href="https://x.com/pat_designs"') expect(html).toContain('I work on benefits forms.') }) From 1e4b269ab34a538315ae4493bbdb2dfe33432a6e Mon Sep 17 00:00:00 2001 From: Daniel Naab Date: Fri, 4 Dec 2026 11:54:12 -0600 Subject: [PATCH 07/10] feat(auth): show pending requesters their request and let them update it Signed-in pending users are sent to a status page showing when they asked, where we'll email them, and their note, which they can edit. Only an actual change is stored and posts an access.request-updated Slack alert; repeat submissions no longer post alerts. Users who already have an entry no longer see the blank request form. Refs #142 Pot-Run: 7979 --- .../app/routes/auth/components.tsx | 102 ++++-- src/entrypoints/app/routes/auth/index.tsx | 172 +++++++--- src/services/auth/access-store.ts | 9 + test/access-store.test.ts | 30 ++ test/auth-routes.test.ts | 300 ++++++++++++++++++ test/notify-slack.test.ts | 13 + 6 files changed, 563 insertions(+), 63 deletions(-) diff --git a/src/entrypoints/app/routes/auth/components.tsx b/src/entrypoints/app/routes/auth/components.tsx index cc7e89718..a37a26213 100644 --- a/src/entrypoints/app/routes/auth/components.tsx +++ b/src/entrypoints/app/routes/auth/components.tsx @@ -2,6 +2,30 @@ import type { FC } from 'hono/jsx' import type { SessionUser } from '../../../../services/auth' import { resolveUrl } from '../../../../shared/base-path' +/** The optional, casual note a requester leaves with their request. */ +export const RequestNoteField: FC<{ value?: string | null }> = ({ value }) => ( +
+ + + Where you work, who sent you our way, what you'd like to try — whatever + helps us say yes faster. + + +
+) + export const RequestAccessPage: FC<{ user: SessionUser | null }> = ({ user, }) => ( @@ -25,24 +49,7 @@ export const RequestAccessPage: FC<{ user: SessionUser | null }> = ({ method="post" action={resolveUrl('/auth/request-access')} > -
- - - Where you work, who sent you our way, what you'd like to try — - whatever helps us say yes faster. - -