From 7458cf0637f04638518bbc7b8e749c990f2c564c Mon Sep 17 00:00:00 2001 From: GrittyBot <30755786+codeforphilly-bot@users.noreply.github.com> Date: Sun, 29 Nov 2026 22:12:53 +0000 Subject: [PATCH 01/26] chore(plans): mark slack-account-link in-progress Co-Authored-By: Claude Opus 5.5 --- plans/slack-account-link.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/plans/slack-account-link.md b/plans/slack-account-link.md index 1b8cd7d..39c5226 100644 --- a/plans/slack-account-link.md +++ b/plans/slack-account-link.md @@ -1,5 +1,5 @@ --- -status: planned +status: in-progress depends: [] specs: - specs/api/slack-link.md From cb661635f40b40fe0acb576cc11c871fd67dee08 Mon Sep 17 00:00:00 2001 From: GrittyBot <30755786+codeforphilly-bot@users.noreply.github.com> Date: Sun, 29 Nov 2026 22:14:50 +0000 Subject: [PATCH 02/26] docs(specs): settle the gaps the Slack link and agent feed left open - slack-link: the code is 8 characters shown as two groups of four (the example had 7); the code response carries botDmUrl so the Account row can link the bot's name to a DM, as the screen asks; an account with no private profile is refused (the link lives there); redemption fails closed with no workspace configured; a 409 does not consume the code - auth: /me's slack field, which account.md already reads - conventions: the linking pair counts as credential endpoints - data-model: agent-grants contract is v2 (the new scopes change it) - agent-applications: application.visible is at notifiedAt (when the hold ended for a held one), so the cursor never skips it; events appear once a minute old; next is never null; where decidedBy, decidedVia and closedBy sit; the decide scope without its companions is refused at use (401), and a foreign workspace is not_project_admin - architecture: SLACK_TEAM_ID and SLACK_OPS_BOT_DM_URL Co-Authored-By: Claude Opus 5.5 --- specs/api/agent-applications.md | 18 ++++++++++++++---- specs/api/auth.md | 9 ++++++--- specs/api/conventions.md | 2 +- specs/api/slack-link.md | 23 +++++++++++++++-------- specs/architecture.md | 2 ++ specs/data-model.md | 2 +- 6 files changed, 39 insertions(+), 17 deletions(-) diff --git a/specs/api/agent-applications.md b/specs/api/agent-applications.md index ad9d059..8e89328 100644 --- a/specs/api/agent-applications.md +++ b/specs/api/agent-applications.md @@ -50,17 +50,23 @@ not a stored log): | Type | When (`at`) | | ---- | ----------- | -| `application.visible` | the application's `visibleAt` arrived (admins were notified) | +| `application.visible` | admins were notified (`notifiedAt`: at once, or when a held application's hold ended) | | `application.reminder` | the 14-day reminder went out (`remindedAt`) | | `application.accepted` | accepted (`decidedAt`), with `decidedBy` and `decidedVia` | | `application.closed` | closed (`closedAt`), with `closedBy` and, for an admin close, `decidedBy` | +- `application` also carries `decidedBy` (`{ slug, fullName }`, or `null`), + `decidedVia` and `closedBy`, as they stand now. - `admins` lists the project's active admins; `slackUserId` is set only for an admin with a verified [Slack link](slack-link.md). No email address, ever. - Applications from deactivated applicants produce no events, and their earlier events drop out of the feed. - Ordered by `at`, then record id. The cursor is stable across restarts - (it encodes the last `at` and id). + (it encodes the last `at` and id). `metadata.next` is the cursor to pass + next time: the last event's, or, when there are none, the position reached, + so it is never `null`. +- An event appears once it is a minute old, so a write whose timestamp was + taken just before it committed cannot land behind a cursor already read. ## POST /api/agent/applications/:projectSlug/:personSlug/decision @@ -81,7 +87,7 @@ Records an accept or a close that a project admin made in Slack. | Field | Required | Notes | | ----- | -------- | ----- | | decision | yes | `accept` \| `close` | -| onBehalfOf | yes | The Slack user who decided. Must resolve through a verified link to a person who is, now, an active project admin of `:projectSlug` ([authorization.md → On behalf of a project admin](../behaviors/authorization.md#on-behalf-of-a-project-admin)). | +| onBehalfOf | yes | The Slack user who decided; `slackTeamId` must be the workspace the site serves. Must resolve through a verified link to a person who is, now, an active project admin of `:projectSlug` ([authorization.md → On behalf of a project admin](../behaviors/authorization.md#on-behalf-of-a-project-admin)). | | role, fillRoleIds | no | As for the site's accept ([projects-applications.md](projects-applications.md)). | | note | no | For `close`: emailed to the applicant, never stored. | @@ -100,8 +106,12 @@ screen. ### Errors +- `401 unauthenticated` — no grant with `projects:applications:decide`, or a + grant that holds it without `projects:applications:read` and `slack:link` + (refused at use as well as at mint) - `403 forbidden` (`error.code = "not_project_admin"`) — the Slack user is not - linked, or the linked person is not an active admin of this project + linked (or names another workspace), or the linked person is not an active + admin of this project - `404 not_found` — no open, visible application from that person - `429 rate_limited` — more than 30 decisions per agent in 24 hours diff --git a/specs/api/auth.md b/specs/api/auth.md index cb69e3b..b887bb4 100644 --- a/specs/api/auth.md +++ b/specs/api/auth.md @@ -223,7 +223,7 @@ Empty body. The flow is purely redirect-driven. ## GET /api/auth/me -Returns the current Person (full PersonResponse shape — see [api/people.md](people.md)) plus `accountLevel`, `hasGitHubLink`, and `lastLoginMethod`. Used by the SPA on load to bootstrap the auth context and decide whether to render the "Connect GitHub" banner. +Returns the current Person (full PersonResponse shape — see [api/people.md](people.md)) plus `accountLevel`, `hasGitHubLink`, `lastLoginMethod`, and `slack`. Used by the SPA on load to bootstrap the auth context and decide whether to render the "Connect GitHub" banner. ### Response — 200 @@ -234,14 +234,17 @@ Returns the current Person (full PersonResponse shape — see [api/people.md](pe "person": { /* PersonResponse */ }, "accountLevel": "staff", "hasGitHubLink": true, - "lastLoginMethod": "github" + "lastLoginMethod": "github", + "slack": { "linked": true, "linkedAt": "2026-11-20T…" } } } ``` `hasGitHubLink` is `Person.githubUserId !== null`. `lastLoginMethod` is one of `"github" | "legacy_password" | "password_reset"`; the SPA can use it to render UI hints (e.g., "Signed in via password — connect GitHub for faster sign-in next time" inline on `/account`). -If no session, returns 200 with `data.person = null`, `data.accountLevel = "anonymous"`, `hasGitHubLink = false`, `lastLoginMethod = null`. (We deliberately do not 401 here — the frontend calls this on every page load including public pages.) +`slack` is whether the person has a verified [Slack link](slack-link.md) and since when (`{ linked: false, linkedAt: null }` when not); it never carries the Slack user id. + +If no session, returns 200 with `data.person = null`, `data.accountLevel = "anonymous"`, `hasGitHubLink = false`, `lastLoginMethod = null`, `slack = null`. (We deliberately do not 401 here — the frontend calls this on every page load including public pages.) The PersonResponse for self includes `email` (fetched from PrivateProfile) and `newsletter` state. For staff viewing other people, see [api/people.md](people.md) on which private fields are visible. diff --git a/specs/api/conventions.md b/specs/api/conventions.md index 5a4482c..009c89d 100644 --- a/specs/api/conventions.md +++ b/specs/api/conventions.md @@ -165,7 +165,7 @@ Only `/api/**` requests are counted. The SPA shell, its assets, and image thumbn - Unauthenticated reads: 300 requests / minute / IP - Authenticated reads: 300 requests / minute / account - Writes: 30 requests / minute / account (30 / minute / IP when anonymous) -- Credential endpoints: 20 requests / minute / IP. These are the routes that accept or mint a credential: `POST /api/auth/login`, `/api/auth/github/start` and `/callback`, `/api/auth/link-github`, `/api/auth/password-reset/*`, and `POST /api/account-claim/by-password`. Session reads such as `GET /api/auth/me` (called on every page load) and `/api/auth/refresh` are ordinary reads. +- Credential endpoints: 20 requests / minute / IP. These are the routes that accept or mint a credential: `POST /api/auth/login`, `/api/auth/github/start` and `/callback`, `/api/auth/link-github`, `/api/auth/password-reset/*`, `POST /api/account-claim/by-password`, and the Slack linking pair `POST /api/account/slack-link/code` and `POST /api/agent/slack-links` ([slack-link.md](slack-link.md)). Session reads such as `GET /api/auth/me` (called on every page load) and `/api/auth/refresh` are ordinary reads. Per-IP caps assume the gateway delivers the real client address in the first `X-Forwarded-For` hop (the NodeBalancer speaks PROXY protocol to Envoy — cfp-live-cluster #203). diff --git a/specs/api/slack-link.md b/specs/api/slack-link.md index 4b0c244..d3ffb77 100644 --- a/specs/api/slack-link.md +++ b/specs/api/slack-link.md @@ -25,31 +25,37 @@ No body. Returns a fresh code and invalidates any earlier unredeemed code for the caller. ```json -{ "success": true, "data": { "code": "K7Q-4MZP", "expiresAt": "..." } } +{ "success": true, "data": { "code": "K7QW-4MZP", "expiresAt": "...", "botDmUrl": "https://…" } } ``` -- 8 characters from an unambiguous alphabet (no `0/O`, `1/I/L`), shown with a - hyphen; matched case-insensitively, hyphen optional. +- 8 characters from an unambiguous alphabet (no `0/O`, `1/I/L`), shown as two + groups of four with a hyphen; matched case-insensitively, hyphen optional. +- `botDmUrl` is a link that opens a direct message with the ops bot in Slack, + from configuration (`SLACK_OPS_BOT_DM_URL`), or `null` when none is set; the + Account screen links the bot's name to it. - Lives **10 minutes**, redeemable once. - Held **in memory only**, as a hash; a restart drops pending codes and the member asks for a new one. Codes are never written to either store or a log. - Counts as a credential endpoint for rate limiting ([conventions.md](conventions.md#rate-limiting)); at most 5 codes per account per hour. -- Refused for agent accounts (`422`). +- Refused for agent accounts (`422`, `error.code = "agent_account"`) and for + an account with no private profile (`422`, `error.code = + "no_private_profile"`), since the link is stored there. ## POST /api/agent/slack-links The bot calls this when a member DMs it a code. ```json -{ "code": "K7Q-4MZP", "slackTeamId": "T…", "slackUserId": "U…" } +{ "code": "K7QW-4MZP", "slackTeamId": "T…", "slackUserId": "U…" } ``` On success, in the same request: sets `PrivateProfile.slack = { teamId, userId, linkedAt }` for the person who issued the code and consumes the code. -`slackTeamId` must be the workspace the site serves (configured; mismatch -`422`). +`slackTeamId` must be the workspace the site serves (`SLACK_TEAM_ID`; +mismatch `422`). With no workspace configured every redemption is refused +(`422`): the site fails closed rather than link to an unknown workspace. ```json { "success": true, "data": { "personSlug": "jane", "linkedAt": "..." } } @@ -63,7 +69,8 @@ The bot replies to the member in the DM; the site emails nothing. code; one response for all three - `409 conflict` (`error.code = "slack_user_linked"`) — that Slack user is already linked to a different site account; the member disconnects the other - account first + account first. The code is not consumed, so it still works for its ten + minutes once they have. - `429 rate_limited` — more than 10 failed redemptions per agent per hour (guessing); further calls are refused for an hour diff --git a/specs/architecture.md b/specs/architecture.md index a5fed30..b297777 100644 --- a/specs/architecture.md +++ b/specs/architecture.md @@ -181,6 +181,8 @@ Runtime configuration (sealed-secrets in our cluster): | `SAML_PRIVATE_KEY` / `SAML_CERTIFICATE` | Slack SAML IdP cert chain — see [api/saml.md](api/saml.md) | | `SAML_ENTITY_ID` | Optional. Stable SAML IdP entity ID / assertion `Issuer` (default `https://codeforphilly.org/api/saml/slack/metadata`). Deliberately independent of `CFP_SITE_HOST` so cutover doesn't change the identifier Slack has on file — see [api/saml.md#idp-identity-and-hosts](api/saml.md#idp-identity-and-hosts). | | `SLACK_TEAM_HOST` | Slack workspace host (default `codeforphilly.slack.com`). Used by the `/chat` redirect ([api/chat](screens/chat.md)) and the SAML SP entity binding (ACS URL, NameQualifier). Never used for our own IdP entity ID or endpoint URLs. | +| `SLACK_TEAM_ID` | The Slack workspace id (`T…`) the site serves. A [Slack link](api/slack-link.md) or an agent's on-behalf decision naming another workspace is refused; unset, no link can be made. | +| `SLACK_OPS_BOT_DM_URL` | Optional. A link that opens a direct message with the ops bot; the Account screen's Slack row links the bot's name to it. | | `POSTMARK_SERVER_TOKEN` | Optional. When set, mutates the notifier from the no-op `LoggingNotifier` to the live `EmailNotifier` (Postmark transport). | | `POSTMARK_MESSAGE_STREAM` | Optional. Postmark message stream for outbound mail (default `outbound`). | | `CFP_NOTIFICATION_FROM` | Required when `POSTMARK_SERVER_TOKEN` is set; the `From:` address on outbound mail. | diff --git a/specs/data-model.md b/specs/data-model.md index 4ce5cf4..0be806e 100644 --- a/specs/data-model.md +++ b/specs/data-model.md @@ -206,7 +206,7 @@ is (its hash is private — [private-storage.md](behaviors/private-storage.md)). **Sheet:** `agent-grants` **Path template:** `agent-grants/${personSlug}/${id}.toml` -**Contract:** `codeforphilly.org/agent-grants/v1` +**Contract:** `codeforphilly.org/agent-grants/v2` (v2 adds the Slack and applications scopes) | Field | Type | Notes | | ------- | ------ | ------- | From 842bcb2c91140a1327c52ae85a55d40277404d04 Mon Sep 17 00:00:00 2001 From: GrittyBot <30755786+codeforphilly-bot@users.noreply.github.com> Date: Sun, 29 Nov 2026 22:14:54 +0000 Subject: [PATCH 03/26] feat(shared): the Slack and applications scopes, and the Slack link on private profiles AGENT_SCOPES gains slack:link, projects:applications:read and projects:applications:decide, with AGENT_SCOPE_REQUIRES naming each scope's companions. agent-grants/v2 is generated and vendored into the API mirror (with gitsheets contracts adopt; provenance lands when the data repo adopts from the published URL). PrivateProfile gains the optional slack { teamId, userId, linkedAt }. Co-Authored-By: Claude Opus 5.5 --- apps/api/gitsheets/agent-grants.toml | 2 +- .../codeforphilly.org/agent-grants/v2.toml | 46 +++++++++++++ .../codeforphilly.org/agent-grants/v2.json | 65 +++++++++++++++++++ packages/shared/src/contracts.ts | 3 +- packages/shared/src/schemas/agent-grant.ts | 24 +++++-- packages/shared/src/schemas/index.ts | 4 +- .../shared/src/schemas/private-profile.ts | 12 ++++ 7 files changed, 148 insertions(+), 8 deletions(-) create mode 100644 apps/api/gitsheets/contracts/codeforphilly.org/agent-grants/v2.toml create mode 100644 contracts/codeforphilly.org/agent-grants/v2.json diff --git a/apps/api/gitsheets/agent-grants.toml b/apps/api/gitsheets/agent-grants.toml index aaebbb5..105cdd9 100644 --- a/apps/api/gitsheets/agent-grants.toml +++ b/apps/api/gitsheets/agent-grants.toml @@ -7,4 +7,4 @@ root = "agent-grants" # Public on purpose: which programs may act, with which scopes, granted by # whom, until when. The token and its hash are never here; the hash lives in # the site's private store. The only writer is the site. -implements = ["codeforphilly.org/agent-grants/v1"] +implements = ["codeforphilly.org/agent-grants/v2"] diff --git a/apps/api/gitsheets/contracts/codeforphilly.org/agent-grants/v2.toml b/apps/api/gitsheets/contracts/codeforphilly.org/agent-grants/v2.toml new file mode 100644 index 0000000..32d71cb --- /dev/null +++ b/apps/api/gitsheets/contracts/codeforphilly.org/agent-grants/v2.toml @@ -0,0 +1,46 @@ +"$id" = "https://codeforphilly.org/agent-grants/v2" +"$schema" = "http://json-schema.org/draft-07/schema#" +required = ["createdAt", "createdBySlug", "expiresAt", "id", "label", "personSlug", "scopes"] +title = "Agent grant" +type = "object" + +[properties.createdAt] +format = "date-time" +pattern = '^(?:(?:\d\d[2468][048]|\d\d[13579][26]|\d\d0[48]|[02468][048]00|[13579][26]00)-02-29|\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\d|30)|(?:02)-(?:0[1-9]|1\d|2[0-8])))T(?:(?:[01]\d|2[0-3]):[0-5]\d(?::[0-5]\d(?:\.\d+)?)?(?:Z|([+-](?:[01]\d|2[0-3]):[0-5]\d)))$' +type = "string" + +[properties.createdBySlug] +minLength = 1 +type = "string" + +[properties.expiresAt] +format = "date-time" +pattern = '^(?:(?:\d\d[2468][048]|\d\d[13579][26]|\d\d0[48]|[02468][048]00|[13579][26]00)-02-29|\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\d|30)|(?:02)-(?:0[1-9]|1\d|2[0-8])))T(?:(?:[01]\d|2[0-3]):[0-5]\d(?::[0-5]\d(?:\.\d+)?)?(?:Z|([+-](?:[01]\d|2[0-3]):[0-5]\d)))$' +type = "string" + +[properties.id] +format = "uuid" +pattern = "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$" +type = "string" + +[properties.label] +maxLength = 80 +minLength = 1 +type = "string" + +[properties.personSlug] +minLength = 1 +type = "string" + +[properties.revokedAt] +format = "date-time" +pattern = '^(?:(?:\d\d[2468][048]|\d\d[13579][26]|\d\d0[48]|[02468][048]00|[13579][26]00)-02-29|\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\d|30)|(?:02)-(?:0[1-9]|1\d|2[0-8])))T(?:(?:[01]\d|2[0-3]):[0-5]\d(?::[0-5]\d(?:\.\d+)?)?(?:Z|([+-](?:[01]\d|2[0-3]):[0-5]\d)))$' +type = "string" + +[properties.scopes] +minItems = 1 +type = "array" + +[properties.scopes.items] +enum = ["moderation:read", "moderation:vote", "moderation:purge", "slack:link", "projects:applications:read", "projects:applications:decide"] +type = "string" diff --git a/contracts/codeforphilly.org/agent-grants/v2.json b/contracts/codeforphilly.org/agent-grants/v2.json new file mode 100644 index 0000000..42e97f9 --- /dev/null +++ b/contracts/codeforphilly.org/agent-grants/v2.json @@ -0,0 +1,65 @@ +{ + "$schema": "http://json-schema.org/draft-07/schema#", + "$id": "https://codeforphilly.org/agent-grants/v2", + "title": "Agent grant", + "type": "object", + "properties": { + "id": { + "type": "string", + "format": "uuid", + "pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$" + }, + "personSlug": { + "type": "string", + "minLength": 1 + }, + "label": { + "type": "string", + "minLength": 1, + "maxLength": 80 + }, + "scopes": { + "minItems": 1, + "type": "array", + "items": { + "type": "string", + "enum": [ + "moderation:read", + "moderation:vote", + "moderation:purge", + "slack:link", + "projects:applications:read", + "projects:applications:decide" + ] + } + }, + "createdAt": { + "type": "string", + "format": "date-time", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d(?:\\.\\d+)?)?(?:Z|([+-](?:[01]\\d|2[0-3]):[0-5]\\d)))$" + }, + "createdBySlug": { + "type": "string", + "minLength": 1 + }, + "expiresAt": { + "type": "string", + "format": "date-time", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d(?:\\.\\d+)?)?(?:Z|([+-](?:[01]\\d|2[0-3]):[0-5]\\d)))$" + }, + "revokedAt": { + "type": "string", + "format": "date-time", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d(?:\\.\\d+)?)?(?:Z|([+-](?:[01]\\d|2[0-3]):[0-5]\\d)))$" + } + }, + "required": [ + "createdAt", + "createdBySlug", + "expiresAt", + "id", + "label", + "personSlug", + "scopes" + ] +} diff --git a/packages/shared/src/contracts.ts b/packages/shared/src/contracts.ts index f87b312..3afdb92 100644 --- a/packages/shared/src/contracts.ts +++ b/packages/shared/src/contracts.ts @@ -66,7 +66,8 @@ export const SHEET_CONTRACTS = { // v1 was hand-authored before contracts were generated; v2 is the first // generated version (it adds the evaluatedAt datetime pattern). 'person-evaluations': { schema: PersonEvaluationSchema, version: 2, title: 'Person evaluation' }, - 'agent-grants': { schema: AgentGrantSchema, version: 1, title: 'Agent grant' }, + // v2 adds the Slack and applications scopes (specs/api/agents.md → Grants). + 'agent-grants': { schema: AgentGrantSchema, version: 2, title: 'Agent grant' }, 'spam-purges': { schema: SpamPurgeSchema, version: 1, title: 'Spam purge' }, } as const satisfies Record; diff --git a/packages/shared/src/schemas/agent-grant.ts b/packages/shared/src/schemas/agent-grant.ts index a9d42a2..a07f8ea 100644 --- a/packages/shared/src/schemas/agent-grant.ts +++ b/packages/shared/src/schemas/agent-grant.ts @@ -4,13 +4,29 @@ import { references } from '../references.js'; /** * The scopes an agent grant may carry — specs/api/agents.md → Grants. There - * are no others; `moderation:purge` is never implied by another scope and a - * grant carrying it must also carry `moderation:read` (enforced where grants - * are minted, not here, so the published contract stays a plain list). + * are no others. `moderation:purge` is never implied by another scope and a + * grant carrying it must also carry `moderation:read`; + * `projects:applications:decide` must also carry `projects:applications:read` + * and `slack:link` ({@link AGENT_SCOPE_REQUIRES}). Those rules are enforced + * where grants are minted and where the scope is used, not here, so the + * published contract stays a plain list. */ -export const AGENT_SCOPES = ['moderation:read', 'moderation:vote', 'moderation:purge'] as const; +export const AGENT_SCOPES = [ + 'moderation:read', + 'moderation:vote', + 'moderation:purge', + 'slack:link', + 'projects:applications:read', + 'projects:applications:decide', +] as const; export type AgentScope = (typeof AGENT_SCOPES)[number]; +/** The companion scopes a scope cannot be granted (or used) without. */ +export const AGENT_SCOPE_REQUIRES: Readonly>> = { + 'moderation:purge': ['moderation:read'], + 'projects:applications:decide': ['projects:applications:read', 'slack:link'], +}; + /** * A scoped API grant for an agent account (an automated moderator) — the * `agent-grants` sheet, `agent-grants/${personSlug}/${id}`. Public: which diff --git a/packages/shared/src/schemas/index.ts b/packages/shared/src/schemas/index.ts index 9ea3269..d1d0041 100644 --- a/packages/shared/src/schemas/index.ts +++ b/packages/shared/src/schemas/index.ts @@ -55,7 +55,7 @@ export { RevocationSchema } from './revocation.js'; export type { Revocation } from './revocation.js'; export { PrivateProfileSchema } from './private-profile.js'; -export type { PrivateProfile, Newsletter, GitHubFacts, EmailBounce } from './private-profile.js'; +export type { PrivateProfile, Newsletter, GitHubFacts, EmailBounce, SlackLink } from './private-profile.js'; export { LegacyPasswordCredentialSchema } from './legacy-password-credential.js'; export type { LegacyPasswordCredential } from './legacy-password-credential.js'; @@ -79,7 +79,7 @@ export { } from './person-evaluation.js'; export type { PersonEvaluation, EvaluatorKind } from './person-evaluation.js'; -export { AgentGrantSchema, AgentGrantSecretSchema, AGENT_SCOPES } from './agent-grant.js'; +export { AgentGrantSchema, AgentGrantSecretSchema, AGENT_SCOPES, AGENT_SCOPE_REQUIRES } from './agent-grant.js'; export type { AgentGrant, AgentGrantSecret, AgentScope } from './agent-grant.js'; export { diff --git a/packages/shared/src/schemas/private-profile.ts b/packages/shared/src/schemas/private-profile.ts index aaaa6dc..fbf092e 100644 --- a/packages/shared/src/schemas/private-profile.ts +++ b/packages/shared/src/schemas/private-profile.ts @@ -35,6 +35,16 @@ const EmailBounceSchema = z.object({ inactive: z.boolean().optional(), }); +/** + * The verified link to a Slack user (specs/api/slack-link.md). Set and + * cleared only by the linking endpoints; the only mapping anything routes on. + */ +const SlackLinkSchema = z.object({ + teamId: z.string().regex(/^[A-Z0-9]{2,32}$/), + userId: z.string().regex(/^[A-Z0-9]{2,32}$/), + linkedAt: z.string().datetime({ offset: true }), +}); + export const PrivateProfileSchema = z.object({ personId: z.string().uuid(), email: z.string().email().toLowerCase(), @@ -44,6 +54,7 @@ export const PrivateProfileSchema = z.object({ /** Set whenever the SAML IdP issues an assertion for this person. */ lastSlackSsoAt: z.string().datetime({ offset: true }).nullable().optional(), emailBounce: EmailBounceSchema.nullable().optional(), + slack: SlackLinkSchema.nullable().optional(), updatedAt: z.string().datetime({ offset: true }), }); @@ -51,3 +62,4 @@ export type PrivateProfile = z.infer; export type Newsletter = z.infer; export type GitHubFacts = z.infer; export type EmailBounce = z.infer; +export type SlackLink = z.infer; From c352bace6d5ae9fe862c301355ac1427e0e18b78 Mon Sep 17 00:00:00 2001 From: GrittyBot <30755786+codeforphilly-bot@users.noreply.github.com> Date: Sun, 29 Nov 2026 22:19:19 +0000 Subject: [PATCH 04/26] feat(api): index Slack links on private profiles and keep them through profile rewrites MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit bySlackUserId (teamId:userId → personId) is rebuilt with the other private indices, so a link, a disconnect or a purge is reflected at once. The profile rewrites on a GitHub email change, an account claim, a claim merge and a staff email edit rebuilt the profile field by field and would have dropped the link; they carry it now. Co-Authored-By: Claude Opus 5.5 --- apps/api/src/services/account-claim.ts | 3 +++ apps/api/src/services/github-account.ts | 2 ++ apps/api/src/services/person.write.ts | 1 + apps/api/src/store/private/base.ts | 14 ++++++++++++++ apps/api/src/store/private/interface.ts | 4 ++++ 5 files changed, 24 insertions(+) diff --git a/apps/api/src/services/account-claim.ts b/apps/api/src/services/account-claim.ts index ea03056..d3c501c 100644 --- a/apps/api/src/services/account-claim.ts +++ b/apps/api/src/services/account-claim.ts @@ -560,6 +560,7 @@ export class AccountClaimService { email: primaryEmail.toLowerCase(), emailRefreshedAt: now, newsletter: currentProfile?.newsletter ?? null, + slack: currentProfile?.slack ?? null, updatedAt: now, }); tx.private.putProfile(profile); @@ -704,6 +705,8 @@ export class AccountClaimService { email: requesterProfile.email, emailRefreshedAt: now, newsletter: claimedProfile?.newsletter ?? requesterProfile.newsletter ?? null, + // Same human: a Slack link made from either account survives the merge. + slack: requesterProfile.slack ?? claimedProfile?.slack ?? null, updatedAt: now, }); tx.private.putProfile(merged); diff --git a/apps/api/src/services/github-account.ts b/apps/api/src/services/github-account.ts index 4c2f48f..e51c1df 100644 --- a/apps/api/src/services/github-account.ts +++ b/apps/api/src/services/github-account.ts @@ -165,6 +165,8 @@ export class GitHubAccountService { newsletter: currentProfile?.newsletter ?? null, lastSlackSsoAt: currentProfile?.lastSlackSsoAt ?? null, emailBounce: currentProfile?.emailBounce ?? null, + // The Slack link is the person's, not the address's (slack-link.md). + slack: currentProfile?.slack ?? null, github: identity.user ? githubFactsFrom(identity.user, 'ok', now) : (currentProfile?.github ?? null), updatedAt: now, }); diff --git a/apps/api/src/services/person.write.ts b/apps/api/src/services/person.write.ts index 4c0f400..9c10308 100644 --- a/apps/api/src/services/person.write.ts +++ b/apps/api/src/services/person.write.ts @@ -173,6 +173,7 @@ export class PersonWriteService { email: input.email.toLowerCase(), emailRefreshedAt: now, newsletter: existingProfile?.newsletter ?? null, + slack: existingProfile?.slack ?? null, updatedAt: now, }); tx.private.putProfile(profile); diff --git a/apps/api/src/store/private/base.ts b/apps/api/src/store/private/base.ts index d91fc48..a165949 100644 --- a/apps/api/src/store/private/base.ts +++ b/apps/api/src/store/private/base.ts @@ -14,6 +14,11 @@ import type { } from '@cfp/shared/schemas'; import type { PrivateIndices, PrivateStore, PrivateStoreTx } from './interface.js'; +/** The `bySlackUserId` key: one site account per Slack user within a workspace. */ +export function slackKey(teamId: string, userId: string): string { + return `${teamId}:${userId}`; +} + /** * Shared in-memory state and logic for both PrivateStore backends. * @@ -34,6 +39,7 @@ export abstract class BasePrivateStore implements PrivateStore { byEmail: new Map(), byUnsubscribeToken: new Map(), legacyPasswordByPersonId: this.legacyPasswords, + bySlackUserId: new Map(), }; /** Fetch the raw bytes of a .jsonl file by key. Return null if absent. */ @@ -84,6 +90,7 @@ export abstract class BasePrivateStore implements PrivateStore { private rebuildIndices(): void { this.indices.byEmail.clear(); this.indices.byUnsubscribeToken.clear(); + this.indices.bySlackUserId.clear(); this.grantIdByHash.clear(); for (const secret of this.grantSecrets.values()) this.grantIdByHash.set(secret.tokenHash, secret.grantId); @@ -93,6 +100,9 @@ export abstract class BasePrivateStore implements PrivateStore { if (token) { this.indices.byUnsubscribeToken.set(token, profile.personId); } + if (profile.slack) { + this.indices.bySlackUserId.set(slackKey(profile.slack.teamId, profile.slack.userId), profile.personId); + } } } @@ -117,6 +127,10 @@ export abstract class BasePrivateStore implements PrivateStore { return this.indices.byEmail.get(email.toLowerCase()) ?? null; } + findPersonIdBySlackUser(teamId: string, userId: string): string | null { + return this.indices.bySlackUserId.get(slackKey(teamId, userId)) ?? null; + } + async *listAllProfiles(): AsyncIterable { for (const profile of this.profiles.values()) { yield profile; diff --git a/apps/api/src/store/private/interface.ts b/apps/api/src/store/private/interface.ts index a71acd3..1bc4b7f 100644 --- a/apps/api/src/store/private/interface.ts +++ b/apps/api/src/store/private/interface.ts @@ -14,6 +14,8 @@ export interface PrivateIndices { readonly byUnsubscribeToken: Map; /** personId → LegacyPasswordCredential */ readonly legacyPasswordByPersonId: Map; + /** `${teamId}:${userId}` → personId, from `slack` on profiles (specs/data-model.md). */ + readonly bySlackUserId: Map; } /** @@ -57,6 +59,8 @@ export interface PrivateStore { putProfile(profile: PrivateProfile): Promise; deleteProfile(personId: string): Promise; findPersonIdByEmail(email: string): Promise; + /** The person whose verified Slack link is this workspace's user, or null. */ + findPersonIdBySlackUser(teamId: string, userId: string): string | null; listAllProfiles(): AsyncIterable; // --- Legacy passwords --- From 0e0df5fec72a5feef24a1999210628f9ef29b8b3 Mon Sep 17 00:00:00 2001 From: GrittyBot <30755786+codeforphilly-bot@users.noreply.github.com> Date: Sun, 29 Nov 2026 22:19:19 +0000 Subject: [PATCH 05/26] feat(api): Slack linking codes, the agent's redemption, and me.slack POST /api/account/slack-link/code issues an 8-character code (two groups of four, no 0/O/1/I/L), hashed in memory for ten minutes, one live code per person, five per hour. POST /api/agent/slack-links (slack:link) redeems it for the Slack user who sent it: unknown, expired, used and orphaned codes answer one 404 code_invalid, ten failures lock the agent out for an hour, another workspace (or none configured) is 422, and a Slack user linked elsewhere is 409 without spending the code. DELETE /api/account/slack-link clears it. /api/auth/me reports { linked, linkedAt }, never the user id. Minting enforces every scope's companions; /api/agent/* routes check scope and companions before the body (401). Both linking paths count as credential endpoints. Co-Authored-By: Claude Opus 5.5 --- apps/api/src/app.ts | 2 + apps/api/src/auth/caller.ts | 24 +- apps/api/src/env.ts | 10 + apps/api/src/lib/errors.ts | 6 +- apps/api/src/plugins/rate-limit.ts | 3 + apps/api/src/plugins/services.ts | 6 + apps/api/src/routes/auth.ts | 4 + apps/api/src/routes/slack-link.ts | 68 +++++ apps/api/src/services/agents.ts | 17 +- apps/api/src/services/slack-link.ts | 222 ++++++++++++++++ apps/api/tests/helpers/agent-fixtures.ts | 6 +- apps/api/tests/slack-link.test.ts | 323 +++++++++++++++++++++++ 12 files changed, 681 insertions(+), 10 deletions(-) create mode 100644 apps/api/src/routes/slack-link.ts create mode 100644 apps/api/src/services/slack-link.ts create mode 100644 apps/api/tests/slack-link.test.ts diff --git a/apps/api/src/app.ts b/apps/api/src/app.ts index 32e9a89..5f44cbc 100644 --- a/apps/api/src/app.ts +++ b/apps/api/src/app.ts @@ -68,6 +68,7 @@ import { attachmentRoutes } from './routes/attachments.js'; import { chatRoutes } from './routes/chat.js'; import { moderationRoutes } from './routes/moderation.js'; import { agentRoutes } from './routes/agents.js'; +import { slackLinkRoutes } from './routes/slack-link.js'; import { webhookRoutes } from './routes/webhooks.js'; import { samlRoutes } from './routes/saml.js'; import { internalRoutes } from './routes/internal.js'; @@ -223,6 +224,7 @@ export async function buildApp(opts: BuildAppOptions = {}): Promise { + const agent = request.agent; + const needed = [scope, ...(AGENT_SCOPE_REQUIRES[scope] ?? [])]; + if (agent && needed.every((s) => agent.scopes.has(s))) { + return { kind: 'agent', session: agentSessionContext(agent), agent }; + } + throw new UnauthenticatedError('An agent grant with this scope is required'); +} diff --git a/apps/api/src/env.ts b/apps/api/src/env.ts index c9f1a2e..79d0cdf 100644 --- a/apps/api/src/env.ts +++ b/apps/api/src/env.ts @@ -117,6 +117,14 @@ export const EnvSchema = z.object({ * See specs/api/webhooks.md. */ POSTMARK_WEBHOOK_SECRET: z.string().min(16).optional(), + /** + * The Slack workspace id (`T…`) the site serves. A Slack link or an + * agent's on-behalf decision naming another workspace is refused; unset, + * no link can be made (specs/api/slack-link.md). + */ + SLACK_TEAM_ID: z.string().regex(/^T[A-Z0-9]+$/).optional(), + /** Optional link that opens a DM with the ops bot, for the Account screen. */ + SLACK_OPS_BOT_DM_URL: z.url().optional(), }); export type Env = z.infer; @@ -159,6 +167,8 @@ export const envJsonSchema = { POSTMARK_SERVER_TOKEN: { type: 'string' }, POSTMARK_MESSAGE_STREAM: { type: 'string', default: 'outbound' }, POSTMARK_WEBHOOK_SECRET: { type: 'string', minLength: 16 }, + SLACK_TEAM_ID: { type: 'string', pattern: '^T[A-Z0-9]+$' }, + SLACK_OPS_BOT_DM_URL: { type: 'string', pattern: '^https://' }, CFP_NOTIFICATION_FROM: { type: 'string', default: 'Code for Philly ', diff --git a/apps/api/src/lib/errors.ts b/apps/api/src/lib/errors.ts index aeb15ef..c41a951 100644 --- a/apps/api/src/lib/errors.ts +++ b/apps/api/src/lib/errors.ts @@ -68,9 +68,11 @@ export class ForbiddenError extends Error { /** Thrown when a resource is not found (404). */ export class ApiNotFoundError extends Error { - constructor(message = 'Not found') { + readonly code: string; + constructor(message = 'Not found', code = 'not_found') { super(message); this.name = 'ApiNotFoundError'; + this.code = code; } } @@ -144,7 +146,7 @@ export function mapError( } if (err instanceof ApiNotFoundError) { - void reply.code(404).send(errorResponse('not_found', err.message, traceId)); + void reply.code(404).send(errorResponse(err.code, err.message, traceId)); return; } diff --git a/apps/api/src/plugins/rate-limit.ts b/apps/api/src/plugins/rate-limit.ts index a239947..c0ca370 100644 --- a/apps/api/src/plugins/rate-limit.ts +++ b/apps/api/src/plugins/rate-limit.ts @@ -89,6 +89,9 @@ const CREDENTIAL_PATHS = [ '/api/auth/link-github', '/api/auth/password-reset/', '/api/account-claim/by-password', + // The Slack linking pair mints and accepts a one-time code (slack-link.md). + '/api/account/slack-link/code', + '/api/agent/slack-links', ]; function pathOf(url: string): string { diff --git a/apps/api/src/plugins/services.ts b/apps/api/src/plugins/services.ts index b37a5bd..b10a457 100644 --- a/apps/api/src/plugins/services.ts +++ b/apps/api/src/plugins/services.ts @@ -43,6 +43,7 @@ import { ServerClient } from 'postmark'; import { FollowerMailer } from '../services/follower-mail.js'; import { ProjectApplicationService } from '../services/project-application.js'; import { ApplicationNotices } from '../services/application-notices.js'; +import { SlackLinkService } from '../services/slack-link.js'; declare module 'fastify' { interface FastifyInstance { @@ -74,6 +75,7 @@ declare module 'fastify' { agents: AgentService; agentPurge: AgentPurgeService; spamPurges: SpamPurgeLogService; + slackLinks: SlackLinkService; }; /** Shared in-memory state — write routes call StateApply.apply against this. */ inMemoryState: InMemoryState; @@ -198,6 +200,10 @@ async function servicesPlugin(fastify: FastifyInstance): Promise { webUrl: dataRepoWebUrl(fastify.config.CFP_DATA_REMOTE), branch: fastify.config.CFP_DATA_BRANCH ?? 'published', }), + slackLinks: new SlackLinkService(state, fastify.store.private, { + teamId: fastify.config.SLACK_TEAM_ID, + botDmUrl: fastify.config.SLACK_OPS_BOT_DM_URL, + }), }); } diff --git a/apps/api/src/routes/auth.ts b/apps/api/src/routes/auth.ts index 6db22ab..6c95e10 100644 --- a/apps/api/src/routes/auth.ts +++ b/apps/api/src/routes/auth.ts @@ -14,6 +14,7 @@ import { createHash, randomBytes } from 'node:crypto'; import type { FastifyInstance, FastifyReply, FastifyRequest } from 'fastify'; import { errors as JoseErrors } from 'jose'; import { ok } from '../lib/response.js'; +import { slackStatus } from '../services/slack-link.js'; import { UnauthenticatedError, ConflictError, ApiNotFoundError } from '../lib/errors.js'; import { REFRESH_TTL_SECONDS, verifyRefresh, issueSession } from '../auth/jwt.js'; import { @@ -300,6 +301,9 @@ export async function authRoutes(fastify: FastifyInstance): Promise { // Undefined when the session predates the loginMethod claim or when // anonymous. Returned as null for the SPA to treat uniformly. lastLoginMethod: session.loginMethod ?? null, + // Whether the person has a verified Slack link, never its user id + // (specs/api/slack-link.md). + slack: person ? slackStatus(await fastify.store.private.getProfile(person.id)) : null, }); }, ); diff --git a/apps/api/src/routes/slack-link.ts b/apps/api/src/routes/slack-link.ts new file mode 100644 index 0000000..af6c40e --- /dev/null +++ b/apps/api/src/routes/slack-link.ts @@ -0,0 +1,68 @@ +/** + * Slack account link routes — specs/api/slack-link.md. + * + * POST /api/account/slack-link/code — user (self): a one-time linking code + * DELETE /api/account/slack-link — user (self): remove the link + * POST /api/agent/slack-links — agent:slack:link: redeem a code + * + * None of these writes a public commit: the link lives on the private + * profile. The code and the Slack ids travel in request and response bodies, + * which are never logged. + */ +import type { FastifyInstance } from 'fastify'; + +import { agentScopeCaller } from '../auth/caller.js'; +import { requireSignedIn } from '../auth/require.js'; +import { ok } from '../lib/response.js'; + +export async function slackLinkRoutes(fastify: FastifyInstance): Promise { + const links = () => fastify.services.slackLinks; + + fastify.post( + '/api/account/slack-link/code', + { schema: { tags: ['slack-link'], summary: 'Issue a one-time Slack linking code for the caller' } }, + async (request) => { + const session = requireSignedIn(request.session); + return ok(await links().issue(session.person!)); + }, + ); + + fastify.delete( + '/api/account/slack-link', + { schema: { tags: ['slack-link'], summary: "Remove the caller's Slack link" } }, + async (request, reply) => { + const session = requireSignedIn(request.session); + await links().unlink(session.person!); + return reply.code(204).send(); + }, + ); + + fastify.post( + '/api/agent/slack-links', + { + // Scope before body: a caller without the grant learns nothing from validation. + preValidation: async (request) => { + agentScopeCaller(request, 'slack:link'); + }, + schema: { + tags: ['slack-link'], + summary: 'Redeem a linking code for the Slack user who sent it (agent:slack:link)', + body: { + type: 'object', + properties: { + code: { type: 'string', maxLength: 32 }, + slackTeamId: { type: 'string', maxLength: 32 }, + slackUserId: { type: 'string', maxLength: 32 }, + }, + required: ['code', 'slackTeamId', 'slackUserId'], + additionalProperties: false, + }, + }, + }, + async (request) => { + const caller = agentScopeCaller(request, 'slack:link'); + const body = request.body as { code: string; slackTeamId: string; slackUserId: string }; + return ok(await links().redeem(caller.agent.person, body)); + }, + ); +} diff --git a/apps/api/src/services/agents.ts b/apps/api/src/services/agents.ts index a7d9d2b..8bc09c9 100644 --- a/apps/api/src/services/agents.ts +++ b/apps/api/src/services/agents.ts @@ -10,6 +10,7 @@ import { uuidv7 } from 'uuidv7'; import { AGENT_SCOPES, + AGENT_SCOPE_REQUIRES, AgentGrantSchema, PersonSchema, agentEvaluatorFor, @@ -80,8 +81,10 @@ function nowIso(): string { } /** - * Validate a grant request: known scopes, at least one, `moderation:purge` - * only with `moderation:read`, `expiresInDays` 1–180 (default 90). + * Validate a grant request: known scopes, at least one, each with its + * companions (`moderation:purge` with `moderation:read`; + * `projects:applications:decide` with `projects:applications:read` and + * `slack:link`), `expiresInDays` 1–180 (default 90). */ export function validateGrantInput(input: GrantInput): { label: string; scopes: AgentScope[]; days: number } { const fields: Record = {}; @@ -91,8 +94,14 @@ export function validateGrantInput(input: GrantInput): { label: string; scopes: const scopes = [...new Set(input.scopes)]; if (scopes.length === 0) fields['scopes'] = 'at least one scope'; else if (scopes.some((s) => !known.has(s))) fields['scopes'] = `unknown scope; allowed: ${AGENT_SCOPES.join(', ')}`; - else if (scopes.includes('moderation:purge') && !scopes.includes('moderation:read')) { - fields['scopes'] = 'moderation:purge requires moderation:read'; + else { + for (const scope of scopes as AgentScope[]) { + const missing = (AGENT_SCOPE_REQUIRES[scope] ?? []).filter((s) => !scopes.includes(s)); + if (missing.length > 0) { + fields['scopes'] = `${scope} requires ${(AGENT_SCOPE_REQUIRES[scope] ?? []).join(' and ')}`; + break; + } + } } const days = input.expiresInDays ?? GRANT_DEFAULT_DAYS; if (!Number.isInteger(days) || days < 1 || days > GRANT_MAX_DAYS) fields['expiresInDays'] = `1–${GRANT_MAX_DAYS}`; diff --git a/apps/api/src/services/slack-link.ts b/apps/api/src/services/slack-link.ts new file mode 100644 index 0000000..b62e5bb --- /dev/null +++ b/apps/api/src/services/slack-link.ts @@ -0,0 +1,222 @@ +/** + * The Slack account link — specs/api/slack-link.md. + * + * A signed-in member asks for a one-time code; the ops bot redeems it with + * the Slack user who sent it in a DM. Both sides are proven: the site knew + * who was signed in when it issued the code, and Slack knows who sent it. + * + * Codes are held in memory only, as SHA-256 hashes, for ten minutes, and are + * redeemable once. They are never written to either store, a commit or a log + * line; a restart drops them. The link itself is `PrivateProfile.slack`. + * + * Every way a code can fail (unknown, expired, used, or its issuer gone) + * answers the same `404 code_invalid`, so the endpoint tells a guesser + * nothing about which accounts or Slack users exist. Ten such failures in an + * hour lock an agent out for an hour. + */ +import { createHash, randomInt } from 'node:crypto'; + +import type { Person, PrivateProfile } from '@cfp/shared/schemas'; + +import { isAgentAccount } from '../auth/agent-grant.js'; +import { ApiNotFoundError, ApiValidationError, ConflictError, RateLimitedError } from '../lib/errors.js'; +import type { InMemoryState } from '../store/memory/state.js'; +import type { PrivateStore } from '../store/private/interface.js'; + +const MINUTE = 60 * 1000; +const HOUR = 60 * MINUTE; + +export const CODE_TTL_MS = 10 * MINUTE; +export const CODES_PER_HOUR = 5; +export const FAILED_REDEMPTIONS_PER_HOUR = 10; +export const REDEMPTION_LOCKOUT_MS = HOUR; + +/** No 0/O, no 1/I/L. */ +export const CODE_ALPHABET = 'ABCDEFGHJKMNPQRSTUVWXYZ23456789'; +export const CODE_LENGTH = 8; + +const SLACK_ID = /^[A-Z0-9]{2,32}$/; + +/** A fresh code, shown as two groups of four: `K7QW-4MZP`. */ +export function generateCode(): string { + let raw = ''; + for (let i = 0; i < CODE_LENGTH; i++) raw += CODE_ALPHABET[randomInt(CODE_ALPHABET.length)]; + return `${raw.slice(0, 4)}-${raw.slice(4)}`; +} + +/** The canonical form of a typed code (upper case, no hyphen or spaces), or null if it cannot be one. */ +export function normalizeCode(input: unknown): string | null { + if (typeof input !== 'string') return null; + const s = input.replace(/[\s-]/g, '').toUpperCase(); + if (s.length !== CODE_LENGTH) return null; + for (const ch of s) if (!CODE_ALPHABET.includes(ch)) return null; + return s; +} + +function hashCode(canonical: string): string { + return createHash('sha256').update(canonical, 'utf8').digest('hex'); +} + +/** What `GET /api/auth/me` reports to the person themselves: never the Slack user id. */ +export function slackStatus(profile: PrivateProfile | null): { linked: boolean; linkedAt: string | null } { + return profile?.slack ? { linked: true, linkedAt: profile.slack.linkedAt } : { linked: false, linkedAt: null }; +} + +interface PendingCode { + readonly personId: string; + readonly expiresAt: number; +} + +export interface SlackLinkConfig { + /** The workspace the site serves; unset, every redemption is refused. */ + readonly teamId?: string | undefined; + readonly botDmUrl?: string | undefined; +} + +export class SlackLinkService { + readonly #state: InMemoryState; + readonly #privateStore: PrivateStore; + readonly #config: SlackLinkConfig; + /** sha256(code) → who issued it, until when. */ + readonly #codes = new Map(); + /** personId → the hash of their one live code. */ + readonly #latest = new Map(); + /** personId → when they asked for codes in the last hour. */ + readonly #issued = new Map(); + /** agent slug → failed redemptions in the last hour. */ + readonly #failures = new Map(); + /** agent slug → refused until. */ + readonly #lockedUntil = new Map(); + /** Redemptions run one at a time, so two cannot link one Slack user to two accounts. */ + #queue: Promise = Promise.resolve(); + + constructor(state: InMemoryState, privateStore: PrivateStore, config: SlackLinkConfig) { + this.#state = state; + this.#privateStore = privateStore; + this.#config = config; + } + + /** POST /api/account/slack-link/code — a fresh code; any earlier one for the person is void. */ + async issue(person: Person, now: Date = new Date()): Promise<{ code: string; expiresAt: string; botDmUrl: string | null }> { + if (isAgentAccount(this.#state, person.slug)) { + throw new ApiValidationError('An agent account cannot link a Slack user', { person: 'agent_account' }, 'agent_account'); + } + if (!(await this.#privateStore.getProfile(person.id))) { + throw new ApiValidationError( + 'This account has no private profile to hold a Slack link', + { person: 'no_private_profile' }, + 'no_private_profile', + ); + } + const t = now.getTime(); + this.#sweep(t); + const recent = (this.#issued.get(person.id) ?? []).filter((at) => t - at < HOUR); + if (recent.length >= CODES_PER_HOUR) { + throw new RateLimitedError(Math.max(1, Math.ceil((recent[0]! + HOUR - t) / 1000))); + } + recent.push(t); + this.#issued.set(person.id, recent); + + this.#void(person.id); + let code: string; + let hash: string; + do { + code = generateCode(); + hash = hashCode(normalizeCode(code)!); + } while (this.#codes.has(hash)); + const expiresAt = t + CODE_TTL_MS; + this.#codes.set(hash, { personId: person.id, expiresAt }); + this.#latest.set(person.id, hash); + return { code, expiresAt: new Date(expiresAt).toISOString(), botDmUrl: this.#config.botDmUrl ?? null }; + } + + /** POST /api/agent/slack-links — link the code's issuer to the Slack user who sent it. */ + redeem( + agent: Person, + input: { code?: unknown; slackTeamId?: unknown; slackUserId?: unknown }, + now: Date = new Date(), + ): Promise<{ personSlug: string; linkedAt: string }> { + const run = this.#queue.then(() => this.#redeem(agent, input, now)); + this.#queue = run.catch(() => undefined); + return run; + } + + async #redeem( + agent: Person, + input: { code?: unknown; slackTeamId?: unknown; slackUserId?: unknown }, + now: Date, + ): Promise<{ personSlug: string; linkedAt: string }> { + const t = now.getTime(); + const locked = this.#lockedUntil.get(agent.slug); + if (locked !== undefined) { + if (locked > t) throw new RateLimitedError(Math.max(1, Math.ceil((locked - t) / 1000))); + this.#lockedUntil.delete(agent.slug); + this.#failures.delete(agent.slug); + } + + const teamId = this.#config.teamId; + if (!teamId || input.slackTeamId !== teamId) { + throw new ApiValidationError('slackTeamId is not the workspace this site serves', { slackTeamId: 'wrong_workspace' }); + } + if (typeof input.slackUserId !== 'string' || !SLACK_ID.test(input.slackUserId)) { + throw new ApiValidationError('slackUserId must be a Slack user id', { slackUserId: 'invalid' }); + } + const userId = input.slackUserId; + + this.#sweep(t); + const canonical = normalizeCode(input.code); + const hash = canonical ? hashCode(canonical) : null; + const pending = hash ? this.#codes.get(hash) : undefined; + const person = pending ? this.#state.people.get(pending.personId) : undefined; + const profile = person ? await this.#privateStore.getProfile(person.id) : null; + if (!hash || !pending || pending.expiresAt <= t || !person || !profile) { + if (hash && pending) this.#void(pending.personId); + this.#fail(agent.slug, t); + throw new ApiNotFoundError('That code is not valid', 'code_invalid'); + } + + const holder = this.#privateStore.findPersonIdBySlackUser(teamId, userId); + if (holder !== null && holder !== person.id) { + // The code is not consumed: it works once the other account disconnects. + throw new ConflictError('That Slack user is linked to a different account', 'slack_user_linked'); + } + + this.#void(person.id); + const linkedAt = now.toISOString(); + // A new link replaces any old one on this account (one Slack user per account). + await this.#privateStore.putProfile({ ...profile, slack: { teamId, userId, linkedAt }, updatedAt: linkedAt }); + return { personSlug: person.slug, linkedAt }; + } + + /** DELETE /api/account/slack-link — clear the caller's link; nothing to do if there is none. */ + async unlink(person: Person, now: Date = new Date()): Promise { + const profile = await this.#privateStore.getProfile(person.id); + if (!profile?.slack) return; + await this.#privateStore.putProfile({ ...profile, slack: null, updatedAt: now.toISOString() }); + } + + /** Drop a person's live code. */ + #void(personId: string): void { + const hash = this.#latest.get(personId); + if (hash) this.#codes.delete(hash); + this.#latest.delete(personId); + } + + #fail(agentSlug: string, t: number): void { + const recent = (this.#failures.get(agentSlug) ?? []).filter((at) => t - at < HOUR); + recent.push(t); + this.#failures.set(agentSlug, recent); + if (recent.length >= FAILED_REDEMPTIONS_PER_HOUR) this.#lockedUntil.set(agentSlug, t + REDEMPTION_LOCKOUT_MS); + } + + /** Forget expired codes and stale counters. */ + #sweep(t: number): void { + for (const [hash, c] of this.#codes) { + if (c.expiresAt <= t) { + this.#codes.delete(hash); + if (this.#latest.get(c.personId) === hash) this.#latest.delete(c.personId); + } + } + for (const [id, times] of this.#issued) if (times.every((at) => t - at >= HOUR)) this.#issued.delete(id); + } +} diff --git a/apps/api/tests/helpers/agent-fixtures.ts b/apps/api/tests/helpers/agent-fixtures.ts index 45465ee..6c4f8f9 100644 --- a/apps/api/tests/helpers/agent-fixtures.ts +++ b/apps/api/tests/helpers/agent-fixtures.ts @@ -8,7 +8,7 @@ import { execFile } from 'node:child_process'; import { promisify } from 'node:util'; -import type { FastifyInstance } from 'fastify'; +import type { FastifyInstance, FastifyServerOptions } from 'fastify'; import { openRepo } from 'gitsheets'; import { expect } from 'vitest'; @@ -59,6 +59,8 @@ export async function startAgentTestEnv(opts: { records: Record; profiles?: Rec[]; env?: Record; + /** A logger for the app (default: none), e.g. one writing to a capture stream. */ + logger?: FastifyServerOptions['logger']; /** More seeding in the same commit (attachments, raw files). */ extra?: (tx: Parameters>['transact']>[1]>[0]) => Promise; }): Promise { @@ -80,7 +82,7 @@ export async function startAgentTestEnv(opts: { ); } const app = await buildApp({ - serverOptions: { logger: false }, + serverOptions: { logger: opts.logger ?? false }, overrideEnv: { CFP_DATA_REPO_PATH: dataRepo.path, STORAGE_BACKEND: 'filesystem', diff --git a/apps/api/tests/slack-link.test.ts b/apps/api/tests/slack-link.test.ts new file mode 100644 index 0000000..c022c2e --- /dev/null +++ b/apps/api/tests/slack-link.test.ts @@ -0,0 +1,323 @@ +/** + * Linking a site account to a Slack user (plans/slack-account-link.md, + * specs/api/slack-link.md): one-time codes, the agent's redemption, the + * refusals that must not reveal anything, disconnect, purge, the companion + * rule at mint, and that no code or Slack id reaches the public store, a + * commit or a log line. + * + * Every person, workspace and Slack id here is invented. + */ +import { readFile } from 'node:fs/promises'; +import { join } from 'node:path'; +import { Writable } from 'node:stream'; + +import { afterEach, describe, expect, it } from 'vitest'; + +import { + bearer, + createAgent, + fid, + personRecord, + privateProfile, + startAgentTestEnv, + type AgentTestEnv, +} from './helpers/agent-fixtures.js'; +import { CODE_ALPHABET, normalizeCode } from '../src/services/slack-link.js'; + +const TEAM = 'TEXAMPLE01'; +const P = { ada: 1, ben: 2, root: 3, sam: 4, noprof: 5 }; +const U_ADA = 'UADA000001'; +const U_OTHER = 'UOTHER0002'; + +function records() { + return { + people: [ + personRecord(P.ada, 'ada'), + personRecord(P.ben, 'ben'), + personRecord(P.root, 'root', { accountLevel: 'administrator' }), + personRecord(P.sam, 'sam', { accountLevel: 'staff' }), + personRecord(P.noprof, 'noprof'), + ], + }; +} +const PROFILES = [P.ada, P.ben, P.root, P.sam].map((k) => privateProfile(fid(k), `p${k}@example.org`)); + +describe('slack account link', () => { + let env: AgentTestEnv; + let logs: string[]; + + const start = async (extraEnv: Record = { SLACK_TEAM_ID: TEAM }) => { + logs = []; + const stream = new Writable({ + write(chunk: Buffer, _enc, cb) { + logs.push(chunk.toString('utf8')); + cb(); + }, + }); + env = await startAgentTestEnv({ + records: records(), + profiles: PROFILES, + env: { ...extraEnv, SLACK_OPS_BOT_DM_URL: 'https://example.slack.com/app_redirect?channel=UBOT' }, + logger: { level: 'trace', stream }, + }); + }; + afterEach(async () => { + await env?.close(); + }); + + const as = async (n: number, level: 'user' | 'staff' | 'administrator' = 'user') => ({ + cookies: { cfp_session: await env.cookie(n, level) }, + }); + const issue = async (n: number) => env.app.inject({ method: 'POST', url: '/api/account/slack-link/code', ...(await as(n)) }); + const codeFor = async (n: number) => { + const res = await issue(n); + expect(res.statusCode, res.body).toBe(200); + return res.json<{ data: { code: string; expiresAt: string; botDmUrl: string | null } }>().data; + }; + const redeem = (token: string, payload: Record) => + env.app.inject({ method: 'POST', url: '/api/agent/slack-links', ...bearer(token), payload }); + const me = async (n: number) => + (await env.app.inject({ method: 'GET', url: '/api/auth/me', ...(await as(n)) })).json<{ + data: { slack: { linked: boolean; linkedAt: string | null } | null }; + }>().data; + const agentWith = async (scopes: string[], slug = 'example-bot') => + (await createAgent(env, (await as(P.root, 'administrator')).cookies.cfp_session, { slug, scopes })).token; + const err = (res: { json: () => unknown }) => { + const { code, message } = (res.json() as { error: { code: string; message: string } }).error; + return { code, message }; + }; + + describe('issuing a code', () => { + it('returns an 8-character code from the unambiguous alphabet, ten minutes, and the bot DM link', async () => { + await start(); + const before = Date.now(); + const data = await codeFor(P.ada); + expect(data.code).toMatch(/^[A-Z2-9]{4}-[A-Z2-9]{4}$/); + for (const ch of data.code.replace('-', '')) expect(CODE_ALPHABET).toContain(ch); + expect(data.code).not.toMatch(/[01OIL]/); + const ttl = Date.parse(data.expiresAt) - before; + expect(ttl).toBeGreaterThan(9.9 * 60_000); + expect(ttl).toBeLessThanOrEqual(10 * 60_000 + 1000); + expect(data.botDmUrl).toBe('https://example.slack.com/app_redirect?channel=UBOT'); + }); + + it('matches case-insensitively with the hyphen optional', () => { + expect(normalizeCode('k7qw-4mzp')).toBe('K7QW4MZP'); + expect(normalizeCode('K7QW4MZP')).toBe('K7QW4MZP'); + expect(normalizeCode('K7QW-4MZ0')).toBeNull(); + expect(normalizeCode('K7Q-4MZP')).toBeNull(); + }); + + it('allows five codes per account per hour', async () => { + await start(); + for (let i = 0; i < 5; i++) expect((await issue(P.ada)).statusCode).toBe(200); + const sixth = await issue(P.ada); + expect(sixth.statusCode).toBe(429); + expect(sixth.headers['retry-after']).toBeDefined(); + // Another account is unaffected. + expect((await issue(P.ben)).statusCode).toBe(200); + }); + + it('is refused to anonymous callers, agent grants and accounts with no private profile', async () => { + await start(); + expect((await env.app.inject({ method: 'POST', url: '/api/account/slack-link/code' })).statusCode).toBe(401); + const token = await agentWith(['slack:link']); + const asAgent = await env.app.inject({ method: 'POST', url: '/api/account/slack-link/code', ...bearer(token) }); + expect(asAgent.statusCode).toBe(401); + const noProfile = await issue(P.noprof); + expect(noProfile.statusCode).toBe(422); + expect(err(noProfile).code).toBe('no_private_profile'); + }); + + it('refuses an agent account (422 agent_account)', async () => { + await start(); + await agentWith(['slack:link']); + const agent = env.app.inMemoryState.people.get(env.app.inMemoryState.personIdBySlug.get('example-bot')!)!; + await expect(env.app.services.slackLinks.issue(agent)).rejects.toMatchObject({ code: 'agent_account' }); + }); + }); + + describe('redeeming a code', () => { + it('links the issuer once; reused, unknown and expired codes all answer the same 404 code_invalid', async () => { + await start(); + const token = await agentWith(['slack:link']); + expect((await me(P.ada)).slack).toEqual({ linked: false, linkedAt: null }); + + const { code } = await codeFor(P.ada); + const ok = await redeem(token, { code: code.toLowerCase().replace('-', ''), slackTeamId: TEAM, slackUserId: U_ADA }); + expect(ok.statusCode, ok.body).toBe(200); + const data = ok.json<{ data: { personSlug: string; linkedAt: string } }>().data; + expect(data.personSlug).toBe('ada'); + expect(await me(P.ada)).toMatchObject({ slack: { linked: true, linkedAt: data.linkedAt } }); + expect(JSON.stringify(await me(P.ada))).not.toContain(U_ADA); + expect(env.app.store.private.findPersonIdBySlackUser(TEAM, U_ADA)).toBe(fid(P.ada)); + + const reused = await redeem(token, { code, slackTeamId: TEAM, slackUserId: U_ADA }); + const unknown = await redeem(token, { code: 'ABCD-EFGH', slackTeamId: TEAM, slackUserId: U_ADA }); + const garbage = await redeem(token, { code: 'not a code', slackTeamId: TEAM, slackUserId: U_ADA }); + + const svc = env.app.services.slackLinks; + const ben = env.app.inMemoryState.people.get(fid(P.ben))!; + const agent = env.app.inMemoryState.people.get(env.app.inMemoryState.personIdBySlug.get('example-bot')!)!; + const old = await svc.issue(ben, new Date(Date.now() - 11 * 60_000)); + const expired = await svc.redeem(agent, { code: old.code, slackTeamId: TEAM, slackUserId: U_OTHER }).catch((e: unknown) => e); + + for (const res of [reused, unknown, garbage]) { + expect(res.statusCode).toBe(404); + expect(err(res)).toEqual(err(reused)); + } + expect(err(reused).code).toBe('code_invalid'); + expect(expired).toMatchObject({ code: 'code_invalid', message: err(reused).message }); + expect((await me(P.ben)).slack?.linked).toBe(false); + }); + + it('a new code voids the earlier one', async () => { + await start(); + const token = await agentWith(['slack:link']); + const first = await codeFor(P.ada); + const second = await codeFor(P.ada); + expect((await redeem(token, { code: first.code, slackTeamId: TEAM, slackUserId: U_ADA })).statusCode).toBe(404); + expect((await redeem(token, { code: second.code, slackTeamId: TEAM, slackUserId: U_ADA })).statusCode).toBe(200); + }); + + it('a Slack user linked to one account cannot be linked to another; disconnect frees it and the code still works', async () => { + await start(); + const token = await agentWith(['slack:link']); + const a = await codeFor(P.ada); + expect((await redeem(token, { code: a.code, slackTeamId: TEAM, slackUserId: U_ADA })).statusCode).toBe(200); + + const b = await codeFor(P.ben); + const conflict = await redeem(token, { code: b.code, slackTeamId: TEAM, slackUserId: U_ADA }); + expect(conflict.statusCode).toBe(409); + expect(err(conflict).code).toBe('slack_user_linked'); + + const del = await env.app.inject({ method: 'DELETE', url: '/api/account/slack-link', ...(await as(P.ada)) }); + expect(del.statusCode).toBe(204); + expect((await me(P.ada)).slack).toEqual({ linked: false, linkedAt: null }); + expect(env.app.store.private.findPersonIdBySlackUser(TEAM, U_ADA)).toBeNull(); + // Disconnecting again is not an error. + expect((await env.app.inject({ method: 'DELETE', url: '/api/account/slack-link', ...(await as(P.ada)) })).statusCode).toBe(204); + + const retry = await redeem(token, { code: b.code, slackTeamId: TEAM, slackUserId: U_ADA }); + expect(retry.statusCode, retry.body).toBe(200); + expect(env.app.store.private.findPersonIdBySlackUser(TEAM, U_ADA)).toBe(fid(P.ben)); + }); + + it('a new link replaces the old one on the same account', async () => { + await start(); + const token = await agentWith(['slack:link']); + expect((await redeem(token, { code: (await codeFor(P.ada)).code, slackTeamId: TEAM, slackUserId: U_ADA })).statusCode).toBe(200); + expect((await redeem(token, { code: (await codeFor(P.ada)).code, slackTeamId: TEAM, slackUserId: U_OTHER })).statusCode).toBe(200); + expect(env.app.store.private.findPersonIdBySlackUser(TEAM, U_ADA)).toBeNull(); + expect(env.app.store.private.findPersonIdBySlackUser(TEAM, U_OTHER)).toBe(fid(P.ada)); + }); + + it('refuses another workspace (422), and every redemption when no workspace is configured', async () => { + await start(); + const token = await agentWith(['slack:link']); + const { code } = await codeFor(P.ada); + const wrong = await redeem(token, { code, slackTeamId: 'TOTHER0001', slackUserId: U_ADA }); + expect(wrong.statusCode).toBe(422); + // The code was not spent on the wrong workspace. + expect((await redeem(token, { code, slackTeamId: TEAM, slackUserId: U_ADA })).statusCode).toBe(200); + await env.close(); + + await start({}); + const token2 = await agentWith(['slack:link']); + const c2 = await codeFor(P.ada); + expect((await redeem(token2, { code: c2.code, slackTeamId: TEAM, slackUserId: U_ADA })).statusCode).toBe(422); + }); + + it('needs a grant with slack:link: other grants, staff and anonymous callers get 401', async () => { + await start(); + const { code } = await codeFor(P.ada); + const payload = { code, slackTeamId: TEAM, slackUserId: U_ADA }; + const modOnly = await agentWith(['moderation:read'], 'mod-bot'); + expect((await redeem(modOnly, payload)).statusCode).toBe(401); + const asStaff = await env.app.inject({ method: 'POST', url: '/api/agent/slack-links', ...(await as(P.sam, 'staff')), payload }); + expect(asStaff.statusCode).toBe(401); + expect((await env.app.inject({ method: 'POST', url: '/api/agent/slack-links', payload })).statusCode).toBe(401); + // A bad body from a caller without the scope still gets 401, not a validation hint. + expect((await redeem(modOnly, { nope: true })).statusCode).toBe(401); + expect((await me(P.ada)).slack?.linked).toBe(false); + }); + + it('locks an agent out for an hour after ten failed redemptions, even for a valid code', async () => { + await start(); + const token = await agentWith(['slack:link']); + const { code } = await codeFor(P.ada); + for (let i = 0; i < 10; i++) { + const res = await redeem(token, { code: `ZZZZ-ZZZ${'ABCDEFGHJK'[i]}`, slackTeamId: TEAM, slackUserId: U_ADA }); + expect(res.statusCode).toBe(404); + } + const eleventh = await redeem(token, { code, slackTeamId: TEAM, slackUserId: U_ADA }); + expect(eleventh.statusCode).toBe(429); + expect(Number(eleventh.headers['retry-after'])).toBeGreaterThan(3500); + expect((await me(P.ada)).slack?.linked).toBe(false); + + // An hour later the lock lifts. + const svc = env.app.services.slackLinks; + const agent = env.app.inMemoryState.people.get(env.app.inMemoryState.personIdBySlug.get('example-bot')!)!; + const later = new Date(Date.now() + 61 * 60_000); + const ada = env.app.inMemoryState.people.get(fid(P.ada))!; + const fresh = await svc.issue(ada, later); + await expect(svc.redeem(agent, { code: fresh.code, slackTeamId: TEAM, slackUserId: U_ADA }, later)).resolves.toMatchObject({ + personSlug: 'ada', + }); + }); + }); + + it('purging the person removes the link', async () => { + await start(); + const token = await agentWith(['slack:link']); + expect((await redeem(token, { code: (await codeFor(P.ben)).code, slackTeamId: TEAM, slackUserId: U_OTHER })).statusCode).toBe(200); + const purge = await env.app.inject({ method: 'POST', url: '/api/people/ben/purge', ...(await as(P.root, 'administrator')) }); + expect(purge.statusCode, purge.body).toBe(204); + expect(env.app.store.private.findPersonIdBySlackUser(TEAM, U_OTHER)).toBeNull(); + const raw = await readFile(join(env.privatePath, 'profiles.jsonl'), 'utf8'); + expect(raw).not.toContain(U_OTHER); + }); + + it('no code or Slack id reaches the public store, a commit or a log line; the link sits on the private profile only', async () => { + await start(); + const token = await agentWith(['slack:link']); + const { code } = await codeFor(P.ada); + expect((await redeem(token, { code, slackTeamId: TEAM, slackUserId: U_ADA })).statusCode).toBe(200); + await redeem(token, { code, slackTeamId: TEAM, slackUserId: U_ADA }); // a failure is logged too + await me(P.ada); + + const history = await env.git('log', '--all', '-p', '--format=%H%n%B'); + const canonical = code.replace('-', ''); + for (const secret of [code, canonical, U_ADA]) { + expect(history).not.toContain(secret); + expect(logs.join('')).not.toContain(secret); + } + expect(logs.length).toBeGreaterThan(0); + const raw = await readFile(join(env.privatePath, 'profiles.jsonl'), 'utf8'); + expect(raw).toContain(U_ADA); + expect(raw).not.toContain(canonical); + }); + + it('minting projects:applications:decide needs projects:applications:read and slack:link', async () => { + await start(); + const adminCookie = (await as(P.root, 'administrator')).cookies.cfp_session; + const mint = (scopes: string[], slug: string) => + env.app.inject({ + method: 'POST', + url: '/api/admin/agents', + cookies: { cfp_session: adminCookie }, + payload: { slug, fullName: `Example ${slug}`, bio: 'An AI ops bot run by the test suite.', grant: { label: 'test', scopes } }, + }); + for (const [i, scopes] of [ + ['projects:applications:decide'], + ['projects:applications:decide', 'projects:applications:read'], + ['projects:applications:decide', 'slack:link'], + ].entries()) { + const res = await mint(scopes, `bad-bot-${i}`); + expect(res.statusCode, res.body).toBe(422); + expect(res.body).toContain('projects:applications:decide requires'); + } + const good = await mint(['projects:applications:decide', 'projects:applications:read', 'slack:link'], 'good-bot'); + expect(good.statusCode, good.body).toBe(201); + }); +}); From b02dc3112a378f1f27bd5f62a28982084e745411 Mon Sep 17 00:00:00 2001 From: GrittyBot <30755786+codeforphilly-bot@users.noreply.github.com> Date: Sun, 29 Nov 2026 22:21:10 +0000 Subject: [PATCH 06/26] feat(web): the Account screen's Slack row, and the new scopes on the mint form MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Connect Slack asks for a code and shows it with the instruction to DM it to the ops bot within ten minutes (the bot's name links to botDmUrl when configured); the row polls /api/auth/me while the code is live and turns "Connected to Slack ✓ since …" when the bot confirms. Disconnect asks first. The row never shows a Slack user id. The agents panel's mint form offers the three new scopes and warns when decide lacks its companions. Co-Authored-By: Claude Opus 5.5 --- apps/web/src/components/account/SlackRow.tsx | 131 ++++++++++++++++++ apps/web/src/components/admin/AgentsPanel.tsx | 12 ++ apps/web/src/hooks/useAuth.tsx | 17 ++- apps/web/src/lib/api.ts | 21 ++- apps/web/src/screens/Account.tsx | 10 +- apps/web/tests/Account.test.tsx | 60 ++++++++ 6 files changed, 241 insertions(+), 10 deletions(-) create mode 100644 apps/web/src/components/account/SlackRow.tsx diff --git a/apps/web/src/components/account/SlackRow.tsx b/apps/web/src/components/account/SlackRow.tsx new file mode 100644 index 0000000..3a2d6f2 --- /dev/null +++ b/apps/web/src/components/account/SlackRow.tsx @@ -0,0 +1,131 @@ +/** + * The Account screen's Slack row — specs/screens/account.md → Card 1, and + * specs/api/slack-link.md. + * + * Not linked: "Connect Slack" asks for a one-time code and shows it with the + * instruction to DM it to the ops bot within ten minutes; while the code is + * live the row polls `GET /api/auth/me` and turns linked when the bot + * confirms it. Linked: "Connected to Slack ✓ since …" with Disconnect. + * The row never shows the Slack user id (the API never sends it here). + */ +import { useEffect, useState } from 'react'; +import { toast } from 'sonner'; + +import { Button } from '@/components/ui/button'; +import { fetchMeOnce, type SlackLinkStatus } from '@/hooks/useAuth'; +import { api, ApiError, type SlackLinkCode } from '@/lib/api'; +import { formatAbsoluteDate } from '@/lib/time'; + +const POLL_MS = 3000; + +export function SlackRow({ initial }: { initial: SlackLinkStatus | null }) { + const [status, setStatus] = useState(initial ?? { linked: false, linkedAt: null }); + const [pending, setPending] = useState(null); + const [busy, setBusy] = useState(false); + + // Poll while a code is live; stop when linked or when it expires. + useEffect(() => { + if (!pending) return; + let cancelled = false; + const tick = async () => { + if (Date.parse(pending.expiresAt) <= Date.now()) { + if (!cancelled) setPending(null); + return; + } + const snap = await fetchMeOnce(); + if (cancelled) return; + if (snap.slack?.linked) { + setStatus(snap.slack); + setPending(null); + toast.success('Slack connected.'); + } + }; + const id = window.setInterval(() => void tick(), POLL_MS); + return () => { + cancelled = true; + window.clearInterval(id); + }; + }, [pending]); + + const connect = async () => { + setBusy(true); + try { + const res = await api.slackLink.issueCode(); + setPending(res.data); + } catch (err) { + toast.error( + err instanceof ApiError && err.status === 429 + ? 'Too many codes in the last hour. Try again later.' + : err instanceof ApiError + ? err.message + : 'Could not get a code', + ); + } finally { + setBusy(false); + } + }; + + const disconnect = async () => { + if (!window.confirm('Disconnect your Slack account? The ops bot will stop reaching you in Slack.')) return; + setBusy(true); + try { + await api.slackLink.disconnect(); + setStatus({ linked: false, linkedAt: null }); + toast.success('Slack disconnected.'); + } catch (err) { + toast.error(err instanceof ApiError ? err.message : 'Could not disconnect'); + } finally { + setBusy(false); + } + }; + + const bot = pending?.botDmUrl ? ( + + the ops bot (opens Slack in a new tab) + + ) : ( + 'the ops bot' + ); + + return ( +
+
+
+
Slack
+
+ {status.linked + ? `Connected to Slack ✓${status.linkedAt ? ` since ${formatAbsoluteDate(status.linkedAt)}` : ''}` + : 'Not linked to a Slack account'} +
+
+ {status.linked ? ( + + ) : ( + !pending && ( + + ) + )} +
+ {status.linked && ( +

+ Lets the ops bot send you project notices in Slack and act on your replies, such as accepting an + application you answer there. +

+ )} + {!status.linked && pending && ( +
+
+ {pending.code} +
+

+ Send this code in a direct message to {bot} in the Code for Philly Slack within 10 minutes. +

+
+ )} +
+ ); +} diff --git a/apps/web/src/components/admin/AgentsPanel.tsx b/apps/web/src/components/admin/AgentsPanel.tsx index 9902986..9bd4117 100644 --- a/apps/web/src/components/admin/AgentsPanel.tsx +++ b/apps/web/src/components/admin/AgentsPanel.tsx @@ -216,6 +216,9 @@ const SCOPE_LABEL: Record = { 'moderation:read': 'read roster', 'moderation:vote': 'staged votes', 'moderation:purge': 'purge', + 'slack:link': 'link members’ Slack accounts', + 'projects:applications:read': 'read application events', + 'projects:applications:decide': 'record an admin’s accept or close', }; /** Mint form + the purge second confirm + the token-once dialog. */ @@ -236,6 +239,9 @@ function MintGrantDialog({ 'moderation:read': true, 'moderation:vote': true, 'moderation:purge': false, + 'slack:link': false, + 'projects:applications:read': false, + 'projects:applications:decide': false, }); const [confirmPurge, setConfirmPurge] = useState(false); const mint = useMutation({ @@ -301,6 +307,12 @@ function MintGrantDialog({ {scopes['moderation:purge'] && !scopes['moderation:read'] && (

The purge scope needs moderation:read too.

)} + {scopes['projects:applications:decide'] && + !(scopes['projects:applications:read'] && scopes['slack:link']) && ( +

+ The decide scope needs projects:applications:read and slack:link too. +

+ )}
diff --git a/apps/web/src/hooks/useAuth.tsx b/apps/web/src/hooks/useAuth.tsx index 448dd07..c3f2d01 100644 --- a/apps/web/src/hooks/useAuth.tsx +++ b/apps/web/src/hooks/useAuth.tsx @@ -23,6 +23,12 @@ export interface AuthPerson { deletedAt?: string | null; } +/** `me.slack`: whether the person has a verified Slack link (never its user id). */ +export interface SlackLinkStatus { + linked: boolean; + linkedAt: string | null; +} + export interface AuthState { /** null = anonymous or not yet loaded */ person: AuthPerson | null; @@ -32,6 +38,8 @@ export interface AuthState { hasGitHubLink: boolean; /** How the current session was minted. null for anonymous or pre-loginMethod sessions. */ lastLoginMethod: LoginMethod | null; + /** The Slack link (specs/api/slack-link.md). null when anonymous. */ + slack: SlackLinkStatus | null; /** Reload auth state from the server */ reload: () => Promise; /** Sign out: calls POST /api/auth/logout then clears state */ @@ -46,22 +54,25 @@ interface MeEnvelope { accountLevel?: AccountLevel; hasGitHubLink?: boolean; lastLoginMethod?: LoginMethod | null; + slack?: SlackLinkStatus | null; }; } -interface MeSnapshot { +export interface MeSnapshot { person: AuthPerson | null; hasGitHubLink: boolean; lastLoginMethod: LoginMethod | null; + slack: SlackLinkStatus | null; } const ANON_SNAPSHOT: MeSnapshot = { person: null, hasGitHubLink: false, lastLoginMethod: null, + slack: null, }; -async function fetchMeOnce(): Promise { +export async function fetchMeOnce(): Promise { try { const res = await fetch('/api/auth/me', { credentials: 'include' }); if (!res.ok) { @@ -73,6 +84,7 @@ async function fetchMeOnce(): Promise { person: json.data?.person ?? null, hasGitHubLink: json.data?.hasGitHubLink ?? false, lastLoginMethod: json.data?.lastLoginMethod ?? null, + slack: json.data?.slack ?? null, }; } catch { // Network error — treat as anonymous, don't throw @@ -149,6 +161,7 @@ export function AuthProvider({ children }: { children: ReactNode }) { loading, hasGitHubLink: snapshot.hasGitHubLink, lastLoginMethod: snapshot.lastLoginMethod, + slack: snapshot.slack, reload, signOut, }} diff --git a/apps/web/src/lib/api.ts b/apps/web/src/lib/api.ts index 27b3cd7..d2c9193 100644 --- a/apps/web/src/lib/api.ts +++ b/apps/web/src/lib/api.ts @@ -943,7 +943,20 @@ export interface MemberDetail { // --- Agents and the spam-purge log (specs/api/agents.md) ------------------- -export type AgentScope = 'moderation:read' | 'moderation:vote' | 'moderation:purge'; +export type AgentScope = + | 'moderation:read' + | 'moderation:vote' + | 'moderation:purge' + | 'slack:link' + | 'projects:applications:read' + | 'projects:applications:decide'; + +/** POST /api/account/slack-link/code — specs/api/slack-link.md. */ +export interface SlackLinkCode { + code: string; + expiresAt: string; + botDmUrl: string | null; +} export interface AgentGrantView { readonly id: string; @@ -1283,6 +1296,12 @@ export const api = { revokeSession: (jti: string): Promise => request(`/api/auth/sessions/${encodeURIComponent(jti)}/revoke`, { method: 'POST' }), }, + slackLink: { + /** A one-time code to DM to the ops bot; any earlier one is void. */ + issueCode: (): Promise> => + request(`/api/account/slack-link/code`, { method: 'POST' }), + disconnect: (): Promise => request(`/api/account/slack-link`, { method: 'DELETE' }), + }, accountClaim: { candidates: (): Promise> => request(`/api/account-claim/candidates`), diff --git a/apps/web/src/screens/Account.tsx b/apps/web/src/screens/Account.tsx index 1eb39dc..4b23f43 100644 --- a/apps/web/src/screens/Account.tsx +++ b/apps/web/src/screens/Account.tsx @@ -6,6 +6,7 @@ import { Button } from '@/components/ui/button'; import { Checkbox } from '@/components/ui/checkbox'; import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'; import { Breadcrumbs } from '@/components/Breadcrumbs'; +import { SlackRow } from '@/components/account/SlackRow'; import { Dialog, DialogContent, @@ -46,7 +47,7 @@ const LINK_GITHUB_ERROR_MESSAGES: Record = { }; export function Account() { - const { person, loading, signOut, reload, hasGitHubLink } = useAuth(); + const { person, loading, signOut, reload, hasGitHubLink, slack } = useAuth(); const navigate = useNavigate(); const queryClient = useQueryClient(); const [searchParams, setSearchParams] = useSearchParams(); @@ -200,12 +201,7 @@ export function Account() { )}
-
-
Slack
- -
+

Profile fields like name, bio, slug, and tags live on the{' '} { }); }); }); + +describe('Account — Slack row', () => { + afterEach(() => { + vi.restoreAllMocks(); + }); + + const CODE = { code: 'K7QW-4MZP', expiresAt: new Date(Date.now() + 10 * 60_000).toISOString(), botDmUrl: 'https://example.slack.com/app_redirect?channel=UBOT' }; + + /** /api/auth/me reports not linked until the code has been issued `pollsUntilLinked` polls ago. */ + function mockSlack(pollsUntilLinked: number | null) { + let issued = false; + let polls = 0; + const json = (body: unknown, status = 200) => + Promise.resolve(new Response(JSON.stringify(body), { status, headers: { 'content-type': 'application/json' } })); + const calls: string[] = []; + vi.spyOn(globalThis, 'fetch').mockImplementation(((input: string, init?: RequestInit) => { + calls.push(`${init?.method ?? 'GET'} ${input}`); + if (input.startsWith('/api/auth/me')) { + if (issued) polls += 1; + const linked = issued && pollsUntilLinked !== null && polls > pollsUntilLinked; + return json(mockOk({ ...githubPerson, slack: linked ? { linked: true, linkedAt: '2026-11-20T12:00:00Z' } : { linked: false, linkedAt: null } })); + } + if (input.startsWith('/api/account/slack-link/code')) { + issued = true; + return json(mockOk(CODE)); + } + if (input.startsWith('/api/account/slack-link')) return Promise.resolve(new Response(null, { status: 204 })); + if (input.startsWith('/api/auth/sessions')) return json(mockOk([])); + return Promise.resolve(new Response(null, { status: 404 })); + }) as typeof fetch); + return calls; + } + + it('Connect Slack shows the code and the DM instruction, then turns connected when the bot confirms', async () => { + const calls = mockSlack(0); + render(); + const button = await screen.findByRole('button', { name: 'Connect Slack' }); + button.click(); + expect(await screen.findByTestId('slack-link-code')).toHaveTextContent('K7QW-4MZP'); + expect(screen.getByText(/within 10 minutes/i)).toBeInTheDocument(); + expect(screen.getByRole('link', { name: /the ops bot/i })).toHaveAttribute('href', CODE.botDmUrl); + await waitFor(() => expect(screen.getByText(/connected to slack ✓ since/i)).toBeInTheDocument(), { timeout: 5000 }); + expect(screen.queryByTestId('slack-link-code')).not.toBeInTheDocument(); + expect(calls).toContain('POST /api/account/slack-link/code'); + }); + + it('a linked account shows Connected with Disconnect, and never a Slack user id', async () => { + vi.spyOn(globalThis, 'fetch').mockImplementation(((input: string) => { + const body = input.startsWith('/api/auth/me') + ? mockOk({ ...githubPerson, slack: { linked: true, linkedAt: '2026-11-20T12:00:00Z' } }) + : mockOk([]); + return Promise.resolve(new Response(JSON.stringify(body), { status: 200, headers: { 'content-type': 'application/json' } })); + }) as typeof fetch); + render(); + expect(await screen.findByText(/connected to slack ✓ since/i)).toBeInTheDocument(); + expect(screen.getByRole('button', { name: 'Disconnect' })).toBeInTheDocument(); + expect(screen.getByText(/act on your replies/i)).toBeInTheDocument(); + expect(document.body.textContent).not.toMatch(/\bU[A-Z0-9]{6,}\b/); + }); +}); From 9f8f68bb56682a0939a7deac68f08fafff6b2db9 Mon Sep 17 00:00:00 2001 From: GrittyBot <30755786+codeforphilly-bot@users.noreply.github.com> Date: Sun, 29 Nov 2026 22:21:19 +0000 Subject: [PATCH 07/26] docs(ops): SLACK_TEAM_ID and SLACK_OPS_BOT_DM_URL Co-Authored-By: Claude Opus 5.5 --- .env.example | 8 ++++++++ docs/operations/deploy.md | 2 ++ 2 files changed, 10 insertions(+) diff --git a/.env.example b/.env.example index a9e7150..72715d8 100644 --- a/.env.example +++ b/.env.example @@ -80,6 +80,14 @@ CFP_JWT_SIGNING_KEY=change-me-to-a-random-string-at-least-32-chars # /chat + /launch redirects. Never used for our own entity ID or endpoints. # SLACK_TEAM_HOST=codeforphilly.slack.com +# Slack workspace id (T…) the site serves. Slack account links and an agent's +# on-behalf decisions naming another workspace are refused; unset, no link can +# be made. See specs/api/slack-link.md. +# SLACK_TEAM_ID=TEXAMPLE01 + +# Optional: a link that opens a DM with the ops bot, shown on /account. +# SLACK_OPS_BOT_DM_URL=https://codeforphilly.slack.com/app_redirect?channel=U... + # --------------------------------------------------------------------------- # Static SPA serving (production only) # --------------------------------------------------------------------------- diff --git a/docs/operations/deploy.md b/docs/operations/deploy.md index 97d90d3..bf3f421 100644 --- a/docs/operations/deploy.md +++ b/docs/operations/deploy.md @@ -287,6 +287,8 @@ comments. Production pod gets these mounted: | `CFP_JWT_SIGNING_KEY` | **Secret** (`codeforphilly-secrets`) | HS256 key (`openssl rand -base64 64`) | | `SAML_PRIVATE_KEY` / `SAML_CERTIFICATE` | **Secret** (`codeforphilly-saml`, prod) | Slack IdP key pair, carried over verbatim from laddr's `saml2` secret so Slack keeps trusting the same cert. Mounted via an extra `envFrom` patch in the live cluster repo; marked `optional` so a sandbox without it still boots. | | `SLACK_TEAM_HOST` | ConfigMap | Slack workspace host (default `codeforphilly.slack.com`). ACS URL, NameID `NameQualifier`, `/chat` + `/launch` redirect target. Never our own IdP identity. | +| `SLACK_TEAM_ID` | ConfigMap | The workspace id (`T…`) of the Code for Philly Slack. Required for [Slack account links](../../specs/api/slack-link.md) and agent decisions on an admin's behalf; unset, every link redemption is refused (fails closed). Not a secret. | +| `SLACK_OPS_BOT_DM_URL` | ConfigMap | Optional. A link that opens a DM with the ops bot (e.g. `https://codeforphilly.slack.com/app_redirect?channel=`); the Account screen's Slack row links the bot's name to it. | | `GIT_SSH_COMMAND` | ConfigMap | Wires `ssh` to the mounted deploy key | | `GIT_AUTHOR_NAME` / `GIT_AUTHOR_EMAIL` | ConfigMap | Committer identity for API-authored data commits | From b071b2192bb3956da2375912a22fab6ab3fbfe76 Mon Sep 17 00:00:00 2001 From: GrittyBot <30755786+codeforphilly-bot@users.noreply.github.com> Date: Sun, 29 Nov 2026 22:38:20 +0000 Subject: [PATCH 08/26] chore(plans): mark slack-account-link done (PR #TBD) Co-Authored-By: Claude Opus 5.5 --- plans/slack-account-link.md | 60 ++++++++++++++++++++++++++++++++----- 1 file changed, 52 insertions(+), 8 deletions(-) diff --git a/plans/slack-account-link.md b/plans/slack-account-link.md index 39c5226..c4a645a 100644 --- a/plans/slack-account-link.md +++ b/plans/slack-account-link.md @@ -1,5 +1,5 @@ --- -status: in-progress +status: done depends: [] specs: - specs/api/slack-link.md @@ -51,15 +51,15 @@ Account screen's Slack row; purge removes the link. ## Validation -- [ ] Tests: a code redeems once for the person who issued it; expired, reused and unknown codes all return the same `404 code_invalid`; issuing a new code voids the old one -- [ ] Tests: a Slack user linked to account A cannot be linked to B (`409 slack_user_linked`); disconnect clears it; wrong `slackTeamId` → `422` -- [ ] Tests: a grant without `slack:link` gets `401`/`403` on the agent route; 11 failed redemptions in an hour are refused -- [ ] No code or Slack id appears in either data store's public side, any commit, or request logs (log redaction test) -- [ ] Minting `projects:applications:decide` without `projects:applications:read` and `slack:link` returns `422` +- [x] Tests: a code redeems once for the person who issued it; expired, reused and unknown codes all return the same `404 code_invalid`; issuing a new code voids the old one +- [x] Tests: a Slack user linked to account A cannot be linked to B (`409 slack_user_linked`); disconnect clears it; wrong `slackTeamId` → `422` +- [x] Tests: a grant without `slack:link` gets `401`/`403` on the agent route; 11 failed redemptions in an hour are refused +- [x] No code or Slack id appears in either data store's public side, any commit, or request logs (log redaction test) +- [x] Minting `projects:applications:decide` without `projects:applications:read` and `slack:link` returns `422` - [ ] `agent-grants/v2` adopted and mirrored; CI passes -- [ ] Browser: Account → Connect Slack shows a code; redeeming it with a test grant via the API turns the row to "Connected" +- [x] Browser: Account → Connect Slack shows a code; redeeming it with a test grant via the API turns the row to "Connected" - [ ] End to end with the ops bot in the real workspace (awaits the bot PR) -- [ ] `npm run type-check && npm run lint && npm test` clean +- [x] `npm run type-check && npm run lint && npm test` clean ## Risks / unknowns @@ -68,4 +68,48 @@ Account screen's Slack row; purge removes the link. ## Notes +- **Two criteria open.** `agent-grants/v2` is generated, published in + `contracts/` and mirrored into `apps/api/gitsheets/` (vendored with + `gitsheets contracts adopt`; the sheet config declares v2), but adopting + it on the data repo's branches is codeforphilly-data work, so CI's + `check:sheet-configs` will report drift until then (as for the v3 + contracts in this branch's base). The end-to-end check waits on the bot's + DM handler; its `awaits:` entry stays because that PR is still to come. +- **Spec fixes** (`docs(specs): settle the gaps…`): the code is 8 characters + shown as two groups of four (the example had 7); the code response carries + `botDmUrl` (`SLACK_OPS_BOT_DM_URL`) so the row can link the bot's name; an + account with no private profile is refused (`422 no_private_profile`); + redemption fails closed with no `SLACK_TEAM_ID`; a 409 does not spend the + code; `/me`'s `slack` in auth.md; both linking paths are credential + endpoints; agent-grants contract v2 in data-model. +- **Lockout is per agent account** (the spec says per agent; the plan's + Approach said per grant): ten `code_invalid` answers in an hour lock that + agent out for an hour, even for a valid code. A wrong workspace or a 409 + does not count as a failure. +- **`/api/agent/*` checks the scope before the body** (a `preValidation` + hook), and the scope's companions at use as well as at mint, so a grant + record written by hand without them is refused (`401`). +- **Profile rewrites keep the link.** Four places rebuilt the private profile + field by field (GitHub email change, claim, claim merge, staff email edit) + and would have dropped `slack`; they carry it. A claim merge keeps a link + made from either account. Not guarded: a lost update if a GitHub sign-in + rewrites the profile in the same instant as a redemption (both + read-then-write the private profile). +- Redemptions run one at a time in-process, so two cannot link one Slack + user to two accounts. Codes are swept on read; a restart drops them. +- Browser check on a local app with made-up fixtures: signed in as a test + member by legacy password, Account → Connect Slack showed a code and the + DM instruction with the bot link; redeeming it with a test grant via the + API turned the row to "Connected to Slack ✓ since …" with Disconnect, on + its next poll. Neither data repo history nor the API log held the code or + the Slack id; the private profiles file held the id. +- Gate at this commit's tree: check-contracts, type-check, lint, tests + (API 68 files / 807, web 36 / 218, shared 5 / 120) clean. + ## Follow-ups + +- codeforphilly-data: adopt `agent-grants/v2` on `empty`, `fixture`, + `legacy-import`, then `published` at release (no migration: v2 only widens + the scope enum). +- Deploy: set `SLACK_TEAM_ID` (and optionally `SLACK_OPS_BOT_DM_URL`) in the + ConfigMap; without it no link can be made. From def6c539c5ff7142746b316297cad17105143b12 Mon Sep 17 00:00:00 2001 From: GrittyBot <30755786+codeforphilly-bot@users.noreply.github.com> Date: Sun, 29 Nov 2026 22:38:20 +0000 Subject: [PATCH 09/26] chore(plans): mark agent-application-feed in-progress Co-Authored-By: Claude Opus 5.5 --- plans/agent-application-feed.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/plans/agent-application-feed.md b/plans/agent-application-feed.md index 70cd393..75cb168 100644 --- a/plans/agent-application-feed.md +++ b/plans/agent-application-feed.md @@ -1,5 +1,5 @@ --- -status: planned +status: in-progress depends: [membership-applications, slack-account-link] specs: - specs/api/agent-applications.md From 81a4167f6fafcf6cc61ee1056d9fee932af0535f Mon Sep 17 00:00:00 2001 From: GrittyBot <30755786+codeforphilly-bot@users.noreply.github.com> Date: Sun, 29 Nov 2026 22:39:47 +0000 Subject: [PATCH 10/26] feat(api): GET /api/agent/events, the application feed for agents projects:applications:read. Events are derived from the membership records on each read: application.visible at notifiedAt, .reminder at remindedAt, .accepted at decidedAt, .closed at closedAt. A held application, one withdrawn before admins could see it, and every event of a deactivated applicant or deleted project are left out. Each event names the project, the applicant's facts, the application (offer, needs, decidedBy, decidedVia, closedBy) and the active admins, with a Slack user id only for a verified link in this workspace; no email anywhere. Ordered by (at, record id, type) with a base64url cursor that survives a restart; 7-day default window; events show once a minute old, and the sweep stamps its notice bookkeeping when it commits rather than when it started, so nothing lands behind a cursor. hasSlackLink reads the typed field now. Co-Authored-By: Claude Opus 5.5 --- apps/api/src/app.ts | 2 + apps/api/src/plugins/services.ts | 3 + apps/api/src/routes/agent-applications.ts | 41 +++ apps/api/src/services/agent-feed.ts | 232 +++++++++++++++ apps/api/src/services/application-notices.ts | 5 +- apps/api/src/services/memberships.ts | 8 +- apps/api/tests/agent-feed.test.ts | 288 +++++++++++++++++++ 7 files changed, 572 insertions(+), 7 deletions(-) create mode 100644 apps/api/src/routes/agent-applications.ts create mode 100644 apps/api/src/services/agent-feed.ts create mode 100644 apps/api/tests/agent-feed.test.ts diff --git a/apps/api/src/app.ts b/apps/api/src/app.ts index 5f44cbc..e3b28c2 100644 --- a/apps/api/src/app.ts +++ b/apps/api/src/app.ts @@ -69,6 +69,7 @@ import { chatRoutes } from './routes/chat.js'; import { moderationRoutes } from './routes/moderation.js'; import { agentRoutes } from './routes/agents.js'; import { slackLinkRoutes } from './routes/slack-link.js'; +import { agentApplicationRoutes } from './routes/agent-applications.js'; import { webhookRoutes } from './routes/webhooks.js'; import { samlRoutes } from './routes/saml.js'; import { internalRoutes } from './routes/internal.js'; @@ -225,6 +226,7 @@ export async function buildApp(opts: BuildAppOptions = {}): Promise { teamId: fastify.config.SLACK_TEAM_ID, botDmUrl: fastify.config.SLACK_OPS_BOT_DM_URL, }), + agentFeed: new AgentFeedService(state, fastify.store.private, { teamId: fastify.config.SLACK_TEAM_ID }), }); } diff --git a/apps/api/src/routes/agent-applications.ts b/apps/api/src/routes/agent-applications.ts new file mode 100644 index 0000000..ad09aa3 --- /dev/null +++ b/apps/api/src/routes/agent-applications.ts @@ -0,0 +1,41 @@ +/** + * Agent applications routes — specs/api/agent-applications.md. + * + * GET /api/agent/events — agent:projects:applications:read + * + * The scope is checked before the query or body is validated, so a caller + * without it learns nothing from a validation error. Signed-in people and + * staff are anonymous here (401), like any caller without the grant. + */ +import type { FastifyInstance } from 'fastify'; + +import { agentScopeCaller } from '../auth/caller.js'; + +export async function agentApplicationRoutes(fastify: FastifyInstance): Promise { + fastify.get( + '/api/agent/events', + { + preValidation: async (request) => { + agentScopeCaller(request, 'projects:applications:read'); + }, + schema: { + tags: ['agent-applications'], + summary: 'Application events after a cursor (agent:projects:applications:read)', + querystring: { + type: 'object', + properties: { + after: { type: 'string', maxLength: 512 }, + limit: { type: 'integer', minimum: 1, maximum: 200 }, + }, + additionalProperties: false, + }, + }, + }, + async (request) => { + agentScopeCaller(request, 'projects:applications:read'); + const q = request.query as { after?: string; limit?: number }; + const { data, next } = await fastify.services.agentFeed.events(q); + return { success: true, data, metadata: { timestamp: new Date().toISOString(), next } }; + }, + ); +} diff --git a/apps/api/src/services/agent-feed.ts b/apps/api/src/services/agent-feed.ts new file mode 100644 index 0000000..a33ea7d --- /dev/null +++ b/apps/api/src/services/agent-feed.ts @@ -0,0 +1,232 @@ +/** + * The application event feed for agents — specs/api/agent-applications.md → + * GET /api/agent/events. + * + * A view, not a stored log: events are derived from the membership records' + * `application` timestamps on every read. + * + * | type | at | + * | ---------------------- | ------------ | + * | application.visible | notifiedAt | + * | application.reminder | remindedAt | + * | application.accepted | decidedAt | + * | application.closed | closedAt | + * + * Hidden records never appear: an application whose hold has not ended (or + * that was closed before admins could see it), and every event of a + * deactivated or missing applicant or a deleted project. No email address + * is in any event; an admin's Slack user id is there only when they have a + * verified link in the workspace the site serves. + * + * Ordered by `(at, record id, type)`. The cursor is that triple, base64url + * JSON, so it survives restarts. An event appears once it is + * {@link FEED_SETTLE_MS} old, so a write whose timestamp was taken just + * before it committed cannot land behind a cursor already handed out. + */ +import type { Person, ProjectMembership } from '@cfp/shared/schemas'; + +import { ApiValidationError } from '../lib/errors.js'; +import { personBySlug, projectBySlug, type InMemoryState } from '../store/memory/state.js'; +import type { PrivateStore } from '../store/private/interface.js'; +import { adminPeople } from './memberships.js'; +import { applicantFacts } from './project-application.js'; + +const DAY = 24 * 60 * 60 * 1000; +export const FEED_DEFAULT_WINDOW_MS = 7 * DAY; +export const FEED_SETTLE_MS = 60 * 1000; +export const FEED_DEFAULT_LIMIT = 100; +export const FEED_MAX_LIMIT = 200; + +export const FEED_EVENT_TYPES = [ + 'application.visible', + 'application.reminder', + 'application.accepted', + 'application.closed', +] as const; +export type FeedEventType = (typeof FEED_EVENT_TYPES)[number]; + +interface Position { + readonly at: number; + readonly id: string; + /** Index into FEED_EVENT_TYPES; -1 sorts before every event at (at, id). */ + readonly t: number; +} + +export function encodeCursor(p: Position): string { + return Buffer.from(JSON.stringify([p.at, p.id, p.t]), 'utf8').toString('base64url'); +} + +export function decodeCursor(cursor: string): Position { + try { + const v: unknown = JSON.parse(Buffer.from(cursor, 'base64url').toString('utf8')); + if ( + Array.isArray(v) && + v.length === 3 && + Number.isFinite(v[0]) && + typeof v[1] === 'string' && + Number.isInteger(v[2]) && + v[2] >= -1 && + v[2] < FEED_EVENT_TYPES.length + ) { + return { at: v[0] as number, id: v[1], t: v[2] as number }; + } + } catch { + // fall through + } + throw new ApiValidationError('after is not a cursor from this feed', { after: 'invalid' }); +} + +function compare(a: Position, b: Position): number { + if (a.at !== b.at) return a.at - b.at; + if (a.id !== b.id) return a.id < b.id ? -1 : 1; + return a.t - b.t; +} + +interface PersonRef { + readonly slug: string; + readonly fullName: string; +} + +export interface FeedEvent { + readonly cursor: string; + readonly type: FeedEventType; + readonly at: string; + readonly project: { readonly slug: string; readonly title: string; readonly chatChannel: string | null }; + readonly applicant: PersonRef & { + readonly accountCreatedAt: string; + readonly hasGitHubLink: boolean; + readonly memberOf: Array<{ slug: string; title: string }>; + }; + readonly application: { + readonly status: 'open' | 'accepted' | 'closed'; + readonly roles: Array<{ id: string; title: string }>; + readonly offer: string | null; + readonly submittedAt: string; + readonly decidedBy: PersonRef | null; + readonly decidedVia: 'site' | 'agent' | null; + readonly closedBy: 'admin' | 'applicant' | 'site' | null; + }; + readonly admins: Array; +} + +/** The raw events one record yields, before visibility and window filters. */ +function eventsOf(m: ProjectMembership): Array { + const app = m.application; + if (!app) return []; + const out: Array = []; + const push = (type: FeedEventType, iso: string | null | undefined) => { + if (!iso) return; + const at = Date.parse(iso); + if (Number.isFinite(at)) out.push({ at, id: m.id, t: FEED_EVENT_TYPES.indexOf(type), type }); + }; + const visibleAt = Date.parse(app.visibleAt); + push('application.visible', app.notifiedAt); + push('application.reminder', app.remindedAt); + if (app.status === 'accepted') push('application.accepted', app.decidedAt); + // Closed before admins could see it (the applicant withdrew during the hold): never shown. + if (app.status === 'closed' && app.closedAt && Date.parse(app.closedAt) >= visibleAt) { + push('application.closed', app.closedAt); + } + return out; +} + +export class AgentFeedService { + readonly #state: InMemoryState; + readonly #privateStore: PrivateStore; + readonly #teamId: string | undefined; + + constructor(state: InMemoryState, privateStore: PrivateStore, opts: { teamId?: string | undefined }) { + this.#state = state; + this.#privateStore = privateStore; + this.#teamId = opts.teamId; + } + + async events( + query: { after?: string | undefined; limit?: number | undefined }, + now: Date = new Date(), + ): Promise<{ data: FeedEvent[]; next: string }> { + const limit = query.limit ?? FEED_DEFAULT_LIMIT; + if (!Number.isInteger(limit) || limit < 1 || limit > FEED_MAX_LIMIT) { + throw new ApiValidationError(`limit is 1–${FEED_MAX_LIMIT}`, { limit: 'out_of_range' }); + } + const after: Position | null = query.after ? decodeCursor(query.after) : null; + const t = now.getTime(); + const horizon = t - FEED_SETTLE_MS; + const floor = t - FEED_DEFAULT_WINDOW_MS; + + const s = this.#state; + const raw: Array = []; + for (const m of s.projectMemberships.values()) { + const app = m.application; + // Held (hold not over) → nothing, whatever else is on the record. + if (!app || Date.parse(app.visibleAt) > t) continue; + const applicant = personBySlug(s, m.personSlug); + if (!applicant || applicant.deletedAt) continue; + const project = projectBySlug(s, m.projectSlug); + if (!project || project.deletedAt) continue; + for (const e of eventsOf(m)) { + if (e.at > horizon) continue; + if (after ? compare(e, after) <= 0 : e.at < floor) continue; + raw.push({ ...e, m }); + } + } + raw.sort(compare); + const page = raw.slice(0, limit); + + const data: FeedEvent[] = []; + for (const e of page) data.push(await this.#serialize(e, e.type, e.m)); + const last = page[page.length - 1]; + const next = last + ? encodeCursor(last) + : (query.after ?? encodeCursor({ at: Math.max(horizon, floor), id: '', t: -1 })); + return { data, next }; + } + + async #serialize(pos: Position, type: FeedEventType, m: ProjectMembership): Promise { + const s = this.#state; + const project = projectBySlug(s, m.projectSlug)!; + const applicant = personBySlug(s, m.personSlug)!; + const app = m.application!; + const facts = applicantFacts(s, applicant, project.slug); + const decider = app.decidedById ? s.people.get(app.decidedById) : undefined; + return { + cursor: encodeCursor(pos), + type, + at: new Date(pos.at).toISOString(), + project: { slug: project.slug, title: project.title, chatChannel: project.chatChannel ?? null }, + applicant: { + slug: applicant.slug, + fullName: applicant.fullName, + accountCreatedAt: facts.accountCreatedAt, + hasGitHubLink: facts.hasGitHubLink, + memberOf: facts.memberOf, + }, + application: { + status: app.status, + roles: app.roleIds.map((id) => ({ id, title: s.helpWantedRoles.get(id)?.title ?? 'Removed need' })), + offer: app.offer ?? null, + submittedAt: app.submittedAt, + decidedBy: decider && !decider.deletedAt ? ref(decider) : null, + decidedVia: app.decidedVia ?? null, + closedBy: app.closedBy ?? null, + }, + admins: await this.#admins(project.slug), + }; + } + + /** The project's active admins, each with a Slack user id only when verified-linked in this workspace. */ + async #admins(projectSlug: string): Promise { + const out: Array = []; + for (const person of adminPeople(this.#state, projectSlug)) { + if (person.deletedAt) continue; + const slack = (await this.#privateStore.getProfile(person.id))?.slack; + const linked = slack && this.#teamId !== undefined && slack.teamId === this.#teamId; + out.push({ ...ref(person), slackUserId: linked ? slack.userId : null }); + } + return out; + } +} + +function ref(p: Person): PersonRef { + return { slug: p.slug, fullName: p.fullName }; +} diff --git a/apps/api/src/services/application-notices.ts b/apps/api/src/services/application-notices.ts index 1d8707b..32b2800 100644 --- a/apps/api/src/services/application-notices.ts +++ b/apps/api/src/services/application-notices.ts @@ -195,7 +195,10 @@ export class ApplicationSweepService { else if (!app.remindedAt && t >= visibleAt + REMINDER_AFTER_MS) due.push({ m, reminder: true }); } if (due.length > 0) { - const at = now.toISOString(); + // Taken now, not at the start of the run: the closes and their emails + // above may have taken a while, and the agent feed orders events by + // these stamps (agent-applications.md → GET /api/agent/events). + const at = new Date(Math.max(now.getTime(), Date.now())).toISOString(); const marked = due.map(({ m, reminder }) => ({ reminder, m: { ...m, application: { ...m.application!, ...(reminder ? { remindedAt: at } : { notifiedAt: at }) } }, diff --git a/apps/api/src/services/memberships.ts b/apps/api/src/services/memberships.ts index 5559a10..4bf18b2 100644 --- a/apps/api/src/services/memberships.ts +++ b/apps/api/src/services/memberships.ts @@ -105,13 +105,9 @@ export function hasDeliverableEmail(profile: PrivateProfile | null | undefined): return Boolean(profile?.email) && profile?.emailBounce?.inactive !== true; } -/** - * A verified Slack link on the profile (specs/api/slack-link.md). The field - * arrives with the Slack-linking plan; until then no profile carries it. - */ +/** A verified Slack link on the profile (specs/api/slack-link.md). */ export function hasSlackLink(profile: PrivateProfile | null | undefined): boolean { - const slack = (profile as { slack?: unknown } | null | undefined)?.slack; - return slack !== undefined && slack !== null; + return Boolean(profile?.slack); } /** diff --git a/apps/api/tests/agent-feed.test.ts b/apps/api/tests/agent-feed.test.ts new file mode 100644 index 0000000..6f33165 --- /dev/null +++ b/apps/api/tests/agent-feed.test.ts @@ -0,0 +1,288 @@ +/** + * The application event feed for agents (plans/agent-application-feed.md, + * specs/api/agent-applications.md → GET /api/agent/events): the four event + * types at the right `at`, the 7-day window, paging that returns every event + * once across pages and a restart, hidden records left out, admins' Slack + * ids only when linked, no email anywhere, and the scope. + * + * Every person, workspace and Slack id here is invented; addresses are example.org. + */ +import { afterEach, beforeEach, describe, expect, it } from 'vitest'; + +import { buildApp } from '../src/app.js'; +import { FEED_SETTLE_MS } from '../src/services/agent-feed.js'; +import { + JWT_KEY, + bearer, + createAgent, + daysAgo, + fid, + minutesAgo, + personRecord, + privateProfile, + startAgentTestEnv, + type AgentTestEnv, + type Rec, +} from './helpers/agent-fixtures.js'; + +const TEAM = 'TEXAMPLE01'; +const P = { + ada: 1, bounce: 2, olly: 3, ben: 4, root: 5, sam: 6, + dee: 10, old: 11, acc: 12, clo: 13, nina: 14, wd: 15, hal: 16, fresh: 17, far: 18, gina: 19, +}; +const T = '2026-05-01T00:00:00.000Z'; +const ROLE = fid(300); + +let n = 1000; +const rec = (project: string, person: string, state: 'follower' | 'applicant' | 'member', over: Rec = {}): Rec => ({ + id: fid(n++), + projectSlug: project, + personSlug: person, + state, + isAdmin: false, + muted: false, + followedAt: T, + createdAt: T, + updatedAt: T, + ...(state === 'member' ? { via: 'legacy', joinedAt: T } : {}), + ...over, +}); +const app = (over: Rec): Rec => ({ application: { status: 'open', roleIds: [], offer: 'Happy to help.', ...over } }); + +// Times, fixed per run. +const at = { + deeVisible: minutesAgo(180), + oldVisible: daysAgo(15), + oldReminded: daysAgo(1), + accNotified: minutesAgo(300), + accDecided: minutesAgo(120), + cloNotified: minutesAgo(240), + cloClosed: minutesAgo(60), + ninaVisible: new Date(Date.now() + 6 * 3600_000).toISOString(), + wdVisible: minutesAgo(30), + wdClosed: minutesAgo(90), + freshNotified: new Date(Date.now() - 10_000).toISOString(), + ginaVisible: minutesAgo(200), +}; + +function records(): Record { + n = 1000; + return { + people: [ + ...Object.entries(P).map(([slug, k]) => + personRecord(k, slug, { + ...(slug === 'olly' || slug === 'hal' ? { deletedAt: daysAgo(2) } : {}), + ...(slug === 'root' ? { accountLevel: 'administrator' } : {}), + ...(slug === 'sam' ? { accountLevel: 'staff' } : {}), + ...(slug === 'nina' ? { createdAt: minutesAgo(60) } : {}), + ...(slug === 'dee' ? { githubUserId: 4242, githubLogin: 'dee-gh' } : {}), + }), + ), + ], + projects: [ + { id: fid(50), slug: 'proj', title: 'Project Proj', stage: 'testing', featured: false, chatChannel: 'proj-chat', createdAt: T, updatedAt: T }, + { id: fid(51), slug: 'side', title: 'Side', stage: 'testing', featured: false, createdAt: T, updatedAt: T }, + ], + 'help-wanted-roles': [ + { id: ROLE, projectSlug: 'proj', postedById: fid(P.ada), title: 'Frontend dev', description: 'React.', status: 'open', createdAt: T, updatedAt: T }, + ], + 'project-memberships': [ + rec('proj', 'ada', 'member', { isAdmin: true }), + rec('proj', 'bounce', 'member', { isAdmin: true }), + rec('proj', 'olly', 'member', { isAdmin: true }), + rec('proj', 'ben', 'member'), + rec('side', 'dee', 'member'), + rec('proj', 'dee', 'applicant', app({ roleIds: [ROLE], submittedAt: at.deeVisible, visibleAt: at.deeVisible, notifiedAt: at.deeVisible })), + rec('proj', 'old', 'applicant', app({ submittedAt: at.oldVisible, visibleAt: at.oldVisible, notifiedAt: at.oldVisible, remindedAt: at.oldReminded })), + rec('proj', 'acc', 'member', { + via: 'application', joinedAt: at.accDecided, + ...app({ status: 'accepted', submittedAt: at.accNotified, visibleAt: at.accNotified, notifiedAt: at.accNotified, decidedById: fid(P.ada), decidedAt: at.accDecided, decidedVia: 'site' }), + }), + rec('proj', 'clo', 'follower', app({ + status: 'closed', submittedAt: at.cloNotified, visibleAt: at.cloNotified, notifiedAt: at.cloNotified, + closedBy: 'admin', closedAt: at.cloClosed, decidedById: fid(P.ada), decidedAt: at.cloClosed, decidedVia: 'site', + })), + // Held: a new account; admins have not been told. + rec('proj', 'nina', 'applicant', app({ submittedAt: minutesAgo(30), visibleAt: at.ninaVisible, notifiedAt: null })), + // Withdrawn during the hold, before admins could see it. + rec('proj', 'wd', 'follower', app({ status: 'closed', submittedAt: minutesAgo(120), visibleAt: at.wdVisible, closedBy: 'applicant', closedAt: at.wdClosed })), + // Deactivated applicant. + rec('proj', 'hal', 'applicant', app({ submittedAt: at.deeVisible, visibleAt: at.deeVisible, notifiedAt: at.deeVisible })), + // Too new to have settled. + rec('proj', 'fresh', 'applicant', app({ submittedAt: at.freshNotified, visibleAt: at.freshNotified, notifiedAt: at.freshNotified })), + // Outside the default window entirely. + rec('proj', 'far', 'applicant', app({ submittedAt: daysAgo(10), visibleAt: daysAgo(10), notifiedAt: daysAgo(10) })), + // Visible but the sweep has not notified yet. + rec('proj', 'gina', 'applicant', app({ submittedAt: at.ginaVisible, visibleAt: at.ginaVisible, notifiedAt: null })), + ], + }; +} + +const PROFILES = Object.entries(P).map(([slug, k]) => + privateProfile(fid(k), `${slug}@example.org`, { + ...(slug === 'ada' ? { slack: { teamId: TEAM, userId: 'UADA000001', linkedAt: T } } : {}), + ...(slug === 'olly' ? { slack: { teamId: TEAM, userId: 'UOLLY00001', linkedAt: T } } : {}), + // A link in some other workspace never counts. + ...(slug === 'bounce' ? { slack: { teamId: 'TOTHER0001', userId: 'UBOUNCE001', linkedAt: T } } : {}), + }), +); + +interface Ev { + cursor: string; + type: string; + at: string; + applicant: { slug: string }; + application: { status: string; decidedBy: { slug: string } | null; decidedVia: string | null; closedBy: string | null; roles: Array<{ title: string }> }; + admins: Array<{ slug: string; slackUserId: string | null }>; + project: { slug: string; chatChannel: string | null }; +} + +describe('agent application feed', () => { + let env: AgentTestEnv; + let token: string; + + beforeEach(async () => { + env = await startAgentTestEnv({ records: records(), profiles: PROFILES, env: { SLACK_TEAM_ID: TEAM } }); + token = (await createAgent(env, await env.cookie(P.root, 'administrator'), { slug: 'example-bot', scopes: ['projects:applications:read'] })).token; + }); + afterEach(async () => { + await env.close(); + }); + + const feed = async (query = '', tok = token) => { + const res = await env.app.inject({ method: 'GET', url: `/api/agent/events${query}`, ...bearer(tok) }); + expect(res.statusCode, res.body).toBe(200); + return res.json<{ data: Ev[]; metadata: { next: string } }>(); + }; + const key = (e: Ev) => `${e.type} ${e.applicant.slug}`; + + it('yields each event type once at the right at, in order, from the last 7 days', async () => { + const { data, metadata } = await feed(); + expect(data.map(key)).toEqual([ + 'application.reminder old', + 'application.visible acc', + 'application.visible clo', + 'application.visible dee', + 'application.accepted acc', + 'application.closed clo', + ]); + const byKey = new Map(data.map((e) => [key(e), e])); + expect(byKey.get('application.visible dee')!.at).toBe(at.deeVisible); + expect(byKey.get('application.reminder old')!.at).toBe(at.oldReminded); + expect(byKey.get('application.accepted acc')!.at).toBe(at.accDecided); + expect(byKey.get('application.closed clo')!.at).toBe(at.cloClosed); + expect(byKey.get('application.accepted acc')!.application).toMatchObject({ status: 'accepted', decidedBy: { slug: 'ada' }, decidedVia: 'site' }); + expect(byKey.get('application.closed clo')!.application).toMatchObject({ status: 'closed', closedBy: 'admin', decidedBy: { slug: 'ada' } }); + expect(byKey.get('application.visible dee')!.application.roles).toEqual([{ id: ROLE, title: 'Frontend dev' }]); + expect(byKey.get('application.visible dee')!).toMatchObject({ + project: { slug: 'proj', title: 'Project Proj', chatChannel: 'proj-chat' }, + applicant: { slug: 'dee', fullName: 'Test dee', hasGitHubLink: true, memberOf: [{ slug: 'side', title: 'Side' }] }, + }); + expect(metadata.next).toBe(data[data.length - 1]!.cursor); + }); + + it("lists the project's active admins with a Slack id only for a verified link in this workspace, and no email anywhere", async () => { + const res = await env.app.inject({ method: 'GET', url: '/api/agent/events', ...bearer(token) }); + const { data } = res.json<{ data: Ev[] }>(); + for (const e of data) { + expect(e.admins).toEqual([ + { slug: 'ada', fullName: 'Test ada', slackUserId: 'UADA000001' }, + { slug: 'bounce', fullName: 'Test bounce', slackUserId: null }, + ]); + } + // Schema test on the whole response: no key named like an email, no address. + const keys: string[] = []; + const walk = (v: unknown) => { + if (Array.isArray(v)) v.forEach(walk); + else if (v && typeof v === 'object') { + for (const [k, x] of Object.entries(v)) { + keys.push(k); + walk(x); + } + } + }; + walk(res.json()); + expect(keys.filter((k) => /mail/i.test(k))).toEqual([]); + expect(res.body).not.toMatch(/@/); + expect(res.body).not.toContain('UOLLY00001'); + expect(res.body).not.toContain('UBOUNCE001'); + }); + + it('pages with next: every event exactly once across pages and across a restart', async () => { + const all = (await feed()).data.map((e) => e.cursor); + const first = await feed('?limit=2'); + expect(first.data).toHaveLength(2); + + // A restart: a second app on the same stores reads on from the cursor. + const second = await buildApp({ + serverOptions: { logger: false }, + overrideEnv: { + CFP_DATA_REPO_PATH: env.dataPath, + STORAGE_BACKEND: 'filesystem', + CFP_PRIVATE_STORAGE_PATH: env.privatePath, + CFP_JWT_SIGNING_KEY: JWT_KEY, + NODE_ENV: 'test', + SLACK_TEAM_ID: TEAM, + }, + }); + await second.ready(); + try { + const seen = first.data.map((e) => e.cursor); + let next = first.metadata.next; + for (let i = 0; i < 10; i++) { + const res = await second.inject({ method: 'GET', url: `/api/agent/events?limit=2&after=${next}`, ...bearer(token) }); + expect(res.statusCode, res.body).toBe(200); + const page = res.json<{ data: Ev[]; metadata: { next: string } }>(); + if (page.data.length === 0) { + expect(page.metadata.next).toBe(next); + break; + } + seen.push(...page.data.map((e) => e.cursor)); + next = page.metadata.next; + } + expect(seen).toEqual(all); + } finally { + await second.close(); + } + }); + + it('a held application yields nothing until admins are notified; a deactivated applicant’s events vanish', async () => { + const svc = env.app.services.agentFeed; + expect((await feed()).data.some((e) => ['nina', 'wd', 'hal', 'gina', 'far'].includes(e.applicant.slug))).toBe(false); + + // The hold ends and the sweep notifies admins; once settled, the event appears at notifiedAt. + const later = new Date(Date.parse(at.ninaVisible) + 60_000); + await env.app.applicationSweep.sweep(later); + const afterSweep = await svc.events({}, new Date(Math.max(later.getTime(), Date.now()) + FEED_SETTLE_MS + 1000)); + const nina = afterSweep.data.find((e) => e.applicant.slug === 'nina'); + expect(nina?.type).toBe('application.visible'); + expect(afterSweep.data.find((e) => e.applicant.slug === 'gina')?.type).toBe('application.visible'); + expect(afterSweep.data.some((e) => e.applicant.slug === 'wd')).toBe(false); + + // dee is deactivated: every one of their events drops out. + const s = env.app.inMemoryState; + s.people.set(fid(P.dee), { ...s.people.get(fid(P.dee))!, deletedAt: new Date().toISOString() }); + expect((await feed()).data.some((e) => e.applicant.slug === 'dee')).toBe(false); + }); + + it('holds back events younger than a minute, and an empty page still gives a cursor to read on from', async () => { + const svc = env.app.services.agentFeed; + const now = await svc.events({}); + expect(now.data.some((e) => e.applicant.slug === 'fresh')).toBe(false); + const soon = await svc.events({ after: now.next }, new Date(Date.now() + FEED_SETTLE_MS + 1000)); + expect(soon.data.map((e) => e.applicant.slug)).toEqual(['fresh']); + + const empty = await svc.events({ after: soon.next }, new Date(Date.now() + FEED_SETTLE_MS + 2000)); + expect(empty.data).toEqual([]); + expect(empty.next).toBe(soon.next); + }); + + it('refuses a grant without the scope, staff and anonymous callers (401), and a bad cursor (422)', async () => { + const linkOnly = (await createAgent(env, await env.cookie(P.root, 'administrator'), { slug: 'link-bot', scopes: ['slack:link'] })).token; + expect((await env.app.inject({ method: 'GET', url: '/api/agent/events', ...bearer(linkOnly) })).statusCode).toBe(401); + expect((await env.app.inject({ method: 'GET', url: '/api/agent/events', cookies: { cfp_session: await env.cookie(P.sam, 'staff') } })).statusCode).toBe(401); + expect((await env.app.inject({ method: 'GET', url: '/api/agent/events' })).statusCode).toBe(401); + const bad = await env.app.inject({ method: 'GET', url: '/api/agent/events?after=nonsense', ...bearer(token) }); + expect(bad.statusCode).toBe(422); + }); +}); From e57769d6b969596be152cac635626c9e1851876a Mon Sep 17 00:00:00 2001 From: GrittyBot <30755786+codeforphilly-bot@users.noreply.github.com> Date: Sun, 29 Nov 2026 22:51:53 +0000 Subject: [PATCH 11/26] chore(plans): mark agent-application-feed done (PR #TBD) Co-Authored-By: Claude Opus 5.5 --- plans/agent-application-feed.md | 40 ++++++++++++++++++++++++++++----- 1 file changed, 34 insertions(+), 6 deletions(-) diff --git a/plans/agent-application-feed.md b/plans/agent-application-feed.md index 75cb168..03dea72 100644 --- a/plans/agent-application-feed.md +++ b/plans/agent-application-feed.md @@ -1,5 +1,5 @@ --- -status: in-progress +status: done depends: [membership-applications, slack-account-link] specs: - specs/api/agent-applications.md @@ -38,12 +38,12 @@ over the `openApplications` index plus recently decided records; sort by ## Validation -- [ ] Tests: each event type appears once at the right `at`; paging with `next` returns every event exactly once across pages and across a restart -- [ ] Tests: a held application yields nothing until notified; a deactivated applicant's events vanish -- [ ] Tests: `admins[].slackUserId` is set only for linked, active admins; no field anywhere carries an email (schema test on the response) -- [ ] A grant without the scope is refused +- [x] Tests: each event type appears once at the right `at`; paging with `next` returns every event exactly once across pages and across a restart +- [x] Tests: a held application yields nothing until notified; a deactivated applicant's events vanish +- [x] Tests: `admins[].slackUserId` is set only for linked, active admins; no field anywhere carries an email (schema test on the response) +- [x] A grant without the scope is refused - [ ] End to end: an application on sandbox produces an AI-marked DM to its linked admin (awaits the bot PR and `mpim:write`) -- [ ] `npm run type-check && npm run lint && npm test` clean +- [x] `npm run type-check && npm run lint && npm test` clean ## Risks / unknowns @@ -51,4 +51,32 @@ over the `openApplications` index plus recently decided records; sort by ## Notes +- **End-to-end criterion open; both `awaits:` entries stay.** The bot's + heartbeat stream and the `mpim:write` install are still to come. +- **`application.visible` is at `notifiedAt`, not `visibleAt`** (spec fixed + in `docs(specs): settle the gaps…`, which this plan's Approach predates). + For a held application the sweep sets `notifiedAt` after `visibleAt`, so + an event at `visibleAt` could land behind a cursor already read. +- **A one-minute settle window.** An event shows once it is a minute old; + and the sweep now stamps its notice bookkeeping when it commits, not when + the run started (closes and their emails come first). Together they keep + a late-committed stamp from landing behind a handed-out cursor. Spec says so. +- **Cursor** is base64url JSON `[at ms, record id, type index]`; comparison + is numeric on `at`, so mixed timestamp spellings in records sort right. + `metadata.next` is never null: with no events it is the `after` passed, or + the settle horizon. +- **Hidden** also covers an application the applicant withdrew during its + hold (closed before `visibleAt`): no event at all. A visible application + the sweep has not yet notified has no `visible` event until it does. +- `application` carries `decidedBy`/`decidedVia`/`closedBy` as they stand + now (spec addition); `status` is the current one, so a `visible` event read + late may show `accepted`. +- The feed scans every membership on each read; fine at this scale. +- Smoke on a local app with made-up fixtures: the test grant read two + `application.visible` events with admins and no `@` anywhere in the body. +- Gate at this commit's tree: check-contracts, type-check, lint, tests + (API 69 files / 813, web 36 / 217, shared 5 / 120) clean. + ## Follow-ups + +None on the site side. From 7a2bc96863af250963b79ff527dd3c6656926065 Mon Sep 17 00:00:00 2001 From: GrittyBot <30755786+codeforphilly-bot@users.noreply.github.com> Date: Sun, 29 Nov 2026 22:51:53 +0000 Subject: [PATCH 12/26] chore(plans): mark agent-decide-on-behalf in-progress Co-Authored-By: Claude Opus 5.5 --- plans/agent-decide-on-behalf.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/plans/agent-decide-on-behalf.md b/plans/agent-decide-on-behalf.md index 6e28ba7..16e4d2f 100644 --- a/plans/agent-decide-on-behalf.md +++ b/plans/agent-decide-on-behalf.md @@ -1,5 +1,5 @@ --- -status: planned +status: in-progress depends: [agent-application-feed, needs-on-applications] specs: - specs/api/agent-applications.md From d9e7d3eeceb12ffecb67b6439f2cb0f7d52a1ce1 Mon Sep 17 00:00:00 2001 From: GrittyBot <30755786+codeforphilly-bot@users.noreply.github.com> Date: Sun, 29 Nov 2026 22:53:14 +0000 Subject: [PATCH 13/26] feat(api): the confirmation email to an admin an agent decided for MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit "The ops bot recorded that you accepted …", naming the agent, how to undo it, and a link to the Applications screen. Co-Authored-By: Claude Opus 5.5 --- apps/api/src/notify/email-notifier.ts | 11 ++++++++ apps/api/src/notify/index.ts | 23 ++++++++++++++++ apps/api/src/notify/membership-templates.ts | 29 +++++++++++++++++++++ apps/api/tests/membership-templates.test.ts | 17 ++++++++++++ 4 files changed, 80 insertions(+) diff --git a/apps/api/src/notify/email-notifier.ts b/apps/api/src/notify/email-notifier.ts index 6723dd2..db7d6a9 100644 --- a/apps/api/src/notify/email-notifier.ts +++ b/apps/api/src/notify/email-notifier.ts @@ -14,6 +14,7 @@ import type { EventReminderNotification, EventRsvpNotification, EventUpdatedNotification, + AgentDecisionConfirmation, ApplicationDecisionNotification, MemberAddedNotification, NewApplicationNotification, @@ -34,6 +35,7 @@ import { renderWelcomeEmail, } from './templates.js'; import { + renderAgentDecisionConfirmationEmail, renderApplicationDecisionEmail, renderMemberAddedEmail, renderNewApplicationEmail, @@ -92,6 +94,15 @@ export class EmailNotifier implements Notifier { return this.#deliver('application notice', ctx, n.email, renderNewApplicationEmail(n, this.#siteHost)); } + async notifyAgentDecisionConfirmation(n: AgentDecisionConfirmation): Promise<{ delivered: boolean }> { + const ctx = { kind: `application.agent-${n.decision}`, project: n.projectSlug }; + if (!n.email) { + this.#log.warn(ctx, 'agent decision confirmation: no email address; skipped'); + return { delivered: false }; + } + return this.#deliver('agent decision confirmation', ctx, n.email, renderAgentDecisionConfirmationEmail(n, this.#siteHost)); + } + async notifyApplicationDecision(n: ApplicationDecisionNotification): Promise<{ delivered: boolean }> { const ctx = { kind: `application.${n.outcome}`, project: n.projectSlug }; if (!n.email) { diff --git a/apps/api/src/notify/index.ts b/apps/api/src/notify/index.ts index 18c61d4..0271417 100644 --- a/apps/api/src/notify/index.ts +++ b/apps/api/src/notify/index.ts @@ -156,7 +156,25 @@ export interface ApplicationDecisionNotification { readonly chatChannel: string | null; } +/** + * To a project admin: an agent recorded a decision in their name + * (specs/behaviors/authorization.md → On behalf of a project admin), so a + * decision they did not make surfaces at once. + */ +export interface AgentDecisionConfirmation { + readonly email: string; + /** The admin's name. */ + readonly fullName: string; + readonly projectTitle: string; + readonly projectSlug: string; + readonly applicantName: string; + readonly decision: 'accepted' | 'closed'; + /** The agent account's name, e.g. "Example Ops Bot". */ + readonly agentName: string; +} + export interface Notifier { + notifyAgentDecisionConfirmation(n: AgentDecisionConfirmation): Promise<{ delivered: boolean }>; notifyNewApplication(n: NewApplicationNotification): Promise<{ delivered: boolean }>; notifyApplicationDecision(n: ApplicationDecisionNotification): Promise<{ delivered: boolean }>; notifyMemberAdded(n: MemberAddedNotification): Promise<{ delivered: boolean }>; @@ -193,6 +211,11 @@ export class LoggingNotifier implements Notifier { return { delivered: true }; } + async notifyAgentDecisionConfirmation(n: AgentDecisionConfirmation): Promise<{ delivered: boolean }> { + this.#log.info({ kind: `application.agent-${n.decision}`, project: n.projectSlug }, 'agent decision confirmation'); + return { delivered: true }; + } + async notifyApplicationDecision(n: ApplicationDecisionNotification): Promise<{ delivered: boolean }> { // Never the note: it is emailed and stored nowhere, logs included. this.#log.info({ kind: `application.${n.outcome}`, project: n.projectSlug }, 'application decision notification'); diff --git a/apps/api/src/notify/membership-templates.ts b/apps/api/src/notify/membership-templates.ts index 2ff93a4..3470c0d 100644 --- a/apps/api/src/notify/membership-templates.ts +++ b/apps/api/src/notify/membership-templates.ts @@ -7,6 +7,7 @@ * never turned into a link by us. */ import type { + AgentDecisionConfirmation, ApplicationDecisionNotification, MemberAddedNotification, NewApplicationNotification, @@ -197,3 +198,31 @@ export function renderApplicationDecisionEmail(n: ApplicationDecisionNotificatio footer, ); } + +/** + * To the project admin an agent named: "The ops bot recorded that you + * accepted …", with a link to the Applications screen, so a decision they + * did not make surfaces at once (authorization.md → On behalf of a project admin). + */ +export function renderAgentDecisionConfirmationEmail(n: AgentDecisionConfirmation, siteHost: string): MembershipEmail { + const verb = n.decision === 'accepted' ? 'accepted' : 'closed'; + const what = + n.decision === 'accepted' + ? `accepted ${n.applicantName}'s application to ${n.projectTitle}; they are now a member` + : `closed ${n.applicantName}'s application to ${n.projectTitle}; they are still following the project`; + return renderBlocks( + `The ops bot recorded that you ${verb} an application to ${n.projectTitle}`, + [ + { p: `Hi ${n.fullName}, the ops bot (${n.agentName}) recorded in your name that you ${what}.` }, + { + p: + "If you didn't say so, tell the organizers. " + + (n.decision === 'accepted' + ? 'You can undo it by removing the member from the project.' + : 'You can undo it by adding the person to the project directly.'), + }, + { link: `${projectUrl(siteHost, n.projectSlug)}/applications`, label: 'Open the Applications screen' }, + ], + `You're receiving this because you are an admin of ${n.projectTitle} and your Slack account is linked to Code for Philly.`, + ); +} diff --git a/apps/api/tests/membership-templates.test.ts b/apps/api/tests/membership-templates.test.ts index 986befb..8cdc807 100644 --- a/apps/api/tests/membership-templates.test.ts +++ b/apps/api/tests/membership-templates.test.ts @@ -6,6 +6,7 @@ import { describe, expect, it } from 'vitest'; import { + renderAgentDecisionConfirmationEmail, renderMemberAddedEmail, renderNewNeedEmail, renderProjectUpdateEmail, @@ -41,4 +42,20 @@ describe('membership email templates', () => { expect(e.html).toContain('<script>'); expect(e.html).not.toContain('href="https://spam.example"'); }); + + it('the agent decision confirmation tells the admin what was recorded in their name, and how to undo it', () => { + const accepted = renderAgentDecisionConfirmationEmail( + { ...base, applicantName: 'Cam Applicant', decision: 'accepted', agentName: 'Example Bot' }, + HOST, + ); + expect(accepted.subject).toBe('The ops bot recorded that you accepted an application to Proj'); + expect(accepted.text).toContain("recorded in your name that you accepted Cam Applicant's application to Proj"); + expect(accepted.text).toContain('removing the member'); + expect(accepted.text).toContain('https://example.org/projects/proj/applications'); + const closed = renderAgentDecisionConfirmationEmail( + { ...base, applicantName: 'Cam Applicant', decision: 'closed', agentName: 'Example Bot' }, + HOST, + ); + expect(closed.text).toContain('adding the person to the project directly'); + }); }); From 264d60fc0ad28e37c052a07c544dc82cd38f54ee Mon Sep 17 00:00:00 2001 From: GrittyBot <30755786+codeforphilly-bot@users.noreply.github.com> Date: Sun, 29 Nov 2026 22:53:14 +0000 Subject: [PATCH 14/26] feat(api): an agent records a project admin's accept or close POST /api/agent/applications/:projectSlug/:personSlug/decision under projects:applications:decide, which must hold its two companions at use (401 otherwise). onBehalfOf must name a Slack user in the configured workspace with a verified link to a person who is not deactivated, not an agent, and is a project-admin of this project right now, checked with the site's project-admin marker alone so staff powers do not carry over (403 not_project_admin otherwise). Checked before the lock to name the admin in the commit and again under it, with the 30-per-24-hours cap per agent across its grants (records plus an in-process log). The effect is the site's accept or close run as that admin, with decidedVia = agent and agentGrantId; the commit is the agent's with Actor-Kind, Grant-Id and On-Behalf-Of. Unknown body fields (isAdmin above all) are refused, not dropped. The applicant gets the usual email and the admin a confirmation. Co-Authored-By: Claude Opus 5.5 --- apps/api/src/plugins/services.ts | 8 +- apps/api/src/routes/agent-applications.ts | 95 ++++- apps/api/src/services/agent-decision.ts | 185 +++++++++ apps/api/src/services/application-notices.ts | 34 ++ apps/api/src/services/project-application.ts | 23 +- apps/api/tests/agent-decision.test.ts | 413 +++++++++++++++++++ 6 files changed, 753 insertions(+), 5 deletions(-) create mode 100644 apps/api/src/services/agent-decision.ts create mode 100644 apps/api/tests/agent-decision.test.ts diff --git a/apps/api/src/plugins/services.ts b/apps/api/src/plugins/services.ts index 12c02ce..abce77f 100644 --- a/apps/api/src/plugins/services.ts +++ b/apps/api/src/plugins/services.ts @@ -45,6 +45,7 @@ import { ProjectApplicationService } from '../services/project-application.js'; import { ApplicationNotices } from '../services/application-notices.js'; import { SlackLinkService } from '../services/slack-link.js'; import { AgentFeedService } from '../services/agent-feed.js'; +import { AgentDecisionService } from '../services/agent-decision.js'; declare module 'fastify' { interface FastifyInstance { @@ -78,6 +79,7 @@ declare module 'fastify' { spamPurges: SpamPurgeLogService; slackLinks: SlackLinkService; agentFeed: AgentFeedService; + agentDecisions: AgentDecisionService; }; /** Shared in-memory state — write routes call StateApply.apply against this. */ inMemoryState: InMemoryState; @@ -143,6 +145,7 @@ async function servicesPlugin(fastify: FastifyInstance): Promise { ); const githubAccount = new GitHubAccountService(state); + const applications = new ProjectApplicationService(state, fastify.store.private); fastify.decorate('services', { projects: new ProjectService(state, fts, fastify.store.private), people: new PersonService(state, fts, fastify.store.private), @@ -157,7 +160,7 @@ async function servicesPlugin(fastify: FastifyInstance): Promise { eventSeriesWrite: new EventSeriesWriteService(state), projectsWrite: new ProjectWriteService(state), projectMembershipsWrite: new ProjectMembershipWriteService(state), - applications: new ProjectApplicationService(state, fastify.store.private), + applications, projectUpdatesWrite: new ProjectUpdateWriteService(state), projectBuzzWrite: new ProjectBuzzWriteService(state), helpWantedWrite: new HelpWantedWriteService(state), @@ -207,6 +210,9 @@ async function servicesPlugin(fastify: FastifyInstance): Promise { botDmUrl: fastify.config.SLACK_OPS_BOT_DM_URL, }), agentFeed: new AgentFeedService(state, fastify.store.private, { teamId: fastify.config.SLACK_TEAM_ID }), + agentDecisions: new AgentDecisionService(state, fastify.store.private, applications, { + teamId: fastify.config.SLACK_TEAM_ID, + }), }); } diff --git a/apps/api/src/routes/agent-applications.ts b/apps/api/src/routes/agent-applications.ts index ad09aa3..1f06427 100644 --- a/apps/api/src/routes/agent-applications.ts +++ b/apps/api/src/routes/agent-applications.ts @@ -1,7 +1,9 @@ /** * Agent applications routes — specs/api/agent-applications.md. * - * GET /api/agent/events — agent:projects:applications:read + * GET /api/agent/events — agent:projects:applications:read + * POST /api/agent/applications/:projectSlug/:personSlug/decision + * — agent:projects:applications:decide (with its two companions) * * The scope is checked before the query or body is validated, so a caller * without it learns nothing from a validation error. Signed-in people and @@ -10,6 +12,12 @@ import type { FastifyInstance } from 'fastify'; import { agentScopeCaller } from '../auth/caller.js'; +import { ApiValidationError } from '../lib/errors.js'; +import { ok } from '../lib/response.js'; +import type { AgentDecisionInput } from '../services/agent-decision.js'; +import { buildTransactionOptions } from '../store/commit-meta.js'; + +const DECISION_FIELDS = new Set(['decision', 'onBehalfOf', 'role', 'fillRoleIds', 'note']); export async function agentApplicationRoutes(fastify: FastifyInstance): Promise { fastify.get( @@ -38,4 +46,89 @@ export async function agentApplicationRoutes(fastify: FastifyInstance): Promise< return { success: true, data, metadata: { timestamp: new Date().toISOString(), next } }; }, ); + + fastify.post( + '/api/agent/applications/:projectSlug/:personSlug/decision', + { + preValidation: async (request) => { + agentScopeCaller(request, 'projects:applications:decide'); + // Refuse, rather than silently drop, anything the grant may not ask for + // (isAdmin above all): the schema's additionalProperties would strip it. + const body = request.body; + if (body && typeof body === 'object' && !Array.isArray(body)) { + const extra = Object.keys(body).filter((k) => !DECISION_FIELDS.has(k)); + if (extra.length > 0) { + throw new ApiValidationError('Unknown fields', Object.fromEntries(extra.map((k) => [k, 'not allowed']))); + } + } + }, + schema: { + tags: ['agent-applications'], + summary: "Record a project admin's accept or close of an open application (agent:projects:applications:decide)", + params: { + type: 'object', + properties: { projectSlug: { type: 'string' }, personSlug: { type: 'string' } }, + required: ['projectSlug', 'personSlug'], + }, + body: { + type: 'object', + properties: { + decision: { type: 'string', enum: ['accept', 'close'] }, + onBehalfOf: { + type: 'object', + properties: { + slackTeamId: { type: 'string', maxLength: 32 }, + slackUserId: { type: 'string', maxLength: 32 }, + }, + required: ['slackTeamId', 'slackUserId'], + additionalProperties: false, + }, + role: { type: ['string', 'null'] }, + fillRoleIds: { type: 'array', items: { type: 'string' } }, + note: { type: ['string', 'null'] }, + }, + required: ['decision', 'onBehalfOf'], + // No isAdmin, no anything else: the grant accepts or closes, nothing more. + additionalProperties: false, + }, + }, + }, + async (request) => { + const caller = agentScopeCaller(request, 'projects:applications:decide'); + const { projectSlug, personSlug } = request.params as { projectSlug: string; personSlug: string }; + const svc = fastify.services.agentDecisions; + const input = svc.validate(request.body as Partial); + // Refuse early (before taking the lock), and name the admin for the commit; + // decide() checks both again under the lock. + svc.checkCap(caller.agent.person.slug, new Date()); + const { admin } = svc.resolveAdmin(projectSlug, input.onBehalfOf); + + const accept = input.decision === 'accept'; + const result = await fastify.store.transact( + buildTransactionOptions({ + request, + session: caller.session, + action: accept ? 'project-membership.accept' : 'project-membership.close', + subjectType: 'project-membership', + subjectSlug: `${projectSlug}/${personSlug}`, + responseCode: 200, + extraTrailers: { 'On-Behalf-Of': admin.slug, ...(accept ? {} : { 'Closed-By': 'admin' }) }, + }), + async (tx) => svc.decide(tx, caller.agent, projectSlug, personSlug, input, admin.id), + (value) => value.stateApply.apply(fastify.inMemoryState, fastify.fts), + ); + const { membership: m, note, project, applicant } = result.value; + svc.noteDecision(caller.agent.person.slug, m.id, new Date(m.application!.decidedAt!)); + + // The applicant hears exactly as for a site decision; the admin gets a confirmation. + void fastify.applicationNotices + .toApplicant(m, accept ? 'accepted' : 'closed', note) + .catch((err: unknown) => fastify.log.error({ err }, 'application decision email failed')); + void fastify.applicationNotices + .confirmAgentDecision(admin, project, applicant, accept ? 'accepted' : 'closed', caller.agent.person) + .catch((err: unknown) => fastify.log.error({ err }, 'agent decision confirmation failed')); + + return ok({ state: m.state, decidedBy: { slug: admin.slug } }); + }, + ); } diff --git a/apps/api/src/services/agent-decision.ts b/apps/api/src/services/agent-decision.ts new file mode 100644 index 0000000..2e32d7c --- /dev/null +++ b/apps/api/src/services/agent-decision.ts @@ -0,0 +1,185 @@ +/** + * An agent records a project admin's accept or close — specs/api/agent-applications.md → + * POST /api/agent/applications/:projectSlug/:personSlug/decision, and + * specs/behaviors/authorization.md → On behalf of a project admin. + * + * The one place a grant acts for a person, so every check fails closed: + * + * - the grant holds `projects:applications:decide` and both companions + * (checked by the route, {@link agentScopeCaller}); + * - the named Slack user is in the workspace the site serves and resolves + * through a verified link (`PrivateProfile.slack`) to a person who exists, + * is not deactivated, is not an agent account, and is — right now — a + * `member` with `isAdmin` on this project. Staff powers do not carry over: + * the check is the site's `project-admin` marker alone; + * - at most {@link AGENT_DECISIONS_PER_DAY} decisions per agent in any + * rolling 24 hours; + * - the application is open and visible (else 404), so a replay of a decided + * application changes nothing. + * + * The effects are the site's accept and close, run as the named admin (for + * `decidedById` and the authorization check) with `decidedVia = agent` and + * `agentGrantId`; the route commits as the agent with `Actor-Kind: agent`, + * `Grant-Id` and `On-Behalf-Of: `, and emails the admin a + * confirmation. + */ +import type { Person, Project } from '@cfp/shared/schemas'; + +import { grantsOf, isAgentAccount, type AgentPrincipal } from '../auth/agent-grant.js'; +import type { SessionContext } from '../auth/middleware.js'; +import { requireAuth } from '../auth/require.js'; +import { ApiNotFoundError, ApiValidationError, ForbiddenError, RateLimitedError } from '../lib/errors.js'; +import { projectBySlug, type InMemoryState } from '../store/memory/state.js'; +import type { PrivateStore } from '../store/private/interface.js'; +import type { DualStoreTx } from '../store/store.js'; +import { membershipsOfProject } from './memberships.js'; +import { NOTE_MAX, type DecideResult, type ProjectApplicationService } from './project-application.js'; + +const DAY = 24 * 60 * 60 * 1000; +export const AGENT_DECISIONS_PER_DAY = 30; + +export interface AgentDecisionInput { + readonly decision: 'accept' | 'close'; + readonly onBehalfOf: { readonly slackTeamId: string; readonly slackUserId: string }; + readonly role?: string | null; + readonly fillRoleIds?: string[]; + readonly note?: string | null; +} + +export type AgentDecisionResult = DecideResult & { readonly admin: Person; readonly note: string | null }; + +const NOT_ADMIN = 'The named Slack user is not a linked, active admin of this project'; + +export class AgentDecisionService { + readonly #state: InMemoryState; + readonly #privateStore: PrivateStore; + readonly #applications: ProjectApplicationService; + readonly #teamId: string | undefined; + /** agent slug → decisions recorded in this process (membership id and when), for the cap. */ + readonly #log = new Map>(); + + constructor( + state: InMemoryState, + privateStore: PrivateStore, + applications: ProjectApplicationService, + opts: { teamId?: string | undefined }, + ) { + this.#state = state; + this.#privateStore = privateStore; + this.#applications = applications; + this.#teamId = opts.teamId; + } + + /** Shape checks that need no state. */ + validate(input: Partial): AgentDecisionInput { + const fields: Record = {}; + if (input.decision !== 'accept' && input.decision !== 'close') fields['decision'] = 'accept or close'; + const ob = input.onBehalfOf; + if (!ob || typeof ob.slackTeamId !== 'string' || typeof ob.slackUserId !== 'string') { + fields['onBehalfOf'] = '{ slackTeamId, slackUserId }'; + } + if (input.decision === 'close' && (input.role !== undefined || input.fillRoleIds !== undefined)) { + fields['role'] = 'role and fillRoleIds are for accept'; + } + if (input.decision === 'accept' && input.note != null) fields['note'] = 'note is for close'; + if (typeof input.note === 'string' && input.note.length > NOTE_MAX) fields['note'] = `at most ${NOTE_MAX} characters`; + if (Object.keys(fields).length > 0) throw new ApiValidationError('Invalid decision', fields); + return input as AgentDecisionInput; + } + + /** + * The project admin the request names, or `403 not_project_admin`. Called + * once before the write (to name them in the commit) and again under the + * write lock, where it must resolve to the same person. + */ + resolveAdmin(projectSlug: string, onBehalfOf: AgentDecisionInput['onBehalfOf']): { admin: Person; project: Project } { + const project = projectBySlug(this.#state, projectSlug); + if (!project || project.deletedAt) throw new ApiNotFoundError(`Project '${projectSlug}' not found`); + const refuse = (): never => { + throw new ForbiddenError(NOT_ADMIN, 'not_project_admin'); + }; + + const teamId = this.#teamId; + if (!teamId || onBehalfOf.slackTeamId !== teamId) return refuse(); + const personId = this.#privateStore.findPersonIdBySlackUser(teamId, onBehalfOf.slackUserId); + if (!personId) return refuse(); + const admin = this.#state.people.get(personId); + if (!admin || admin.deletedAt || isAgentAccount(this.#state, admin.slug)) return refuse(); + + // `project-admin` alone, as a plain user: staff and administrator powers do not carry over. + const asAdmin: SessionContext = { person: admin, accountLevel: 'user', personId: admin.id }; + try { + requireAuth('project-admin', { session: asAdmin, project, memberships: membershipsOfProject(this.#state, project.slug) }); + } catch { + return refuse(); + } + return { admin, project }; + } + + /** Decision times in the last 24 hours for every grant of this agent: the records and this process's log. */ + recentDecisions(agentSlug: string, now: number): number[] { + const grants = new Set(grantsOf(this.#state, agentSlug).map((g) => g.id)); + const seen = new Set(); + const times: number[] = []; + const add = (id: string, at: number) => { + const key = `${id}@${at}`; + if (!Number.isFinite(at) || now - at >= DAY || seen.has(key)) return; + seen.add(key); + times.push(at); + }; + for (const m of this.#state.projectMemberships.values()) { + const app = m.application; + if (app?.decidedVia === 'agent' && app.agentGrantId && grants.has(app.agentGrantId) && app.decidedAt) { + add(m.id, Date.parse(app.decidedAt)); + } + } + const log = (this.#log.get(agentSlug) ?? []).filter((e) => now - e.at < DAY); + this.#log.set(agentSlug, log); + for (const e of log) add(e.id, e.at); + return times.sort((a, b) => a - b); + } + + /** Throws 429 when the agent has reached its daily cap. */ + checkCap(agentSlug: string, now: Date): void { + const recent = this.recentDecisions(agentSlug, now.getTime()); + if (recent.length >= AGENT_DECISIONS_PER_DAY) { + const frees = recent[recent.length - AGENT_DECISIONS_PER_DAY]! + DAY; + throw new RateLimitedError(Math.max(1, Math.ceil((frees - now.getTime()) / 1000))); + } + } + + /** + * Run under the write lock: cap, admin (must still be `expectedAdminId`), + * then the site's accept or close as that admin, marked as the agent's. + */ + async decide( + tx: DualStoreTx, + agent: AgentPrincipal, + projectSlug: string, + personSlug: string, + input: AgentDecisionInput, + expectedAdminId: string, + now: Date = new Date(), + ): Promise { + this.checkCap(agent.person.slug, now); + const { admin } = this.resolveAdmin(projectSlug, input.onBehalfOf); + if (admin.id !== expectedAdminId) throw new ForbiddenError(NOT_ADMIN, 'not_project_admin'); + const asAdmin: SessionContext = { person: admin, accountLevel: 'user', personId: admin.id }; + const via = { agentGrantId: agent.grant.id }; + if (input.decision === 'accept') { + const fill = input.fillRoleIds !== undefined ? { fillRoleIds: input.fillRoleIds } : {}; + const role = input.role !== undefined ? { role: input.role } : {}; + const result = await this.#applications.accept(tx, projectSlug, personSlug, { ...role, ...fill }, asAdmin, now, via); + return { ...result, admin, note: null }; + } + const result = await this.#applications.close(tx, projectSlug, personSlug, { note: input.note ?? null }, asAdmin, now, via); + return { ...result, admin }; + } + + /** Count a decision toward the cap once its commit has landed. */ + noteDecision(agentSlug: string, membershipId: string, at: Date): void { + const log = this.#log.get(agentSlug) ?? []; + log.push({ id: membershipId, at: at.getTime() }); + this.#log.set(agentSlug, log); + } +} diff --git a/apps/api/src/services/application-notices.ts b/apps/api/src/services/application-notices.ts index 32b2800..0974a0f 100644 --- a/apps/api/src/services/application-notices.ts +++ b/apps/api/src/services/application-notices.ts @@ -96,6 +96,40 @@ export class ApplicationNotices { return attempted; } + /** + * Tell the admin an agent named that it recorded a decision in their name + * (authorization.md → On behalf of a project admin). Skipped, never + * redirected, when they have no deliverable address. + */ + async confirmAgentDecision( + admin: Person, + project: { slug: string; title: string }, + applicant: Person, + decision: 'accepted' | 'closed', + agent: Person, + ): Promise { + const profile = await this.#d.privateStore.getProfile(admin.id); + if (!profile || !hasDeliverableEmail(profile)) { + this.#d.log.info({ project: project.slug, decision }, 'agent decision confirmation: no deliverable address; skipped'); + return false; + } + try { + await this.#d.notifier.notifyAgentDecisionConfirmation({ + email: profile.email, + fullName: admin.fullName, + projectTitle: project.title, + projectSlug: project.slug, + applicantName: applicant.fullName, + decision, + agentName: agent.fullName, + }); + return true; + } catch (err) { + this.#d.log.error({ err, project: project.slug, decision }, 'agent decision confirmation: send threw'); + return false; + } + } + /** Tell the applicant the outcome. The note goes only into this email. */ async toApplicant( m: ProjectMembership, diff --git a/apps/api/src/services/project-application.ts b/apps/api/src/services/project-application.ts index e79ae26..2ef28d9 100644 --- a/apps/api/src/services/project-application.ts +++ b/apps/api/src/services/project-application.ts @@ -146,6 +146,20 @@ export interface ApplyInput { readonly offer?: string | null; } +/** + * How a decision was made: on the site by the session's person, or by an + * agent on that person's behalf (`decidedVia = agent`, `agentGrantId`) — + * specs/api/agent-applications.md. The session is always the deciding + * admin; the agent is the commit author, set by the caller. + */ +export interface DecisionVia { + readonly agentGrantId: string; +} + +function viaFields(via: DecisionVia | undefined): { decidedVia: 'site' | 'agent'; agentGrantId?: string } { + return via ? { decidedVia: 'agent', agentGrantId: via.agentGrantId } : { decidedVia: 'site' }; +} + export interface DecideResult { readonly membership: ProjectMembership; readonly stateApply: StateApply; @@ -355,6 +369,7 @@ export class ProjectApplicationService { input: { role?: string | null; isAdmin?: boolean; fillRoleIds?: string[] }, session: SessionContext, now: Date = new Date(), + via?: DecisionVia, ): Promise { const { project, applicant, existing } = this.#openApplicationOrThrow(projectSlug, personSlug, session, now); checkRole(input.role); @@ -379,7 +394,7 @@ export class ProjectApplicationService { role: role === null ? null : role.slice(0, 80), via: 'application', joinedAt: at, - application: { ...app, status: 'accepted', decidedById: session.person!.id, decidedAt: at, decidedVia: 'site' }, + application: { ...app, status: 'accepted', decidedById: session.person!.id, decidedAt: at, ...viaFields(via) }, updatedAt: at, }); await tx.public['project-memberships'].upsert(membership); @@ -400,13 +415,14 @@ export class ProjectApplicationService { input: { note?: string | null }, session: SessionContext, now: Date = new Date(), + via?: DecisionVia, ): Promise { const { project, applicant, existing } = this.#openApplicationOrThrow(projectSlug, personSlug, session, now); const note = typeof input.note === 'string' && input.note.trim() !== '' ? input.note : null; if (note !== null && note.length > NOTE_MAX) { throw new ApiValidationError(`note is at most ${NOTE_MAX} characters`, { note: 'too_long' }); } - const membership = this.#closed(existing, 'admin', now, session.person!.id); + const membership = this.#closed(existing, 'admin', now, session.person!.id, via); await tx.public['project-memberships'].upsert(membership); return { membership, stateApply: new StateApply().upsertMembership(membership), project, applicant, note }; } @@ -421,6 +437,7 @@ export class ProjectApplicationService { closedBy: 'admin' | 'applicant' | 'site', now: Date, decidedById: string | null, + via?: DecisionVia, ): ProjectMembership { const at = iso(now); return asFollower(m, at, { @@ -429,7 +446,7 @@ export class ProjectApplicationService { status: 'closed', closedBy, closedAt: at, - ...(decidedById ? { decidedById, decidedAt: at, decidedVia: 'site' as const } : {}), + ...(decidedById ? { decidedById, decidedAt: at, ...viaFields(via) } : {}), }, }); } diff --git a/apps/api/tests/agent-decision.test.ts b/apps/api/tests/agent-decision.test.ts new file mode 100644 index 0000000..983b361 --- /dev/null +++ b/apps/api/tests/agent-decision.test.ts @@ -0,0 +1,413 @@ +/** + * An agent records a project admin's accept or close from Slack + * (plans/agent-decide-on-behalf.md, specs/api/agent-applications.md → + * POST …/decision, specs/behaviors/authorization.md → On behalf of a + * project admin). The happy paths, the commit and record, the confirmation + * email, and every refusal: unlinked, other workspace, linked to a + * non-admin, staff who is not an admin, deactivated, demoted, wrong + * project, missing scope or companions, the daily cap, replay, and every + * other route the grant must not reach. + * + * Every person, workspace and Slack id here is invented; addresses are example.org. + */ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; + +import type { ProjectMembership } from '@cfp/shared/schemas'; + +import { AGENT_DECISIONS_PER_DAY } from '../src/services/agent-decision.js'; +import { StateApply } from '../src/store/state-apply.js'; +import { + bearer, + createAgent, + daysAgo, + fid, + minutesAgo, + mintGrant, + personRecord, + privateProfile, + startAgentTestEnv, + type AgentTestEnv, + type Rec, +} from './helpers/agent-fixtures.js'; + +const TEAM = 'TEXAMPLE01'; +const P = { + ada: 1, olly: 2, dana: 3, sam: 4, ben: 5, ivy: 6, root: 7, una: 8, + cara: 10, dev: 11, eli: 12, fay: 13, gus: 14, hana: 15, +}; +const U = { ada: 'UADA000001', olly: 'UOLLY00001', dana: 'UDANA00001', sam: 'USAM000001', ivy: 'UIVY000001', ben: 'UBEN000001' }; +const ROLE = fid(300); +const T = '2026-05-01T00:00:00.000Z'; +const RECENT = minutesAgo(90); +const NOTE = 'We are full on frontend this season, thank you.'; + +let n = 1000; +const rec = (project: string, person: string, state: 'follower' | 'applicant' | 'member', over: Rec = {}): Rec => ({ + id: fid(n++), + projectSlug: project, + personSlug: person, + state, + isAdmin: false, + muted: false, + followedAt: T, + createdAt: T, + updatedAt: T, + ...(state === 'member' ? { via: 'legacy', joinedAt: T } : {}), + ...over, +}); +const openApp = (over: Rec = {}): Rec => ({ + application: { status: 'open', roleIds: [], offer: 'Glad to help.', submittedAt: RECENT, visibleAt: RECENT, notifiedAt: RECENT, ...over }, +}); +const project = (k: number, slug: string): Rec => ({ + id: fid(50 + k), slug, title: `Project ${slug}`, stage: 'testing', featured: false, chatChannel: slug, createdAt: T, updatedAt: T, +}); + +function records(): Record { + n = 1000; + return { + people: Object.entries(P).map(([slug, k]) => + personRecord(k, slug, { + ...(slug === 'olly' ? { deletedAt: daysAgo(1) } : {}), + ...(slug === 'sam' ? { accountLevel: 'staff' } : {}), + ...(slug === 'root' ? { accountLevel: 'administrator' } : {}), + ...(slug === 'una' ? { accountLevel: 'staff' } : {}), + }), + ), + projects: [project(0, 'proj'), project(1, 'side')], + 'help-wanted-roles': [ + { id: ROLE, projectSlug: 'proj', postedById: fid(P.ada), title: 'Frontend dev', description: 'React.', status: 'open', createdAt: T, updatedAt: T }, + ], + 'project-memberships': [ + rec('proj', 'ada', 'member', { isAdmin: true, role: 'Founder' }), + rec('proj', 'olly', 'member', { isAdmin: true }), // deactivated admin + rec('proj', 'dana', 'member'), // a member, not (or no longer) an admin + rec('proj', 'ben', 'member'), + rec('proj', 'una', 'member', { isAdmin: true }), // staff who is an admin here: counts as an admin + rec('side', 'ivy', 'member', { isAdmin: true }), // admin of another project only + rec('proj', 'cara', 'applicant', openApp({ roleIds: [ROLE] })), + rec('proj', 'dev', 'applicant', openApp()), + rec('proj', 'eli', 'applicant', openApp()), + rec('proj', 'fay', 'applicant', openApp({ visibleAt: new Date(Date.now() + 6 * 3600_000).toISOString(), notifiedAt: null })), + rec('proj', 'gus', 'member', { + via: 'application', joinedAt: minutesAgo(30), + ...openApp({ status: 'accepted', decidedById: fid(P.ada), decidedAt: minutesAgo(30), decidedVia: 'site' }), + }), + rec('proj', 'hana', 'applicant', openApp()), + ], + }; +} + +const slack = (userId: string, teamId = TEAM): Rec => ({ slack: { teamId, userId, linkedAt: T } }); +const PROFILES = Object.entries(P).map(([slug, k]) => + privateProfile(fid(k), `${slug}@example.org`, { + ...(slug === 'ada' ? slack(U.ada) : {}), + ...(slug === 'olly' ? slack(U.olly) : {}), + ...(slug === 'dana' ? slack(U.dana) : {}), + ...(slug === 'sam' ? slack(U.sam) : {}), + ...(slug === 'ivy' ? slack(U.ivy) : {}), + ...(slug === 'una' ? slack('UUNA000001') : {}), + // ben's link is in some other workspace. + ...(slug === 'ben' ? slack(U.ben, 'TOTHER0001') : {}), + }), +); + +const ALL = ['slack:link', 'projects:applications:read', 'projects:applications:decide']; + +describe('agent decisions on a project admin’s behalf', () => { + let env: AgentTestEnv; + let agent: { token: string; grantId: string; personId: string }; + let adminCookie: string; + + beforeEach(async () => { + env = await startAgentTestEnv({ records: records(), profiles: PROFILES, env: { SLACK_TEAM_ID: TEAM } }); + adminCookie = await env.cookie(P.root, 'administrator'); + agent = await createAgent(env, adminCookie, { slug: 'example-bot', scopes: ALL }); + }); + afterEach(async () => { + vi.restoreAllMocks(); + await env.close(); + }); + + const decide = (person: string, body: Rec, token = agent.token, projectSlug = 'proj') => + env.app.inject({ + method: 'POST', + url: `/api/agent/applications/${projectSlug}/${person}/decision`, + ...bearer(token), + payload: body, + }); + const by = (userId: string, teamId = TEAM) => ({ slackTeamId: teamId, slackUserId: userId }); + const record = (person: string, projectSlug = 'proj'): ProjectMembership | undefined => { + const s = env.app.inMemoryState; + for (const id of s.membershipsByPerson.get(person) ?? []) { + const m = s.projectMemberships.get(id); + if (m?.projectSlug === projectSlug) return m; + } + return undefined; + }; + const head = async () => (await env.git('rev-parse', 'HEAD')).trim(); + const lastCommit = async () => env.git('log', '-1', '--format=%an <%ae>%n%B'); + const spies = () => ({ + applicant: vi.spyOn(env.app.notifier, 'notifyApplicationDecision'), + confirm: vi.spyOn(env.app.notifier, 'notifyAgentDecisionConfirmation'), + }); + const settle = () => new Promise((r) => setTimeout(r, 20)); + const errCode = (res: { json: () => unknown }) => (res.json() as { error: { code: string } }).error.code; + + it('accepts for a linked active admin: the record names the admin and the grant, the commit is the agent’s', async () => { + const mail = spies(); + const res = await decide('cara', { decision: 'accept', onBehalfOf: by(U.ada), fillRoleIds: [ROLE] }); + expect(res.statusCode, res.body).toBe(200); + expect(res.json<{ data: unknown }>().data).toEqual({ state: 'member', decidedBy: { slug: 'ada' } }); + + const m = record('cara')!; + expect(m).toMatchObject({ state: 'member', via: 'application', role: 'Frontend dev' }); + expect(m.application).toMatchObject({ + status: 'accepted', decidedById: fid(P.ada), decidedVia: 'agent', agentGrantId: agent.grantId, + }); + expect(env.app.inMemoryState.helpWantedRoles.get(ROLE)).toMatchObject({ status: 'filled' }); + + const commit = await lastCommit(); + expect(commit).toMatch(/^Example example-bot /); + expect(commit).toMatch(/^Action: project-membership\.accept$/m); + expect(commit).toMatch(/^Actor-Kind: agent$/m); + expect(commit).toMatch(new RegExp(`^Grant-Id: ${agent.grantId}$`, 'm')); + expect(commit).toMatch(/^On-Behalf-Of: ada$/m); + expect(commit).not.toContain(U.ada); + + await settle(); + expect(mail.applicant).toHaveBeenCalledTimes(1); + expect(mail.applicant.mock.calls[0]![0]).toMatchObject({ email: 'cara@example.org', outcome: 'accepted' }); + expect(mail.confirm).toHaveBeenCalledTimes(1); + expect(mail.confirm.mock.calls[0]![0]).toMatchObject({ + email: 'ada@example.org', decision: 'accepted', applicantName: 'Test cara', projectSlug: 'proj', agentName: 'Example example-bot', + }); + }); + + it('closes for a linked active admin; the note goes to the applicant only, never to the record or a commit', async () => { + const mail = spies(); + const res = await decide('dev', { decision: 'close', onBehalfOf: by(U.ada), note: NOTE }); + expect(res.statusCode, res.body).toBe(200); + expect(res.json<{ data: unknown }>().data).toEqual({ state: 'follower', decidedBy: { slug: 'ada' } }); + expect(record('dev')!.application).toMatchObject({ + status: 'closed', closedBy: 'admin', decidedById: fid(P.ada), decidedVia: 'agent', agentGrantId: agent.grantId, + }); + const commit = await lastCommit(); + expect(commit).toMatch(/^Action: project-membership\.close$/m); + expect(commit).toMatch(/^Closed-By: admin$/m); + expect(commit).toMatch(/^On-Behalf-Of: ada$/m); + expect(await env.git('log', '--all', '-p')).not.toContain(NOTE); + await settle(); + expect(mail.applicant.mock.calls[0]![0]).toMatchObject({ email: 'dev@example.org', outcome: 'closed', note: NOTE }); + expect(mail.confirm).toHaveBeenCalledTimes(1); + expect(mail.confirm.mock.calls[0]![0]).toMatchObject({ email: 'ada@example.org', decision: 'closed' }); + }); + + it('a staff member who is also an admin of the project counts as an admin', async () => { + const res = await decide('eli', { decision: 'accept', onBehalfOf: by('UUNA000001') }); + expect(res.statusCode, res.body).toBe(200); + expect(record('eli')!.application!.decidedById).toBe(fid(P.una)); + }); + + describe('refuses with 403 not_project_admin, writing and sending nothing', () => { + const cases: Array<[string, () => Rec]> = [ + ['an unlinked Slack user', () => by('UNOBODY001')], + ['a Slack id linked in another workspace', () => by(U.ben, 'TOTHER0001')], + ['an admin’s Slack id named in another workspace', () => by(U.ada, 'TOTHER0001')], + ['a Slack user linked to an account that is not an admin', () => by(U.dana)], + ['linked staff who is not an admin of the project', () => by(U.sam)], + ['a deactivated admin', () => by(U.olly)], + ['an admin of a different project', () => by(U.ivy)], + ]; + for (const [label, who] of cases) { + it(label, async () => { + const mail = spies(); + const before = await head(); + for (const decision of ['accept', 'close']) { + const res = await decide('cara', { decision, onBehalfOf: who() }); + expect(res.statusCode, res.body).toBe(403); + expect(errCode(res)).toBe('not_project_admin'); + } + expect(await head()).toBe(before); + expect(record('cara')!.state).toBe('applicant'); + await settle(); + expect(mail.applicant).not.toHaveBeenCalled(); + expect(mail.confirm).not.toHaveBeenCalled(); + }); + } + + it('an admin demoted since: refused at once', async () => { + expect((await decide('cara', { decision: 'close', onBehalfOf: by(U.ada) })).statusCode).toBe(200); + const demote = await env.app.inject({ + method: 'PATCH', + url: '/api/projects/proj/members/ada', + cookies: { cfp_session: adminCookie }, + payload: { isAdmin: false, confirmLastAdmin: true }, + }); + expect(demote.statusCode, demote.body).toBe(200); + const res = await decide('dev', { decision: 'accept', onBehalfOf: by(U.ada) }); + expect(res.statusCode).toBe(403); + expect(record('dev')!.state).toBe('applicant'); + }); + + it('an admin who disconnected Slack: refused', async () => { + const del = await env.app.inject({ method: 'DELETE', url: '/api/account/slack-link', cookies: { cfp_session: await env.cookie(P.ada, 'user') } }); + expect(del.statusCode).toBe(204); + expect((await decide('cara', { decision: 'accept', onBehalfOf: by(U.ada) })).statusCode).toBe(403); + }); + + it('no workspace configured: refused for everyone', async () => { + await env.close(); + env = await startAgentTestEnv({ records: records(), profiles: PROFILES }); + agent = await createAgent(env, await env.cookie(P.root, 'administrator'), { slug: 'example-bot', scopes: ALL }); + expect((await decide('cara', { decision: 'accept', onBehalfOf: by(U.ada) })).statusCode).toBe(403); + }); + }); + + describe('scope', () => { + it('a grant without the decide scope, staff and anonymous callers get 401', async () => { + const readLink = await mintGrant(env, adminCookie, 'example-bot', ['slack:link', 'projects:applications:read']); + expect((await decide('cara', { decision: 'accept', onBehalfOf: by(U.ada) }, readLink.token)).statusCode).toBe(401); + const asStaff = await env.app.inject({ + method: 'POST', url: '/api/agent/applications/proj/cara/decision', + cookies: { cfp_session: await env.cookie(P.sam, 'staff') }, + payload: { decision: 'accept', onBehalfOf: by(U.ada) }, + }); + expect(asStaff.statusCode).toBe(401); + const asAdminOfProject = await env.app.inject({ + method: 'POST', url: '/api/agent/applications/proj/cara/decision', + cookies: { cfp_session: await env.cookie(P.ada, 'user') }, + payload: { decision: 'accept', onBehalfOf: by(U.ada) }, + }); + expect(asAdminOfProject.statusCode).toBe(401); + const anon = await env.app.inject({ method: 'POST', url: '/api/agent/applications/proj/cara/decision', payload: { decision: 'accept', onBehalfOf: by(U.ada) } }); + expect(anon.statusCode).toBe(401); + expect(record('cara')!.state).toBe('applicant'); + }); + + it('a grant holding decide without its companions is refused at use (401)', async () => { + for (const scopes of [ + ['projects:applications:decide'], + ['projects:applications:decide', 'slack:link'], + ['projects:applications:decide', 'projects:applications:read'], + ]) { + // As if a grant record had been written by hand: mint rejects these. + const g = env.app.inMemoryState.agentGrants.get(agent.grantId)!; + env.app.inMemoryState.agentGrants.set(agent.grantId, { ...g, scopes: scopes as typeof g.scopes }); + const res = await decide('cara', { decision: 'accept', onBehalfOf: by(U.ada) }); + expect(res.statusCode, scopes.join(',')).toBe(401); + } + expect(record('cara')!.state).toBe('applicant'); + }); + + it('a revoked grant is refused', async () => { + const revoke = await env.app.inject({ + method: 'POST', url: `/api/admin/agents/example-bot/grants/${agent.grantId}/revoke`, cookies: { cfp_session: adminCookie }, payload: {}, + }); + expect(revoke.statusCode, revoke.body).toBe(200); + expect((await decide('cara', { decision: 'accept', onBehalfOf: by(U.ada) })).statusCode).toBe(401); + }); + }); + + describe('what it reaches', () => { + it('only open, visible applications: a held one, a decided one and a replay are 404', async () => { + expect((await decide('fay', { decision: 'accept', onBehalfOf: by(U.ada) })).statusCode).toBe(404); + expect((await decide('gus', { decision: 'close', onBehalfOf: by(U.ada) })).statusCode).toBe(404); + expect((await decide('cara', { decision: 'accept', onBehalfOf: by(U.ada) })).statusCode).toBe(200); + const before = await head(); + expect((await decide('cara', { decision: 'accept', onBehalfOf: by(U.ada) })).statusCode).toBe(404); + expect((await decide('cara', { decision: 'close', onBehalfOf: by(U.ada) })).statusCode).toBe(404); + expect(await head()).toBe(before); + expect((await decide('nobody', { decision: 'accept', onBehalfOf: by(U.ada) })).statusCode).toBe(404); + }); + + it('never adds, removes or promotes members, or touches needs or the project, through any route', async () => { + const before = await head(); + const tries: Array<[string, string, Rec | undefined]> = [ + ['POST', '/api/projects/proj/members', { personSlug: 'hana', isAdmin: true }], + ['PATCH', '/api/projects/proj/members/ben', { isAdmin: true }], + ['DELETE', '/api/projects/proj/members/ben', undefined], + ['POST', '/api/projects/proj/applications/hana/accept', {}], + ['POST', '/api/projects/proj/applications/hana/close', {}], + ['POST', '/api/projects/proj/help-wanted', { title: 'Spam', description: 'x' }], + ['PATCH', `/api/projects/proj/help-wanted/${ROLE}`, { title: 'Changed' }], + ['POST', `/api/projects/proj/help-wanted/${ROLE}/close`, {}], + ['PATCH', '/api/projects/proj', { title: 'Changed' }], + ['DELETE', '/api/projects/proj', undefined], + ['POST', '/api/projects/proj/follow', {}], + ['POST', '/api/projects/proj/applications', { offer: 'hi' }], + ]; + for (const [method, url, payload] of tries) { + const res = await env.app.inject({ method: method as 'POST', url, ...bearer(agent.token), ...(payload ? { payload } : {}) }); + expect([401, 403, 404], `${method} ${url} → ${res.statusCode}`).toContain(res.statusCode); + } + // The decision endpoint itself takes no isAdmin or anything else. + const promote = await decide('hana', { decision: 'accept', onBehalfOf: by(U.ada), isAdmin: true }); + expect(promote.statusCode).toBe(422); + expect(await head()).toBe(before); + expect(record('hana')!.state).toBe('applicant'); + }); + + it('git log --grep On-Behalf-Of lists exactly the agent’s decisions', async () => { + // A site decision by the admin herself carries no On-Behalf-Of. + const site = await env.app.inject({ + method: 'POST', url: '/api/projects/proj/applications/hana/accept', cookies: { cfp_session: await env.cookie(P.ada, 'user') }, payload: {}, + }); + expect(site.statusCode, site.body).toBe(200); + expect((await decide('cara', { decision: 'accept', onBehalfOf: by(U.ada) })).statusCode).toBe(200); + expect((await decide('dev', { decision: 'close', onBehalfOf: by('UUNA000001') })).statusCode).toBe(200); + const listed = (await env.git('log', '--grep=^On-Behalf-Of: ', '--format=%ae %(trailers:key=On-Behalf-Of,valueonly,separator=)')) + .trim() + .split('\n'); + expect(listed).toEqual([ + 'example-bot@users.noreply.codeforphilly.org una', + 'example-bot@users.noreply.codeforphilly.org ada', + ]); + }); + }); + + describe('the daily cap', () => { + /** Commit `count` agent decisions to the data repo, `ageMs` ago, for `grantId`. */ + const seedDecisions = async (count: number, grantId: string, ageMs: number) => { + const at = new Date(Date.now() - ageMs).toISOString(); + const ms: ProjectMembership[] = []; + for (let i = 0; i < count; i++) { + ms.push({ + id: fid(5000 + ageMs / 1000 + i), projectSlug: 'side', personSlug: `seed-${ageMs / 1000}-${i}`, state: 'member', isAdmin: false, muted: false, + via: 'application', followedAt: T, joinedAt: at, createdAt: T, updatedAt: at, + application: { status: 'accepted', roleIds: [], offer: 'x', submittedAt: T, visibleAt: T, decidedById: fid(P.ivy), decidedAt: at, decidedVia: 'agent', agentGrantId: grantId }, + } as ProjectMembership); + } + await env.app.store.transact({ message: 'seed agent decisions', author: { name: 'cfp test', email: 'test@example.org' } }, async (tx) => { + for (const m of ms) await tx.public['project-memberships'].upsert(m); + }); + const apply = new StateApply(); + for (const m of ms) apply.upsertMembership(m); + apply.apply(env.app.inMemoryState, env.app.fts); + }; + + it(`the ${AGENT_DECISIONS_PER_DAY + 1}st decision in 24 hours is 429, counted across the agent’s grants`, async () => { + const second = await mintGrant(env, adminCookie, 'example-bot', ALL); + await seedDecisions(AGENT_DECISIONS_PER_DAY - 2, agent.grantId, 3600_000); + await seedDecisions(5, agent.grantId, 25 * 3600_000); // older than a day: not counted + expect((await decide('cara', { decision: 'accept', onBehalfOf: by(U.ada) })).statusCode).toBe(200); // 29 + expect((await decide('dev', { decision: 'accept', onBehalfOf: by(U.ada) }, second.token)).statusCode).toBe(200); // 30 + const before = await head(); + const over = await decide('eli', { decision: 'close', onBehalfOf: by(U.ada) }); + expect(over.statusCode).toBe(429); + expect(Number(over.headers['retry-after'])).toBeGreaterThan(0); + const viaSecond = await decide('eli', { decision: 'close', onBehalfOf: by(U.ada) }, second.token); + expect(viaSecond.statusCode).toBe(429); + expect(await head()).toBe(before); + expect(record('eli')!.state).toBe('applicant'); + }); + + it('a decision whose record is later replaced still counts (the in-process log)', async () => { + await seedDecisions(AGENT_DECISIONS_PER_DAY - 1, agent.grantId, 3600_000); + expect((await decide('cara', { decision: 'accept', onBehalfOf: by(U.ada) })).statusCode).toBe(200); + // The member is removed: the record (and its application) is gone. + const remove = await env.app.inject({ method: 'DELETE', url: '/api/projects/proj/members/cara', cookies: { cfp_session: adminCookie } }); + expect(remove.statusCode, remove.body).toBe(204); + expect((await decide('dev', { decision: 'accept', onBehalfOf: by(U.ada) })).statusCode).toBe(429); + }); + }); +}); From 793a6dae77d6522bee7d479988c5b52435b3bc75 Mon Sep 17 00:00:00 2001 From: GrittyBot <30755786+codeforphilly-bot@users.noreply.github.com> Date: Sun, 29 Nov 2026 22:53:14 +0000 Subject: [PATCH 15/26] test(web): "via the ops bot" on an agent-recorded decision Co-Authored-By: Claude Opus 5.5 --- apps/web/tests/ProjectApplications.test.tsx | 20 ++++++++++++++++++-- 1 file changed, 18 insertions(+), 2 deletions(-) diff --git a/apps/web/tests/ProjectApplications.test.tsx b/apps/web/tests/ProjectApplications.test.tsx index 3824468..3b83a88 100644 --- a/apps/web/tests/ProjectApplications.test.tsx +++ b/apps/web/tests/ProjectApplications.test.tsx @@ -29,7 +29,7 @@ const ITEM = { }, }; -function mockApi(listStatus = 200) { +function mockApi(listStatus = 200, item: unknown = ITEM) { return vi.spyOn(globalThis, 'fetch').mockImplementation(((input: string, init?: RequestInit) => { if (input.startsWith('/api/auth/me')) { return Promise.resolve(json(200, mockOk({ person: { id: 'u1', slug: 'ada', fullName: 'Ada', accountLevel: 'user', avatarUrl: null }, accountLevel: 'user' }))); @@ -37,7 +37,7 @@ function mockApi(listStatus = 200) { if (input.includes('/applications/pat/')) return Promise.resolve(json(200, mockOk({}))); if (input.includes('/api/projects/proj/applications')) { if (listStatus !== 200) return Promise.resolve(json(listStatus, { success: false, error: { code: 'forbidden', message: 'no' } })); - return Promise.resolve(json(200, { success: true, data: [ITEM], metadata: { page: 1, perPage: 20, totalItems: 1, totalPages: 1, counts: { open: 1, accepted: 0, closed: 0 } } })); + return Promise.resolve(json(200, { success: true, data: [item], metadata: { page: 1, perPage: 20, totalItems: 1, totalPages: 1, counts: { open: 1, accepted: 0, closed: 0 } } })); } if (input.startsWith('/api/projects/proj')) return Promise.resolve(json(200, mockOk({ slug: 'proj', title: 'Proj' }))); void init; @@ -101,4 +101,20 @@ describe('ProjectApplications', () => { render(); expect(await screen.findByText(/only this project's admins and site staff/i)).toBeInTheDocument(); }); + + it('an agent-recorded decision says "via the ops bot", naming the admin who decided', async () => { + mockApi(200, { + ...ITEM, + state: 'member', + application: { + ...ITEM.application, + status: 'accepted', + decidedBy: { slug: 'ada', fullName: 'Ada Admin', avatarUrl: null }, + decidedAt: '2026-11-21T00:00:00Z', + decidedVia: 'agent', + }, + }); + render(); + expect(await screen.findByText(/Accepted by Ada Admin, .* via the ops bot/)).toBeInTheDocument(); + }); }); From b7368893a75c56ac5873ff27837673748c6e3831 Mon Sep 17 00:00:00 2001 From: GrittyBot <30755786+codeforphilly-bot@users.noreply.github.com> Date: Sun, 29 Nov 2026 23:04:27 +0000 Subject: [PATCH 16/26] chore(plans): mark agent-decide-on-behalf done (PR #TBD) Co-Authored-By: Claude Opus 5.5 --- plans/agent-decide-on-behalf.md | 61 +++++++++++++++++++++++++++++---- 1 file changed, 54 insertions(+), 7 deletions(-) diff --git a/plans/agent-decide-on-behalf.md b/plans/agent-decide-on-behalf.md index 16e4d2f..5ff5ccf 100644 --- a/plans/agent-decide-on-behalf.md +++ b/plans/agent-decide-on-behalf.md @@ -1,5 +1,5 @@ --- -status: in-progress +status: done depends: [agent-application-feed, needs-on-applications] specs: - specs/api/agent-applications.md @@ -46,13 +46,13 @@ override disabled. ## Validation -- [ ] Tests: a linked active admin's accept and close succeed; commit author is the agent with `Actor-Kind: agent`, `Grant-Id` and `On-Behalf-Of: `; the record has `decidedById` = admin, `decidedVia = agent`, `agentGrantId` -- [ ] Tests: unlinked Slack user, linked non-admin, linked staff who is not a project admin, and a deactivated admin all get `403 not_project_admin` -- [ ] Tests: the grant cannot add, remove, promote or touch needs through any route -- [ ] Tests: the named admin gets one confirmation email per decision; the 31st decision in 24 hours → `429` -- [ ] `git log --grep='^On-Behalf-Of: '` on the test repo lists exactly the agent's decisions +- [x] Tests: a linked active admin's accept and close succeed; commit author is the agent with `Actor-Kind: agent`, `Grant-Id` and `On-Behalf-Of: `; the record has `decidedById` = admin, `decidedVia = agent`, `agentGrantId` +- [x] Tests: unlinked Slack user, linked non-admin, linked staff who is not a project admin, and a deactivated admin all get `403 not_project_admin` +- [x] Tests: the grant cannot add, remove, promote or touch needs through any route +- [x] Tests: the named admin gets one confirmation email per decision; the 31st decision in 24 hours → `429` +- [x] `git log --grep='^On-Behalf-Of: '` on the test repo lists exactly the agent's decisions - [ ] End to end: an admin answers in a Slack DM and the application moves on the site (awaits the bot PR) -- [ ] `npm run type-check && npm run lint && npm test` clean +- [x] `npm run type-check && npm run lint && npm test` clean ## Risks / unknowns @@ -60,4 +60,51 @@ override disabled. ## Notes +- **End-to-end criterion open; its `awaits:` entry stays** until the bot's + DM reply handling lands. +- **Fail-closed order.** The route checks the scope and both companions + before the body (401; a hand-written grant record without them is refused + too), refuses unknown body fields with 422 rather than letting the schema + strip them (so `isAdmin` can never ride along), checks the cap, and + resolves the admin; under the write lock it checks the cap again and + re-resolves the admin, who must be the same person the commit names. +- **Who counts as the admin.** The Slack user must be in `SLACK_TEAM_ID` + (unset → everyone is refused), resolve through `bySlackUserId` to a person + who exists, is not deactivated, is not an agent account, and passes the + site's `project-admin` marker evaluated as a plain `user`: staff and + administrator levels add nothing, while a staff member who is a project + admin counts (tested). Refusals tested: unlinked id, link in another + workspace, an admin's id named under another workspace, linked non-admin, + linked staff not an admin here, deactivated admin, admin of another + project, admin demoted since, admin who disconnected, no workspace + configured, missing scope, decide without either companion, revoked grant. + Each writes no commit and sends no email. +- **Replay** of a decided application, a held one, or an unknown person is + `404` with no commit. +- **The cap** counts the agent's decisions in 24 hours across all its + grants, from records (`decidedVia = agent`, `agentGrantId` of any of its + grants) plus an in-process log, so removing a member it accepted does not + free a slot (tested). The log resets on restart; records still count. +- **Service reuse.** `accept`/`close` take an optional `{ agentGrantId }`; + the session passed is the admin's (for `decidedById` and the marker + check), the commit session is the agent's. Applicant email is as for a + site decision; the admin's confirmation is a new template. +- "via the ops bot" on the Applications screen already existed on this + branch; a web test now covers it. +- Smoke on a local app with made-up fixtures: linked a test admin through + the code flow, then the test grant accepted one application and closed + another (with a note) for her. Commits were authored by the agent with + `Actor-Kind: agent`, `On-Behalf-Of: ada` (and `Closed-By: admin`); the + note appeared nowhere in the data repo; an unlinked Slack id got `403 + not_project_admin`; the Applications screen showed "Accepted by … via the + ops bot" and "Closed by … via the ops bot". Email went to the logging + notifier (no Postmark locally). +- Gate at this commit's tree: check-contracts, type-check, lint, tests + (API 70 files / 835, web 36 / 218, shared 5 / 120) and `npm run build` + clean. `check:sheet-configs` not run (needs the data repo; known v3/v2 + drift until codeforphilly-data adopts). + ## Follow-ups + +- Send one agent-decision confirmation email on sandbox before release, with + the other new templates, to confirm Postmark's sender and stream. From d38155c7ddb4e5bb07f9ba44eebf3e4a192c437e Mon Sep 17 00:00:00 2001 From: GrittyBot <30755786+codeforphilly-bot@users.noreply.github.com> Date: Sun, 29 Nov 2026 23:05:48 +0000 Subject: [PATCH 17/26] chore(plans): record PR #270 on the Slack-chain plans The three closeout commits were made before the pull request existed. Co-Authored-By: Claude Fable 5.2 --- plans/agent-application-feed.md | 1 + plans/agent-decide-on-behalf.md | 1 + plans/slack-account-link.md | 1 + 3 files changed, 3 insertions(+) diff --git a/plans/agent-application-feed.md b/plans/agent-application-feed.md index 03dea72..102daa5 100644 --- a/plans/agent-application-feed.md +++ b/plans/agent-application-feed.md @@ -7,6 +7,7 @@ specs: awaits: - "CodeForPhilly/grittybot — heartbeat stream that reads GET /api/agent/events and DMs admins, marked as AI (bot repo, by PR)" - "GrittyBot Slack app gains mpim:write (group DMs), merged in the bot repo and installed by a workspace admin" +pr: 270 --- # Plan: Application event feed for agents diff --git a/plans/agent-decide-on-behalf.md b/plans/agent-decide-on-behalf.md index 5ff5ccf..c4f3edf 100644 --- a/plans/agent-decide-on-behalf.md +++ b/plans/agent-decide-on-behalf.md @@ -9,6 +9,7 @@ specs: - specs/screens/project-applications.md awaits: - "CodeForPhilly/grittybot — DM reply/button handling that records an admin's accept or close via the decision endpoint (bot repo, by PR)" +pr: 270 --- # Plan: Agent records an admin's decision from Slack diff --git a/plans/slack-account-link.md b/plans/slack-account-link.md index c4a645a..095b116 100644 --- a/plans/slack-account-link.md +++ b/plans/slack-account-link.md @@ -10,6 +10,7 @@ specs: - specs/screens/account.md awaits: - "CodeForPhilly/grittybot — DM handler that takes a linking code and calls POST /api/agent/slack-links (bot repo, by PR)" +pr: 270 --- # Plan: Link a site account to a Slack user From 72dcd22c0208a4dfcb806463cdaf10b10a37b8f2 Mon Sep 17 00:00:00 2001 From: GrittyBot <30755786+codeforphilly-bot@users.noreply.github.com> Date: Sun, 29 Nov 2026 23:57:24 +0000 Subject: [PATCH 18/26] chore(plans): reopen slack-account-link for automatic linking Operator-approved on PR #270: the site links an account to a Slack user by itself when the user found by its email has the handle the site asserted at sign-in. Scope, approach and validation amended; the earlier closeout's ticks stand. Co-Authored-By: Claude Opus 5.5 --- plans/slack-account-link.md | 29 +++++++++++++++++++++++++++-- 1 file changed, 27 insertions(+), 2 deletions(-) diff --git a/plans/slack-account-link.md b/plans/slack-account-link.md index 095b116..aa87ea3 100644 --- a/plans/slack-account-link.md +++ b/plans/slack-account-link.md @@ -1,8 +1,11 @@ --- -status: done +status: in-progress depends: [] specs: - specs/api/slack-link.md + - specs/api/saml.md + - specs/api/auth.md + - specs/architecture.md - specs/api/agents.md - specs/data-model.md - specs/behaviors/private-storage.md @@ -28,7 +31,20 @@ use, rate limited); `DELETE /api/account/slack-link`; `POST read and decide endpoints themselves land in later plans); `me.slack`; the Account screen's Slack row; purge removes the link. -**Out:** the bot's side (awaited); anything that uses the link. +**Reopened (operator-approved, PR #270): automatic linking.** Every Slack +account in the workspace is created through the site's SAML sign-in, and +for most members Slack's handle equals the `slackSamlNameId` the site +asserted. The site gets its own read-only Slack token and links an account +by itself when two independent facts agree: the Slack user that +`users.lookupByEmail` finds for the account's private-profile email has a +handle exactly equal to `slackSamlNameId`, and is a full, active, human +member of the configured workspace. Links record how they were made +(`via: auto | code`) and when last verified; automatic links are +re-verified with age and before an on-behalf decision; a member who +disconnects is not silently re-linked. The code stays as the fallback. + +**Out:** the bot's side (awaited); anything that uses the link; +punctuation-normalised handle matching. ## Implements @@ -49,6 +65,12 @@ Account screen's Slack row; purge removes the link. 4. `AGENT_SCOPES` gains the three scopes; mint enforces the companion rules; `agent-grants/v2` contract adopted and mirrored. 5. Web: Slack row with code display and polling of `/api/auth/me`. +6. (Reopened) A `SlackDirectory` interface with a fetch client for + `users.lookupByEmail` and a fake for tests; an auto-link service with a + site-wide call budget, Retry-After backoff, per-person result cache and + in-flight dedupe; triggers at Slack SAML sign-in (delayed), on `/me`, and + when the feed needs an admin's id; re-verification of automatic links + before use and before decisions; the opt-out on disconnect. ## Validation @@ -60,6 +82,9 @@ Account screen's Slack row; purge removes the link. - [ ] `agent-grants/v2` adopted and mirrored; CI passes - [x] Browser: Account → Connect Slack shows a code; redeeming it with a test grant via the API turns the row to "Connected" - [ ] End to end with the ops bot in the real workspace (awaits the bot PR) +- [ ] Tests (automatic): both matches link (`via: auto`); an email match with a different handle, a handle match with a different email, a guest, a bot, a deleted user and another workspace do not; no token → no attempt +- [ ] Tests (automatic): a Slack error or rate limit fails closed without failing the request that triggered it; a member who disconnected is not re-linked automatically and can reconnect by code +- [ ] Tests (automatic): a re-check that no longer matches removes the link and the on-behalf decision is refused `not_project_admin`; the email never appears in logs or responses - [x] `npm run type-check && npm run lint && npm test` clean ## Risks / unknowns From 5e0981d79d697252bf9fe59a50f3d2dd40ba19bb Mon Sep 17 00:00:00 2001 From: GrittyBot <30755786+codeforphilly-bot@users.noreply.github.com> Date: Sun, 29 Nov 2026 23:58:13 +0000 Subject: [PATCH 19/26] docs(specs): link Slack accounts automatically when email and handle agree Operator-approved design on PR #270. With its own read-only token (SLACK_BOT_TOKEN: users:read, users:read.email) the site links an account when users.lookupByEmail for the private-profile email returns a full, active, human member of SLACK_TEAM_ID whose handle exactly equals slackSamlNameId. It runs one person at a time: about a minute after Slack SAML sign-in, on /me (waiting at most 1.5 s), and for up to 5 admins per feed request; at most 20 Slack calls a minute, honouring Retry-After; no-match cached 24 h, errors 15 min. Automatic links are re-verified when used past 24 h, always before an on-behalf decision (a mismatch removes the link; either failure refuses not_project_admin); the feed stops carrying an id unverified for 7 days. Links record via (auto | code) and verifiedAt; disconnecting records an opt-out the automatic path honours and a code link clears. The code stays as the fallback. Co-Authored-By: Claude Opus 5.5 --- specs/api/agent-applications.md | 13 +++- specs/api/auth.md | 4 +- specs/api/saml.md | 2 +- specs/api/slack-link.md | 119 +++++++++++++++++++++++++---- specs/architecture.md | 1 + specs/behaviors/private-storage.md | 5 +- specs/data-model.md | 3 +- specs/screens/account.md | 3 +- 8 files changed, 125 insertions(+), 25 deletions(-) diff --git a/specs/api/agent-applications.md b/specs/api/agent-applications.md index 8e89328..1ab9507 100644 --- a/specs/api/agent-applications.md +++ b/specs/api/agent-applications.md @@ -58,7 +58,11 @@ not a stored log): - `application` also carries `decidedBy` (`{ slug, fullName }`, or `null`), `decidedVia` and `closedBy`, as they stand now. - `admins` lists the project's active admins; `slackUserId` is set only for an - admin with a verified [Slack link](slack-link.md). No email address, ever. + admin with a verified [Slack link](slack-link.md) (an automatic link + unverified for more than 7 days does not count). Building the feed may + link or re-verify a few admins automatically + ([slack-link.md → When it runs](slack-link.md#when-it-runs)). No email + address, ever. - Applications from deactivated applicants produce no events, and their earlier events drop out of the feed. - Ordered by `at`, then record id. The cursor is stable across restarts @@ -87,7 +91,7 @@ Records an accept or a close that a project admin made in Slack. | Field | Required | Notes | | ----- | -------- | ----- | | decision | yes | `accept` \| `close` | -| onBehalfOf | yes | The Slack user who decided; `slackTeamId` must be the workspace the site serves. Must resolve through a verified link to a person who is, now, an active project admin of `:projectSlug` ([authorization.md → On behalf of a project admin](../behaviors/authorization.md#on-behalf-of-a-project-admin)). | +| onBehalfOf | yes | The Slack user who decided; `slackTeamId` must be the workspace the site serves. An automatic link more than 24 hours past its `verifiedAt` is re-verified first ([slack-link.md → Re-verification](slack-link.md#re-verification)). Must resolve through a verified link to a person who is, now, an active project admin of `:projectSlug` ([authorization.md → On behalf of a project admin](../behaviors/authorization.md#on-behalf-of-a-project-admin)). | | role, fillRoleIds | no | As for the site's accept ([projects-applications.md](projects-applications.md)). | | note | no | For `close`: emailed to the applicant, never stored. | @@ -110,8 +114,9 @@ screen. grant that holds it without `projects:applications:read` and `slack:link` (refused at use as well as at mint) - `403 forbidden` (`error.code = "not_project_admin"`) — the Slack user is not - linked (or names another workspace), or the linked person is not an active - admin of this project + linked (or names another workspace), the linked person is not an active + admin of this project, or an automatic link failed or could not get its + re-verification - `404 not_found` — no open, visible application from that person - `429 rate_limited` — more than 30 decisions per agent in 24 hours diff --git a/specs/api/auth.md b/specs/api/auth.md index b887bb4..b654c4f 100644 --- a/specs/api/auth.md +++ b/specs/api/auth.md @@ -235,14 +235,14 @@ Returns the current Person (full PersonResponse shape — see [api/people.md](pe "accountLevel": "staff", "hasGitHubLink": true, "lastLoginMethod": "github", - "slack": { "linked": true, "linkedAt": "2026-11-20T…" } + "slack": { "linked": true, "linkedAt": "2026-11-20T…", "via": "auto" } } } ``` `hasGitHubLink` is `Person.githubUserId !== null`. `lastLoginMethod` is one of `"github" | "legacy_password" | "password_reset"`; the SPA can use it to render UI hints (e.g., "Signed in via password — connect GitHub for faster sign-in next time" inline on `/account`). -`slack` is whether the person has a verified [Slack link](slack-link.md) and since when (`{ linked: false, linkedAt: null }` when not); it never carries the Slack user id. +`slack` is whether the person has a verified [Slack link](slack-link.md), since when, and how it was made (`via`: `auto` or `code`; `{ linked: false, linkedAt: null, via: null }` when not); it never carries the Slack user id. For a signed-in person with no link, `/me` may first try the [automatic link](slack-link.md#when-it-runs), waiting at most 1.5 seconds. If no session, returns 200 with `data.person = null`, `data.accountLevel = "anonymous"`, `hasGitHubLink = false`, `lastLoginMethod = null`, `slack = null`. (We deliberately do not 401 here — the frontend calls this on every page load including public pages.) diff --git a/specs/api/saml.md b/specs/api/saml.md index 24dc394..f22366a 100644 --- a/specs/api/saml.md +++ b/specs/api/saml.md @@ -122,7 +122,7 @@ Rules: - `SAMLResponse` (base64-encoded signed XML) - `RelayState` — the channel/redir path so Slack lands the user in the right place -6. **Slack SSO stamp.** Set `PrivateProfile.lastSlackSsoAt = now` for the person (best-effort; a private-store failure never fails the assertion). Surfaced on the staff roster ([api/moderation.md](moderation.md)). +6. **Slack SSO stamp.** Set `PrivateProfile.lastSlackSsoAt = now` for the person (best-effort; a private-store failure never fails the assertion). Surfaced on the staff roster ([api/moderation.md](moderation.md)). The same moment schedules the person's [automatic Slack link](slack-link.md#when-it-runs) check, about a minute later and never in the assertion's path. The destination URL inside the Response includes the `redir` so Slack's POST endpoint sees it. diff --git a/specs/api/slack-link.md b/specs/api/slack-link.md index d3ffb77..18179b0 100644 --- a/specs/api/slack-link.md +++ b/specs/api/slack-link.md @@ -2,14 +2,98 @@ A verified link between a site account and a Slack user, so the ops bot can reach project admins in Slack and, when allowed, act on what they say there -([agent-applications.md](agent-applications.md)). Both sides are proven: the -site knows who is signed in when it issues a code, and Slack knows who sent -the code to the bot. - -The site is already the SAML sign-in for the Slack workspace -([saml.md](saml.md)), but it does not learn the Slack user id from that, and -the self-typed `Person.slackHandle` proves nothing. This link is the only -mapping anything routes on. +([agent-applications.md](agent-applications.md)). A link is made one of two +ways, and the link records which (`via`): + +- **Automatically** (`via = auto`), by the site alone, when two independent + facts agree: the Slack user Slack finds for the account's email has the + handle the site asserted for this person at Slack sign-in. See + [Automatic link](#automatic-link). +- **By code** (`via = code`), the fallback for anyone the automatic path + cannot link: the site knows who is signed in when it issues a code, and + Slack knows who sent the code to the bot. + +The site is the SAML sign-in for the Slack workspace ([saml.md](saml.md)), +but the assertion does not tell it the Slack user id, and the self-typed +`Person.slackHandle` proves nothing. This link is the only mapping anything +routes on; an agent never asserts one. + +## Automatic link + +Every Slack account in the workspace is created through the site's SAML +sign-in, and Slack keeps the NameID the site asserted (`slackSamlNameId`) as +the account's handle (`user.name`). Neither the handle nor the email alone is +trusted (a member may be able to change either in Slack); both must agree. + +The site links a person to a Slack user when **all** hold: + +1. `SLACK_BOT_TOKEN` and `SLACK_TEAM_ID` are configured. The token is the + site's own, read-only, with the scopes `users:read` and `users:read.email`. + Without both, the automatic path is off and nothing else changes. +2. `users.lookupByEmail` for the person's private-profile email returns a + user whose `name` **exactly** equals the person's `slackSamlNameId` (no + case folding, no punctuation normalising). +3. That user's `team_id` is `SLACK_TEAM_ID`, and it is not `deleted`, not a + bot (`is_bot`, or Slackbot), and not a guest (`is_restricted`, + `is_ultra_restricted`). +4. The person exists, is not deactivated, is not an agent account, has a + private profile, has no link already, and has not opted out (below). +5. No other account is linked to that Slack user. (If one is, nothing + happens; the code path's `409` still applies there.) + +The link is stored as for a code link, with `via = auto` and `verifiedAt`. +A failed match, a Slack error or a rate limit changes nothing and never fails +the request that triggered the attempt. + +### When it runs + +The site has no list of members to sweep and never fans out across all of +them; it checks one person at a time, when it has a reason to: + +- **At Slack SAML sign-in**, about a minute after the assertion is issued + (a first sign-in creates the Slack account only once Slack consumes the + assertion). This clears that person's cached "no match". +- **On `GET /api/auth/me`** for a signed-in person with no link and no + opt-out, when no result for them is cached. `/me` waits at most 1.5 + seconds for it; a slower lookup finishes in the background and shows on + the next load. +- **When the agent feed needs an admin's Slack id** and the admin has no + link (or an automatic link due for re-verification), for at most 5 admins + per feed request; the rest wait for a later request. + +Limits and caching, all in memory (a restart forgets them): + +- At most 20 Slack calls a minute across the site, below `users.lookupByEmail`'s + rate tier; a `429` from Slack stops all calls for its `Retry-After`. + Calls over budget are skipped, not queued. +- A "no match" for a person is cached for 24 hours; a Slack error for 15 + minutes. One attempt per person runs at a time. + +### Re-verification + +An automatic link is re-checked (the same lookup and the same five +conditions, for the same Slack user) when it is used and its `verifiedAt` is +more than **24 hours** old: + +- **Before an on-behalf decision** ([agent-applications.md](agent-applications.md)), + always, before the write. If it no longer matches, the link is removed and + the decision is refused `403 not_project_admin`; if Slack cannot be + asked (no token, an error, a rate limit), the decision is refused the same + way and the link is kept. +- **When the feed or `/me` uses it**, within the budget above. A re-check + that no longer matches removes the link. If a re-check cannot run, the + link is still used until it is **7 days** past `verifiedAt`; after that + the feed carries `slackUserId: null` for that admin until a re-check + succeeds. + +Code links are not re-verified: the member proved them by DM. + +### Opt-out + +Disconnecting (`DELETE /api/account/slack-link`) records +`slackAutoLinkOptOutAt` on the private profile, and the automatic path never +links that person again. Redeeming a code clears the opt-out: reconnecting is +always on purpose. ## Endpoints @@ -21,7 +105,7 @@ mapping anything routes on. ## POST /api/account/slack-link/code -No body. Returns a fresh code and invalidates any earlier unredeemed code for +The fallback for a member the automatic path cannot link. No body. Returns a fresh code and invalidates any earlier unredeemed code for the caller. ```json @@ -52,7 +136,8 @@ The bot calls this when a member DMs it a code. ``` On success, in the same request: sets `PrivateProfile.slack = { teamId, -userId, linkedAt }` for the person who issued the code and consumes the code. +userId, linkedAt, via: "code", verifiedAt }` for the person who issued the +code, clears any `slackAutoLinkOptOutAt`, and consumes the code. `slackTeamId` must be the workspace the site serves (`SLACK_TEAM_ID`; mismatch `422`). With no workspace configured every redemption is refused (`422`): the site fails closed rather than link to an unknown workspace. @@ -76,11 +161,13 @@ The bot replies to the member in the DM; the site emails nothing. ## DELETE /api/account/slack-link -Clears `PrivateProfile.slack`. `204`. No error if there was none. +Clears `PrivateProfile.slack` and records `slackAutoLinkOptOutAt`, so the +automatic path does not link the account again ([Opt-out](#opt-out)). `204`. +No error if there was no link (the opt-out is recorded either way). ## Notes -- **Private only.** The link lives on the private profile +- **Private only.** The link and the opt-out live on the private profile ([private-storage.md](../behaviors/private-storage.md)), changes no public record, and makes no public commit. The Slack user id is returned only to agents holding `projects:applications:read`, for the admins of an @@ -89,5 +176,9 @@ Clears `PrivateProfile.slack`. `204`. No error if there was none. user per account (a new link replaces the old). - **Purge** removes it with the private profile. **Deactivation** leaves it in place but the deactivated person is never resolved as an admin. -- `GET /api/auth/me` reports `slack: { linked, linkedAt }` to the person - themselves. +- `GET /api/auth/me` reports `slack: { linked, linkedAt, via }` to the + person themselves. +- **No email leaves the site toward anyone but Slack.** The automatic path + sends the person's email to Slack's API (which already holds it for that + member) and to nothing else; neither the email nor the Slack user id is + logged, and no response says whether a lookup found anyone. diff --git a/specs/architecture.md b/specs/architecture.md index b297777..92e3644 100644 --- a/specs/architecture.md +++ b/specs/architecture.md @@ -182,6 +182,7 @@ Runtime configuration (sealed-secrets in our cluster): | `SAML_ENTITY_ID` | Optional. Stable SAML IdP entity ID / assertion `Issuer` (default `https://codeforphilly.org/api/saml/slack/metadata`). Deliberately independent of `CFP_SITE_HOST` so cutover doesn't change the identifier Slack has on file — see [api/saml.md#idp-identity-and-hosts](api/saml.md#idp-identity-and-hosts). | | `SLACK_TEAM_HOST` | Slack workspace host (default `codeforphilly.slack.com`). Used by the `/chat` redirect ([api/chat](screens/chat.md)) and the SAML SP entity binding (ACS URL, NameQualifier). Never used for our own IdP entity ID or endpoint URLs. | | `SLACK_TEAM_ID` | The Slack workspace id (`T…`) the site serves. A [Slack link](api/slack-link.md) or an agent's on-behalf decision naming another workspace is refused; unset, no link can be made. | +| `SLACK_BOT_TOKEN` | Optional secret. The site's own read-only Slack token (scopes `users:read`, `users:read.email`), used only for the [automatic Slack link](api/slack-link.md#automatic-link). Unset, the automatic link is off and code links still work. | | `SLACK_OPS_BOT_DM_URL` | Optional. A link that opens a direct message with the ops bot; the Account screen's Slack row links the bot's name to it. | | `POSTMARK_SERVER_TOKEN` | Optional. When set, mutates the notifier from the no-op `LoggingNotifier` to the live `EmailNotifier` (Postmark transport). | | `POSTMARK_MESSAGE_STREAM` | Optional. Postmark message stream for outbound mail (default `outbound`). | diff --git a/specs/behaviors/private-storage.md b/specs/behaviors/private-storage.md index 8287da4..d838c41 100644 --- a/specs/behaviors/private-storage.md +++ b/specs/behaviors/private-storage.md @@ -75,7 +75,7 @@ the agent account deletes its lines with the rest of its private data. "status": "ok", "checkedAt": "2026-09-18T20:00:00Z" }, "lastSlackSsoAt": "2026-09-18T01:12:00Z", - "slack": { "teamId": "T…", "userId": "U…", "linkedAt": "2026-11-20T…" }, + "slack": { "teamId": "T…", "userId": "U…", "linkedAt": "2026-11-20T…", "via": "auto", "verifiedAt": "2026-11-20T…" }, "emailBounce": { "type": "HardBounce", "bouncedAt": "2026-09-10T...", "description": "…", "inactive": true }, "updatedAt": "2026-05-15T18:42:00Z" } @@ -83,7 +83,8 @@ the agent account deletes its lines with the rest of its private data. `slack` is optional: the verified link to a Slack user, set and cleared only by [api/slack-link.md](../api/slack-link.md); it is what an agent's Slack user id -resolves through. The other three trailing fields are optional and exist for +resolves through. `slackAutoLinkOptOutAt` (optional) records that the member +disconnected, so the automatic link leaves them alone. The other three trailing fields are optional and exist for staff moderation ([api/moderation.md](../api/moderation.md)): - `github` — what GitHub said about the linked account, captured at every GitHub diff --git a/specs/data-model.md b/specs/data-model.md index 0be806e..4d8c0c4 100644 --- a/specs/data-model.md +++ b/specs/data-model.md @@ -120,7 +120,8 @@ The sensitive complement to a Person. Stored in the **private store** (S3-compat | email | string | the user's most-recent GitHub-verified primary email. Refreshed on every OAuth login. Lowercased for canonical form. | | emailRefreshedAt | iso8601 | when `email` was last refreshed from GitHub | | newsletter | object nullable | newsletter subscription state (see below) | -| slack | object nullable | the verified link to a Slack user: `{ teamId, userId, linkedAt }`. Set and cleared only by [api/slack-link.md](api/slack-link.md). | +| slack | object nullable | the verified link to a Slack user: `{ teamId, userId, linkedAt, via, verifiedAt }`, `via` = `auto` \| `code` (absent means `code`), `verifiedAt` when an automatic link last re-checked. Set and cleared only by [api/slack-link.md](api/slack-link.md). | +| slackAutoLinkOptOutAt | iso8601 nullable | the member disconnected Slack; the automatic link never re-links them. Cleared by a code link. | | updatedAt | iso8601 | | The `newsletter` sub-object: diff --git a/specs/screens/account.md b/specs/screens/account.md index eb844e6..f43d8ec 100644 --- a/specs/screens/account.md +++ b/specs/screens/account.md @@ -31,7 +31,8 @@ The card's contents depend on `me.hasGitHubLink`: - Refresh timestamp ("Last updated when you signed in on {date}") - **Slack** — the verified link to a Slack user ([api/slack-link.md](../api/slack-link.md)), from `me.slack`: - Not linked: "Connect Slack" button. It shows a one-time code and the instruction "Send this code in a direct message to the ops bot in the Code for Philly Slack within 10 minutes," with the bot's name linked to a DM with it. The row polls `GET /api/auth/me` while the code is live and turns linked when the bot confirms it. - - Linked: "Connected to Slack ✓ since {linkedAt}" with "Disconnect". Under it: "Lets the ops bot send you project notices in Slack and act on your replies, such as accepting an application you answer there." + - Linked: "Connected to Slack ✓ since {linkedAt}", followed by "(matched automatically)" when `via = auto` or "(by code)" when `via = code`, with "Disconnect". Under it: "Lets the ops bot send you project notices in Slack and act on your replies, such as accepting an application you answer there." + - Disconnect's confirm says the site will not reconnect the account by itself; "Connect Slack" (the code) reconnects it. - The row never shows the Slack user id. **State B — GitHub not yet linked** (`me.hasGitHubLink === false`) From 28a2b5b2ff18fc64c2640241212bb953cc841777 Mon Sep 17 00:00:00 2001 From: GrittyBot <30755786+codeforphilly-bot@users.noreply.github.com> Date: Mon, 30 Nov 2026 00:04:56 +0000 Subject: [PATCH 20/26] feat(shared): how a Slack link was made, when it was verified, and the opt-out PrivateProfile.slack gains via (auto | code; absent means code) and verifiedAt; the profile gains slackAutoLinkOptOutAt. Co-Authored-By: Claude Opus 5.5 --- packages/shared/src/schemas/private-profile.ts | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/packages/shared/src/schemas/private-profile.ts b/packages/shared/src/schemas/private-profile.ts index fbf092e..43102bc 100644 --- a/packages/shared/src/schemas/private-profile.ts +++ b/packages/shared/src/schemas/private-profile.ts @@ -43,6 +43,10 @@ const SlackLinkSchema = z.object({ teamId: z.string().regex(/^[A-Z0-9]{2,32}$/), userId: z.string().regex(/^[A-Z0-9]{2,32}$/), linkedAt: z.string().datetime({ offset: true }), + /** How it was made: the site matched email and handle, or the member sent a code. Absent → `code`. */ + via: z.enum(['auto', 'code']).optional(), + /** When an automatic link was last re-checked against Slack (and when a code link was made). */ + verifiedAt: z.string().datetime({ offset: true }).optional(), }); export const PrivateProfileSchema = z.object({ @@ -55,6 +59,8 @@ export const PrivateProfileSchema = z.object({ lastSlackSsoAt: z.string().datetime({ offset: true }).nullable().optional(), emailBounce: EmailBounceSchema.nullable().optional(), slack: SlackLinkSchema.nullable().optional(), + /** The member disconnected Slack: the automatic link never re-links them. Cleared by a code link. */ + slackAutoLinkOptOutAt: z.string().datetime({ offset: true }).nullable().optional(), updatedAt: z.string().datetime({ offset: true }), }); From a680ff49276052b036a3b508abb96941ebccbe65 Mon Sep 17 00:00:00 2001 From: GrittyBot <30755786+codeforphilly-bot@users.noreply.github.com> Date: Mon, 30 Nov 2026 00:04:56 +0000 Subject: [PATCH 21/26] feat(api): a Slack directory client for users.lookupByEmail Behind an interface so tests use a fake. 429 and ratelimited become SlackRateLimitedError with Retry-After; users_not_found is null; anything else is SlackApiError carrying Slack's error string, never the email. Co-Authored-By: Claude Opus 5.5 --- apps/api/src/slack/directory.ts | 89 +++++++++++++++++++++++++++++++++ 1 file changed, 89 insertions(+) create mode 100644 apps/api/src/slack/directory.ts diff --git a/apps/api/src/slack/directory.ts b/apps/api/src/slack/directory.ts new file mode 100644 index 0000000..8ddf472 --- /dev/null +++ b/apps/api/src/slack/directory.ts @@ -0,0 +1,89 @@ +/** + * The one Slack API call the site makes: `users.lookupByEmail`, with the + * site's own read-only token (scopes `users:read`, `users:read.email`) — + * specs/api/slack-link.md → Automatic link. + * + * Behind an interface so tests use a fake and never touch the network. + * The email is sent to Slack only; it is never logged here or by callers. + */ + +/** The fields of a Slack user the automatic link looks at. */ +export interface SlackDirectoryUser { + readonly id: string; + /** The handle; Slack keeps the SAML NameID the site asserted at first sign-in. */ + readonly name: string; + readonly team_id?: string; + readonly deleted?: boolean; + readonly is_bot?: boolean; + readonly is_restricted?: boolean; + readonly is_ultra_restricted?: boolean; +} + +/** Slack said 429: stop calling for `retryAfterSeconds`. */ +export class SlackRateLimitedError extends Error { + readonly retryAfterSeconds: number; + constructor(retryAfterSeconds: number) { + super('Slack rate limited'); + this.name = 'SlackRateLimitedError'; + this.retryAfterSeconds = retryAfterSeconds; + } +} + +/** Any other failure: a network error, a non-OK status, or `ok: false` with an error other than not-found. */ +export class SlackApiError extends Error { + /** Slack's `error` string or the HTTP status; never the request's arguments. */ + readonly slackError: string; + constructor(slackError: string) { + super(`Slack API error: ${slackError}`); + this.name = 'SlackApiError'; + this.slackError = slackError; + } +} + +export interface SlackDirectory { + /** The user with this email, or null when Slack has none. Throws the errors above. */ + lookupUserByEmail(email: string): Promise; +} + +/** The real client, over `fetch`. */ +export class FetchSlackDirectory implements SlackDirectory { + readonly #token: string; + readonly #fetch: typeof fetch; + + constructor(token: string, fetchImpl: typeof fetch = fetch) { + this.#token = token; + this.#fetch = fetchImpl; + } + + async lookupUserByEmail(email: string): Promise { + let res: Response; + try { + res = await this.#fetch('https://slack.com/api/users.lookupByEmail', { + method: 'POST', + headers: { + authorization: `Bearer ${this.#token}`, + 'content-type': 'application/x-www-form-urlencoded', + }, + body: new URLSearchParams({ email }).toString(), + signal: AbortSignal.timeout(5000), + }); + } catch (err) { + throw new SlackApiError(err instanceof Error && err.name === 'TimeoutError' ? 'timeout' : 'network'); + } + if (res.status === 429) { + const retry = Number(res.headers.get('retry-after')); + throw new SlackRateLimitedError(Number.isFinite(retry) && retry > 0 ? retry : 60); + } + if (!res.ok) throw new SlackApiError(`http_${res.status}`); + let body: { ok?: boolean; error?: string; user?: SlackDirectoryUser }; + try { + body = (await res.json()) as typeof body; + } catch { + throw new SlackApiError('invalid_json'); + } + if (body.ok && body.user) return body.user; + if (body.error === 'users_not_found') return null; + if (body.error === 'ratelimited') throw new SlackRateLimitedError(60); + throw new SlackApiError(typeof body.error === 'string' ? body.error : 'unknown'); + } +} From c4b9da367e0803b0e418c4a801245cff9115b9e1 Mon Sep 17 00:00:00 2001 From: GrittyBot <30755786+codeforphilly-bot@users.noreply.github.com> Date: Mon, 30 Nov 2026 00:04:56 +0000 Subject: [PATCH 22/26] feat(api): link Slack accounts automatically when email and handle agree With SLACK_BOT_TOKEN and SLACK_TEAM_ID, the site links a person when the Slack user found for their private-profile email has a handle exactly equal to slackSamlNameId and is a full, active, human member of the workspace. Runs about a minute after Slack SAML sign-in, on /me (waiting at most 1.5 s), and for up to 5 admins per feed request; 20 Slack calls a minute site-wide, Retry-After honoured, no-match cached 24 h and errors 15 min, one attempt per person at a time; never throws to its caller. Automatic links past 24 h are re-checked when used and always before an on-behalf decision: a mismatch removes the link, and the decision is refused not_project_admin if the link is removed or could not be re-checked (resolved again under the write lock). The feed drops an automatic link unverified for 7 days. Code links record via=code and clear the opt-out; disconnecting records it. Profile rewrites carry the opt-out. me.slack reports via. The email is never logged. Co-Authored-By: Claude Opus 5.5 --- apps/api/src/env.ts | 7 + apps/api/src/plugins/services.ts | 14 +- apps/api/src/routes/agent-applications.ts | 5 +- apps/api/src/routes/auth.ts | 17 +- apps/api/src/routes/saml.ts | 2 + apps/api/src/services/account-claim.ts | 2 + apps/api/src/services/agent-decision.ts | 28 +- apps/api/src/services/agent-feed.ts | 31 ++- apps/api/src/services/github-account.ts | 1 + apps/api/src/services/person.write.ts | 1 + apps/api/src/services/slack-auto-link.ts | 321 +++++++++++++++++++++ apps/api/src/services/slack-link.ts | 27 +- apps/api/src/store/private/base.ts | 4 + apps/api/src/store/private/interface.ts | 2 + apps/api/tests/slack-auto-link.test.ts | 325 ++++++++++++++++++++++ apps/api/tests/slack-link.test.ts | 4 +- 16 files changed, 771 insertions(+), 20 deletions(-) create mode 100644 apps/api/src/services/slack-auto-link.ts create mode 100644 apps/api/tests/slack-auto-link.test.ts diff --git a/apps/api/src/env.ts b/apps/api/src/env.ts index 79d0cdf..f05b09a 100644 --- a/apps/api/src/env.ts +++ b/apps/api/src/env.ts @@ -123,6 +123,12 @@ export const EnvSchema = z.object({ * no link can be made (specs/api/slack-link.md). */ SLACK_TEAM_ID: z.string().regex(/^T[A-Z0-9]+$/).optional(), + /** + * The site's own read-only Slack token (scopes users:read, + * users:read.email), used only for the automatic Slack link + * (specs/api/slack-link.md → Automatic link). Unset → automatic linking is off. + */ + SLACK_BOT_TOKEN: z.string().startsWith('xoxb-').optional(), /** Optional link that opens a DM with the ops bot, for the Account screen. */ SLACK_OPS_BOT_DM_URL: z.url().optional(), }); @@ -168,6 +174,7 @@ export const envJsonSchema = { POSTMARK_MESSAGE_STREAM: { type: 'string', default: 'outbound' }, POSTMARK_WEBHOOK_SECRET: { type: 'string', minLength: 16 }, SLACK_TEAM_ID: { type: 'string', pattern: '^T[A-Z0-9]+$' }, + SLACK_BOT_TOKEN: { type: 'string', pattern: '^xoxb-' }, SLACK_OPS_BOT_DM_URL: { type: 'string', pattern: '^https://' }, CFP_NOTIFICATION_FROM: { type: 'string', diff --git a/apps/api/src/plugins/services.ts b/apps/api/src/plugins/services.ts index abce77f..80e1324 100644 --- a/apps/api/src/plugins/services.ts +++ b/apps/api/src/plugins/services.ts @@ -46,6 +46,8 @@ import { ApplicationNotices } from '../services/application-notices.js'; import { SlackLinkService } from '../services/slack-link.js'; import { AgentFeedService } from '../services/agent-feed.js'; import { AgentDecisionService } from '../services/agent-decision.js'; +import { SlackAutoLinkService } from '../services/slack-auto-link.js'; +import { FetchSlackDirectory } from '../slack/directory.js'; declare module 'fastify' { interface FastifyInstance { @@ -80,6 +82,7 @@ declare module 'fastify' { slackLinks: SlackLinkService; agentFeed: AgentFeedService; agentDecisions: AgentDecisionService; + slackAutoLink: SlackAutoLinkService; }; /** Shared in-memory state — write routes call StateApply.apply against this. */ inMemoryState: InMemoryState; @@ -146,6 +149,13 @@ async function servicesPlugin(fastify: FastifyInstance): Promise { const githubAccount = new GitHubAccountService(state); const applications = new ProjectApplicationService(state, fastify.store.private); + // The automatic Slack link (slack-link.md → Automatic link): off without the site's own token. + const slackAutoLink = new SlackAutoLinkService(state, fastify.store.private, { + teamId: fastify.config.SLACK_TEAM_ID, + directory: fastify.config.SLACK_BOT_TOKEN ? new FetchSlackDirectory(fastify.config.SLACK_BOT_TOKEN) : null, + log: fastify.log, + }); + fastify.addHook('onClose', async () => slackAutoLink.close()); fastify.decorate('services', { projects: new ProjectService(state, fts, fastify.store.private), people: new PersonService(state, fts, fastify.store.private), @@ -209,10 +219,12 @@ async function servicesPlugin(fastify: FastifyInstance): Promise { teamId: fastify.config.SLACK_TEAM_ID, botDmUrl: fastify.config.SLACK_OPS_BOT_DM_URL, }), - agentFeed: new AgentFeedService(state, fastify.store.private, { teamId: fastify.config.SLACK_TEAM_ID }), + agentFeed: new AgentFeedService(state, fastify.store.private, { teamId: fastify.config.SLACK_TEAM_ID, autoLink: slackAutoLink }), agentDecisions: new AgentDecisionService(state, fastify.store.private, applications, { teamId: fastify.config.SLACK_TEAM_ID, + autoLink: slackAutoLink, }), + slackAutoLink, }); } diff --git a/apps/api/src/routes/agent-applications.ts b/apps/api/src/routes/agent-applications.ts index 1f06427..9764478 100644 --- a/apps/api/src/routes/agent-applications.ts +++ b/apps/api/src/routes/agent-applications.ts @@ -101,7 +101,10 @@ export async function agentApplicationRoutes(fastify: FastifyInstance): Promise< // Refuse early (before taking the lock), and name the admin for the commit; // decide() checks both again under the lock. svc.checkCap(caller.agent.person.slug, new Date()); - const { admin } = svc.resolveAdmin(projectSlug, input.onBehalfOf); + const { admin } = svc.resolveAdmin(projectSlug, input.onBehalfOf, { requireFresh: false }); + // An automatic link past its age is re-checked against Slack before the write + // (slack-link.md → Re-verification); decide() refuses one that is still stale. + await svc.refreshLink(admin); const accept = input.decision === 'accept'; const result = await fastify.store.transact( diff --git a/apps/api/src/routes/auth.ts b/apps/api/src/routes/auth.ts index 6c95e10..4956d8a 100644 --- a/apps/api/src/routes/auth.ts +++ b/apps/api/src/routes/auth.ts @@ -32,7 +32,7 @@ import { verifyLegacyPassword, } from '../auth/legacy-password.js'; import type { SessionMeta } from '../auth/session-metadata.js'; -import type { LegacyPasswordCredential, PasswordToken } from '@cfp/shared/schemas'; +import type { LegacyPasswordCredential, PasswordToken, Person } from '@cfp/shared/schemas'; import { generateCsrfState, generatePkceVerifier, @@ -101,6 +101,19 @@ async function persistSessionMetadata( await fastify.sessionMetadata.add(meta, fastify.store.private); } +/** + * `me.slack`: may first try the automatic Slack link, waiting at most + * ME_WAIT_MS; a Slack failure never fails `/me` (slack-link.md → When it runs). + */ +async function selfSlackStatus(fastify: FastifyInstance, person: Person) { + try { + await fastify.services.slackAutoLink.refreshForSelf(person); + } catch { + // never fails /me + } + return slackStatus(await fastify.store.private.getProfile(person.id)); +} + export async function authRoutes(fastify: FastifyInstance): Promise { // --------------------------------------------------------------------------- @@ -303,7 +316,7 @@ export async function authRoutes(fastify: FastifyInstance): Promise { lastLoginMethod: session.loginMethod ?? null, // Whether the person has a verified Slack link, never its user id // (specs/api/slack-link.md). - slack: person ? slackStatus(await fastify.store.private.getProfile(person.id)) : null, + slack: person ? await selfSlackStatus(fastify, person) : null, }); }, ); diff --git a/apps/api/src/routes/saml.ts b/apps/api/src/routes/saml.ts index 801b1cb..46060bc 100644 --- a/apps/api/src/routes/saml.ts +++ b/apps/api/src/routes/saml.ts @@ -401,6 +401,8 @@ async function stampSlackSso(fastify: FastifyInstance, personId: string): Promis if (!profile) return; const now = new Date().toISOString(); await fastify.store.private.putProfile({ ...profile, lastSlackSsoAt: now, updatedAt: now }); + // The person is entering Slack: check the automatic link about a minute from now. + fastify.services.slackAutoLink.scheduleAfterSignIn(personId); } catch (err) { fastify.log.warn({ err, personId }, 'could not stamp lastSlackSsoAt'); } diff --git a/apps/api/src/services/account-claim.ts b/apps/api/src/services/account-claim.ts index d3c501c..bfa7ee3 100644 --- a/apps/api/src/services/account-claim.ts +++ b/apps/api/src/services/account-claim.ts @@ -561,6 +561,7 @@ export class AccountClaimService { emailRefreshedAt: now, newsletter: currentProfile?.newsletter ?? null, slack: currentProfile?.slack ?? null, + slackAutoLinkOptOutAt: currentProfile?.slackAutoLinkOptOutAt ?? null, updatedAt: now, }); tx.private.putProfile(profile); @@ -707,6 +708,7 @@ export class AccountClaimService { newsletter: claimedProfile?.newsletter ?? requesterProfile.newsletter ?? null, // Same human: a Slack link made from either account survives the merge. slack: requesterProfile.slack ?? claimedProfile?.slack ?? null, + slackAutoLinkOptOutAt: requesterProfile.slackAutoLinkOptOutAt ?? claimedProfile?.slackAutoLinkOptOutAt ?? null, updatedAt: now, }); tx.private.putProfile(merged); diff --git a/apps/api/src/services/agent-decision.ts b/apps/api/src/services/agent-decision.ts index 2e32d7c..1d2e2c2 100644 --- a/apps/api/src/services/agent-decision.ts +++ b/apps/api/src/services/agent-decision.ts @@ -34,6 +34,7 @@ import type { PrivateStore } from '../store/private/interface.js'; import type { DualStoreTx } from '../store/store.js'; import { membershipsOfProject } from './memberships.js'; import { NOTE_MAX, type DecideResult, type ProjectApplicationService } from './project-application.js'; +import { linkAge, REVERIFY_AFTER_MS, type SlackAutoLinkService } from './slack-auto-link.js'; const DAY = 24 * 60 * 60 * 1000; export const AGENT_DECISIONS_PER_DAY = 30; @@ -55,6 +56,7 @@ export class AgentDecisionService { readonly #privateStore: PrivateStore; readonly #applications: ProjectApplicationService; readonly #teamId: string | undefined; + readonly #autoLink: SlackAutoLinkService | undefined; /** agent slug → decisions recorded in this process (membership id and when), for the cap. */ readonly #log = new Map>(); @@ -62,12 +64,22 @@ export class AgentDecisionService { state: InMemoryState, privateStore: PrivateStore, applications: ProjectApplicationService, - opts: { teamId?: string | undefined }, + opts: { teamId?: string | undefined; autoLink?: SlackAutoLinkService }, ) { this.#state = state; this.#privateStore = privateStore; this.#applications = applications; this.#teamId = opts.teamId; + this.#autoLink = opts.autoLink; + } + + /** + * Re-verify the admin's automatic link if it is due (slack-link.md → + * Re-verification). A mismatch removes the link; either failure leaves it + * stale, and {@link resolveAdmin} then refuses `not_project_admin`. + */ + async refreshLink(admin: Person, now: Date = new Date()): Promise { + if (this.#autoLink) await this.#autoLink.freshForDecision(admin, now); } /** Shape checks that need no state. */ @@ -92,7 +104,11 @@ export class AgentDecisionService { * once before the write (to name them in the commit) and again under the * write lock, where it must resolve to the same person. */ - resolveAdmin(projectSlug: string, onBehalfOf: AgentDecisionInput['onBehalfOf']): { admin: Person; project: Project } { + resolveAdmin( + projectSlug: string, + onBehalfOf: AgentDecisionInput['onBehalfOf'], + opts: { requireFresh: boolean; now?: Date } = { requireFresh: true }, + ): { admin: Person; project: Project } { const project = projectBySlug(this.#state, projectSlug); if (!project || project.deletedAt) throw new ApiNotFoundError(`Project '${projectSlug}' not found`); const refuse = (): never => { @@ -105,6 +121,12 @@ export class AgentDecisionService { if (!personId) return refuse(); const admin = this.#state.people.get(personId); if (!admin || admin.deletedAt || isAgentAccount(this.#state, admin.slug)) return refuse(); + if (opts.requireFresh) { + // An automatic link must have been verified within the last day (code links stand). + const link = this.#privateStore.peekProfile(admin.id)?.slack; + if (!link || link.userId !== onBehalfOf.slackUserId) return refuse(); + if (link.via === 'auto' && linkAge(link, (opts.now ?? new Date()).getTime()) > REVERIFY_AFTER_MS) return refuse(); + } // `project-admin` alone, as a plain user: staff and administrator powers do not carry over. const asAdmin: SessionContext = { person: admin, accountLevel: 'user', personId: admin.id }; @@ -162,7 +184,7 @@ export class AgentDecisionService { now: Date = new Date(), ): Promise { this.checkCap(agent.person.slug, now); - const { admin } = this.resolveAdmin(projectSlug, input.onBehalfOf); + const { admin } = this.resolveAdmin(projectSlug, input.onBehalfOf, { requireFresh: true, now }); if (admin.id !== expectedAdminId) throw new ForbiddenError(NOT_ADMIN, 'not_project_admin'); const asAdmin: SessionContext = { person: admin, accountLevel: 'user', personId: admin.id }; const via = { agentGrantId: agent.grant.id }; diff --git a/apps/api/src/services/agent-feed.ts b/apps/api/src/services/agent-feed.ts index a33ea7d..2d5b784 100644 --- a/apps/api/src/services/agent-feed.ts +++ b/apps/api/src/services/agent-feed.ts @@ -30,6 +30,7 @@ import { personBySlug, projectBySlug, type InMemoryState } from '../store/memory import type { PrivateStore } from '../store/private/interface.js'; import { adminPeople } from './memberships.js'; import { applicantFacts } from './project-application.js'; +import { FEED_ATTEMPTS_PER_REQUEST, type AutoLinkBudget, type SlackAutoLinkService } from './slack-auto-link.js'; const DAY = 24 * 60 * 60 * 1000; export const FEED_DEFAULT_WINDOW_MS = 7 * DAY; @@ -134,11 +135,17 @@ export class AgentFeedService { readonly #state: InMemoryState; readonly #privateStore: PrivateStore; readonly #teamId: string | undefined; + readonly #autoLink: SlackAutoLinkService | undefined; - constructor(state: InMemoryState, privateStore: PrivateStore, opts: { teamId?: string | undefined }) { + constructor( + state: InMemoryState, + privateStore: PrivateStore, + opts: { teamId?: string | undefined; autoLink?: SlackAutoLinkService }, + ) { this.#state = state; this.#privateStore = privateStore; this.#teamId = opts.teamId; + this.#autoLink = opts.autoLink; } async events( @@ -173,8 +180,18 @@ export class AgentFeedService { raw.sort(compare); const page = raw.slice(0, limit); + // Up to a few automatic links or re-checks per request; never a fan-out. + const budget: AutoLinkBudget = { left: FEED_ATTEMPTS_PER_REQUEST }; + const admins = new Map(); const data: FeedEvent[] = []; - for (const e of page) data.push(await this.#serialize(e, e.type, e.m)); + for (const e of page) { + let list = admins.get(e.m.projectSlug); + if (!list) { + list = await this.#admins(e.m.projectSlug, budget, now); + admins.set(e.m.projectSlug, list); + } + data.push(this.#serialize(e, e.type, e.m, list)); + } const last = page[page.length - 1]; const next = last ? encodeCursor(last) @@ -182,7 +199,7 @@ export class AgentFeedService { return { data, next }; } - async #serialize(pos: Position, type: FeedEventType, m: ProjectMembership): Promise { + #serialize(pos: Position, type: FeedEventType, m: ProjectMembership, admins: FeedEvent['admins']): FeedEvent { const s = this.#state; const project = projectBySlug(s, m.projectSlug)!; const applicant = personBySlug(s, m.personSlug)!; @@ -210,15 +227,19 @@ export class AgentFeedService { decidedVia: app.decidedVia ?? null, closedBy: app.closedBy ?? null, }, - admins: await this.#admins(project.slug), + admins, }; } /** The project's active admins, each with a Slack user id only when verified-linked in this workspace. */ - async #admins(projectSlug: string): Promise { + async #admins(projectSlug: string, budget: AutoLinkBudget, now: Date): Promise { const out: Array = []; for (const person of adminPeople(this.#state, projectSlug)) { if (person.deletedAt) continue; + if (this.#autoLink) { + out.push({ ...ref(person), slackUserId: await this.#autoLink.slackIdForFeed(person, budget, now) }); + continue; + } const slack = (await this.#privateStore.getProfile(person.id))?.slack; const linked = slack && this.#teamId !== undefined && slack.teamId === this.#teamId; out.push({ ...ref(person), slackUserId: linked ? slack.userId : null }); diff --git a/apps/api/src/services/github-account.ts b/apps/api/src/services/github-account.ts index e51c1df..fb09436 100644 --- a/apps/api/src/services/github-account.ts +++ b/apps/api/src/services/github-account.ts @@ -167,6 +167,7 @@ export class GitHubAccountService { emailBounce: currentProfile?.emailBounce ?? null, // The Slack link is the person's, not the address's (slack-link.md). slack: currentProfile?.slack ?? null, + slackAutoLinkOptOutAt: currentProfile?.slackAutoLinkOptOutAt ?? null, github: identity.user ? githubFactsFrom(identity.user, 'ok', now) : (currentProfile?.github ?? null), updatedAt: now, }); diff --git a/apps/api/src/services/person.write.ts b/apps/api/src/services/person.write.ts index 9c10308..fbeaf81 100644 --- a/apps/api/src/services/person.write.ts +++ b/apps/api/src/services/person.write.ts @@ -174,6 +174,7 @@ export class PersonWriteService { emailRefreshedAt: now, newsletter: existingProfile?.newsletter ?? null, slack: existingProfile?.slack ?? null, + slackAutoLinkOptOutAt: existingProfile?.slackAutoLinkOptOutAt ?? null, updatedAt: now, }); tx.private.putProfile(profile); diff --git a/apps/api/src/services/slack-auto-link.ts b/apps/api/src/services/slack-auto-link.ts new file mode 100644 index 0000000..1819719 --- /dev/null +++ b/apps/api/src/services/slack-auto-link.ts @@ -0,0 +1,321 @@ +/** + * The automatic Slack link — specs/api/slack-link.md → Automatic link. + * + * The site links a person to a Slack user by itself when two independent + * facts agree: the user Slack finds for the person's private-profile email + * (`users.lookupByEmail`) has a handle exactly equal to the person's + * `slackSamlNameId`, and is a full, active, human member of the configured + * workspace. An agent never asserts a link. + * + * One person at a time, only when there is a reason (Slack SAML sign-in, + * `/me`, the agent feed needing an admin's id); never a sweep. Calls are + * budgeted site-wide and honour Slack's Retry-After; results are cached + * per person. Nothing here throws to its caller: a failed lookup leaves + * things as they were and never fails the request that triggered it. + * + * The email goes to Slack and nowhere else: never into a log line, an error + * or a response. Log lines carry the person id and Slack's error string only. + */ +import type { FastifyBaseLogger } from 'fastify'; +import type { Person, PrivateProfile, SlackLink } from '@cfp/shared/schemas'; + +import { isAgentAccount } from '../auth/agent-grant.js'; +import type { InMemoryState } from '../store/memory/state.js'; +import type { PrivateStore } from '../store/private/interface.js'; +import { SlackRateLimitedError, type SlackDirectory, type SlackDirectoryUser } from '../slack/directory.js'; + +const MINUTE = 60 * 1000; +const HOUR = 60 * MINUTE; +const DAY = 24 * HOUR; + +export const AUTO_LINK_CALLS_PER_MINUTE = 20; +export const NO_MATCH_TTL_MS = DAY; +export const ERROR_TTL_MS = 15 * MINUTE; +/** An automatic link older than this is re-checked when used, and always before a decision. */ +export const REVERIFY_AFTER_MS = DAY; +/** An automatic link unverified this long is not used by the feed until a re-check succeeds. */ +export const STALE_MAX_MS = 7 * DAY; +export const SIGN_IN_DELAY_MS = MINUTE; +export const ME_WAIT_MS = 1500; +export const FEED_ATTEMPTS_PER_REQUEST = 5; + +export type AutoLinkOutcome = + | 'off' // no token or workspace configured + | 'skipped' // not eligible, cached, or over budget: Slack was not asked + | 'linked' + | 'no_match' + | 'verified' + | 'removed' + | 'error'; // Slack failed or rate limited + +/** How many Slack calls one request may still make. */ +export interface AutoLinkBudget { + left: number; +} + +export function linkAge(link: SlackLink, now: number): number { + return now - Date.parse(link.verifiedAt ?? link.linkedAt); +} + +export class SlackAutoLinkService { + readonly #state: InMemoryState; + readonly #privateStore: PrivateStore; + readonly #teamId: string | undefined; + readonly #log: FastifyBaseLogger; + #directory: SlackDirectory | null; + /** Call times in the last minute, site-wide. */ + #calls: number[] = []; + #backoffUntil = 0; + /** personId → a cached negative result. */ + readonly #results = new Map(); + readonly #inflight = new Map>(); + readonly #timers = new Set(); + + constructor( + state: InMemoryState, + privateStore: PrivateStore, + opts: { teamId?: string | undefined; directory: SlackDirectory | null; log: FastifyBaseLogger }, + ) { + this.#state = state; + this.#privateStore = privateStore; + this.#teamId = opts.teamId; + this.#directory = opts.directory; + this.#log = opts.log; + } + + /** Swap the directory (tests use a fake; null turns the automatic link off). */ + useDirectory(directory: SlackDirectory | null): void { + this.#directory = directory; + this.#results.clear(); + this.#calls = []; + this.#backoffUntil = 0; + } + + get enabled(): boolean { + return this.#directory !== null && this.#teamId !== undefined; + } + + /** Cancel scheduled sign-in checks (app shutdown). */ + close(): void { + for (const t of this.#timers) clearTimeout(t); + this.#timers.clear(); + } + + /** Try to link a person who has no link. Never throws. */ + attempt(person: Person, opts: { budget?: AutoLinkBudget; now?: Date } = {}): Promise { + return this.#once(person.id, () => this.#attempt(person, opts.budget, opts.now ?? new Date())); + } + + /** Re-check an automatic link against Slack. Never throws. */ + reverify(person: Person, opts: { budget?: AutoLinkBudget; now?: Date } = {}): Promise { + return this.#once(person.id, () => this.#reverify(person, opts.budget, opts.now ?? new Date())); + } + + /** + * For `/me`: try the automatic link when the person has none, waiting at + * most `waitMs`; re-check a due automatic link in the background. + */ + async refreshForSelf(person: Person, waitMs = ME_WAIT_MS): Promise { + if (!this.enabled) return; + const profile = await this.#privateStore.getProfile(person.id); + if (!profile) return; + if (profile.slack) { + if (profile.slack.via === 'auto' && linkAge(profile.slack, Date.now()) > REVERIFY_AFTER_MS) { + void this.reverify(person); + } + return; + } + if (profile.slackAutoLinkOptOutAt || this.#cached(person.id, Date.now())) return; + let timer: NodeJS.Timeout | undefined; + await Promise.race([ + this.attempt(person), + new Promise((resolve) => { + timer = setTimeout(resolve, waitMs); + }), + ]); + if (timer) clearTimeout(timer); + } + + /** + * The Slack user id the feed may carry for an admin, or null: links (or + * re-checks) within the request's budget, and drops an automatic link + * unverified for {@link STALE_MAX_MS}. + */ + async slackIdForFeed(person: Person, budget: AutoLinkBudget, now: Date = new Date()): Promise { + let profile = await this.#privateStore.getProfile(person.id); + if (!profile) return null; + if (!profile.slack && this.enabled) { + if ((await this.attempt(person, { budget, now })) === 'linked') profile = await this.#privateStore.getProfile(person.id); + } else if (profile.slack?.via === 'auto' && linkAge(profile.slack, now.getTime()) > REVERIFY_AFTER_MS) { + await this.reverify(person, { budget, now }); + profile = await this.#privateStore.getProfile(person.id); + } + const link = profile?.slack; + if (!link || this.#teamId === undefined || link.teamId !== this.#teamId) return null; + if (link.via === 'auto' && linkAge(link, now.getTime()) > STALE_MAX_MS) return null; + return link.userId; + } + + /** + * Before an on-behalf decision: a code link stands; an automatic link must + * have been verified within {@link REVERIFY_AFTER_MS}, re-checking it now + * if not. False when it no longer matches (it is removed) or cannot be checked. + */ + async freshForDecision(person: Person, now: Date = new Date()): Promise { + const link = (await this.#privateStore.getProfile(person.id))?.slack; + if (!link) return false; + if (link.via !== 'auto' || linkAge(link, now.getTime()) <= REVERIFY_AFTER_MS) return true; + return (await this.reverify(person, { now })) === 'verified'; + } + + /** + * At Slack SAML sign-in: forget any cached result and check about a minute + * later (a first sign-in creates the Slack account only once Slack has + * consumed the assertion). + */ + scheduleAfterSignIn(personId: string, delayMs = SIGN_IN_DELAY_MS): void { + if (!this.enabled) return; + this.#results.delete(personId); + const timer = setTimeout(() => { + this.#timers.delete(timer); + const person = this.#state.people.get(personId); + if (person) void this.attempt(person); + }, delayMs); + timer.unref(); + this.#timers.add(timer); + } + + // --------------------------------------------------------------------------- + + #once(personId: string, run: () => Promise): Promise { + const running = this.#inflight.get(personId); + if (running) return running; + const p = run() + .catch((err: unknown) => { + this.#log.error({ err: err instanceof Error ? err.name : 'error', personId }, 'slack auto-link: unexpected failure'); + return 'error' as const; + }) + .finally(() => this.#inflight.delete(personId)); + this.#inflight.set(personId, p); + return p; + } + + #cached(personId: string, t: number): boolean { + const r = this.#results.get(personId); + if (!r) return false; + if (t - r.at < (r.kind === 'no_match' ? NO_MATCH_TTL_MS : ERROR_TTL_MS)) return true; + this.#results.delete(personId); + return false; + } + + /** Who may be linked automatically at all. */ + #eligible(person: Person, profile: PrivateProfile | null): profile is PrivateProfile { + return ( + profile !== null && + !person.deletedAt && + typeof person.slackSamlNameId === 'string' && + person.slackSamlNameId.length > 0 && + !isAgentAccount(this.#state, person.slug) + ); + } + + /** Both facts agree, and the user is a full, active, human member of this workspace. */ + #matches(person: Person, user: SlackDirectoryUser | null): user is SlackDirectoryUser { + return ( + user !== null && + user.name === person.slackSamlNameId && + user.team_id === this.#teamId && + user.deleted !== true && + user.is_bot !== true && + user.id !== 'USLACKBOT' && + user.is_restricted !== true && + user.is_ultra_restricted !== true + ); + } + + /** Take one call from the site-wide budget (and the request's, if given). */ + #take(t: number, budget: AutoLinkBudget | undefined): boolean { + if (t < this.#backoffUntil) return false; + if (budget && budget.left <= 0) return false; + this.#calls = this.#calls.filter((at) => t - at < MINUTE); + if (this.#calls.length >= AUTO_LINK_CALLS_PER_MINUTE) return false; + this.#calls.push(t); + if (budget) budget.left -= 1; + return true; + } + + /** Ask Slack; null on not found, 'error' on failure (cached for the person). */ + async #lookup(personId: string, email: string, t: number): Promise { + try { + return await this.#directory!.lookupUserByEmail(email); + } catch (err) { + if (err instanceof SlackRateLimitedError) { + this.#backoffUntil = Date.now() + err.retryAfterSeconds * 1000; + this.#log.warn({ retryAfter: err.retryAfterSeconds }, 'slack auto-link: rate limited by Slack'); + } else { + const slackError = (err as { slackError?: unknown }).slackError; + this.#log.warn({ personId, slackError: typeof slackError === 'string' ? slackError : 'unknown' }, 'slack auto-link: lookup failed'); + } + this.#results.set(personId, { kind: 'error', at: t }); + return 'error'; + } + } + + async #attempt(person: Person, budget: AutoLinkBudget | undefined, now: Date): Promise { + if (!this.enabled) return 'off'; + const t = now.getTime(); + const profile = await this.#privateStore.getProfile(person.id); + if (!this.#eligible(person, profile) || profile.slack || profile.slackAutoLinkOptOutAt) return 'skipped'; + if (this.#cached(person.id, t) || !this.#take(t, budget)) return 'skipped'; + + const user = await this.#lookup(person.id, profile.email, t); + if (user === 'error') return 'error'; + const teamId = this.#teamId!; + if (!this.#matches(person, user)) { + this.#results.set(person.id, { kind: 'no_match', at: t }); + return 'no_match'; + } + const holder = this.#privateStore.findPersonIdBySlackUser(teamId, user.id); + if (holder !== null && holder !== person.id) { + this.#results.set(person.id, { kind: 'no_match', at: t }); + return 'no_match'; + } + // Re-read: the profile may have changed while Slack answered. + const fresh = await this.#privateStore.getProfile(person.id); + if (!fresh || fresh.slack || fresh.slackAutoLinkOptOutAt || fresh.email !== profile.email) return 'skipped'; + const at = new Date().toISOString(); + await this.#privateStore.putProfile({ + ...fresh, + slack: { teamId, userId: user.id, linkedAt: at, via: 'auto', verifiedAt: at }, + updatedAt: at, + }); + this.#results.delete(person.id); + this.#log.info({ personId: person.id }, 'slack auto-link: linked'); + return 'linked'; + } + + async #reverify(person: Person, budget: AutoLinkBudget | undefined, now: Date): Promise { + const profile = await this.#privateStore.getProfile(person.id); + const link = profile?.slack; + if (!profile || !link || link.via !== 'auto') return 'skipped'; + if (!this.enabled || !this.#take(now.getTime(), budget)) return 'error'; + + const user = await this.#lookup(person.id, profile.email, now.getTime()); + if (user === 'error') return 'error'; + const still = + this.#eligible(person, profile) && this.#matches(person, user) && user.id === link.userId && link.teamId === this.#teamId; + const fresh = await this.#privateStore.getProfile(person.id); + const same = fresh?.slack && fresh.slack.userId === link.userId && fresh.slack.teamId === link.teamId && fresh.slack.via === 'auto'; + if (!fresh || !same) return 'skipped'; + const at = new Date().toISOString(); + if (still) { + await this.#privateStore.putProfile({ ...fresh, slack: { ...fresh.slack!, verifiedAt: at }, updatedAt: at }); + return 'verified'; + } + // No longer both facts: the link goes. Not an opt-out; a later match may link again. + await this.#privateStore.putProfile({ ...fresh, slack: null, updatedAt: at }); + this.#results.set(person.id, { kind: 'no_match', at: now.getTime() }); + this.#log.info({ personId: person.id }, 'slack auto-link: re-check no longer matches; link removed'); + return 'removed'; + } +} diff --git a/apps/api/src/services/slack-link.ts b/apps/api/src/services/slack-link.ts index b62e5bb..7ed8b32 100644 --- a/apps/api/src/services/slack-link.ts +++ b/apps/api/src/services/slack-link.ts @@ -58,8 +58,12 @@ function hashCode(canonical: string): string { } /** What `GET /api/auth/me` reports to the person themselves: never the Slack user id. */ -export function slackStatus(profile: PrivateProfile | null): { linked: boolean; linkedAt: string | null } { - return profile?.slack ? { linked: true, linkedAt: profile.slack.linkedAt } : { linked: false, linkedAt: null }; +export function slackStatus( + profile: PrivateProfile | null, +): { linked: boolean; linkedAt: string | null; via: 'auto' | 'code' | null } { + return profile?.slack + ? { linked: true, linkedAt: profile.slack.linkedAt, via: profile.slack.via ?? 'code' } + : { linked: false, linkedAt: null, via: null }; } interface PendingCode { @@ -184,15 +188,26 @@ export class SlackLinkService { this.#void(person.id); const linkedAt = now.toISOString(); // A new link replaces any old one on this account (one Slack user per account). - await this.#privateStore.putProfile({ ...profile, slack: { teamId, userId, linkedAt }, updatedAt: linkedAt }); + // Reconnecting by code is on purpose: it clears any opt-out of the automatic link. + await this.#privateStore.putProfile({ + ...profile, + slack: { teamId, userId, linkedAt, via: 'code', verifiedAt: linkedAt }, + slackAutoLinkOptOutAt: null, + updatedAt: linkedAt, + }); return { personSlug: person.slug, linkedAt }; } - /** DELETE /api/account/slack-link — clear the caller's link; nothing to do if there is none. */ + /** + * DELETE /api/account/slack-link — clear the caller's link and record the + * opt-out, so the automatic link never re-links them (slack-link.md → Opt-out). + */ async unlink(person: Person, now: Date = new Date()): Promise { const profile = await this.#privateStore.getProfile(person.id); - if (!profile?.slack) return; - await this.#privateStore.putProfile({ ...profile, slack: null, updatedAt: now.toISOString() }); + if (!profile) return; + if (!profile.slack && profile.slackAutoLinkOptOutAt) return; + const at = now.toISOString(); + await this.#privateStore.putProfile({ ...profile, slack: null, slackAutoLinkOptOutAt: at, updatedAt: at }); } /** Drop a person's live code. */ diff --git a/apps/api/src/store/private/base.ts b/apps/api/src/store/private/base.ts index a165949..6c8df5b 100644 --- a/apps/api/src/store/private/base.ts +++ b/apps/api/src/store/private/base.ts @@ -110,6 +110,10 @@ export abstract class BasePrivateStore implements PrivateStore { return this.profiles.get(personId) ?? null; } + peekProfile(personId: string): PrivateProfile | null { + return this.profiles.get(personId) ?? null; + } + async putProfile(profile: PrivateProfile): Promise { const parsed = PrivateProfileSchema.parse(profile); this.profiles.set(parsed.personId, parsed); diff --git a/apps/api/src/store/private/interface.ts b/apps/api/src/store/private/interface.ts index 1bc4b7f..368df94 100644 --- a/apps/api/src/store/private/interface.ts +++ b/apps/api/src/store/private/interface.ts @@ -56,6 +56,8 @@ export interface PrivateStore { // --- Profiles --- getProfile(personId: string): Promise; + /** The in-memory profile, synchronously (for checks that run under the write lock). */ + peekProfile(personId: string): PrivateProfile | null; putProfile(profile: PrivateProfile): Promise; deleteProfile(personId: string): Promise; findPersonIdByEmail(email: string): Promise; diff --git a/apps/api/tests/slack-auto-link.test.ts b/apps/api/tests/slack-auto-link.test.ts new file mode 100644 index 0000000..1d756f3 --- /dev/null +++ b/apps/api/tests/slack-auto-link.test.ts @@ -0,0 +1,325 @@ +/** + * The automatic Slack link (plans/slack-account-link.md, reopened; + * specs/api/slack-link.md → Automatic link): email and handle must both + * agree, guests, bots, deleted users and other workspaces never link, no + * token means no attempt, Slack failures fail closed without failing the + * request, the opt-out holds, re-verification removes a stale link and + * refuses a decision, and the email never reaches a log or a response. + * A fake directory stands in for Slack; nothing here touches the network. + * + * Every person, workspace and Slack id here is invented; addresses are example.org. + */ +import { Writable } from 'node:stream'; + +import { afterEach, beforeEach, describe, expect, it } from 'vitest'; + +import { + FetchSlackDirectory, + SlackApiError, + SlackRateLimitedError, + type SlackDirectory, + type SlackDirectoryUser, +} from '../src/slack/directory.js'; +import { FEED_ATTEMPTS_PER_REQUEST } from '../src/services/slack-auto-link.js'; +import { + bearer, + createAgent, + daysAgo, + fid, + minutesAgo, + personRecord, + privateProfile, + startAgentTestEnv, + type AgentTestEnv, + type Rec, +} from './helpers/agent-fixtures.js'; + +const TEAM = 'TEXAMPLE01'; +const P = { + ada: 1, ben: 2, cal: 3, gina: 4, bot: 5, dee: 6, wes: 7, olly: 8, root: 9, cara: 10, + a1: 21, a2: 22, a3: 23, a4: 24, a5: 25, a6: 26, a7: 27, +}; +const T = '2026-05-01T00:00:00.000Z'; +const email = (slug: string) => `${slug}@example.org`; +const user = (id: string, name: string, over: Partial = {}): SlackDirectoryUser => ({ + id, name, team_id: TEAM, deleted: false, is_bot: false, is_restricted: false, is_ultra_restricted: false, ...over, +}); + +class FakeDirectory implements SlackDirectory { + readonly users = new Map(); + calls = 0; + mode: 'ok' | 'error' | 'ratelimit' = 'ok'; + async lookupUserByEmail(address: string): Promise { + this.calls += 1; + if (this.mode === 'error') throw new SlackApiError('internal_error'); + if (this.mode === 'ratelimit') throw new SlackRateLimitedError(30); + return this.users.get(address) ?? null; + } +} + +function fixtureDirectory(): FakeDirectory { + const d = new FakeDirectory(); + d.users.set(email('ada'), user('UADA000001', 'ada')); + d.users.set(email('ben'), user('UBEN000001', 'benny')); // email matches, handle differs + d.users.set('someone-else@example.org', user('UCAL000001', 'cal')); // handle matches, not cal's email + d.users.set(email('gina'), user('UGINA00001', 'gina', { is_restricted: true })); + d.users.set(email('bot'), user('UBOT000001', 'bot', { is_bot: true })); + d.users.set(email('dee'), user('UDEE000001', 'dee', { deleted: true })); + d.users.set(email('wes'), user('UWES000001', 'wes', { team_id: 'TOTHER0001' })); + d.users.set(email('olly'), user('UOLLY00001', 'olly')); + for (let i = 1; i <= 7; i++) d.users.set(email(`a${i}`), user(`UA${i}00000${i}`, `a${i}`)); + return d; +} + +let n = 1000; +const rec = (project: string, person: string, state: 'applicant' | 'member', over: Rec = {}): Rec => ({ + id: fid(n++), projectSlug: project, personSlug: person, state, isAdmin: false, muted: false, followedAt: T, createdAt: T, updatedAt: T, + ...(state === 'member' ? { via: 'legacy', joinedAt: T } : {}), ...over, +}); +const RECENT = minutesAgo(90); +const openApp = (): Rec => ({ application: { status: 'open', roleIds: [], offer: 'Glad to help.', submittedAt: RECENT, visibleAt: RECENT, notifiedAt: RECENT } }); + +function records(): Record { + n = 1000; + return { + people: Object.entries(P).map(([slug, k]) => + personRecord(k, slug, { slackSamlNameId: slug, ...(slug === 'root' ? { accountLevel: 'administrator' } : {}) }), + ), + projects: [ + { id: fid(50), slug: 'proj', title: 'Project Proj', stage: 'testing', featured: false, createdAt: T, updatedAt: T }, + { id: fid(51), slug: 'many', title: 'Many admins', stage: 'testing', featured: false, createdAt: T, updatedAt: T }, + ], + 'project-memberships': [ + rec('proj', 'ada', 'member', { isAdmin: true }), + rec('proj', 'cara', 'applicant', openApp()), + ...[1, 2, 3, 4, 5, 6, 7].map((i) => rec('many', `a${i}`, 'member', { isAdmin: true })), + rec('many', 'ben', 'applicant', openApp()), + ], + }; +} +const PROFILES = Object.entries(P).map(([slug, k]) => + privateProfile(fid(k), email(slug), slug === 'olly' ? { slackAutoLinkOptOutAt: T } : {}), +); + +describe('automatic Slack link', () => { + let env: AgentTestEnv; + let dir: FakeDirectory; + let logs: string[]; + const bodies: string[] = []; + + beforeEach(async () => { + logs = []; + const stream = new Writable({ + write(chunk: Buffer, _e, cb) { + logs.push(chunk.toString('utf8')); + cb(); + }, + }); + env = await startAgentTestEnv({ records: records(), profiles: PROFILES, env: { SLACK_TEAM_ID: TEAM }, logger: { level: 'trace', stream } }); + dir = fixtureDirectory(); + env.app.services.slackAutoLink.useDirectory(dir); + }); + afterEach(async () => { + // The email never reaches a log line or a response, whatever the test did. + const all = logs.join('') + bodies.join(''); + for (const slug of Object.keys(P)) expect(all).not.toContain(email(slug)); + bodies.length = 0; + await env.close(); + }); + + const me = async (k: number) => { + const res = await env.app.inject({ method: 'GET', url: '/api/auth/me', cookies: { cfp_session: await env.cookie(k, 'user') } }); + expect(res.statusCode).toBe(200); + bodies.push(res.body); + return res.json<{ data: { slack: { linked: boolean; via: string | null } } }>().data.slack; + }; + const profile = (k: number) => env.app.store.private.peekProfile(fid(k)); + + it('links when the email lookup finds a user whose handle equals slackSamlNameId', async () => { + expect(await me(P.ada)).toMatchObject({ linked: true, via: 'auto' }); + expect(profile(P.ada)?.slack).toMatchObject({ teamId: TEAM, userId: 'UADA000001', via: 'auto' }); + expect(profile(P.ada)?.slack?.verifiedAt).toBeDefined(); + expect(env.app.store.private.findPersonIdBySlackUser(TEAM, 'UADA000001')).toBe(fid(P.ada)); + expect(bodies.join('')).not.toContain('UADA000001'); + }); + + it('does not link on one fact alone, nor a guest, a bot, a deleted user or another workspace', async () => { + for (const k of [P.ben, P.cal, P.gina, P.bot, P.dee, P.wes]) { + expect(await me(k)).toMatchObject({ linked: false }); + expect(profile(k)?.slack ?? null).toBeNull(); + } + expect(dir.calls).toBe(6); + // A no-match is cached: asking again does not call Slack. + await me(P.ben); + expect(dir.calls).toBe(6); + }); + + it('with no token configured, never asks Slack', async () => { + env.app.services.slackAutoLink.useDirectory(null); + expect(await me(P.ada)).toMatchObject({ linked: false }); + expect(dir.calls).toBe(0); + }); + + it('a Slack error or a rate limit fails closed without failing the request', async () => { + dir.mode = 'error'; + expect(await me(P.ada)).toMatchObject({ linked: false }); + expect(dir.calls).toBe(1); + await me(P.ada); // the error is cached for a while + expect(dir.calls).toBe(1); + + dir.mode = 'ratelimit'; + expect(await me(P.a1)).toMatchObject({ linked: false }); + expect(dir.calls).toBe(2); + // Backing off: nobody else's lookup goes out until Retry-After passes. + dir.mode = 'ok'; + expect(await me(P.a2)).toMatchObject({ linked: false }); + expect(dir.calls).toBe(2); + }); + + it('respects the opt-out: a disconnected member is not re-linked, and can reconnect by code', async () => { + expect(await me(P.olly)).toMatchObject({ linked: false }); + expect(dir.calls).toBe(0); + + expect(await me(P.ada)).toMatchObject({ linked: true, via: 'auto' }); + const del = await env.app.inject({ method: 'DELETE', url: '/api/account/slack-link', cookies: { cfp_session: await env.cookie(P.ada, 'user') } }); + expect(del.statusCode).toBe(204); + expect(profile(P.ada)?.slackAutoLinkOptOutAt).toBeTruthy(); + const calls = dir.calls; + expect(await me(P.ada)).toMatchObject({ linked: false }); + expect(dir.calls).toBe(calls); + // The SAML sign-in trigger honours it too. + env.app.services.slackAutoLink.scheduleAfterSignIn(fid(P.ada), 5); + await new Promise((r) => setTimeout(r, 50)); + expect(profile(P.ada)?.slack ?? null).toBeNull(); + + // Reconnecting on purpose, by code, clears the opt-out. + const agent = await createAgent(env, await env.cookie(P.root, 'administrator'), { slug: 'example-bot', scopes: ['slack:link'] }); + const code = (await env.app.inject({ method: 'POST', url: '/api/account/slack-link/code', cookies: { cfp_session: await env.cookie(P.ada, 'user') } })).json<{ data: { code: string } }>().data.code; + const redeem = await env.app.inject({ method: 'POST', url: '/api/agent/slack-links', ...bearer(agent.token), payload: { code, slackTeamId: TEAM, slackUserId: 'UADA000001' } }); + expect(redeem.statusCode, redeem.body).toBe(200); + expect(profile(P.ada)?.slack).toMatchObject({ via: 'code' }); + expect(profile(P.ada)?.slackAutoLinkOptOutAt ?? null).toBeNull(); + expect(await me(P.ada)).toMatchObject({ linked: true, via: 'code' }); + }); + + it('a Slack SAML sign-in schedules a check that links', async () => { + env.app.services.slackAutoLink.scheduleAfterSignIn(fid(P.ada), 5); + await new Promise((r) => setTimeout(r, 50)); + expect(profile(P.ada)?.slack).toMatchObject({ userId: 'UADA000001', via: 'auto' }); + }); + + describe('the feed', () => { + let token: string; + beforeEach(async () => { + token = (await createAgent(env, await env.cookie(P.root, 'administrator'), { slug: 'feed-bot', scopes: ['projects:applications:read'] })).token; + }); + const feed = async () => { + const res = await env.app.inject({ method: 'GET', url: '/api/agent/events', ...bearer(token) }); + expect(res.statusCode).toBe(200); + bodies.push(res.body); + return res.json<{ data: Array<{ project: { slug: string }; admins: Array<{ slug: string; slackUserId: string | null }> }> }>().data; + }; + + it('links admins it needs, at most a few per request', async () => { + const first = await feed(); + expect(first.find((e) => e.project.slug === 'proj')!.admins).toEqual([{ slug: 'ada', fullName: 'Test ada', slackUserId: 'UADA000001' }]); + const many = first.find((e) => e.project.slug === 'many')!.admins; + expect(dir.calls).toBe(FEED_ATTEMPTS_PER_REQUEST); + expect(many.filter((a) => a.slackUserId !== null)).toHaveLength(FEED_ATTEMPTS_PER_REQUEST - 1); + // The next request picks up the rest. + const second = await feed(); + expect(second.find((e) => e.project.slug === 'many')!.admins.every((a) => a.slackUserId !== null)).toBe(true); + }); + + it('stops carrying an automatic link unverified for 7 days when Slack cannot re-check it', async () => { + await me(P.ada); + const p = profile(P.ada)!; + await env.app.store.private.putProfile({ ...p, slack: { ...p.slack!, verifiedAt: daysAgo(8) } }); + dir.mode = 'error'; + expect((await feed()).find((e) => e.project.slug === 'proj')!.admins[0]!.slackUserId).toBeNull(); + expect(profile(P.ada)?.slack).toBeTruthy(); // kept, just not used + }); + }); + + describe('re-verification before an on-behalf decision', () => { + let token: string; + beforeEach(async () => { + token = (await createAgent(env, await env.cookie(P.root, 'administrator'), { + slug: 'decide-bot', scopes: ['slack:link', 'projects:applications:read', 'projects:applications:decide'], + })).token; + expect(await me(P.ada)).toMatchObject({ linked: true, via: 'auto' }); + }); + const age = async (days: number) => { + const p = profile(P.ada)!; + await env.app.store.private.putProfile({ ...p, slack: { ...p.slack!, verifiedAt: daysAgo(days) } }); + }; + const decide = async () => { + const res = await env.app.inject({ + method: 'POST', url: '/api/agent/applications/proj/cara/decision', ...bearer(token), + payload: { decision: 'accept', onBehalfOf: { slackTeamId: TEAM, slackUserId: 'UADA000001' } }, + }); + bodies.push(res.body); + return res; + }; + + it('a fresh automatic link decides without asking Slack', async () => { + const calls = dir.calls; + expect((await decide()).statusCode).toBe(200); + expect(dir.calls).toBe(calls); + }); + + it('an old link that still matches is re-verified, then decides', async () => { + await age(2); + const res = await decide(); + expect(res.statusCode, res.body).toBe(200); + expect(Date.parse(profile(P.ada)!.slack!.verifiedAt!)).toBeGreaterThan(Date.now() - 60_000); + }); + + it('an old link that no longer matches is removed and the decision refused not_project_admin', async () => { + await age(2); + dir.users.set(email('ada'), user('UADA000001', 'ada-renamed')); + const res = await decide(); + expect(res.statusCode).toBe(403); + expect(res.json<{ error: { code: string } }>().error.code).toBe('not_project_admin'); + expect(profile(P.ada)?.slack ?? null).toBeNull(); + expect(env.app.store.private.findPersonIdBySlackUser(TEAM, 'UADA000001')).toBeNull(); + }); + + it('an old link Slack cannot re-check is refused, and kept', async () => { + await age(2); + dir.mode = 'error'; + const res = await decide(); + expect(res.statusCode).toBe(403); + expect(res.json<{ error: { code: string } }>().error.code).toBe('not_project_admin'); + expect(profile(P.ada)?.slack).toBeTruthy(); + }); + }); +}); + +describe('FetchSlackDirectory', () => { + const respond = (status: number, body: unknown, headers: Record = {}) => + (async () => new Response(JSON.stringify(body), { status, headers: { 'content-type': 'application/json', ...headers } })) as unknown as typeof fetch; + + it('posts the email with the token and returns the user', async () => { + let seen: { url: string; init: RequestInit } | null = null; + const fake = (async (url: string, init: RequestInit) => { + seen = { url, init }; + return new Response(JSON.stringify({ ok: true, user: { id: 'UX', name: 'x' } }), { status: 200 }); + }) as unknown as typeof fetch; + const d = new FetchSlackDirectory('xoxb-test', fake); + expect(await d.lookupUserByEmail('x@example.org')).toEqual({ id: 'UX', name: 'x' }); + expect(seen!.url).toBe('https://slack.com/api/users.lookupByEmail'); + expect((seen!.init.headers as Record).authorization).toBe('Bearer xoxb-test'); + expect(String(seen!.init.body)).toBe('email=x%40example.org'); + }); + + it('maps users_not_found to null, 429 and ratelimited to SlackRateLimitedError, anything else to SlackApiError', async () => { + expect(await new FetchSlackDirectory('xoxb-t', respond(200, { ok: false, error: 'users_not_found' })).lookupUserByEmail('a@example.org')).toBeNull(); + await expect(new FetchSlackDirectory('xoxb-t', respond(429, {}, { 'retry-after': '12' })).lookupUserByEmail('a@example.org')).rejects.toMatchObject({ retryAfterSeconds: 12 }); + await expect(new FetchSlackDirectory('xoxb-t', respond(200, { ok: false, error: 'ratelimited' })).lookupUserByEmail('a@example.org')).rejects.toBeInstanceOf(SlackRateLimitedError); + const err = await new FetchSlackDirectory('xoxb-t', respond(200, { ok: false, error: 'invalid_auth' })).lookupUserByEmail('a@example.org').catch((e: unknown) => e); + expect(err).toBeInstanceOf(SlackApiError); + expect(String((err as Error).message)).not.toContain('a@example.org'); + await expect(new FetchSlackDirectory('xoxb-t', respond(500, {})).lookupUserByEmail('a@example.org')).rejects.toBeInstanceOf(SlackApiError); + }); +}); diff --git a/apps/api/tests/slack-link.test.ts b/apps/api/tests/slack-link.test.ts index c022c2e..073a349 100644 --- a/apps/api/tests/slack-link.test.ts +++ b/apps/api/tests/slack-link.test.ts @@ -141,7 +141,7 @@ describe('slack account link', () => { it('links the issuer once; reused, unknown and expired codes all answer the same 404 code_invalid', async () => { await start(); const token = await agentWith(['slack:link']); - expect((await me(P.ada)).slack).toEqual({ linked: false, linkedAt: null }); + expect((await me(P.ada)).slack).toEqual({ linked: false, linkedAt: null, via: null }); const { code } = await codeFor(P.ada); const ok = await redeem(token, { code: code.toLowerCase().replace('-', ''), slackTeamId: TEAM, slackUserId: U_ADA }); @@ -193,7 +193,7 @@ describe('slack account link', () => { const del = await env.app.inject({ method: 'DELETE', url: '/api/account/slack-link', ...(await as(P.ada)) }); expect(del.statusCode).toBe(204); - expect((await me(P.ada)).slack).toEqual({ linked: false, linkedAt: null }); + expect((await me(P.ada)).slack).toEqual({ linked: false, linkedAt: null, via: null }); expect(env.app.store.private.findPersonIdBySlackUser(TEAM, U_ADA)).toBeNull(); // Disconnecting again is not an error. expect((await env.app.inject({ method: 'DELETE', url: '/api/account/slack-link', ...(await as(P.ada)) })).statusCode).toBe(204); From fb6977d861e831a025cfaa3d3b9f596278f3f86b Mon Sep 17 00:00:00 2001 From: GrittyBot <30755786+codeforphilly-bot@users.noreply.github.com> Date: Mon, 30 Nov 2026 00:04:56 +0000 Subject: [PATCH 23/26] feat(web): the Slack row says whether the link was matched automatically or made by code Disconnect's confirm says the site will not reconnect by itself. Co-Authored-By: Claude Opus 5.5 --- apps/web/src/components/account/SlackRow.tsx | 17 +++++++++++++---- apps/web/src/hooks/useAuth.tsx | 2 ++ apps/web/tests/Account.test.tsx | 8 ++++---- 3 files changed, 19 insertions(+), 8 deletions(-) diff --git a/apps/web/src/components/account/SlackRow.tsx b/apps/web/src/components/account/SlackRow.tsx index 3a2d6f2..5cd311a 100644 --- a/apps/web/src/components/account/SlackRow.tsx +++ b/apps/web/src/components/account/SlackRow.tsx @@ -5,7 +5,9 @@ * Not linked: "Connect Slack" asks for a one-time code and shows it with the * instruction to DM it to the ops bot within ten minutes; while the code is * live the row polls `GET /api/auth/me` and turns linked when the bot - * confirms it. Linked: "Connected to Slack ✓ since …" with Disconnect. + * confirms it. Linked: "Connected to Slack ✓ since …", saying whether the + * site matched it automatically or it was made by code, with Disconnect + * (after which the site does not reconnect it by itself). * The row never shows the Slack user id (the API never sends it here). */ import { useEffect, useState } from 'react'; @@ -66,11 +68,16 @@ export function SlackRow({ initial }: { initial: SlackLinkStatus | null }) { }; const disconnect = async () => { - if (!window.confirm('Disconnect your Slack account? The ops bot will stop reaching you in Slack.')) return; + if ( + !window.confirm( + 'Disconnect your Slack account? The ops bot will stop reaching you in Slack, and the site will not reconnect it by itself. You can reconnect with Connect Slack.', + ) + ) + return; setBusy(true); try { await api.slackLink.disconnect(); - setStatus({ linked: false, linkedAt: null }); + setStatus({ linked: false, linkedAt: null, via: null }); toast.success('Slack disconnected.'); } catch (err) { toast.error(err instanceof ApiError ? err.message : 'Could not disconnect'); @@ -94,7 +101,9 @@ export function SlackRow({ initial }: { initial: SlackLinkStatus | null }) {

Slack
{status.linked - ? `Connected to Slack ✓${status.linkedAt ? ` since ${formatAbsoluteDate(status.linkedAt)}` : ''}` + ? `Connected to Slack ✓${status.linkedAt ? ` since ${formatAbsoluteDate(status.linkedAt)}` : ''}${ + status.via === 'auto' ? ' (matched automatically)' : status.via === 'code' ? ' (by code)' : '' + }` : 'Not linked to a Slack account'}
diff --git a/apps/web/src/hooks/useAuth.tsx b/apps/web/src/hooks/useAuth.tsx index c3f2d01..1a548fd 100644 --- a/apps/web/src/hooks/useAuth.tsx +++ b/apps/web/src/hooks/useAuth.tsx @@ -27,6 +27,8 @@ export interface AuthPerson { export interface SlackLinkStatus { linked: boolean; linkedAt: string | null; + /** How the link was made: matched automatically, or by a code sent to the bot. */ + via?: 'auto' | 'code' | null; } export interface AuthState { diff --git a/apps/web/tests/Account.test.tsx b/apps/web/tests/Account.test.tsx index c35c028..205cee7 100644 --- a/apps/web/tests/Account.test.tsx +++ b/apps/web/tests/Account.test.tsx @@ -177,7 +177,7 @@ describe('Account — Slack row', () => { if (input.startsWith('/api/auth/me')) { if (issued) polls += 1; const linked = issued && pollsUntilLinked !== null && polls > pollsUntilLinked; - return json(mockOk({ ...githubPerson, slack: linked ? { linked: true, linkedAt: '2026-11-20T12:00:00Z' } : { linked: false, linkedAt: null } })); + return json(mockOk({ ...githubPerson, slack: linked ? { linked: true, linkedAt: '2026-11-20T12:00:00Z', via: 'code' } : { linked: false, linkedAt: null, via: null } })); } if (input.startsWith('/api/account/slack-link/code')) { issued = true; @@ -198,7 +198,7 @@ describe('Account — Slack row', () => { expect(await screen.findByTestId('slack-link-code')).toHaveTextContent('K7QW-4MZP'); expect(screen.getByText(/within 10 minutes/i)).toBeInTheDocument(); expect(screen.getByRole('link', { name: /the ops bot/i })).toHaveAttribute('href', CODE.botDmUrl); - await waitFor(() => expect(screen.getByText(/connected to slack ✓ since/i)).toBeInTheDocument(), { timeout: 5000 }); + await waitFor(() => expect(screen.getByText(/connected to slack ✓ since .* \(by code\)/i)).toBeInTheDocument(), { timeout: 5000 }); expect(screen.queryByTestId('slack-link-code')).not.toBeInTheDocument(); expect(calls).toContain('POST /api/account/slack-link/code'); }); @@ -206,12 +206,12 @@ describe('Account — Slack row', () => { it('a linked account shows Connected with Disconnect, and never a Slack user id', async () => { vi.spyOn(globalThis, 'fetch').mockImplementation(((input: string) => { const body = input.startsWith('/api/auth/me') - ? mockOk({ ...githubPerson, slack: { linked: true, linkedAt: '2026-11-20T12:00:00Z' } }) + ? mockOk({ ...githubPerson, slack: { linked: true, linkedAt: '2026-11-20T12:00:00Z', via: 'auto' } }) : mockOk([]); return Promise.resolve(new Response(JSON.stringify(body), { status: 200, headers: { 'content-type': 'application/json' } })); }) as typeof fetch); render(); - expect(await screen.findByText(/connected to slack ✓ since/i)).toBeInTheDocument(); + expect(await screen.findByText(/connected to slack ✓ since .* \(matched automatically\)/i)).toBeInTheDocument(); expect(screen.getByRole('button', { name: 'Disconnect' })).toBeInTheDocument(); expect(screen.getByText(/act on your replies/i)).toBeInTheDocument(); expect(document.body.textContent).not.toMatch(/\bU[A-Z0-9]{6,}\b/); From 7c04803a183ac42a7ac73cdf10537691a9bf8f11 Mon Sep 17 00:00:00 2001 From: GrittyBot <30755786+codeforphilly-bot@users.noreply.github.com> Date: Mon, 30 Nov 2026 00:04:56 +0000 Subject: [PATCH 24/26] docs(ops): SLACK_BOT_TOKEN, the site's read-only Slack token Co-Authored-By: Claude Opus 5.5 --- .env.example | 4 ++++ docs/operations/deploy.md | 1 + docs/operations/secrets.md | 18 ++++++++++++++++++ 3 files changed, 23 insertions(+) diff --git a/.env.example b/.env.example index 72715d8..3057676 100644 --- a/.env.example +++ b/.env.example @@ -85,6 +85,10 @@ CFP_JWT_SIGNING_KEY=change-me-to-a-random-string-at-least-32-chars # be made. See specs/api/slack-link.md. # SLACK_TEAM_ID=TEXAMPLE01 +# Optional: the site's own read-only Slack token (scopes users:read, +# users:read.email) for the automatic Slack link. Unset → link by code only. +# SLACK_BOT_TOKEN=xoxb-... + # Optional: a link that opens a DM with the ops bot, shown on /account. # SLACK_OPS_BOT_DM_URL=https://codeforphilly.slack.com/app_redirect?channel=U... diff --git a/docs/operations/deploy.md b/docs/operations/deploy.md index bf3f421..4530e47 100644 --- a/docs/operations/deploy.md +++ b/docs/operations/deploy.md @@ -288,6 +288,7 @@ comments. Production pod gets these mounted: | `SAML_PRIVATE_KEY` / `SAML_CERTIFICATE` | **Secret** (`codeforphilly-saml`, prod) | Slack IdP key pair, carried over verbatim from laddr's `saml2` secret so Slack keeps trusting the same cert. Mounted via an extra `envFrom` patch in the live cluster repo; marked `optional` so a sandbox without it still boots. | | `SLACK_TEAM_HOST` | ConfigMap | Slack workspace host (default `codeforphilly.slack.com`). ACS URL, NameID `NameQualifier`, `/chat` + `/launch` redirect target. Never our own IdP identity. | | `SLACK_TEAM_ID` | ConfigMap | The workspace id (`T…`) of the Code for Philly Slack. Required for [Slack account links](../../specs/api/slack-link.md) and agent decisions on an admin's behalf; unset, every link redemption is refused (fails closed). Not a secret. | +| `SLACK_BOT_TOKEN` | **Secret** (`codeforphilly-secrets`) | Optional. The site's own read-only Slack token (scopes `users:read`, `users:read.email`) for the [automatic Slack link](../../specs/api/slack-link.md#automatic-link). Unset, members link by code only. See [secrets.md](secrets.md#slack_bot_token). | | `SLACK_OPS_BOT_DM_URL` | ConfigMap | Optional. A link that opens a DM with the ops bot (e.g. `https://codeforphilly.slack.com/app_redirect?channel=`); the Account screen's Slack row links the bot's name to it. | | `GIT_SSH_COMMAND` | ConfigMap | Wires `ssh` to the mounted deploy key | | `GIT_AUTHOR_NAME` / `GIT_AUTHOR_EMAIL` | ConfigMap | Committer identity for API-authored data commits | diff --git a/docs/operations/secrets.md b/docs/operations/secrets.md index a614b09..ae610bd 100644 --- a/docs/operations/secrets.md +++ b/docs/operations/secrets.md @@ -191,6 +191,24 @@ for local dev but means real users get no outbound mail in production. merge → `kubectl rollout restart` → delete the old token in Postmark. - **Cadence:** every 12 months, plus immediately on suspected leak. +### `SLACK_BOT_TOKEN` + +The site's own read-only Slack bot token (`xoxb-…`), used only for the +[automatic Slack link](../../specs/api/slack-link.md#automatic-link): it +calls `users.lookupByEmail` for one member at a time. Optional: unset, the +automatic link is off and members link by code. Needs `SLACK_TEAM_ID` too. + +- **Generate:** a Slack app in the Code for Philly workspace, owned by the + site (not the ops bot's app), with bot scopes **`users:read`** and + **`users:read.email`** and nothing else; a workspace admin installs it and + copies the Bot User OAuth Token. +- **Rotation impact:** none; the next lookup uses the new token. While it is + missing or invalid, lookups fail closed (no links made, decisions on stale + automatic links refused). +- **Rotation procedure:** reinstall or regenerate in the app's OAuth page → + `--merge-into` → merge → `kubectl rollout restart`. +- **Cadence:** on suspected leak, or when an admin who installed it leaves. + ### Data-repo deploy key SSH ed25519 private key with **write** access to the `codeforphilly-data` From b8ee18d69a3900918f94dbf96be5554860f9d3ec Mon Sep 17 00:00:00 2001 From: GrittyBot <30755786+codeforphilly-bot@users.noreply.github.com> Date: Mon, 30 Nov 2026 00:15:46 +0000 Subject: [PATCH 25/26] chore(plans): mark slack-account-link done again, with the automatic link (PR #270) Co-Authored-By: Claude Opus 5.5 --- plans/slack-account-link.md | 53 ++++++++++++++++++++++++++++++++++--- 1 file changed, 49 insertions(+), 4 deletions(-) diff --git a/plans/slack-account-link.md b/plans/slack-account-link.md index aa87ea3..f1e1eb1 100644 --- a/plans/slack-account-link.md +++ b/plans/slack-account-link.md @@ -1,5 +1,5 @@ --- -status: in-progress +status: done depends: [] specs: - specs/api/slack-link.md @@ -82,9 +82,9 @@ punctuation-normalised handle matching. - [ ] `agent-grants/v2` adopted and mirrored; CI passes - [x] Browser: Account → Connect Slack shows a code; redeeming it with a test grant via the API turns the row to "Connected" - [ ] End to end with the ops bot in the real workspace (awaits the bot PR) -- [ ] Tests (automatic): both matches link (`via: auto`); an email match with a different handle, a handle match with a different email, a guest, a bot, a deleted user and another workspace do not; no token → no attempt -- [ ] Tests (automatic): a Slack error or rate limit fails closed without failing the request that triggered it; a member who disconnected is not re-linked automatically and can reconnect by code -- [ ] Tests (automatic): a re-check that no longer matches removes the link and the on-behalf decision is refused `not_project_admin`; the email never appears in logs or responses +- [x] Tests (automatic): both matches link (`via: auto`); an email match with a different handle, a handle match with a different email, a guest, a bot, a deleted user and another workspace do not; no token → no attempt +- [x] Tests (automatic): a Slack error or rate limit fails closed without failing the request that triggered it; a member who disconnected is not re-linked automatically and can reconnect by code +- [x] Tests (automatic): a re-check that no longer matches removes the link and the on-behalf decision is refused `not_project_admin`; the email never appears in logs or responses - [x] `npm run type-check && npm run lint && npm test` clean ## Risks / unknowns @@ -94,6 +94,47 @@ punctuation-normalised handle matching. ## Notes +- **Reopened and closed again on PR #270 for the automatic link** + (operator-approved). Spec in `docs(specs): link Slack accounts + automatically…`; the earlier Notes below still describe the code path. +- **When it runs, and why.** At Slack SAML sign-in (the moment the site knows + the person is entering Slack; delayed a minute because a first sign-in + creates the Slack account only after Slack consumes the assertion, and it + clears a cached no-match); on `/me` (what the Account screen reads; waits + at most 1.5 s so a slow Slack never slows page loads, and only when + nothing is cached, so it is not a lookup per page view); when the feed + needs an admin's Slack id (the one consumer that needs it; at most 5 per + request). No sweep: the site never fans out across members. +- **Budget and cache** (in memory, reset on restart): 20 Slack calls a + minute site-wide, under `users.lookupByEmail`'s rate tier; a Slack 429 + stops all calls for its Retry-After; over-budget calls are skipped, not + queued. No-match cached 24 h, errors 15 min; one lookup per person at a time. +- **Re-verification ages.** An automatic link is re-checked when used past + 24 h, and always before an on-behalf decision (mismatch → link removed and + `403 not_project_admin`; Slack unavailable → refused the same way, link + kept; the decision service re-checks freshness under the write lock). The + feed keeps using a link it could not re-check for up to 7 days, then + carries `slackUserId: null` until a re-check succeeds. Code links are not + re-checked. +- **Exact matching only.** No case folding or punctuation normalising (the + coordinator measured 298 members who would match only if dots and + underscores were ignored). Widening that is a possible later change and + would need its own spec decision. +- **Opt-out.** Disconnect records `slackAutoLinkOptOutAt` even when there was + no link; a code link clears it. A re-check mismatch removes the link but + does not record an opt-out. +- **Not verified against real Slack.** Every test uses a fake directory; the + fetch client is tested against a fake `fetch`. Untested in the real + workspace: field values (`team_id` on an Enterprise Grid install, handle + spelling), the real rate tier, and whether members can change their + handle or email. +- The profile rewrites (GitHub email change, claim, claim merge, staff email + edit) carry the opt-out as well as the link. An email change does not drop + an automatic link at once; its next re-check uses the new email and + removes it if it no longer matches. +- Gate at this commit's tree: check-contracts, type-check, lint, tests + (API 71 files / 849, web 36 / 218, shared 5 / 120) and `npm run build` clean. + - **Two criteria open.** `agent-grants/v2` is generated, published in `contracts/` and mirrored into `apps/api/gitsheets/` (vendored with `gitsheets contracts adopt`; the sheet config declares v2), but adopting @@ -134,6 +175,10 @@ punctuation-normalised handle matching. ## Follow-ups +- Deploy: create the site's own Slack app with `users:read` and + `users:read.email`, install it, and set `SLACK_BOT_TOKEN` in the sealed + Secret; spot-check one automatic link on sandbox. + - codeforphilly-data: adopt `agent-grants/v2` on `empty`, `fixture`, `legacy-import`, then `published` at release (no migration: v2 only widens the scope enum). From a18bba4a509e2fd3c6b899ec084bd831f9d4c3a9 Mon Sep 17 00:00:00 2001 From: GrittyBot <30755786+codeforphilly-bot@users.noreply.github.com> Date: Mon, 30 Nov 2026 00:52:57 +0000 Subject: [PATCH 26/26] chore(api): sync sheet configs with codeforphilly-data agent-grants v2 adoption apps/api/gitsheets/ mirrors codeforphilly-data's empty branch after it adopts agent-grants/v2: sources.toml records the v2 provenance, and the v1 document no sheet declares any more goes. Co-Authored-By: Claude Opus 5.5 --- .../codeforphilly.org/agent-grants/v1.toml | 46 ------------------- apps/api/gitsheets/contracts/sources.toml | 4 ++ 2 files changed, 4 insertions(+), 46 deletions(-) delete mode 100644 apps/api/gitsheets/contracts/codeforphilly.org/agent-grants/v1.toml diff --git a/apps/api/gitsheets/contracts/codeforphilly.org/agent-grants/v1.toml b/apps/api/gitsheets/contracts/codeforphilly.org/agent-grants/v1.toml deleted file mode 100644 index 6cc58e3..0000000 --- a/apps/api/gitsheets/contracts/codeforphilly.org/agent-grants/v1.toml +++ /dev/null @@ -1,46 +0,0 @@ -"$id" = "https://codeforphilly.org/agent-grants/v1" -"$schema" = "http://json-schema.org/draft-07/schema#" -required = ["createdAt", "createdBySlug", "expiresAt", "id", "label", "personSlug", "scopes"] -title = "Agent grant" -type = "object" - -[properties.createdAt] -format = "date-time" -pattern = '^(?:(?:\d\d[2468][048]|\d\d[13579][26]|\d\d0[48]|[02468][048]00|[13579][26]00)-02-29|\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\d|30)|(?:02)-(?:0[1-9]|1\d|2[0-8])))T(?:(?:[01]\d|2[0-3]):[0-5]\d(?::[0-5]\d(?:\.\d+)?)?(?:Z|([+-](?:[01]\d|2[0-3]):[0-5]\d)))$' -type = "string" - -[properties.createdBySlug] -minLength = 1 -type = "string" - -[properties.expiresAt] -format = "date-time" -pattern = '^(?:(?:\d\d[2468][048]|\d\d[13579][26]|\d\d0[48]|[02468][048]00|[13579][26]00)-02-29|\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\d|30)|(?:02)-(?:0[1-9]|1\d|2[0-8])))T(?:(?:[01]\d|2[0-3]):[0-5]\d(?::[0-5]\d(?:\.\d+)?)?(?:Z|([+-](?:[01]\d|2[0-3]):[0-5]\d)))$' -type = "string" - -[properties.id] -format = "uuid" -pattern = "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$" -type = "string" - -[properties.label] -maxLength = 80 -minLength = 1 -type = "string" - -[properties.personSlug] -minLength = 1 -type = "string" - -[properties.revokedAt] -format = "date-time" -pattern = '^(?:(?:\d\d[2468][048]|\d\d[13579][26]|\d\d0[48]|[02468][048]00|[13579][26]00)-02-29|\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\d|30)|(?:02)-(?:0[1-9]|1\d|2[0-8])))T(?:(?:[01]\d|2[0-3]):[0-5]\d(?::[0-5]\d(?:\.\d+)?)?(?:Z|([+-](?:[01]\d|2[0-3]):[0-5]\d)))$' -type = "string" - -[properties.scopes] -minItems = 1 -type = "array" - -[properties.scopes.items] -enum = ["moderation:read", "moderation:vote", "moderation:purge"] -type = "string" diff --git a/apps/api/gitsheets/contracts/sources.toml b/apps/api/gitsheets/contracts/sources.toml index 4b46aeb..cbf6043 100644 --- a/apps/api/gitsheets/contracts/sources.toml +++ b/apps/api/gitsheets/contracts/sources.toml @@ -2,6 +2,10 @@ adopted = 2026-11-12T19:53:17.251Z source = "https://raw.githubusercontent.com/CodeForPhilly/codeforphilly-ng/71bf951824e93b7537025fcc1cd479cd88fb1331/contracts/codeforphilly.org/agent-grants/v1.json" +["codeforphilly.org/agent-grants/v2"] +adopted = 2026-11-30T00:52:16.731Z +source = "https://raw.githubusercontent.com/CodeForPhilly/codeforphilly-ng/842bcb2c91140a1327c52ae85a55d40277404d04/contracts/codeforphilly.org/agent-grants/v2.json" + ["codeforphilly.org/blog-posts/v1"] adopted = 2026-10-14T03:31:18.13Z source = "https://raw.githubusercontent.com/CodeForPhilly/codeforphilly-ng/7fe6b81a0bbd05b7a4e6896d55e181fdb61cfe42/contracts/codeforphilly.org/blog-posts/v1.json"