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/catalog/architecture/threat-model.md b/catalog/architecture/threat-model.md index 4c7726342..215bc326b 100644 --- a/catalog/architecture/threat-model.md +++ b/catalog/architecture/threat-model.md @@ -163,7 +163,7 @@ See [system overview](system-overview.md) and [data model](data-model.md) for fu ### Browser to Hono application (authentication) -**What crosses:** OAuth authorization codes, encrypted session cookies, user identity information (login, display name, avatar URL). +**What crosses:** OAuth authorization codes, encrypted session cookies, user identity information (login, display name, avatar URL). At every sign-in the callback also reads the user's GitHub email addresses (with primary/verified flags) and an allowlist of public profile fields (company, location, blog, bio, public email, Twitter username, profile URL, account creation date), and persists them. Access requesters may submit an optional free-text note (max 1000 characters) with their request. **Threats:** - **Session hijacking** -- stolen session cookies used to impersonate authenticated users. @@ -174,6 +174,9 @@ See [system overview](system-overview.md) and [data model](data-model.md) for fu - **Open redirect** -- attacker crafts sign-in URL with `returnTo` pointing to external site. - **Session fixation** -- attacker sets a known session cookie before user authenticates. - **Authentication mistaken for authorization** -- a valid session cookie held by a GitHub user who is *not* approved. The request-access flow deliberately issues a temporary session to unapproved requesters so the request page knows who they are, and revoked users may still hold cookies minted before revocation. Until 2026-12-04 the session reader set `user` for any decryptable cookie and the approval check lived only in `requireAuth(accessStore)` on `/admin/*`, `/new`, `/settings` and top-level `/forms`. Routes that checked only `user` presence or ownership — `POST /:owner/:slug/fork` (then edit/authoring routes on the fork, which run paid LLM pipelines), `POST /:owner/:slug/compare/:range/comments`, and the project-scoped `/:owner/:slug/forms/*` router (mounted without an access store) — admitted pending, revoked and no-entry users. +- **Personal data at rest** -- email addresses, profile details and request notes stored in the per-deployment SQLite database could be exposed by a host compromise, a leaked backup, or an admin page bug. +- **Stored XSS / markup injection via user-controlled text** -- the request note, display name, company and other profile fields are attacker-controlled (any GitHub user can sign in and request access) and are shown to admins on `/admin/users` and in Slack. +- **Script URLs in profile links** -- GitHub's `blog` field is free text; rendered as an `href` it could carry a `javascript:` URL. **Mitigations:** - Session cookies use AES-GCM encryption with PBKDF2-derived key (100k iterations, SHA-256) and random 12-byte IV per session. Cookie attributes: `HttpOnly`, `SameSite=Lax`, 7-day max-age. `Secure` flag set in production. @@ -184,8 +187,33 @@ See [system overview](system-overview.md) and [data model](data-model.md) for fu - Access is resolved centrally, once per request, by `sessionReader(accessStore)`: after decrypting the cookie it looks up the user's access entry. Only an `approved` entry populates `c.get('user')`, so every route that checks `user` is approval-gated by default. A pending or no-entry session is exposed only as `c.get('requester')`, which only the request-access auth pages read; everywhere else the requester appears signed out. A revoked user's cookie is deleted. The one exception for a missing entry is a login in `ALLOWED_USERS`: those are approved at sign-in, but each deployment has its own access database, so a cookie minted on another branch can arrive before the row exists; the env allowlist is treated as authoritative for them. `ALLOWED_EMAIL_DOMAINS` users cannot be re-verified without an OAuth token, so on a deployment with no row they appear signed out until they sign in there. `requireAuth()` now only checks for an approved `user`. Covered by `test/auth-approval-gate.test.ts`, `test/auth-middleware.test.ts` and `test/server.test.ts`. - Sign-out is POST-only (form submission), preventing GET-based CSRF. SameSite=Lax prevents cross-origin POST cookie sending. - Session cookie is only created after successful OAuth callback with a fresh random IV, so pre-set cookies are simply invalid. +- Profile fields are allowlisted rather than storing the raw `/user` payload, so account-internal data (plan, 2FA status, private repo counts) is never persisted. Emails are replaced wholesale at each sign-in, so removed addresses disappear. +- The admin page renders all user-controlled text through Hono JSX, which escapes it; the note is shown as plain text with `white-space: pre-line` (no raw HTML anywhere). The `blog` value is only linked when it parses as an `http(s)` URL; anything else is shown as text. The GitHub profile link is used only when it starts with `https://github.com/`. +- Slack notifications escape `&`, `<` and `>` in user-supplied text (note, name, company), so it cannot produce `` pings or disguised links. +- The note is never included in outbound email (see "Hono application to SES"). +- `/admin/users` and its actions require an admin (`requireAdmin`); state changes are POST-only under `SameSite=Lax` cookies. -**Residual risk:** The `returnTo` parameter is not validated against a whitelist of internal paths -- an attacker could craft a sign-in link that redirects to an external site after authentication. Mitigation: validate that `returnTo` starts with `/` and does not contain `//` or protocol schemes. No server-side session revocation -- sessions rely on cookie expiry (7 days). No PKCE in the OAuth flow (GitHub OAuth Apps do not support PKCE; only GitHub Apps do). No rate limiting on the OAuth callback endpoint beyond GitHub's own rate limits. +**Residual risk:** The `returnTo` parameter is not validated against a whitelist of internal paths -- an attacker could craft a sign-in link that redirects to an external site after authentication. Mitigation: validate that `returnTo` starts with `/` and does not contain `//` or protocol schemes. No server-side session revocation -- sessions rely on cookie expiry (7 days). No PKCE in the OAuth flow (GitHub OAuth Apps do not support PKCE; only GitHub Apps do). No rate limiting on the OAuth callback endpoint beyond GitHub's own rate limits. Contact details and notes are kept indefinitely: there is no retention or deletion policy for denied or revoked users, and the database holds them in plain text (follow-up). Any signed-in GitHub user can create a pending request with a note, so the admin page can be spammed; there is no rate limit on access requests. + +### Hono application to SES (outbound email) + +**What crosses:** When an admin approves an access request, the app sends one email through Amazon SES (`@aws-sdk/client-sesv2`, isolated to `src/services/email/ses-sender.ts`) to the requester's stored contact address, using the EC2 instance role's credentials. The message carries the requester's display name and login and a link to the deployment. + +**Threats:** +- **Mail to arbitrary recipients** -- an attacker uses the approve action to send mail to addresses they choose (spam or phishing relay). +- **Content injection** -- user-controlled text (name, note) placed into an email to phish the recipient or inject HTML. +- **Credential misuse** -- the instance role's SES permission is used to send other mail from the domain. +- **Spoofing the sender domain** -- third parties send mail claiming to be from the Forms Lab domain. +- **Send failure blocks access** -- SES errors or throttling prevent a user from being approved. + +**Mitigations:** +- The recipient is always the requester's stored **verified** GitHub address (primary verified, else first verified), never a form-supplied value. The approve route takes only a login, and sends only when that login had a pending or revoked access entry that this request approves; unknown or already-approved logins get no mail. +- Content is a fixed template (`renderAccessApprovedEmail`). Only the display name, login, deployment name and deployment URL are interpolated; all are HTML-escaped in the HTML part. The free-text note is never put in outbound mail. +- The IAM policy grants only `ses:SendEmail` on the one SES domain identity, provisioned by Pulumi. Easy DKIM records are published in Route53 so receivers can authenticate the domain. +- Only `main` sends mail: branch deployments omit `EMAIL_FROM` and use a logging sender that sends nothing. +- `send` never throws; approval is committed before sending, and the outcome (`sentAt` or an error reason) is recorded on the access entry and shown on the admin page. + +**Residual risk:** The SES account starts in the sandbox, where mail only reaches verified recipients; leaving it is a manual AWS support request, and until then most approval emails fail with a recorded error. No SPF or DMARC record is published yet, so DKIM alone authenticates the domain. A compromised host can send mail as the domain within SES quotas. Requester email addresses are disclosed to AWS SES as a processor. ### Hono application to LLM (form shaping) @@ -273,6 +301,11 @@ See [system overview](system-overview.md) and [data model](data-model.md) for fu | Session hijacking | Browser-Hono Auth | Medium | High | AES-GCM encrypted cookies, HttpOnly, SameSite=Lax | Mitigated | | Unapproved/revoked session used as authorization | Browser-Hono Auth | High | High | Central approval check in `sessionReader`; requesters exposed only to auth pages | Mitigated | | Open redirect via returnTo | Browser-Hono Auth | Low | Medium | None -- returnTo not validated | Unmitigated | +| Stored XSS via request note or profile fields | Browser-Hono Auth | Medium | High | JSX escaping on admin page, Slack escaping, http(s)-only links | Mitigated | +| Contact data kept for denied/revoked users | Browser-Hono Auth | Certain | Medium | None -- no retention policy yet | Accepted (follow-up) | +| Approval email to arbitrary recipient | Hono-SES | Low | Medium | Recipient is stored verified address; admin-only POST; fixed template | Mitigated | +| SES credential misuse | Hono-SES | Low | Medium | IAM scoped to `ses:SendEmail` on one identity | Partially mitigated | +| Approval emails undelivered (SES sandbox) | Hono-SES | Certain | Low | Outcome recorded and shown to admin; manual sandbox exit | Accepted | | Prompt injection via form labels | Hono-LLM (form shaping) | Medium | Medium | Output validation, Zod schema enforcement | Partially mitigated | | FormSpec metadata leakage | Hono-LLM (form shaping) | Certain | Low | HTTPS, LLM provider data policies | Accepted | | Unauthorized FormSpec mutation | Hono-LLM (form shaping) | Low | High | requireAuth + requireOwner middleware | Mitigated | @@ -306,6 +339,7 @@ See [system overview](system-overview.md) and [data model](data-model.md) for fu | 2026-04-18 | Story 7 | Added PDF output trust boundary for completed PDF download. Threats: unauthorized access, field mapping tampering. Both mitigated. | | 2026-05-02 | PR #122 | Updated secrets management references from sops-nix to AWS Secrets Manager. Updated residual risk for secrets to reflect IAM role fetch pattern and .env files on disk. | | 2026-12-04 | fix/auth-require-approved | Authentication boundary: documented a live hole where any valid session cookie (pending requesters, revoked users, users with no access entry) passed `user`-presence and ownership checks on fork, compare comments and project-scoped form routes. Fixed centrally: `sessionReader(accessStore)` sets `user` only for approved users and exposes others as `requester` for the request-access pages; revoked cookies are cleared. | +| 2026-12-04 | #142 | Added "Hono application to SES (outbound email)" boundary for approval emails. Updated authentication boundary for stored GitHub emails, profile details and the free-text request note (escaping on admin page and Slack, never in email). Added residual risk: no retention policy for denied/revoked users. | ## Sources @@ -315,3 +349,4 @@ See [system overview](system-overview.md) and [data model](data-model.md) for fu - [Caddy reverse proxy decision](../decisions/infrastructure/caddy-reverse-proxy.md) - [GitHub webhook deploys decision](../decisions/infrastructure/github-webhook-deploys.md) - [Nix-built processes decision](../decisions/infrastructure/nix-built-processes.md) +- [Story #142 design: access request contact details and approval email](https://github.com/flexion/forms-lab/blob/main/notes/story-142-access-request-contact-details/design.md) 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/notes/flight-board.md b/notes/flight-board.md index 2652bac7a..f303ad6f3 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 | pr-open (#144) | .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`). 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/entrypoints/app/public/styles.css b/src/entrypoints/app/public/styles.css index 194e9b1c8..b315843e2 100644 --- a/src/entrypoints/app/public/styles.css +++ b/src/entrypoints/app/public/styles.css @@ -98,6 +98,7 @@ @import "../routes/owner/edit/editor-layout.css" layer(block); @import "../routes/owner/compare/styles.css" layer(block); @import "../routes/settings/styles.css" layer(block); +@import "../routes/admin/styles.css" layer(block); /* Utility */ @import "./utilities.css" layer(utility); diff --git a/src/entrypoints/app/routes/admin/components.tsx b/src/entrypoints/app/routes/admin/components.tsx index 0b8901fa3..c62acab26 100644 --- a/src/entrypoints/app/routes/admin/components.tsx +++ b/src/entrypoints/app/routes/admin/components.tsx @@ -1,16 +1,203 @@ import type { FC } from 'hono/jsx' -import type { AccessEntry } from '../../../../services/auth' import { resolveUrl } from '../../../../shared/base-path' -interface EnrichedEntry extends AccessEntry { +export interface AdminEmailView { + address: string + primary: boolean + verified: boolean +} + +/** Outcome of the approval email, or null when none was attempted. */ +export type ApprovalEmailStatus = + | { sent: true; date: string } + | { sent: false; reason: string } + | null + +/** Display data for one user row; computed by the route (P4). */ +export interface AdminUserRow { + login: string name: string avatarUrl: string | null + source: string + requestedDate: string | null + 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. */ + blog: { label: string; href: string | null } | null + profileUrl: string + githubCreatedDate: string | null + note: string | null + approvalEmail: ApprovalEmailStatus } +const UserIdentity: FC<{ user: AdminUserRow }> = ({ user: u }) => ( +
+ {u.avatarUrl && ( + + )} + + {u.name} (@{u.login}) + +
+) + +const EmailFlags: FC<{ email: AdminEmailView }> = ({ email }) => ( + <> + {email.primary && Primary} + {email.verified ? 'Verified' : 'Unverified'} + +) + +/** Contact email up front; everything else in a collapsible block. */ +const ContactDetails: FC<{ user: AdminUserRow }> = ({ user: u }) => ( +
+

+ {u.contactEmail ? ( + + {u.contactEmail.address} + + ) : ( + No verified email + )} +

+
+ Details for @{u.login} +
+ {u.contactEmail && ( + <> +
Contact email
+
+ {u.contactEmail.address} +
+ + )} + {u.otherEmails.length > 0 && ( + <> +
Other emails
+
+
    + {u.otherEmails.map((e) => ( +
  • + {e.address} +
  • + ))} +
+
+ + )} + {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
+
{u.company}
+ + )} + {u.location && ( + <> +
Location
+
{u.location}
+ + )} + {u.blog && ( + <> +
Website
+
+ {u.blog.href ? ( + + {u.blog.label} + + ) : ( + u.blog.label + )} +
+ + )} +
GitHub
+
+ + GitHub profile for @{u.login} + +
+ {u.githubCreatedDate && ( + <> +
Account created
+
{u.githubCreatedDate}
+ + )} +
Note
+
+ {u.note ?? No note} +
+
+
+
+) + +const ApprovalEmailLine: FC<{ status: ApprovalEmailStatus }> = ({ status }) => + status === null ? null : ( +

+ {status.sent + ? `Approval email sent ${status.date}` + : `Approval email not sent: ${status.reason}`} +

+ ) + export const AdminUsersPage: FC<{ - pending: EnrichedEntry[] - approved: EnrichedEntry[] - revoked: EnrichedEntry[] + pending: AdminUserRow[] + approved: AdminUserRow[] + revoked: AdminUserRow[] }> = ({ pending, approved, revoked }) => (

User Management

@@ -32,29 +219,10 @@ export const AdminUsersPage: FC<{ {pending.map((u) => ( -
- {u.avatarUrl && ( - - )} - - {u.name} (@{u.login}) - -
- - - {u.requestedAt - ? new Date(u.requestedAt * 1000).toLocaleDateString() - : '\u2014'} + + + {u.requestedDate ?? '\u2014'}
( -
- {u.avatarUrl && ( - - )} - - {u.name} (@{u.login}) - -
+ + + {u.source} @@ -183,23 +337,7 @@ export const AdminUsersPage: FC<{ {revoked.map((u) => ( -
- {u.avatarUrl && ( - - )} - - {u.name} (@{u.login}) - -
+ {u.decidedBy ?? '\u2014'} diff --git a/src/entrypoints/app/routes/admin/index.tsx b/src/entrypoints/app/routes/admin/index.tsx index 3ec5daf5f..9a8504c12 100644 --- a/src/entrypoints/app/routes/admin/index.tsx +++ b/src/entrypoints/app/routes/admin/index.tsx @@ -1,16 +1,51 @@ import { Hono } from 'hono' import { Layout } from '../../../../design-system/components/flex-layout' import type { AccessStore, UserStore } from '../../../../services/auth' -import { resolveUrl } from '../../../../shared/base-path' +import { contactEmail } from '../../../../services/auth' +import type { EmailSender } from '../../../../services/email' +import { renderAccessApprovedEmail } from '../../../../services/email' +import { getDeploymentName, resolveUrl } from '../../../../shared/base-path' +import { getExternalOrigin } from '../../../../shared/external-origin' import { requireAdmin } from '../../middleware/auth' import { AdminUsersPage } from './components' +import { toAdminUserRow } from './view-model' + +const NO_EMAIL_ERROR = 'no verified email on file' export function createAdminRoutes( accessStore: AccessStore, userStore: UserStore, + emailSender: EmailSender, ): Hono { const admin = new Hono() + /** + * Tell a newly approved user they're in. Never throws and never blocks + * approval; the outcome is recorded on the access entry for the admin page. + * The recipient is always the stored verified address, never form input. + */ + async function sendApprovalEmail(login: string, origin: string) { + const profile = userStore.get(login) + const to = profile ? contactEmail(profile) : null + if (!profile || !to) { + accessStore.recordApprovalEmail(login, { error: NO_EMAIL_ERROR }) + return + } + const message = renderAccessApprovedEmail({ + name: profile.name, + login, + deploymentUrl: `${origin}${resolveUrl('/')}`, + deploymentName: getDeploymentName(), + }) + const result = await emailSender.send({ to, ...message }) + accessStore.recordApprovalEmail( + login, + result.ok + ? { sentAt: Math.floor(Date.now() / 1000) } + : { error: result.error }, + ) + } + // All admin routes require admin admin.use('*', requireAdmin()) @@ -21,14 +56,7 @@ export function createAdminRoutes( const revoked = accessStore.listByStatus('revoked') const enriched = (entries: typeof pending) => - entries.map((entry) => { - const profile = userStore.get(entry.login) - return { - ...entry, - name: profile?.name ?? entry.login, - avatarUrl: profile?.avatarUrl ?? null, - } - }) + entries.map((entry) => toAdminUserRow(entry, userStore.get(entry.login))) const pendingUsers = enriched(pending) const approvedUsers = enriched(approved) @@ -51,7 +79,13 @@ export function createAdminRoutes( const login = String(body.login ?? '').trim() const user = c.get('user') if (login && user) { + // Only email people whose request this approval actually grants: + // unknown logins and already-approved users get nothing. + const before = accessStore.get(login) accessStore.approve(login, user.login) + if (before && before.status !== 'approved') { + await sendApprovalEmail(login, getExternalOrigin(c.req)) + } } return c.redirect(resolveUrl('/admin/users')) }) diff --git a/src/entrypoints/app/routes/admin/styles.css b/src/entrypoints/app/routes/admin/styles.css new file mode 100644 index 000000000..9077ee06b --- /dev/null +++ b/src/entrypoints/app/routes/admin/styles.css @@ -0,0 +1,41 @@ +/* Admin user management — per-user contact details + Intent: keep each table row compact. The contact email is always visible; + the rest sits in a disclosure the admin opens when deciding. */ + +.admin-user__contact { + margin: 0; +} + +.admin-user__details { + margin-block-start: var(--flex-space-2xs); + + & summary { + cursor: pointer; + } +} + +.admin-user__fields { + display: grid; + grid-template-columns: max-content 1fr; + gap: var(--flex-space-2xs) var(--flex-space-sm); + margin: var(--flex-space-xs) 0 0; + + & dt { + font-weight: 600; + } + + & dd { + margin: 0; + } +} + +.admin-user__emails { + list-style: none; + margin: 0; + padding: 0; +} + +/* The note is plain text; keep the requester's line breaks. */ +.admin-user__note { + white-space: pre-line; +} diff --git a/src/entrypoints/app/routes/admin/view-model.ts b/src/entrypoints/app/routes/admin/view-model.ts new file mode 100644 index 000000000..094b74aa9 --- /dev/null +++ b/src/entrypoints/app/routes/admin/view-model.ts @@ -0,0 +1,119 @@ +import type { + AccessEntry, + UserEmail, + UserProfile, +} from '../../../../services/auth' +import { contactEmail } from '../../../../services/auth' +import type { AdminUserRow, ApprovalEmailStatus } from './components' + +const dateFormat = new Intl.DateTimeFormat('en-US', { + year: 'numeric', + month: 'short', + day: 'numeric', + timeZone: 'UTC', +}) + +/** Epoch seconds or an ISO string → "Dec 4, 2026"; null when absent or unparseable. */ +export function formatDate(value: number | string | null): string | null { + if (value === null || value === '') return null + const date = + typeof value === 'number' ? new Date(value * 1000) : new Date(value) + return Number.isNaN(date.getTime()) ? null : dateFormat.format(date) +} + +/** + * An http(s) URL safe to put in an href, or null. GitHub's `blog` field is + * free text and often has no scheme ("example.org"); anything with a + * non-http scheme (e.g. `javascript:`) is never linked. + */ +export function safeWebUrl(value: string | null): string | null { + const raw = value?.trim() + if (!raw) return null + const candidate = /^[a-z][a-z0-9+.-]*:/i.test(raw) ? raw : `https://${raw}` + try { + const url = new URL(candidate) + return url.protocol === 'https:' || url.protocol === 'http:' + ? candidate + : null + } catch { + return null + } +} + +function profileUrl(login: string, htmlUrl: string | null): string { + return htmlUrl?.startsWith('https://github.com/') + ? htmlUrl + : `https://github.com/${encodeURIComponent(login)}` +} + +function approvalEmailStatus(entry: AccessEntry): ApprovalEmailStatus { + if (entry.approvalEmailSentAt !== null) { + return { + sent: true, + date: formatDate(entry.approvalEmailSentAt) ?? 'unknown date', + } + } + if (entry.approvalEmailError !== null) { + return { sent: false, reason: entry.approvalEmailError } + } + return null +} + +function emailView(e: UserEmail) { + return { address: e.email, primary: e.primary, verified: e.verified } +} + +/** Everything the admin page shows about one access entry. */ +export function toAdminUserRow( + entry: AccessEntry, + profile: UserProfile | null, +): AdminUserRow { + const contact = profile ? contactEmail(profile) : null + const contactRecord = profile?.emails.find((e) => e.email === contact) + const blog = profile?.blog?.trim() || null + return { + login: entry.login, + name: profile?.name || entry.login, + avatarUrl: profile?.avatarUrl || null, + source: entry.source, + requestedDate: formatDate(entry.requestedAt), + decidedBy: entry.decidedBy, + contactEmail: contactRecord ? emailView(contactRecord) : null, + 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, + profileUrl: profileUrl(entry.login, profile?.htmlUrl ?? null), + githubCreatedDate: formatDate(profile?.githubCreatedAt ?? null), + note: entry.note, + 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/src/entrypoints/app/routes/auth/components.tsx b/src/entrypoints/app/routes/auth/components.tsx index 73016837d..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, }) => ( @@ -20,22 +44,84 @@ export const RequestAccessPage: FC<{ user: SessionUser | null }> = ({ You don't currently have access to Forms Lab. Click below to request access from an administrator.

- - + + +
+ +
) -export const AccessPendingPage: FC = () => ( +/** What a signed-in, pending requester sees about their own request. */ +export interface PendingRequestView { + /** Formatted submission date (UTC), or null if unknown. */ + submittedDate: string | null + /** Where the approval email will go, or null if we have no verified address. */ + contactEmail: string | null + note: string | null +} + +export const AccessPendingPage: FC<{ + request: PendingRequestView | null + updated: boolean +}> = ({ request, updated }) => (

Access Request Pending

-

Your request is being reviewed. You'll be notified when approved.

+ {updated && ( +
+

Your request has been updated. Thanks!

+
+ )} + {request ? ( + <> +

+ Thanks — your request is in + {request.submittedDate && <> (sent {request.submittedDate})}, and + an administrator will take a look soon. +

+ {request.contactEmail ? ( +

+ We'll email you at {request.contactEmail} as soon + as you're approved. +

+ ) : ( +

+ We'd like to email you when you're approved, but we don't have a + verified email address for you yet. If you add and verify an email + in your{' '} + + GitHub email settings + {' '} + and sign in again, we'll be able to let you know. +

+ )} +
+ +
+ +
+ + + ) : ( +

Your request is being reviewed. You'll be notified when approved.

+ )}

Back to home

diff --git a/src/entrypoints/app/routes/auth/index.tsx b/src/entrypoints/app/routes/auth/index.tsx index b79b7336e..7cdd54a03 100644 --- a/src/entrypoints/app/routes/auth/index.tsx +++ b/src/entrypoints/app/routes/auth/index.tsx @@ -1,24 +1,79 @@ -import { Hono } from 'hono' +import { type Context, Hono } from 'hono' import { deleteCookie, setCookie } from 'hono/cookie' import { Layout } from '../../../../design-system/components/flex-layout' import type { ActivityStore } from '../../../../services/activity' -import type { AccessStore, UserStore } from '../../../../services/auth' +import type { + AccessStatus, + AccessStore, + GitHubUser, + UserStore, +} from '../../../../services/auth' import { COOKIE_MAX_AGE, COOKIE_NAME, + contactEmail, encryptSession, exchangeCodeForToken, fetchUserEmails, fetchUserProfile, hasAllowedEmailDomain, } from '../../../../services/auth' -import { getBasePath, resolveUrl } from '../../../../shared/base-path' +import { getDeploymentName, resolveUrl } from '../../../../shared/base-path' +import { getExternalOrigin } from '../../../../shared/external-origin' +import { formatDate } from '../admin/view-model' import { AccessDeniedPage, AccessPendingPage, + type PendingRequestView, RequestAccessPage, } from './components' +const NOTE_MAX_LENGTH = 1000 + +/** Trim the optional request note, cap its length; empty → null. */ +function parseNote(value: unknown): string | null { + if (typeof value !== 'string') return null + const trimmed = value.trim().slice(0, NOTE_MAX_LENGTH) + return trimmed === '' ? null : trimmed +} + +/** Where a user who already has an access entry belongs. */ +function redirectForStatus(c: Context, status: AccessStatus) { + switch (status) { + case 'pending': + return c.redirect(resolveUrl('/auth/access-pending')) + case 'approved': + return c.redirect(resolveUrl('/')) + case 'revoked': + return c.redirect(resolveUrl('/auth/access-denied')) + } +} + +/** + * Temporary session for someone who is not approved yet, so the + * request-access and access-pending pages know who they are. + */ +async function startRequesterSession( + c: Context, + ghUser: GitHubUser, + sessionSecret: string, +): Promise { + const encryptedSession = await encryptSession( + { + login: ghUser.login, + name: ghUser.name ?? ghUser.login, + avatarUrl: ghUser.avatar_url, + }, + sessionSecret, + ) + setCookie(c, COOKIE_NAME, encryptedSession, { + httpOnly: true, + sameSite: 'Lax', + maxAge: COOKIE_MAX_AGE, + path: '/', + }) +} + export function createAuthRoutes( userStore: UserStore, accessStore: AccessStore, @@ -27,21 +82,55 @@ export function createAuthRoutes( const auth = new Hono() /** - * Get the external origin (scheme + host) from the request. - * Behind a reverse proxy like Caddy, the internal request uses http://localhost, - * so we check X-Forwarded-Proto and X-Forwarded-Host/Host headers. + * Slack details for an access request: who, how to reach them, why. + * An update always mentions the note, so a removed note is visible. */ - function getExternalOrigin(c: { - req: { header: (name: string) => string | undefined; url: string } - }): string { - const proto = - c.req.header('x-forwarded-proto') || - new URL(c.req.url).protocol.replace(':', '') - const host = - c.req.header('x-forwarded-host') || - c.req.header('host') || - new URL(c.req.url).host - return `${proto}://${host}` + function requestDetails( + user: { login: string; name: string }, + deployment: string, + note: string | null, + kind: 'requested' | 'updated', + ): string { + const profile = userStore.get(user.login) + const email = profile ? contactEmail(profile) : null + const action = + kind === 'requested' + ? 'requested access to' + : 'updated their access request for' + const lines = [ + `${user.name} (${user.login}) ${action} Forms Lab (deployment: ${deployment})`, + `Email: ${email ?? 'no verified email'}`, + ] + if (profile?.company) lines.push(`Company: ${profile.company}`) + if (note) lines.push(`Note: ${note}`) + else if (kind === 'updated') lines.push('Note: (removed)') + return lines.join('\n') + } + + /** Best-effort Slack alert; access lists are per-deployment, so name the branch and link to its admin page. */ + async function notifyAccessRequest( + c: Context, + user: { login: string; name: string }, + note: string | null, + kind: 'requested' | 'updated', + ): Promise { + try { + const { notifyEvent } = await import('../../../../services/notifications') + const deployment = getDeploymentName() + await notifyEvent({ + type: + kind === 'requested' ? 'access.requested' : 'access.request-updated', + title: + kind === 'requested' + ? `Access requested by @${user.login} on ${deployment}` + : `Access request updated by @${user.login} on ${deployment}`, + status: 'info', + details: requestDetails(user, deployment, note, kind), + url: `${getExternalOrigin(c.req)}${resolveUrl('/admin/users')}`, + }) + } catch { + // Notification failure should not block the request + } } // GET /auth/signin - Redirect to GitHub OAuth @@ -61,7 +150,7 @@ export function createAuthRoutes( // Build absolute callback URL from the current request so it works // under any base path (e.g., /main/auth/callback, /story-2/auth/callback) - const callbackUrl = `${getExternalOrigin(c)}${resolveUrl('/auth/callback')}` + const callbackUrl = `${getExternalOrigin(c.req)}${resolveUrl('/auth/callback')}` const authUrl = new URL('https://github.com/login/oauth/authorize') authUrl.searchParams.set('client_id', clientId) @@ -101,7 +190,7 @@ export function createAuthRoutes( try { // Build callback URL to match what was sent during authorization - const callbackUrl = `${getExternalOrigin(c)}${resolveUrl('/auth/callback')}` + const callbackUrl = `${getExternalOrigin(c.req)}${resolveUrl('/auth/callback')}` // Exchange code for token const token = await exchangeCodeForToken( @@ -114,6 +203,13 @@ export function createAuthRoutes( // Fetch user profile const ghUser = await fetchUserProfile(token) + // Fetch emails once for every user: saved as contact details and + // reused for the domain check below. A failure means "no emails". + const emails = await fetchUserEmails(token).catch((error) => { + console.warn('Email fetch failed:', error) + return [] + }) + // --- Three-layer authorization --- // Layer 1: env var bypass const allowedUsers = (process.env.ALLOWED_USERS ?? 'danielnaab') @@ -140,7 +236,6 @@ export function createAuthRoutes( allowedDomains.push('flexion.us') } - const emails = await fetchUserEmails(token) if (hasAllowedEmailDomain(emails, allowedDomains)) { accessStore.setApproved(ghUser.login, 'domain') } else { @@ -150,30 +245,17 @@ export function createAuthRoutes( if (!entry) { // New external user — persist profile, set session so // request-access page knows who they are, redirect - userStore.upsert({ - login: ghUser.login, - name: ghUser.name ?? ghUser.login, - avatarUrl: ghUser.avatar_url, - }) - const sessionData = { - login: ghUser.login, - name: ghUser.name ?? ghUser.login, - avatarUrl: ghUser.avatar_url, - } - const encryptedSession = await encryptSession( - sessionData, - sessionSecret, - ) - setCookie(c, COOKIE_NAME, encryptedSession, { - httpOnly: true, - sameSite: 'Lax', - maxAge: COOKIE_MAX_AGE, - path: '/', - }) + userStore.saveGitHubProfile(ghUser, emails) + await startRequesterSession(c, ghUser, sessionSecret) return c.redirect(resolveUrl('/auth/request-access')) } if (entry.status === 'pending') { + // Keep contact details current while the request waits, so + // requests made before details were captured get them too. + // The session lets the status page show and update the request. + userStore.saveGitHubProfile(ghUser, emails) + await startRequesterSession(c, ghUser, sessionSecret) return c.redirect(resolveUrl('/auth/access-pending')) } @@ -188,17 +270,13 @@ export function createAuthRoutes( } } - // Persist user profile - userStore.upsert({ - login: ghUser.login, - name: ghUser.name ?? ghUser.login, - avatarUrl: ghUser.avatar_url, - }) + // Persist user profile and emails + userStore.saveGitHubProfile(ghUser, emails) // Create session const sessionData = { login: ghUser.login, - name: ghUser.name, + name: ghUser.name ?? ghUser.login, avatarUrl: ghUser.avatar_url, } @@ -236,11 +314,13 @@ export function createAuthRoutes( return c.redirect(resolveUrl('/')) }) - // GET /auth/request-access — shows "request access" page - // Requesters (signed in but not approved) are only visible here; the - // session reader treats them as signed out everywhere else. + // GET /auth/request-access — blank form for users with no entry yet. + // Requesters (signed in but not approved) are only visible on these auth + // pages; the session reader treats them as signed out everywhere else. auth.get('/request-access', (c) => { const user = c.get('requester') ?? c.get('user') + const entry = user ? accessStore.get(user.login) : null + if (entry) return redirectForStatus(c, entry.status) return c.html( @@ -248,40 +328,58 @@ export function createAuthRoutes( ) }) - // POST /auth/request-access — records the request + // POST /auth/request-access — records a new request, or updates the + // note of a pending one. Approved and revoked users change nothing. auth.post('/request-access', async (c) => { const user = c.get('requester') ?? c.get('user') if (!user) { return c.redirect(resolveUrl('/auth/signin')) } - accessStore.requestAccess(user.login) + const entry = accessStore.get(user.login) + if (entry && entry.status !== 'pending') { + return redirectForStatus(c, entry.status) + } - // Fire notification (best-effort). Access lists are per-deployment, so - // name the branch and link to that deployment's admin page. - try { - const { notifyEvent } = await import('../../../../services/notifications') - const deployment = getBasePath().replace(/^\/|\/$/g, '') || 'root' - await notifyEvent({ - type: 'access.requested', - title: `Access requested by @${user.login} on ${deployment}`, - status: 'info', - details: `${user.name} (${user.login}) requested access to Forms Lab (deployment: ${deployment})`, - url: `${getExternalOrigin(c)}${resolveUrl('/admin/users')}`, - }) - } catch { - // Notification failure should not block the request + const body = await c.req.parseBody() + const note = parseNote(body.note) + + if (!entry) { + accessStore.requestAccess(user.login, note) + await notifyAccessRequest(c, user, note, 'requested') + } else if (note !== entry.note) { + accessStore.updateNote(user.login, note) + await notifyAccessRequest(c, user, note, 'updated') } - // Clear the temporary session — they don't have access yet - deleteCookie(c, COOKIE_NAME) - return c.redirect(resolveUrl('/auth/access-pending')) + // Keep the session: the session reader only exposes it to these auth + // pages, so the requester can come back to their status page. + return c.redirect( + resolveUrl( + entry ? '/auth/access-pending?updated=1' : '/auth/access-pending', + ), + ) }) - // GET /auth/access-pending + // GET /auth/access-pending — a pending requester's own status and note; + // a generic message for anyone else. auth.get('/access-pending', (c) => { + const user = c.get('requester') ?? null + const entry = user ? accessStore.get(user.login) : null + let request: PendingRequestView | null = null + if (user && entry?.status === 'pending') { + const profile = userStore.get(user.login) + request = { + submittedDate: formatDate(entry.requestedAt), + contactEmail: profile ? contactEmail(profile) : null, + note: entry.note, + } + } return c.html( - - + + , ) }) diff --git a/src/entrypoints/app/routes/owner/components.tsx b/src/entrypoints/app/routes/owner/components.tsx index 475872495..3d11cd8eb 100644 --- a/src/entrypoints/app/routes/owner/components.tsx +++ b/src/entrypoints/app/routes/owner/components.tsx @@ -25,7 +25,7 @@ export { ConfidenceBadge } from '../../../../design-system/components/flex-confi // --------------------------------------------------------------------------- export const ProfilePage: FC<{ - user: UserProfile + user: Pick projects: ProjectIndex[] currentUser: SessionUser | null }> = ({ user, projects, currentUser }) => { diff --git a/src/entrypoints/app/routes/owner/index.tsx b/src/entrypoints/app/routes/owner/index.tsx index 6e140716b..34dc36ab5 100644 --- a/src/entrypoints/app/routes/owner/index.tsx +++ b/src/entrypoints/app/routes/owner/index.tsx @@ -7,6 +7,7 @@ import { getCorpusMetadata } from '../../../../services/rag' import { resolveVariantBadge } from '../../../../services/variant-preferences' import { resolveUrl } from '../../../../shared/base-path' import { AppError, UnauthenticatedError } from '../../../../shared/errors' +import { getExternalOrigin } from '../../../../shared/external-origin' import type { VariantRegistry } from '../../../../shared/strategy-registry' import { BlobPage, @@ -19,17 +20,6 @@ import { TreePage, } from './components' -function getExternalOrigin(c: Context): string { - const proto = - c.req.header('x-forwarded-proto') || - new URL(c.req.url).protocol.replace(':', '') - const host = - c.req.header('x-forwarded-host') || - c.req.header('host') || - new URL(c.req.url).host - return `${proto}://${host}` -} - export function createOwnerRoutes( service: ProjectService, userStore: UserStore, @@ -54,8 +44,6 @@ export function createOwnerRoutes( login: owner, name: owner, avatarUrl: '', - createdAt: 0, - updatedAt: 0, } return c.html( @@ -83,7 +71,7 @@ export function createOwnerRoutes( service.getProject(owner, slug, user, branch), service.listBranches(slug), ]) - const origin = getExternalOrigin(c) + const origin = getExternalOrigin(c.req) // Read extraction provenance from the branch being viewed so the // badge reflects which variant produced the currently-displayed // spec (including on pre-promotion `import` branches). diff --git a/src/entrypoints/app/server.tsx b/src/entrypoints/app/server.tsx index 029f1b1d3..4c1be3d62 100644 --- a/src/entrypoints/app/server.tsx +++ b/src/entrypoints/app/server.tsx @@ -11,6 +11,7 @@ import { Layout } from '../../design-system/components/flex-layout' import { createActivityStore } from '../../services/activity' import { createAccessStore, createUserStore } from '../../services/auth' import type { DataCollectionSpec } from '../../services/data-collection' +import { createEmailSenderFromEnv } from '../../services/email' import { createExtractorRegistry } from '../../services/extraction' import { createAuthoringCriteriaRegistry, @@ -81,6 +82,8 @@ const projectStore = createProjectStore(projectDbPath) const cacheStore = createCacheStore(cacheDbPath) const userStore = createUserStore(projectDbPath) const accessStore = createAccessStore(projectDbPath) +// Outbound mail to users; a logging no-op unless EMAIL_FROM is set. +const emailSender = createEmailSenderFromEnv() const formProjectRepo = createFormProjectRepo(reposPath) // Variant registries: one per task. Each user's preferred variant is @@ -298,7 +301,7 @@ app.route('/auth', createAuthRoutes(userStore, accessStore, { activityStore })) // Mount admin routes (requireAdmin is applied inside createAdminRoutes) app.use('/admin/*', requireAuth()) -app.route('/admin', createAdminRoutes(accessStore, userStore)) +app.route('/admin', createAdminRoutes(accessStore, userStore, emailSender)) // Mount settings routes (variant picker) app.route( diff --git a/src/entrypoints/notify/slack.ts b/src/entrypoints/notify/slack.ts index b7467e44e..eee467d29 100644 --- a/src/entrypoints/notify/slack.ts +++ b/src/entrypoints/notify/slack.ts @@ -6,10 +6,22 @@ const STATUS_COLORS: Record = { info: '#6c757d', } +/** + * Escape text for Slack mrkdwn. Slack treats `<...>` as control sequences + * (``, `<@user>`, ``), so user-controlled text must + * have `&`, `<` and `>` replaced by their HTML entities. + * https://api.slack.com/reference/surfaces/formatting#escaping + */ +export function escapeSlackText(text: string): string { + return text.replace(/&/g, '&').replace(//g, '>') +} + export function formatSlackMessage(event: NotifyEvent): object { + const title = escapeSlackText(event.title) + // The url is built by our services, not users; it is the link target. const titleText = event.url - ? `*[${event.type}]* <${event.url}|${event.title}>` - : `*[${event.type}]* ${event.title}` + ? `*[${event.type}]* <${event.url}|${title}>` + : `*[${event.type}]* ${title}` const blocks: object[] = [ { @@ -27,7 +39,7 @@ export function formatSlackMessage(event: NotifyEvent): object { elements: [ { type: 'mrkdwn', - text: event.details, + text: escapeSlackText(event.details), }, ], }) diff --git a/src/services/auth/access-store.ts b/src/services/auth/access-store.ts index 10b644009..e73f9a015 100644 --- a/src/services/auth/access-store.ts +++ b/src/services/auth/access-store.ts @@ -10,18 +10,41 @@ export interface AccessEntry { requestedAt: number | null decidedAt: number | null decidedBy: string | null + /** Free-text note the requester left with their request. */ + note: string | null + /** When the approval email was sent (epoch seconds), if it was. */ + approvalEmailSentAt: number | null + /** Why the approval email was not sent, if it wasn't. */ + approvalEmailError: string | null } export interface AccessStore { get(login: string): AccessEntry | null - requestAccess(login: string): void + requestAccess(login: string, note?: string | null): void + /** Replace the note of a pending request; approved and revoked rows are untouched. */ + updateNote(login: string, note: string | null): void approve(login: string, decidedBy: string): void deny(login: string, decidedBy: string): void revoke(login: string, decidedBy: string): void setApproved(login: string, source: AccessSource): void listByStatus(status: AccessStatus): AccessEntry[] + /** Record the outcome of the approval email; sets one field, clears the other. */ + recordApprovalEmail( + login: string, + result: { sentAt: number } | { error: string }, + ): void } +const COLUMNS = + 'login, status, source, requested_at, decided_at, decided_by, note, approval_email_sent_at, approval_email_error' + +/** Columns added after the original table; all nullable. */ +const ADDED_COLUMNS: ReadonlyArray<[name: string, type: string]> = [ + ['note', 'TEXT'], + ['approval_email_sent_at', 'INTEGER'], + ['approval_email_error', 'TEXT'], +] + export function createAccessStore(dbPath: string): AccessStore { const db = new Database(dbPath) db.run('PRAGMA journal_mode = WAL') @@ -35,6 +58,18 @@ export function createAccessStore(dbPath: string): AccessStore { decided_by TEXT ) `) + const existing = new Set( + ( + db.query('PRAGMA table_info(user_access)').all() as Array<{ + name: string + }> + ).map((c) => c.name), + ) + for (const [name, type] of ADDED_COLUMNS) { + if (!existing.has(name)) { + db.run(`ALTER TABLE user_access ADD COLUMN ${name} ${type}`) + } + } function rowToEntry(row: Record): AccessEntry { return { @@ -44,27 +79,49 @@ export function createAccessStore(dbPath: string): AccessStore { requestedAt: (row.requested_at as number) ?? null, decidedAt: (row.decided_at as number) ?? null, decidedBy: (row.decided_by as string) ?? null, + note: (row.note as string) ?? null, + approvalEmailSentAt: (row.approval_email_sent_at as number) ?? null, + approvalEmailError: (row.approval_email_error as string) ?? null, } } return { get(login: string): AccessEntry | null { const row = db - .query( - 'SELECT login, status, source, requested_at, decided_at, decided_by FROM user_access WHERE login = ?', - ) + .query(`SELECT ${COLUMNS} FROM user_access WHERE login = ?`) .get(login) as Record | null if (!row) return null return rowToEntry(row) }, - requestAccess(login: string): void { + requestAccess(login: string, note?: string | null): void { const now = Math.floor(Date.now() / 1000) db.run( - `INSERT INTO user_access (login, status, source, requested_at) - VALUES (?, 'pending', 'request', ?) + `INSERT INTO user_access (login, status, source, requested_at, note) + VALUES (?, 'pending', 'request', ?, ?) ON CONFLICT(login) DO NOTHING`, - [login, now], + [login, now, note ?? null], + ) + }, + + updateNote(login: string, note: string | null): void { + db.run( + `UPDATE user_access SET note = ? WHERE login = ? AND status = 'pending'`, + [note, login], + ) + }, + + recordApprovalEmail( + login: string, + result: { sentAt: number } | { error: string }, + ): void { + const sentAt = 'sentAt' in result ? result.sentAt : null + const error = 'error' in result ? result.error : null + db.run( + `UPDATE user_access + SET approval_email_sent_at = ?, approval_email_error = ? + WHERE login = ?`, + [sentAt, error, login], ) }, @@ -108,7 +165,7 @@ export function createAccessStore(dbPath: string): AccessStore { listByStatus(status: AccessStatus): AccessEntry[] { const rows = db .query( - 'SELECT login, status, source, requested_at, decided_at, decided_by FROM user_access WHERE status = ? ORDER BY requested_at DESC, decided_at DESC', + `SELECT ${COLUMNS} FROM user_access WHERE status = ? ORDER BY requested_at DESC, decided_at DESC`, ) .all(status) as Record[] return rows.map(rowToEntry) diff --git a/src/services/auth/github-oauth.ts b/src/services/auth/github-oauth.ts index 6840a11da..c5bc47130 100644 --- a/src/services/auth/github-oauth.ts +++ b/src/services/auth/github-oauth.ts @@ -1,7 +1,23 @@ +/** + * The fields of GitHub's `/user` response that we use. The response holds + * more (plan, 2FA status, private repo counts); only these public, + * person-describing fields are ever stored. + */ export interface GitHubUser { login: string - name: string + /** GitHub allows an empty display name; callers fall back to `login`. */ + name: string | null avatar_url: string + id?: number | null + company?: string | null + location?: string | null + blog?: string | null + bio?: string | null + /** Public profile email — not verified by us; see `fetchUserEmails`. */ + email?: string | null + twitter_username?: string | null + html_url?: string | null + created_at?: string | null } export async function exchangeCodeForToken( diff --git a/src/services/auth/index.ts b/src/services/auth/index.ts index b3ede8e5a..e30b1d187 100644 --- a/src/services/auth/index.ts +++ b/src/services/auth/index.ts @@ -2,6 +2,7 @@ // External imports (other services, entrypoints, design-system) MUST come // through this file. Enforced by test/architecture/dependency-rule.test.ts. +export type { UserEmail, UserProfile } from '../../types/models' export type { AccessEntry, AccessSource, @@ -27,4 +28,4 @@ export { } from './session' export type { SessionUser } from './types' export type { UserStore } from './user-store' -export { createUserStore } from './user-store' +export { contactEmail, createUserStore } from './user-store' diff --git a/src/services/auth/user-store.ts b/src/services/auth/user-store.ts index 02a75dab6..e9205d401 100644 --- a/src/services/auth/user-store.ts +++ b/src/services/auth/user-store.ts @@ -1,12 +1,78 @@ import { Database } from 'bun:sqlite' -import type { UserProfile } from '../../types/models' +import type { UserEmail, UserProfile } from '../../types/models' +import type { GitHubEmail, GitHubUser } from './github-oauth' export interface UserStore { upsert(user: { login: string; name: string; avatarUrl: string }): void + /** + * Save the allowlisted GitHub profile fields and replace this login's + * email addresses with `emails`. Called at every sign-in. + */ + saveGitHubProfile(ghUser: GitHubUser, emails: GitHubEmail[]): void get(login: string): UserProfile | null exists(login: string): boolean } +/** Profile columns added after the original table; all nullable. */ +const PROFILE_COLUMNS: ReadonlyArray<[name: string, type: string]> = [ + ['github_id', 'INTEGER'], + ['company', 'TEXT'], + ['location', 'TEXT'], + ['blog', 'TEXT'], + ['bio', 'TEXT'], + ['public_email', 'TEXT'], + ['twitter_username', 'TEXT'], + ['html_url', 'TEXT'], + ['github_created_at', 'TEXT'], +] + +function addMissingColumns( + db: Database, + table: string, + columns: ReadonlyArray<[name: string, type: string]>, +): void { + const existing = new Set( + ( + db.query(`PRAGMA table_info(${table})`).all() as Array<{ name: string }> + ).map((c) => c.name), + ) + for (const [name, type] of columns) { + if (!existing.has(name)) { + db.run(`ALTER TABLE ${table} ADD COLUMN ${name} ${type}`) + } + } +} + +/** Primary verified email, else first verified, else null. */ +export function contactEmail(profile: UserProfile): string | null { + const verified = profile.emails.filter((e) => e.verified) + return (verified.find((e) => e.primary) ?? verified[0])?.email ?? null +} + +interface UserRow { + login: string + name: string + avatar_url: string + created_at: number + updated_at: number + github_id: number | null + company: string | null + location: string | null + blog: string | null + bio: string | null + public_email: string | null + twitter_username: string | null + html_url: string | null + github_created_at: string | number | null +} + +interface EmailRow { + email: string + is_primary: number + verified: number + visibility: string | null +} + export function createUserStore(dbPath: string): UserStore { const db = new Database(dbPath) db.run('PRAGMA journal_mode = WAL') @@ -19,6 +85,77 @@ export function createUserStore(dbPath: string): UserStore { updated_at INTEGER NOT NULL ) `) + addMissingColumns(db, 'users', PROFILE_COLUMNS) + db.run(` + 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) + ) + `) + + const saveProfile = db.transaction( + (ghUser: GitHubUser, emails: GitHubEmail[]) => { + const now = Math.floor(Date.now() / 1000) + db.run( + `INSERT INTO users ( + login, name, avatar_url, created_at, updated_at, + github_id, company, location, blog, bio, public_email, + twitter_username, html_url, github_created_at + ) + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) + ON CONFLICT(login) DO UPDATE SET + name = excluded.name, + avatar_url = excluded.avatar_url, + updated_at = excluded.updated_at, + github_id = excluded.github_id, + company = excluded.company, + location = excluded.location, + blog = excluded.blog, + bio = excluded.bio, + public_email = excluded.public_email, + twitter_username = excluded.twitter_username, + html_url = excluded.html_url, + github_created_at = excluded.github_created_at`, + [ + ghUser.login, + ghUser.name || ghUser.login, + ghUser.avatar_url ?? '', + now, + now, + ghUser.id ?? null, + ghUser.company ?? null, + ghUser.location ?? null, + ghUser.blog ?? null, + ghUser.bio ?? null, + ghUser.email ?? null, + ghUser.twitter_username ?? null, + ghUser.html_url ?? null, + ghUser.created_at ?? null, + ], + ) + db.run('DELETE FROM user_emails WHERE login = ?', [ghUser.login]) + for (const e of emails) { + db.run( + `INSERT OR REPLACE INTO user_emails + (login, email, is_primary, verified, visibility, updated_at) + VALUES (?, ?, ?, ?, ?, ?)`, + [ + ghUser.login, + e.email, + e.primary ? 1 : 0, + e.verified ? 1 : 0, + e.visibility ?? null, + now, + ], + ) + } + }, + ) return { upsert(user: { login: string; name: string; avatarUrl: string }): void { @@ -34,25 +171,49 @@ export function createUserStore(dbPath: string): UserStore { ) }, + saveGitHubProfile(ghUser: GitHubUser, emails: GitHubEmail[]): void { + saveProfile(ghUser, emails) + }, + get(login: string): UserProfile | null { const row = db .query( - 'SELECT login, name, avatar_url, created_at, updated_at FROM users WHERE login = ?', + `SELECT login, name, avatar_url, created_at, updated_at, + github_id, company, location, blog, bio, public_email, + twitter_username, html_url, github_created_at + FROM users WHERE login = ?`, ) - .get(login) as { - login: string - name: string - avatar_url: string - created_at: number - updated_at: number - } | null + .get(login) as UserRow | null if (!row) return null + const emailRows = db + .query( + `SELECT email, is_primary, verified, visibility + FROM user_emails WHERE login = ? + ORDER BY rowid ASC`, + ) + .all(login) as EmailRow[] + const emails: UserEmail[] = emailRows.map((e) => ({ + email: e.email, + primary: e.is_primary === 1, + verified: e.verified === 1, + visibility: e.visibility, + })) return { login: row.login, name: row.name, avatarUrl: row.avatar_url, createdAt: row.created_at, updatedAt: row.updated_at, + githubId: row.github_id, + company: row.company, + location: row.location, + blog: row.blog, + bio: row.bio, + publicEmail: row.public_email, + twitterUsername: row.twitter_username, + htmlUrl: row.html_url, + githubCreatedAt: row.github_created_at, + emails, } }, 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/src/shared/base-path.ts b/src/shared/base-path.ts index cb71810a4..3bea1ab96 100644 --- a/src/shared/base-path.ts +++ b/src/shared/base-path.ts @@ -53,3 +53,12 @@ export function resolveUrl(path: string): string { // Combine base path with clean path return `${base}${clean}` } + +/** + * Human name for this deployment: the base path without slashes + * (e.g. `story-142`), or `root` when the app is served at `/`. + * Access lists are per-deployment, so notifications name the one they're about. + */ +export function getDeploymentName(): string { + return getBasePath().replace(/^\/|\/$/g, '') || 'root' +} diff --git a/src/shared/external-origin.ts b/src/shared/external-origin.ts new file mode 100644 index 000000000..d11d622f5 --- /dev/null +++ b/src/shared/external-origin.ts @@ -0,0 +1,21 @@ +/** The parts of an incoming request needed to work out its public origin. */ +export interface OriginRequest { + url: string + header(name: string): string | undefined +} + +/** + * External origin (scheme + host) of a request, for building absolute links. + * Behind a reverse proxy like Caddy the internal request is http://localhost, + * so X-Forwarded-Proto and X-Forwarded-Host/Host take precedence. + */ +export function getExternalOrigin(req: OriginRequest): string { + const proto = + req.header('x-forwarded-proto') || + new URL(req.url).protocol.replace(':', '') + const host = + req.header('x-forwarded-host') || + req.header('host') || + new URL(req.url).host + return `${proto}://${host}` +} diff --git a/src/types/models.ts b/src/types/models.ts index cfe0d5f33..180222022 100644 --- a/src/types/models.ts +++ b/src/types/models.ts @@ -247,4 +247,25 @@ export interface UserProfile { avatarUrl: string createdAt: number updatedAt: number + githubId: number | null + company: string | null + location: string | null + blog: string | null + bio: string | null + /** Public profile email from GitHub (unverified by us). */ + publicEmail: string | null + twitterUsername: string | null + htmlUrl: string | null + /** GitHub account creation time as GitHub reported it (ISO string). */ + githubCreatedAt: string | number | null + /** All addresses from GitHub `/user/emails`, replaced at each sign-in. */ + emails: UserEmail[] +} + +/** One GitHub email address with its flags. */ +export interface UserEmail { + email: string + primary: boolean + verified: boolean + visibility: string | null } diff --git a/test/access-store.test.ts b/test/access-store.test.ts index 334453c67..3814170a9 100644 --- a/test/access-store.test.ts +++ b/test/access-store.test.ts @@ -1,3 +1,4 @@ +import { Database } from 'bun:sqlite' import { afterEach, describe, expect, it } from 'bun:test' import { unlinkSync } from 'node:fs' import { createAccessStore } from '../src/services/auth' @@ -102,4 +103,105 @@ describe('AccessStore', () => { const second = store.get('octocat') expect(second?.requestedAt).toBe(first?.requestedAt) }) + + it('stores the note with the request', () => { + const store = createAccessStore(TEST_DB) + store.requestAccess('octocat', 'I work at Acme') + expect(store.get('octocat')?.note).toBe('I work at Acme') + expect(store.listByStatus('pending')[0]?.note).toBe('I work at Acme') + }) + + it('stores null note when none given', () => { + const store = createAccessStore(TEST_DB) + store.requestAccess('octocat') + const entry = store.get('octocat') + expect(entry?.note).toBeNull() + expect(entry?.approvalEmailSentAt).toBeNull() + expect(entry?.approvalEmailError).toBeNull() + }) + + it('does not overwrite an existing request note', () => { + const store = createAccessStore(TEST_DB) + store.requestAccess('octocat', 'first') + store.requestAccess('octocat', 'second') + expect(store.get('octocat')?.note).toBe('first') + }) + + it('updateNote changes the note of a pending request only', () => { + const store = createAccessStore(TEST_DB) + store.requestAccess('octocat', 'first') + const before = store.get('octocat') + store.updateNote('octocat', 'second') + expect(store.get('octocat')?.note).toBe('second') + expect(store.get('octocat')?.requestedAt).toBe(before?.requestedAt) + store.updateNote('octocat', null) + expect(store.get('octocat')?.note).toBeNull() + expect(store.get('octocat')?.status).toBe('pending') + }) + + it('updateNote leaves approved and revoked rows untouched', () => { + const store = createAccessStore(TEST_DB) + store.requestAccess('approved1', 'kept') + store.approve('approved1', 'admin1') + store.requestAccess('revoked1', 'kept') + store.deny('revoked1', 'admin1') + + store.updateNote('approved1', 'changed') + store.updateNote('revoked1', 'changed') + store.updateNote('nobody', 'changed') + + expect(store.get('approved1')?.note).toBe('kept') + expect(store.get('approved1')?.status).toBe('approved') + expect(store.get('revoked1')?.note).toBe('kept') + expect(store.get('revoked1')?.status).toBe('revoked') + expect(store.get('nobody')).toBeNull() + }) + + it('records approval email success and failure, each clearing the other', () => { + const store = createAccessStore(TEST_DB) + store.requestAccess('octocat') + store.approve('octocat', 'admin1') + + store.recordApprovalEmail('octocat', { error: 'email not configured' }) + let entry = store.get('octocat') + expect(entry?.approvalEmailError).toBe('email not configured') + expect(entry?.approvalEmailSentAt).toBeNull() + + store.recordApprovalEmail('octocat', { sentAt: 1234 }) + entry = store.get('octocat') + expect(entry?.approvalEmailSentAt).toBe(1234) + expect(entry?.approvalEmailError).toBeNull() + expect(store.listByStatus('approved')[0]?.approvalEmailSentAt).toBe(1234) + + store.recordApprovalEmail('octocat', { error: 'boom' }) + entry = store.get('octocat') + expect(entry?.approvalEmailSentAt).toBeNull() + expect(entry?.approvalEmailError).toBe('boom') + }) + + it('migrates an old-schema user_access table', () => { + const old = new Database(TEST_DB) + old.run(` + CREATE TABLE user_access ( + login TEXT PRIMARY KEY, + status TEXT NOT NULL CHECK (status IN ('approved', 'pending', 'revoked')), + source TEXT NOT NULL CHECK (source IN ('domain', 'env', 'admin', 'request')), + requested_at INTEGER, + decided_at INTEGER, + decided_by TEXT + ) + `) + old.run( + "INSERT INTO user_access (login, status, source, requested_at) VALUES ('legacy', 'pending', 'request', 5)", + ) + old.close() + + const store = createAccessStore(TEST_DB) + createAccessStore(TEST_DB) // idempotent + const entry = store.get('legacy') + expect(entry?.status).toBe('pending') + expect(entry?.note).toBeNull() + store.recordApprovalEmail('legacy', { sentAt: 9 }) + expect(store.get('legacy')?.approvalEmailSentAt).toBe(9) + }) }) diff --git a/test/admin-routes.test.ts b/test/admin-routes.test.ts index 6ddf46930..55ece62b1 100644 --- a/test/admin-routes.test.ts +++ b/test/admin-routes.test.ts @@ -9,6 +9,11 @@ import { createUserStore, encryptSession, } from '../src/services/auth' +import type { + EmailMessage, + EmailResult, + EmailSender, +} from '../src/services/email' const TEST_DB = '/tmp/test-admin-routes.sqlite' const SECRET = 'test-secret-key-32-bytes-long!' @@ -45,7 +50,20 @@ async function regularCookie() { ) } -function buildApp() { +/** Records every message; answers each send with `result`. */ +function fakeEmailSender(result: EmailResult = { ok: true }) { + const sent: EmailMessage[] = [] + const sender: EmailSender = { + configured: true, + async send(message) { + sent.push(message) + return result + }, + } + return { sender, sent } +} + +function buildApp(emailSender: EmailSender = fakeEmailSender().sender) { const accessStore = createAccessStore(TEST_DB) const userStore = createUserStore(TEST_DB) const app = new Hono() @@ -55,10 +73,75 @@ function buildApp() { accessStore.setApproved('adminuser', 'admin') accessStore.setApproved('regular', 'admin') app.use('*', sessionReader(accessStore)) - app.route('/admin', createAdminRoutes(accessStore, userStore)) + app.route('/admin', createAdminRoutes(accessStore, userStore, emailSender)) return { app, accessStore, userStore } } +/** A requester with a full GitHub profile and three addresses. */ +function saveRequesterProfile( + userStore: ReturnType, + login = 'pendinguser', +) { + userStore.saveGitHubProfile( + { + login, + name: 'Pat Requester', + avatar_url: 'https://example.com/p.png', + id: 42, + company: 'Acme Agency', + location: 'Springfield', + blog: 'pat.example.org', + 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', + }, + [ + { + email: 'old@example.org', + primary: false, + verified: true, + visibility: null, + }, + { + email: 'pat@example.gov', + primary: true, + verified: true, + visibility: 'private', + }, + { + email: 'unverified@example.net', + primary: false, + verified: false, + visibility: null, + }, + ], + ) +} + +async function postApprove(app: Hono, login: string) { + const cookie = await adminCookie() + return app.request('/admin/users/approve', { + method: 'POST', + headers: { + Cookie: `${COOKIE_NAME}=${cookie}`, + 'Content-Type': 'application/x-www-form-urlencoded', + 'x-forwarded-proto': 'https', + 'x-forwarded-host': 'forms.example.com', + }, + body: `login=${login}`, + }) +} + +async function getAdminPage(app: Hono) { + const cookie = await adminCookie() + const res = await app.request('/admin/users', { + headers: { Cookie: `${COOKIE_NAME}=${cookie}` }, + }) + return res.text() +} + describe('Admin Routes', () => { afterEach(cleanup) @@ -153,4 +236,212 @@ describe('Admin Routes', () => { expect(entry?.status).toBe('approved') expect(entry?.source).toBe('admin') }) + + describe('approval email', () => { + it('sends the approval email to the contact address', async () => { + const { sender, sent } = fakeEmailSender() + const { app, accessStore, userStore } = buildApp(sender) + saveRequesterProfile(userStore) + accessStore.requestAccess('pendinguser') + + const res = await postApprove(app, 'pendinguser') + + expect(res.status).toBe(302) + expect(sent).toHaveLength(1) + expect(sent[0].to).toBe('pat@example.gov') + expect(sent[0].subject).toContain('access approved') + expect(sent[0].text).toContain('https://forms.example.com/') + expect(sent[0].text).toContain('Pat Requester') + }) + + it('records when the email was sent', async () => { + const { app, accessStore, userStore } = buildApp() + saveRequesterProfile(userStore) + accessStore.requestAccess('pendinguser') + + const before = Math.floor(Date.now() / 1000) + await postApprove(app, 'pendinguser') + + const entry = accessStore.get('pendinguser') + expect(entry?.approvalEmailSentAt).toBeGreaterThanOrEqual(before) + expect(entry?.approvalEmailError).toBeNull() + }) + + it('records a failed send and still approves the user', async () => { + const { sender } = fakeEmailSender({ ok: false, error: 'SES throttled' }) + const { app, accessStore, userStore } = buildApp(sender) + saveRequesterProfile(userStore) + accessStore.requestAccess('pendinguser') + + const res = await postApprove(app, 'pendinguser') + + expect(res.status).toBe(302) + const entry = accessStore.get('pendinguser') + expect(entry?.status).toBe('approved') + expect(entry?.approvalEmailError).toBe('SES throttled') + expect(entry?.approvalEmailSentAt).toBeNull() + }) + + it('records an error and sends nothing when there is no verified email', async () => { + const { sender, sent } = fakeEmailSender() + const { app, accessStore, userStore } = buildApp(sender) + userStore.saveGitHubProfile( + { login: 'noemail', name: null, avatar_url: 'https://e.com/a.png' }, + [ + { + email: 'x@example.net', + primary: true, + verified: false, + visibility: null, + }, + ], + ) + accessStore.requestAccess('noemail') + + await postApprove(app, 'noemail') + + expect(sent).toHaveLength(0) + const entry = accessStore.get('noemail') + expect(entry?.status).toBe('approved') + expect(entry?.approvalEmailError).toBe('no verified email on file') + }) + + it('records an error when the user has no profile at all', async () => { + const { sender, sent } = fakeEmailSender() + const { app, accessStore } = buildApp(sender) + accessStore.requestAccess('ghost') + + await postApprove(app, 'ghost') + + expect(sent).toHaveLength(0) + expect(accessStore.get('ghost')?.approvalEmailError).toBe( + 'no verified email on file', + ) + }) + + it('sends nothing for an unknown login', async () => { + const { sender, sent } = fakeEmailSender() + const { app, accessStore, userStore } = buildApp(sender) + saveRequesterProfile(userStore, 'stranger') + + const res = await postApprove(app, 'stranger') + + expect(res.status).toBe(302) + expect(sent).toHaveLength(0) + expect(accessStore.get('stranger')).toBeNull() + }) + + it('sends nothing when the user is already approved', async () => { + const { sender, sent } = fakeEmailSender() + const { app, accessStore, userStore } = buildApp(sender) + saveRequesterProfile(userStore) + accessStore.setApproved('pendinguser', 'admin') + + await postApprove(app, 'pendinguser') + + expect(sent).toHaveLength(0) + }) + + it('sends when re-approving a revoked user', async () => { + const { sender, sent } = fakeEmailSender() + const { app, accessStore, userStore } = buildApp(sender) + saveRequesterProfile(userStore) + accessStore.requestAccess('pendinguser') + accessStore.deny('pendinguser', 'adminuser') + + await postApprove(app, 'pendinguser') + + expect(sent).toHaveLength(1) + expect(accessStore.get('pendinguser')?.status).toBe('approved') + }) + }) + + describe('admin page contact details', () => { + it('shows the contact email, other emails with flags and profile details', async () => { + const { app, accessStore, userStore } = buildApp() + saveRequesterProfile(userStore) + accessStore.requestAccess('pendinguser', 'I work on benefits forms.') + + const html = await getAdminPage(app) + + expect(html).toContain('href="mailto:pat@example.gov"') + expect(html).toContain('old@example.org') + expect(html).toContain('unverified@example.net') + expect(html).toContain('Primary') + expect(html).toContain('Verified') + expect(html).toContain('Unverified') + expect(html).toContain('Acme Agency') + expect(html).toContain('Springfield') + 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.') + }) + + it('escapes the note and keeps its line breaks', async () => { + const { app, accessStore, userStore } = buildApp() + saveRequesterProfile(userStore) + accessStore.requestAccess( + 'pendinguser', + 'line one\n', + ) + + 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/auth-routes.test.ts b/test/auth-routes.test.ts index d2aa71668..0d8972c1c 100644 --- a/test/auth-routes.test.ts +++ b/test/auth-routes.test.ts @@ -2,7 +2,14 @@ import { afterEach, beforeEach, describe, expect, it, mock } from 'bun:test' import { Hono } from 'hono' import { sessionReader } from '../src/entrypoints/app/middleware/auth' import { createAuthRoutes } from '../src/entrypoints/app/routes/auth' -import type { AccessStore, GitHubUser, UserStore } from '../src/services/auth' +import type { + AccessEntry, + AccessStore, + GitHubEmail, + GitHubUser, + UserProfile, + UserStore, +} from '../src/services/auth' import { COOKIE_NAME, encryptSession } from '../src/services/auth' describe('Auth Routes', () => { @@ -26,6 +33,7 @@ describe('Auth Routes', () => { // Create mock UserStore mockUserStore = { upsert: mock(() => {}), + saveGitHubProfile: mock(() => {}), get: mock(() => null), exists: mock(() => false), } @@ -39,6 +47,8 @@ describe('Auth Routes', () => { revoke: mock(() => {}), setApproved: mock(() => {}), listByStatus: mock(() => []), + recordApprovalEmail: mock(() => {}), + updateNote: mock(() => {}), } // Create app @@ -136,12 +146,8 @@ describe('Auth Routes', () => { expect(cookie).toContain('Secure') expect(cookie).toContain('SameSite=Lax') - // Verify user was persisted - expect(mockUserStore.upsert).toHaveBeenCalledWith({ - login: 'testuser', - name: 'Test User', - avatarUrl: 'https://example.com/avatar.png', - }) + // Verify user was persisted (no /user/emails mock → empty list) + expect(mockUserStore.saveGitHubProfile).toHaveBeenCalledWith(mockUser, []) }) it('redirects to request-access for unauthorized user', async () => { @@ -233,6 +239,162 @@ describe('Auth Routes', () => { }) }) + describe('GET /auth/callback persists GitHub profile and emails', () => { + const emails: GitHubEmail[] = [ + { + email: 'person@flexion.us', + primary: true, + verified: true, + visibility: 'private', + }, + { + email: 'person@example.com', + primary: false, + verified: false, + visibility: null, + }, + ] + + function mockGitHub(user: GitHubUser, userEmails: GitHubEmail[]) { + const calls: string[] = [] + global.fetch = mock(async (url: string | URL) => { + const u = url.toString() + calls.push(u) + if (u === 'https://github.com/login/oauth/access_token') { + return new Response(JSON.stringify({ access_token: 'gho_t' })) + } + if (u === 'https://api.github.com/user') { + return new Response(JSON.stringify(user)) + } + if (u === 'https://api.github.com/user/emails') { + return new Response(JSON.stringify(userEmails)) + } + return new Response('', { status: 404 }) + }) as unknown as typeof fetch + return calls + } + + async function signIn() { + const state = encodeURIComponent(JSON.stringify({ returnTo: '/' })) + return app.request(`/auth/callback?code=c&state=${state}`) + } + + const fullUser: GitHubUser = { + login: 'person', + name: null, + avatar_url: 'https://example.com/a.png', + id: 42, + company: 'Acme', + location: 'Here', + html_url: 'https://github.com/person', + } + + it('env-allowlisted users: fetches emails and saves them', async () => { + process.env.ALLOWED_USERS = 'person' + const calls = mockGitHub(fullUser, emails) + const res = await signIn() + expect(res.headers.get('Location')).toBe('/') + expect(mockAccessStore.setApproved).toHaveBeenCalledWith('person', 'env') + expect(mockUserStore.saveGitHubProfile).toHaveBeenCalledWith( + fullUser, + emails, + ) + expect( + calls.filter((u) => u === 'https://api.github.com/user/emails'), + ).toHaveLength(1) + }) + + it('domain-approved users: reuses the one emails fetch and saves them', async () => { + process.env.ALLOWED_USERS = 'someoneelse' + const calls = mockGitHub(fullUser, emails) + const res = await signIn() + expect(res.headers.get('Location')).toBe('/') + expect(mockAccessStore.setApproved).toHaveBeenCalledWith( + 'person', + 'domain', + ) + expect(mockUserStore.saveGitHubProfile).toHaveBeenCalledWith( + fullUser, + emails, + ) + expect( + calls.filter((u) => u === 'https://api.github.com/user/emails'), + ).toHaveLength(1) + }) + + it('new requesters: saves profile and emails before request-access', async () => { + process.env.ALLOWED_USERS = 'someoneelse' + const outsideEmails: GitHubEmail[] = [ + { + email: 'person@example.com', + primary: true, + verified: true, + visibility: null, + }, + ] + mockGitHub(fullUser, outsideEmails) + const res = await signIn() + expect(res.headers.get('Location')).toBe('/auth/request-access') + expect(mockAccessStore.setApproved).not.toHaveBeenCalled() + expect(mockUserStore.saveGitHubProfile).toHaveBeenCalledWith( + fullUser, + outsideEmails, + ) + }) + + 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') + // Same temporary session new requesters get, so the status page + // knows who they are. + expect(res.headers.get('Set-Cookie')).toContain(`${COOKIE_NAME}=`) + expect(res.headers.get('Set-Cookie')).not.toContain('Max-Age=0') + 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) + const base = global.fetch + global.fetch = mock(async (url: string | URL, init?: RequestInit) => { + if (url.toString() === 'https://api.github.com/user/emails') { + return new Response('', { status: 403 }) + } + return base(url, init) + }) as unknown as typeof fetch + const res = await signIn() + expect(res.headers.get('Location')).toBe('/') + expect(mockUserStore.saveGitHubProfile).toHaveBeenCalledWith(fullUser, []) + }) + }) + describe('POST /auth/signout', () => { it('clears session cookie and redirects to home', async () => { const res = await app.request('/auth/signout', { @@ -260,10 +422,26 @@ describe('Auth Routes', () => { expect(res.status).toBe(200) expect(await res.text()).toContain('@outsider') }) + + it('offers an optional, labelled note field', async () => { + const res = await app.request('/auth/request-access') + const html = await res.text() + const textarea = html.match(/]*>/)?.[0] ?? '' + expect(textarea).toContain('name="note"') + expect(textarea).toContain('maxlength="1000"') + expect(textarea).not.toContain('required') + const id = textarea.match(/id="([^"]+)"/)?.[1] + expect(id).toBeTruthy() + expect(html).toContain(`for="${id}"`) + expect(html).toContain('Tell us a little about yourself') + expect(html).toContain('Request Access') + }) }) describe('POST /auth/request-access', () => { - async function postRequestAccess(): Promise> { + async function postRequestAccess( + form?: Record, + ): Promise> { let notified: Record | undefined global.fetch = mock(async (_url: string | URL, init?: RequestInit) => { notified = JSON.parse(String(init?.body)) @@ -280,14 +458,100 @@ describe('Auth Routes', () => { Cookie: `${COOKIE_NAME}=${cookie}`, 'x-forwarded-proto': 'https', 'x-forwarded-host': 'forms.example.test', + ...(form + ? { 'Content-Type': 'application/x-www-form-urlencoded' } + : {}), }, + body: form ? new URLSearchParams(form).toString() : undefined, }) expect(res.status).toBe(302) - expect(mockAccessStore.requestAccess).toHaveBeenCalledWith('outsider') + expect(mockAccessStore.requestAccess).toHaveBeenCalled() if (!notified) throw new Error('no notification sent') return notified } + function profile(overrides: Partial = {}): UserProfile { + return { + login: 'outsider', + name: 'Out Sider', + avatarUrl: '', + createdAt: 0, + updatedAt: 0, + githubId: null, + company: null, + location: null, + blog: null, + bio: null, + publicEmail: null, + twitterUsername: null, + htmlUrl: null, + githubCreatedAt: null, + emails: [], + ...overrides, + } + } + + it('stores a null note when none is submitted', async () => { + await postRequestAccess() + expect(mockAccessStore.requestAccess).toHaveBeenCalledWith( + 'outsider', + null, + ) + }) + + it('stores the trimmed note', async () => { + await postRequestAccess({ note: ' I work at Acme ' }) + expect(mockAccessStore.requestAccess).toHaveBeenCalledWith( + 'outsider', + 'I work at Acme', + ) + }) + + it('stores null for a whitespace-only note', async () => { + await postRequestAccess({ note: ' \n ' }) + expect(mockAccessStore.requestAccess).toHaveBeenCalledWith( + 'outsider', + null, + ) + }) + + it('caps the note at 1000 characters', async () => { + await postRequestAccess({ note: 'x'.repeat(1500) }) + const calls = (mockAccessStore.requestAccess as ReturnType) + .mock.calls + expect(String(calls[0]?.[1])).toHaveLength(1000) + }) + + it('includes contact email, company and note in the notification', async () => { + mockUserStore.get = mock(() => + profile({ + company: 'Acme', + emails: [ + { + email: 'out@acme.test', + primary: true, + verified: true, + visibility: null, + }, + ], + }), + ) + const event = await postRequestAccess({ note: 'Sent by Pat' }) + const details = String(event.details) + expect(details).toContain('out@acme.test') + expect(details).toContain('Acme') + expect(details).toContain('Sent by Pat') + }) + + it('says there is no verified email when none is on file', async () => { + mockUserStore.get = mock(() => profile()) + const event = await postRequestAccess() + const details = String(event.details) + expect(details).toContain('no verified email') + expect(details).not.toContain('Company') + expect(details).not.toContain('Note') + }) + it('links to the admin page of the branch the request came from', async () => { process.env.BASE_PATH = '/story-7-thing' const event = await postRequestAccess() @@ -304,4 +568,307 @@ describe('Auth Routes', () => { expect(event.url).toBe('https://forms.example.test/admin/users') }) }) + + describe('returning requesters', () => { + const REQUESTED_AT = Date.UTC(2026, 10, 3, 23, 30) / 1000 // Nov 3, 2026 UTC + + function accessEntry( + status: AccessEntry['status'], + overrides: Partial = {}, + ): AccessEntry { + return { + login: 'outsider', + status, + source: 'request', + requestedAt: REQUESTED_AT, + decidedAt: null, + decidedBy: null, + note: null, + approvalEmailSentAt: null, + approvalEmailError: null, + ...overrides, + } + } + + function givenEntry(entry: AccessEntry | null) { + mockAccessStore.get = mock(() => entry) as unknown as AccessStore['get'] + } + + function givenProfile(overrides: Partial = {}) { + mockUserStore.get = mock(() => ({ + login: 'outsider', + name: 'Out Sider', + avatarUrl: '', + createdAt: 0, + updatedAt: 0, + githubId: null, + company: null, + location: null, + blog: null, + bio: null, + publicEmail: null, + twitterUsername: null, + htmlUrl: null, + githubCreatedAt: null, + emails: [], + ...overrides, + })) as unknown as UserStore['get'] + } + + async function sessionCookie(): Promise { + const cookie = await encryptSession( + { login: 'outsider', name: 'Out Sider', avatarUrl: '' }, + process.env.SESSION_SECRET as string, + ) + return `${COOKIE_NAME}=${cookie}` + } + + async function get(path: string, signedIn = true) { + return app.request(path, { + headers: signedIn ? { Cookie: await sessionCookie() } : {}, + }) + } + + async function post(form: Record) { + const notified: Record[] = [] + global.fetch = mock(async (_url: string | URL, init?: RequestInit) => { + notified.push(JSON.parse(String(init?.body))) + return new Response('{}', { status: 200 }) + }) as unknown as typeof fetch + const res = await app.request('/auth/request-access', { + method: 'POST', + headers: { + Cookie: await sessionCookie(), + 'Content-Type': 'application/x-www-form-urlencoded', + 'x-forwarded-proto': 'https', + 'x-forwarded-host': 'forms.example.test', + }, + body: new URLSearchParams(form).toString(), + }) + return { res, notified } + } + + describe('GET /auth/request-access', () => { + it('shows the blank form to signed-in users with no entry', async () => { + givenEntry(null) + const res = await get('/auth/request-access') + expect(res.status).toBe(200) + expect(await res.text()).toContain('name="note"') + }) + + it('sends pending users to their status page', async () => { + givenEntry(accessEntry('pending')) + const res = await get('/auth/request-access') + expect(res.status).toBe(302) + expect(res.headers.get('Location')).toBe('/auth/access-pending') + }) + + it('sends approved users home', async () => { + givenEntry(accessEntry('approved')) + const res = await get('/auth/request-access') + expect(res.status).toBe(302) + expect(res.headers.get('Location')).toBe('/') + }) + + it('treats revoked users as signed out and clears their cookie', async () => { + givenEntry(accessEntry('revoked')) + const res = await get('/auth/request-access') + const html = await res.text() + expect(html).not.toContain('@outsider') + expect(res.headers.get('Set-Cookie')).toContain('Max-Age=0') + }) + }) + + describe('GET /auth/access-pending', () => { + it('shows the submitted date and where we will email them', async () => { + givenEntry(accessEntry('pending')) + givenProfile({ + emails: [ + { + email: 'out@acme.test', + primary: true, + verified: true, + visibility: null, + }, + ], + }) + const html = await (await get('/auth/access-pending')).text() + expect(html).toContain('Nov 3, 2026') + expect(html).toContain('out@acme.test') + expect(html).not.toContain('verify an email') + }) + + it('hints at adding a verified GitHub email when none is on file', async () => { + givenEntry(accessEntry('pending')) + givenProfile() + const html = await (await get('/auth/access-pending')).text() + expect(html).toContain('verify an email') + expect(html).toContain('https://github.com/settings/emails') + }) + + it('prefills the escaped note in an update form', async () => { + givenEntry(accessEntry('pending', { note: 'Hi there & co' })) + givenProfile() + const html = await (await get('/auth/access-pending')).text() + const form = + html.match(/]*action="\/auth\/request-access"[^>]*>/)?.[0] ?? + '' + expect(form).toContain('method="post"') + const textarea = html.match(/]*>([^<]*)<\/textarea>/) + expect(textarea?.[0]).toContain('name="note"') + expect(textarea?.[1]).toBe('Hi <b>there</b> & co') + expect(html).not.toContain('there') + expect(html).toContain('Tell us a little about yourself') + expect(html).toContain('Update my request') + expect(html).not.toContain('role="status"') + }) + + it('confirms an update', async () => { + givenEntry(accessEntry('pending')) + givenProfile() + const html = await (await get('/auth/access-pending?updated=1')).text() + expect(html).toContain('role="status"') + expect(html).toContain('Your request has been updated') + }) + + it('confirms an update on the generic page after sign-out of the temporary session', async () => { + const html = await ( + await get('/auth/access-pending?updated=1', false) + ).text() + expect(html).toContain('Your request has been updated') + expect(html).not.toContain(' { + givenEntry(accessEntry('pending', { note: 'secret note' })) + const html = await (await get('/auth/access-pending', false)).text() + expect(html).toContain('Access Request Pending') + expect(html).not.toContain(' { + for (const status of ['approved', 'revoked'] as const) { + givenEntry(accessEntry(status, { note: 'secret note' })) + const html = await (await get('/auth/access-pending')).text() + expect(html).toContain('Access Request Pending') + expect(html).not.toContain(' { + it('creates a request and notifies when there is no entry', async () => { + givenEntry(null) + const { res, notified } = await post({ note: 'hello' }) + expect(res.headers.get('Location')).toBe('/auth/access-pending') + expect(mockAccessStore.requestAccess).toHaveBeenCalledWith( + 'outsider', + 'hello', + ) + expect(mockAccessStore.updateNote).not.toHaveBeenCalled() + expect(notified.map((e) => e.type)).toEqual(['access.requested']) + }) + + it('updates a changed note and sends access.request-updated', async () => { + process.env.BASE_PATH = '/story-7-thing' + givenEntry(accessEntry('pending', { note: 'old' })) + givenProfile({ + company: 'Acme', + emails: [ + { + email: 'out@acme.test', + primary: true, + verified: true, + visibility: null, + }, + ], + }) + const { res, notified } = await post({ note: ' new note ' }) + expect(res.status).toBe(302) + expect(res.headers.get('Location')).toBe( + '/story-7-thing/auth/access-pending?updated=1', + ) + expect(mockAccessStore.updateNote).toHaveBeenCalledWith( + 'outsider', + 'new note', + ) + expect(mockAccessStore.requestAccess).not.toHaveBeenCalled() + expect(notified).toHaveLength(1) + const event = notified[0] as Record + expect(event.type).toBe('access.request-updated') + expect(event.status).toBe('info') + expect(String(event.title)).toContain('@outsider') + expect(String(event.title)).toContain('story-7-thing') + expect(event.url).toBe( + 'https://forms.example.test/story-7-thing/admin/users', + ) + const details = String(event.details) + expect(details).toContain('outsider') + expect(details).toContain('story-7-thing') + expect(details).toContain('out@acme.test') + expect(details).toContain('Company: Acme') + expect(details).toContain('Note: new note') + }) + + it('clears the note when emptied, and says so', async () => { + givenEntry(accessEntry('pending', { note: 'old' })) + givenProfile() + const { notified } = await post({ note: ' ' }) + expect(mockAccessStore.updateNote).toHaveBeenCalledWith( + 'outsider', + null, + ) + expect(notified).toHaveLength(1) + expect(String(notified[0]?.details)).toContain('no verified email') + expect(String(notified[0]?.details)).toContain('Note: (removed)') + }) + + it('does nothing but redirect when the normalized note is unchanged', async () => { + givenEntry(accessEntry('pending', { note: 'same' })) + const { res, notified } = await post({ note: ' same \n' }) + expect(res.headers.get('Location')).toBe( + '/auth/access-pending?updated=1', + ) + expect(mockAccessStore.updateNote).not.toHaveBeenCalled() + expect(mockAccessStore.requestAccess).not.toHaveBeenCalled() + expect(notified).toHaveLength(0) + }) + + it('compares against the capped note', async () => { + givenEntry(accessEntry('pending', { note: 'x'.repeat(1000) })) + const { notified } = await post({ note: 'x'.repeat(1500) }) + expect(mockAccessStore.updateNote).not.toHaveBeenCalled() + expect(notified).toHaveLength(0) + }) + + it('changes nothing for approved users and sends them home', async () => { + givenEntry(accessEntry('approved')) + const { res, notified } = await post({ note: 'again' }) + expect(res.headers.get('Location')).toBe('/') + expect(mockAccessStore.updateNote).not.toHaveBeenCalled() + expect(mockAccessStore.requestAccess).not.toHaveBeenCalled() + expect(notified).toHaveLength(0) + }) + + it('keeps the session so a pending requester can return to their status', async () => { + givenEntry(accessEntry('pending')) + const { res } = await post({ note: 'changed' }) + expect(res.headers.get('Set-Cookie') ?? '').not.toContain('Max-Age=0') + }) + + it('changes nothing for revoked users', async () => { + givenEntry(accessEntry('revoked')) + const { res, notified } = await post({ note: 'again' }) + // Signed out by the session reader; signing in again leads to + // access-denied via the callback. + expect(res.headers.get('Location')).toBe('/auth/signin') + expect(mockAccessStore.updateNote).not.toHaveBeenCalled() + expect(mockAccessStore.requestAccess).not.toHaveBeenCalled() + expect(notified).toHaveLength(0) + }) + }) + }) }) 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/notify-slack.test.ts b/test/notify-slack.test.ts index b4278245f..342bb287d 100644 --- a/test/notify-slack.test.ts +++ b/test/notify-slack.test.ts @@ -210,6 +210,67 @@ describe('formatSlackMessage', () => { }) }) +describe('formatSlackMessage escaping', () => { + type Msg = { + attachments: Array<{ + blocks: Array<{ + type: string + text?: { text: string } + elements?: Array<{ text: string }> + }> + }> + } + const event: NotifyEvent = { + type: 'access.requested', + title: 'Hi & ', + status: 'info', + details: 'Note: 1 < 2 && 3 > 2 <@U123>', + timestamp: '2026-04-11T12:00:00Z', + } + + it('escapes &, < and > in the title', () => { + const msg = formatSlackMessage(event) as Msg + const section = msg.attachments[0].blocks.find((b) => b.type === 'section') + expect(section?.text?.text).toBe( + '*[access.requested]* Hi <!channel> & <https://evil.test|click>', + ) + }) + + it('escapes &, < and > in the details', () => { + const msg = formatSlackMessage(event) as Msg + const details = msg.attachments[0].blocks.filter( + (b) => b.type === 'context', + )[0] + expect(details.elements?.[0].text).toBe( + 'Note: <!here> 1 < 2 && 3 > 2 <@U123>', + ) + }) + + it('escapes access.request-updated events the same way', () => { + const msg = formatSlackMessage({ + ...event, + type: 'access.request-updated', + }) as Msg + const details = msg.attachments[0].blocks.filter( + (b) => b.type === 'context', + )[0] + expect(details.elements?.[0].text).toBe( + 'Note: <!here> 1 < 2 && 3 > 2 <@U123>', + ) + }) + + it('keeps the url link working while escaping its label', () => { + const msg = formatSlackMessage({ + ...event, + url: 'https://forms.example.test/main/admin/users', + }) as Msg + const section = msg.attachments[0].blocks.find((b) => b.type === 'section') + expect(section?.text?.text).toBe( + '*[access.requested]* ', + ) + }) +}) + describe('postToSlack', () => { let originalFetch: typeof globalThis.fetch 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('