From 1955e2d16ff94e150865ecc92ede93bcbde84bba Mon Sep 17 00:00:00 2001 From: GrittyBot <30755786+codeforphilly-bot@users.noreply.github.com> Date: Tue, 1 Dec 2026 04:26:02 +0000 Subject: [PATCH 01/10] docs(specs): say what a claim approval does, and let staff and the ops bot see the queue A staff-review claim request sat a month because the queue page named neither side plainly, nothing linked to it, and nothing could alert anyone. The staff queue response now carries the claimed member's facts and the requester's current account; a screen spec says each card states which GitHub user would sign in as which member and what approve does; the account menu links the queue with a pending count; and an agent with the new account-claims:read scope reads a reduced list (no evidence, no address) to alert staff. The deny note was specced as emailed but never was, and a pre-onboarding request holds no address to send to: the spec now says so and the email is listed as deferred. Co-Authored-By: Claude Opus 5.5 --- specs/api/account-claim.md | 97 +++++++++++++++- specs/api/agents.md | 6 + specs/behaviors/account-migration.md | 8 ++ specs/behaviors/app-shell.md | 11 ++ specs/data-model.md | 4 +- specs/deferred.md | 5 + specs/screens/staff-account-claim-queue.md | 124 +++++++++++++++++++++ 7 files changed, 248 insertions(+), 7 deletions(-) create mode 100644 specs/screens/staff-account-claim-queue.md diff --git a/specs/api/account-claim.md b/specs/api/account-claim.md index 94b1e540..ab5b11d2 100644 --- a/specs/api/account-claim.md +++ b/specs/api/account-claim.md @@ -212,7 +212,9 @@ Same shape as `/api/account-claim/request-staff-review`. The difference: the use ### GET /api/staff/account-claim/queue -Lists pending `AccountClaimRequest` records. +Lists pending (`status = open`) `AccountClaimRequest` records, oldest first, +with what a reviewer needs to judge each one without leaving the page +([screens/staff-account-claim-queue.md](../screens/staff-account-claim-queue.md)). ```json { @@ -220,18 +222,47 @@ Lists pending `AccountClaimRequest` records. "data": [ { "requestId": "...", + "type": "pre-onboarding" | "post-onboarding-merge", "claimedSlug": "janedoe", "claimedPersonId": "01951a3c-...", - "requesterGithubLogin": "janedoe", + "claimedPerson": { + "slug": "janedoe", + "fullName": "Jane Doe", + "createdAt": "2017-03-02T00:00:00Z", + "imported": true, + "githubLogin": null, + "memberOfCount": 3, + "isAgent": false + }, + "requesterGithubLogin": "janedoe-gh", "requesterPersonId": null, + "requesterPerson": null, "evidence": "...", - "submittedAt": "...", - "type": "pre-onboarding" | "post-onboarding-merge" + "submittedAt": "..." } ] } ``` +- `claimedSlug` is the text the requester typed, as typed. +- `claimedPerson` is the member the request would act on, as that member + stands now (by `claimedPersonId`, so a rename since the request shows the + current slug). It is `null` when `claimedPersonId` is `null` (no member had + that username when the request was made) or that member no longer exists or + is deactivated: approve would refuse such a request (`422`), so the reviewer + denies it instead. + - `imported` is `true` for a member carried over from the old site + (`legacyId` set). + - `githubLogin` is the GitHub login the member is already linked to, or + `null`. A linked member cannot be claimed (approve returns `409 + already_claimed`). + - `memberOfCount` counts the projects they are a member of. + - `isAgent` is `true` for an [agent account](agents.md#the-agent-account), + which approve refuses (`409 agent_account`). +- `requesterPerson` is, for a post-onboarding merge, the signed-in account the + requester made since (`{ slug, fullName, createdAt }`), the one approve + merges away; `null` for pre-onboarding, or if that account is gone. + ### POST /api/staff/account-claim/:requestId/approve Approve a request. For pre-onboarding (no requesterPersonId): link the GitHub identity to the claimed Person, issue the user's first session next time they sign in. For post-onboarding (has requesterPersonId): merge the requester's fresh Person into the claimed legacy Person. @@ -245,7 +276,61 @@ Audit-logged via commit trailers (`Action: account-claim.approve`, `Subject-Slug ### POST /api/staff/account-claim/:requestId/deny -Mark the request denied. Optionally include a denial reason that's emailed to the requester. +Mark the request denied. The optional `reason` is stored on the private +request (`reviewedReason`) and nowhere else: no email goes to the requester +(a pre-onboarding request holds no address for them, only the contact they +wrote in their evidence), so staff who want the requester to know reach them +through that contact. Emailing a denial is +[deferred](../deferred.md#denial-email-for-account-claim-requests). + +The approve `reason`, by contrast, becomes the public commit's `Reason:` +trailer, so it must not repeat anything private from the evidence. + +## GET /api/agent/account-claims + +Pending claim requests for an [agent](agents.md) holding +`account-claims:read`, so the org's ops bot can tell staff a request is +waiting. It is an alert feed, not a review surface: staff review on the +[queue screen](../screens/staff-account-claim-queue.md). Signed-in people, +staff included, and callers without the scope get `401`, like the other +agent endpoints ([agent-applications.md](agent-applications.md)). + +### Response — 200 + +```json +{ + "success": true, + "data": [ + { + "requestId": "...", + "type": "pre-onboarding", + "submittedAt": "2026-11-02T15:04:05Z", + "claimedText": "janedoe", + "resolves": true, + "claimedPersonSlug": "janedoe", + "requesterGithubLogin": "janedoe-gh" + } + ], + "metadata": { "timestamp": "...", "count": 1 } +} +``` + +- Open requests only, oldest first, all of them (the queue is short; no + paging). +- `resolves` and `claimedPersonSlug` follow the staff queue's + `claimedPerson`: `claimedPersonSlug` is that member's current slug, or + `null` when `resolves` is `false`. +- `claimedText` is the typed text when it has the shape of a username + ([slug-handles.md](../behaviors/slug-handles.md)), and `null` otherwise: + a requester may type an old email address or a sentence into that field, + and neither leaves the site. +- Nothing else. Never the evidence, the staff note, the requester's or the + member's email, the requester's GitHub id, the requester's person id, or + anything from a private profile. + +### Errors + +- `401 unauthenticated` — no agent grant with `account-claims:read` ## Notes @@ -260,3 +345,5 @@ Mark the request denied. Optionally include a denial reason that's emailed to th - [behaviors/private-storage.md](../behaviors/private-storage.md) - [behaviors/authorization.md](../behaviors/authorization.md) — staff endpoints require `staff` or `administrator` - [screens/account-claim.md](../screens/account-claim.md) +- [screens/staff-account-claim-queue.md](../screens/staff-account-claim-queue.md) +- [api/agents.md](agents.md) — the `account-claims:read` scope diff --git a/specs/api/agents.md b/specs/api/agents.md index 10dd698a..aef9f4cd 100644 --- a/specs/api/agents.md +++ b/specs/api/agents.md @@ -26,6 +26,11 @@ close on that admin's behalf ([agent-applications.md](agent-applications.md)). That last is the only scope that acts for a person ([authorization.md → On behalf of a project admin](../behaviors/authorization.md#on-behalf-of-a-project-admin)). +It can tell staff that an account-claim request is waiting: it reads the +pending requests (which member, which GitHub login, when) but not the +requester's evidence, and it never approves or denies one; staff do that on +the [queue screen](../screens/staff-account-claim-queue.md). + The first agent is Code for Philly's ops bot. The site does not care what runs behind a grant; it cares that the grant is narrow, attributable and revocable. @@ -91,6 +96,7 @@ and a hard expiry. | `slack:link` | `POST /api/agent/slack-links`: redeem a member's linking code ([slack-link.md](slack-link.md)). | | `projects:applications:read` | `GET /api/agent/events`: application events with the offer text and the admins' linked Slack ids ([agent-applications.md](agent-applications.md)). | | `projects:applications:decide` | `POST /api/agent/applications/:projectSlug/:personSlug/decision`: accept or close an open application on a named, verified project admin's behalf. Requires `projects:applications:read` and `slack:link`. | +| `account-claims:read` | `GET /api/agent/account-claims`: the pending account-claim requests, reduced to what an alert needs, without the evidence or any address ([account-claim.md](account-claim.md#get-apiagentaccount-claims)). | There are no other scopes. A grant does not make its holder `user`, `self` or `staff` anywhere else ([authorization.md → Agent grants](../behaviors/authorization.md#agent-grants)). diff --git a/specs/behaviors/account-migration.md b/specs/behaviors/account-migration.md index ccb9617c..f09392e7 100644 --- a/specs/behaviors/account-migration.md +++ b/specs/behaviors/account-migration.md @@ -186,6 +186,14 @@ User provides the candidate's pre-cutover password — verified against `LegacyP User submits a claim request with the old slug + free-form proof. Staff reviews via side-channel and approves or denies. Same as today. +Requests wait on the [staff queue screen](../screens/staff-account-claim-queue.md), +which staff reach from the account menu with a count of pending requests. An +agent holding `account-claims:read` can read a reduced list of pending +requests, without the proof, to alert staff +([api/account-claim.md](../api/account-claim.md#get-apiagentaccount-claims)). +A request is only useful if someone looks at it soon: the requester cannot +sign in to their old account until it is decided. + These three proofs no longer gate first sign-in — they're only relevant for the manual "I have a duplicate account, merge it" case. An [agent account](../api/agents.md#the-agent-account) (a person with any diff --git a/specs/behaviors/app-shell.md b/specs/behaviors/app-shell.md index 9bc09407..8b739e9d 100644 --- a/specs/behaviors/app-shell.md +++ b/specs/behaviors/app-shell.md @@ -99,7 +99,18 @@ sheet. - "Sign out" → calls `POST /api/auth/logout`, redirects to `/` - **Staff:** Same dropdown plus a "Staff tools" section: - "Manage tags" → `/tags?staff=true` + - "Members roster" → `/admin/members` ([admin-members.md](../screens/admin-members.md)) + - "Account claims" → `/staff/account-claim` + ([staff-account-claim-queue.md](../screens/staff-account-claim-queue.md)), + followed by the number of pending requests when it is above zero + (from `GET /api/staff/account-claim/queue`, refreshed at most once a + minute and after each decision on the queue screen) - "Recent staff actions" → deferred placeholder + + While any request is pending, the account-menu button carries the same + count as a small badge, and its accessible name adds ", N account claims + pending", so a staff member sees a waiting request without opening the + menu. Members who are not staff never fetch the queue and never see either. - **Administrator:** Staff items plus "Admin" section: - "Manage members" → `/members?staff=true&accountLevel=all` diff --git a/specs/data-model.md b/specs/data-model.md index 4d8c0c4f..8cde6b31 100644 --- a/specs/data-model.md +++ b/specs/data-model.md @@ -207,14 +207,14 @@ 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/v2` (v2 adds the Slack and applications scopes) +**Contract:** `codeforphilly.org/agent-grants/v3` (v2 added the Slack and applications scopes; v3 adds `account-claims:read`) | Field | Type | Notes | | ------- | ------ | ------- | | id | uuid | | | personSlug | string | the agent account. Follows renames like other slug references. | | label | string | 1–80 chars; what and where (e.g. "ops bot, host vm-1") | -| scopes | string[] | from the scope table in [api/agents.md → Grants](api/agents.md#grants): `moderation:read`, `moderation:vote`, `moderation:purge`, `slack:link`, `projects:applications:read`, `projects:applications:decide`; `moderation:purge` requires `moderation:read`, `projects:applications:decide` requires `projects:applications:read` and `slack:link` | +| scopes | string[] | from the scope table in [api/agents.md → Grants](api/agents.md#grants): `moderation:read`, `moderation:vote`, `moderation:purge`, `slack:link`, `projects:applications:read`, `projects:applications:decide`, `account-claims:read`; `moderation:purge` requires `moderation:read`, `projects:applications:decide` requires `projects:applications:read` and `slack:link` | | createdAt | iso8601 | | | createdBySlug | string | the administrator who minted it | | expiresAt | iso8601 | at most 180 days after `createdAt` | diff --git a/specs/deferred.md b/specs/deferred.md index 22098357..06bb05e0 100644 --- a/specs/deferred.md +++ b/specs/deferred.md @@ -111,6 +111,11 @@ When a deferred item is promoted, move it from this file into the relevant spec, - **What:** Using the same verified Slack link and on-behalf-of pattern for other admin acts (stale-need reminders answered in Slack, staff review of new projects, the spam queue). - **Why deferred:** Each act needs its own scope and spec change ([authorization.md](behaviors/authorization.md#on-behalf-of-a-project-admin)); applications are the first. +### Denial email for account-claim requests + +- **What:** Emailing the requester the staff note when a claim request is denied ([api/account-claim.md](api/account-claim.md#post-apistaffaccount-claimrequestiddeny)). +- **Why deferred:** A pre-onboarding request stores no address for the requester, only the contact they wrote in their evidence. Sending one means keeping the requester's verified GitHub email on the request first. Until then staff reply through that contact, and the queue screen says so. + ### Project comments - **What:** Inline comments on project pages (the `Comment::class` references in laddr's Project model). Largely commented-out in the template even in laddr — the feature was half-built. diff --git a/specs/screens/staff-account-claim-queue.md b/specs/screens/staff-account-claim-queue.md new file mode 100644 index 00000000..c618c636 --- /dev/null +++ b/specs/screens/staff-account-claim-queue.md @@ -0,0 +1,124 @@ +# Screen: Staff account-claim queue + +## Route + +`/staff/account-claim` — staff and administrators. A signed-out visitor is +sent to `/login?return=/staff/account-claim`; any other signed-in member gets +the site's 404, as on [admin-members.md](admin-members.md). + +## Purpose + +A member who cannot sign in to their old account (dead email, lost password) +asks staff to connect it to their GitHub account +([account-claim.md](account-claim.md#account-claim-request-staff-review-sub-screen), +[account.md](account.md) for the post-onboarding merge). Each request waits +here until a staff member approves or denies it. + +Approving changes who can sign in as a member, so every card says in words +**which GitHub user wants to sign in as which member**, what approving will +do, and what the reviewer has to go on. A reviewer should never have to guess +which account a slug or a login refers to. + +## How staff find it + +- The account menu's staff tools list **Account claims**, beside **Members + roster**, with the number of pending requests when it is above zero + ([app-shell.md → Auth controls](../behaviors/app-shell.md#auth-controls)). +- The ops bot can alert staff when a request arrives: it reads + [`GET /api/agent/account-claims`](../api/account-claim.md#get-apiagentaccount-claims) + and links here. + +## Data Requirements + +- `GET /api/staff/account-claim/queue` on entry and after each decision +- `POST /api/staff/account-claim/:requestId/approve` / `.../deny` + +## Display Rules + +Heading "Account-claim queue". One sentence under it: "Each request asks to +connect a GitHub account to an existing member account. Check the note +against the member before you approve; approving lets that GitHub account +sign in as the member." + +Empty queue: a card "Nothing pending". + +Requests oldest first. Each card: + +### Title line + +The request in one sentence, with both sides linked: + +- Pre-onboarding: "GitHub user **@login** wants to sign in as **Full Name** + (`slug`)." +- Post-onboarding merge: "GitHub user **@login**, now signed in as **Full + Name** (`slug`), wants to merge into **Full Name** (`slug`)." + +`@login` links to `https://github.com/` (new tab). The member links to +`/members/`. When the claimed text resolves to no member, the member +part reads "the username ``" and no link. + +A small type label after the sentence: "link" for pre-onboarding, "merge" for +post-onboarding. The submitted time, relative with the absolute date on hover. + +### Facts about the claimed member + +When the claim resolves, one line of facts from `claimedPerson`: + +- "Member since {createdAt: MMM yyyy}" +- "Imported from the old site" when `imported`, else "Created on this site" +- "Member of N project(s)" +- "Not linked to GitHub" or, when `githubLogin` is set, "Already linked to + GitHub @{githubLogin}" + +### Warnings (one at most, above the note) + +- **No member:** "No member has this username. Approve is not possible; deny + it, and if you can tell who they are, reply through the contact in their + note." +- **Already linked:** "This member is already linked to GitHub @{login}. + Approve is not possible; deny it." +- **Agent account:** "This is an agent account. It cannot be claimed." + +### Requester's note + +The requester's free text (`evidence`), as written, under the label "Their +note". It may hold a contact address; it is private and never shown +elsewhere. + +### Decision + +- A one-line consequence above the buttons: + - Pre-onboarding: "Approve: @login signs in as `slug` from now on, with its + projects and history. The old password stops working." + - Merge: "Approve: `requester-slug` is merged into `slug` and deleted; its + projects and posts move to `slug`, and @login signs in as `slug`." +- A note field, labelled "Staff note (optional)", with help text under it: + "On approve, the note goes into the public commit log; keep private details + out. On deny, it is kept with the request and not sent to the requester; + reply to them yourself through the contact in their note." +- **Approve** (primary) and **Deny** (outline). Approve is disabled when a + warning above applies. Each button's accessible name names the request + ("Approve @login as slug"), since the page repeats them per card. + +## Actions + +| Action | API call | On success | +| ------ | -------- | ---------- | +| Approve | `POST /api/staff/account-claim/:requestId/approve { reason? }` | Toast "Claim approved"; refetch queue (the card leaves, the menu count drops) | +| Deny | `POST /api/staff/account-claim/:requestId/deny { reason? }` | Toast "Claim denied"; refetch queue | + +On an error the toast shows the API's message and the card stays. + +## Authorization + +Staff and administrators. The queue response holds private evidence, so the +page fetches nothing until the viewer is known to be staff. Agents never see +this page; the agent feed carries no evidence. + +## Coordinates with + +- [api/account-claim.md](../api/account-claim.md) +- [behaviors/account-migration.md](../behaviors/account-migration.md) +- [behaviors/app-shell.md](../behaviors/app-shell.md) +- [screens/account-claim.md](account-claim.md) +- [screens/admin-members.md](admin-members.md) From 663c249bfa80c16e1aec6741659c4243f592defd Mon Sep 17 00:00:00 2001 From: GrittyBot <30755786+codeforphilly-bot@users.noreply.github.com> Date: Tue, 1 Dec 2026 04:26:19 +0000 Subject: [PATCH 02/10] chore(plans): add claim-queue-clarity, in-progress Co-Authored-By: Claude Opus 5.5 --- plans/claim-queue-clarity.md | 78 ++++++++++++++++++++++++++++++++++++ 1 file changed, 78 insertions(+) create mode 100644 plans/claim-queue-clarity.md diff --git a/plans/claim-queue-clarity.md b/plans/claim-queue-clarity.md new file mode 100644 index 00000000..cdd8e3bb --- /dev/null +++ b/plans/claim-queue-clarity.md @@ -0,0 +1,78 @@ +--- +status: in-progress +depends: [account-claim, agent-application-feed] +specs: + - specs/api/account-claim.md + - specs/screens/staff-account-claim-queue.md + - specs/behaviors/app-shell.md + - specs/behaviors/account-migration.md + - specs/api/agents.md + - specs/data-model.md +awaits: + - "CodeForPhilly/codeforphilly-data — adopt agent-grants/v3 from the published URL and declare it on the agent-grants sheet, before a grant with account-claims:read can be minted" +--- + +# Plan: A claim queue staff can read, find and be told about + +## Scope + +A staff-review claim request sat a month. The queue page showed a slug and a +GitHub login with no words on what approving does; nothing linked to the page +or counted what waited there; and the ops bot could not see the requests to +alert anyone. + +**In:** + +- `GET /api/staff/account-claim/queue` gains `claimedPerson` (slug, name, + created, imported, GitHub link, project count, agent) and `requesterPerson`. +- The queue screen per its new spec: a sentence naming both sides with links, + the member's facts, one warning when approve cannot work, the consequence + of approve, and a note field that says truthfully where the note goes. +- "Account claims" in the account menu's staff tools with the pending count, + and a count badge on the menu button. +- Scope `account-claims:read` (agent-grants contract v3) and + `GET /api/agent/account-claims`, open requests reduced to what an alert + needs. + +**Out:** emailing a denial ([deferred](../specs/deferred.md#denial-email-for-account-claim-requests)); +email or Slack notices from the site; the claim flow itself; the bot's stream +(bot repo). + +## Implements + +- [api/account-claim.md](../specs/api/account-claim.md) — the queue fields, deny wording, the agent feed +- [screens/staff-account-claim-queue.md](../specs/screens/staff-account-claim-queue.md) +- [behaviors/app-shell.md](../specs/behaviors/app-shell.md) — Account claims in staff tools +- [api/agents.md](../specs/api/agents.md), [data-model.md](../specs/data-model.md) — the new scope + +## Approach + +- One resolver in `AccountClaimService` gives both feeds the same answer to + "does this request name a live member, and which": `claimedPersonId` to a + person that exists and is not deactivated. +- The agent route copies `/api/agent/events`: `agentScopeCaller` in + `preValidation` and again in the handler, `/api/agent/` prefix, response + built field by field from an allow-list. +- `claimedText` is passed only when it has slug shape, so a typed address + never leaves the site. +- The menu count reuses the queue query (same key) so a decision on the + queue screen updates it. +- `AGENT_SCOPES` gains the scope; contract `agent-grants/v3` generated and + vendored into `apps/api/gitsheets/` as the v2 change was. + +## Validation + +- [ ] Tests: the staff queue carries `claimedPerson` with the member's facts, `null` for an unresolved slug; `requesterPerson` for a merge +- [ ] Tests: the agent feed refuses a grant without the scope, a staff session and anonymous (401) +- [ ] Tests: the agent feed returns only the allowed keys, no evidence, no `@` anywhere, `claimedText` withheld when not slug-shaped +- [ ] Tests: minting a grant with `account-claims:read` works +- [ ] Web tests: a card names both sides with links, says when no member has the username, and disables Approve; the menu shows the count for staff only +- [ ] `check-contracts`, `npm run type-check && npm run lint && npm test` clean +- [ ] Browser check of the queue screen and menu +- [ ] In production: the data repo adopts agent-grants/v3 and the ops bot's grant gains the scope (awaited) + +## Risks / unknowns + +- **Contract order.** Until the data repo declares agent-grants/v3, minting a + grant with the new scope fails its contract there. Existing grants are + unaffected, so the site can deploy first. From ac5a8fab7807c041c8741e1e85f6514656067423 Mon Sep 17 00:00:00 2001 From: GrittyBot <30755786+codeforphilly-bot@users.noreply.github.com> Date: Tue, 1 Dec 2026 04:26:48 +0000 Subject: [PATCH 03/10] feat(shared): the account-claims:read agent scope, in agent-grants v3 AGENT_SCOPES gains account-claims:read, which lets an agent read the pending account-claim requests without their evidence. It has no companion scopes. agent-grants/v3 is generated and vendored into the API mirror (with gitsheets contracts adopt; provenance lands when the data repo adopts from the published URL), and the sheet declares v3. Co-Authored-By: Claude Opus 5.5 --- apps/api/gitsheets/agent-grants.toml | 2 +- .../codeforphilly.org/agent-grants/v3.toml | 46 +++++++++++++ .../codeforphilly.org/agent-grants/v3.json | 66 +++++++++++++++++++ packages/shared/src/contracts.ts | 5 +- packages/shared/src/schemas/agent-grant.ts | 1 + 5 files changed, 117 insertions(+), 3 deletions(-) create mode 100644 apps/api/gitsheets/contracts/codeforphilly.org/agent-grants/v3.toml create mode 100644 contracts/codeforphilly.org/agent-grants/v3.json diff --git a/apps/api/gitsheets/agent-grants.toml b/apps/api/gitsheets/agent-grants.toml index 105cdd92..e01b371c 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/v2"] +implements = ["codeforphilly.org/agent-grants/v3"] diff --git a/apps/api/gitsheets/contracts/codeforphilly.org/agent-grants/v3.toml b/apps/api/gitsheets/contracts/codeforphilly.org/agent-grants/v3.toml new file mode 100644 index 00000000..3ccb2d8f --- /dev/null +++ b/apps/api/gitsheets/contracts/codeforphilly.org/agent-grants/v3.toml @@ -0,0 +1,46 @@ +"$id" = "https://codeforphilly.org/agent-grants/v3" +"$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", "account-claims:read"] +type = "string" diff --git a/contracts/codeforphilly.org/agent-grants/v3.json b/contracts/codeforphilly.org/agent-grants/v3.json new file mode 100644 index 00000000..3436473b --- /dev/null +++ b/contracts/codeforphilly.org/agent-grants/v3.json @@ -0,0 +1,66 @@ +{ + "$schema": "http://json-schema.org/draft-07/schema#", + "$id": "https://codeforphilly.org/agent-grants/v3", + "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", + "account-claims:read" + ] + } + }, + "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 3afdb924..00e10130 100644 --- a/packages/shared/src/contracts.ts +++ b/packages/shared/src/contracts.ts @@ -66,8 +66,9 @@ 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' }, - // v2 adds the Slack and applications scopes (specs/api/agents.md → Grants). - 'agent-grants': { schema: AgentGrantSchema, version: 2, title: 'Agent grant' }, + // v2 added the Slack and applications scopes; v3 adds account-claims:read + // (specs/api/agents.md → Grants). + 'agent-grants': { schema: AgentGrantSchema, version: 3, 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 a07f8eac..63bcdd0b 100644 --- a/packages/shared/src/schemas/agent-grant.ts +++ b/packages/shared/src/schemas/agent-grant.ts @@ -18,6 +18,7 @@ export const AGENT_SCOPES = [ 'slack:link', 'projects:applications:read', 'projects:applications:decide', + 'account-claims:read', ] as const; export type AgentScope = (typeof AGENT_SCOPES)[number]; From b9c667ec3515eebab134a3e8482a32e466ea3bc3 Mon Sep 17 00:00:00 2001 From: GrittyBot <30755786+codeforphilly-bot@users.noreply.github.com> Date: Tue, 1 Dec 2026 04:29:50 +0000 Subject: [PATCH 04/10] feat(api): member facts on the claim queue, and GET /api/agent/account-claims The staff queue now says which member a request would act on, as it stands now (name, created, imported, existing GitHub link, project count, agent), and for a merge which account would be merged away. Both feeds share one resolver, the same one approve's refusal follows. The agent feed lists open requests for a grant with account-claims:read, built field by field: request id, type, submitted time, the typed username (withheld when it is not username-shaped, so a typed address stays private), whether it resolves and to which slug, and the requester's GitHub login. No evidence, note, address or person id. The tests also pin where a staff note goes: an approve note lands in the public commit's Reason trailer, a deny note never reaches the log. Co-Authored-By: Claude Opus 5.5 --- apps/api/src/app.ts | 2 + apps/api/src/routes/account-claim.ts | 14 +- apps/api/src/routes/agent-account-claims.ts | 34 +++ apps/api/src/services/account-claim.ts | 109 +++++++++ apps/api/tests/agent-account-claims.test.ts | 245 ++++++++++++++++++++ apps/api/tests/helpers/agent-fixtures.ts | 7 + 6 files changed, 398 insertions(+), 13 deletions(-) create mode 100644 apps/api/src/routes/agent-account-claims.ts create mode 100644 apps/api/tests/agent-account-claims.test.ts diff --git a/apps/api/src/app.ts b/apps/api/src/app.ts index e3b28c21..b30a6406 100644 --- a/apps/api/src/app.ts +++ b/apps/api/src/app.ts @@ -70,6 +70,7 @@ 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 { agentAccountClaimRoutes } from './routes/agent-account-claims.js'; import { webhookRoutes } from './routes/webhooks.js'; import { samlRoutes } from './routes/saml.js'; import { internalRoutes } from './routes/internal.js'; @@ -227,6 +228,7 @@ export async function buildApp(opts: BuildAppOptions = {}): Promise { requireAuth(request, ['staff']); - const items = await fastify.services.accountClaim.staffQueue(); - return ok( - items.map((r) => ({ - requestId: r.id, - type: r.type, - claimedSlug: r.claimedSlug, - claimedPersonId: r.claimedPersonId, - requesterGithubLogin: r.requesterGithubLogin, - requesterPersonId: r.requesterPersonId, - evidence: r.evidence, - submittedAt: r.submittedAt, - })), - ); + return ok(await fastify.services.accountClaim.staffQueueView()); }, ); diff --git a/apps/api/src/routes/agent-account-claims.ts b/apps/api/src/routes/agent-account-claims.ts new file mode 100644 index 00000000..e223a4f0 --- /dev/null +++ b/apps/api/src/routes/agent-account-claims.ts @@ -0,0 +1,34 @@ +/** + * Agent account-claim feed — specs/api/account-claim.md → GET /api/agent/account-claims. + * + * GET /api/agent/account-claims — agent:account-claims:read + * + * The pending claim requests, reduced to what an alert needs: which member, + * which GitHub login, when. Never the evidence, the staff note, an address, + * or anything from a private profile. As for /api/agent/events, the scope is + * checked before anything else, and 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 agentAccountClaimRoutes(fastify: FastifyInstance): Promise { + fastify.get( + '/api/agent/account-claims', + { + preValidation: async (request) => { + agentScopeCaller(request, 'account-claims:read'); + }, + schema: { + tags: ['account-claim'], + summary: 'Pending account-claim requests, without their evidence (agent:account-claims:read)', + }, + }, + async (request) => { + agentScopeCaller(request, 'account-claims:read'); + const data = await fastify.services.accountClaim.agentQueueView(); + return { success: true, data, metadata: { timestamp: new Date().toISOString(), count: data.length } }; + }, + ); +} diff --git a/apps/api/src/services/account-claim.ts b/apps/api/src/services/account-claim.ts index bfa7ee3d..64fd66a1 100644 --- a/apps/api/src/services/account-claim.ts +++ b/apps/api/src/services/account-claim.ts @@ -101,6 +101,51 @@ export interface StaffDenyResult { readonly request: AccountClaimRequest; } +/** The claimed member as a reviewer sees it (specs/api/account-claim.md → staff queue). */ +export interface ClaimedPersonFacts { + readonly slug: string; + readonly fullName: string; + readonly createdAt: string; + /** Carried over from the old site (`legacyId` set). */ + readonly imported: boolean; + /** The GitHub login the member is already linked to, or null. */ + readonly githubLogin: string | null; + readonly memberOfCount: number; + readonly isAgent: boolean; +} + +/** One row of GET /api/staff/account-claim/queue. Staff only: carries the evidence. */ +export interface StaffQueueItem { + readonly requestId: string; + readonly type: AccountClaimRequest['type']; + readonly claimedSlug: string; + readonly claimedPersonId: string | null; + readonly claimedPerson: ClaimedPersonFacts | null; + readonly requesterGithubLogin: string; + readonly requesterPersonId: string | null; + readonly requesterPerson: { slug: string; fullName: string; createdAt: string } | null; + readonly evidence: string; + readonly submittedAt: string; +} + +/** + * One row of GET /api/agent/account-claims: what an alert needs and nothing + * private. Built field by field; never spread from a request record. + */ +export interface AgentClaimItem { + readonly requestId: string; + readonly type: AccountClaimRequest['type']; + readonly submittedAt: string; + /** The typed text, only when it has the shape of a username. */ + readonly claimedText: string | null; + readonly resolves: boolean; + readonly claimedPersonSlug: string | null; + readonly requesterGithubLogin: string; +} + +/** Username shape (specs/behaviors/slug-handles.md), any case: what may leave the site as typed. */ +const USERNAME_SHAPE = /^[a-z0-9][a-z0-9-]{1,49}$/i; + /** Reconstruct a ResolvedGitHubIdentity from the claim-pending JWT claims. */ export function ghIdentityFromClaim(claims: ClaimPendingClaims): ResolvedGitHubIdentity { const id = Number(claims.sub); @@ -414,6 +459,70 @@ export class AccountClaimService { return all.slice().sort((a, b) => a.submittedAt.localeCompare(b.submittedAt)); } + /** + * The member a request would act on, as it stands now: `claimedPersonId` + * to a person that exists and is not deactivated. Null exactly when + * staffApprove would refuse with `no_claimed_person`. + */ + resolveClaimed(r: AccountClaimRequest): Person | null { + if (!r.claimedPersonId) return null; + const p = this.#state.people.get(r.claimedPersonId); + return p && !p.deletedAt ? p : null; + } + + /** The staff queue with what a reviewer needs (specs/api/account-claim.md). */ + async staffQueueView(): Promise { + return (await this.staffQueue()).map((r) => { + const claimed = this.resolveClaimed(r); + const requester = r.requesterPersonId ? this.#state.people.get(r.requesterPersonId) : undefined; + return { + requestId: r.id, + type: r.type, + claimedSlug: r.claimedSlug, + claimedPersonId: r.claimedPersonId, + claimedPerson: claimed + ? { + slug: claimed.slug, + fullName: claimed.fullName, + createdAt: claimed.createdAt, + imported: claimed.legacyId != null, + githubLogin: claimed.githubUserId ? (claimed.githubLogin ?? null) : null, + memberOfCount: membershipsOfPerson(this.#state, claimed.slug).filter((m) => m.state === 'member').length, + isAgent: isAgentAccount(this.#state, claimed.slug), + } + : null, + requesterGithubLogin: r.requesterGithubLogin, + requesterPersonId: r.requesterPersonId, + requesterPerson: + requester && !requester.deletedAt + ? { slug: requester.slug, fullName: requester.fullName, createdAt: requester.createdAt } + : null, + evidence: r.evidence, + submittedAt: r.submittedAt, + }; + }); + } + + /** + * The pending requests reduced for an agent's alert: no evidence, no staff + * note, no ids beyond the request's, nothing from a private profile. + */ + async agentQueueView(): Promise { + return (await this.staffQueue()).map((r) => { + const claimed = this.resolveClaimed(r); + const typed = r.claimedSlug.trim(); + return { + requestId: r.id, + type: r.type, + submittedAt: r.submittedAt, + claimedText: USERNAME_SHAPE.test(typed) ? typed : null, + resolves: claimed !== null, + claimedPersonSlug: claimed?.slug ?? null, + requesterGithubLogin: r.requesterGithubLogin, + }; + }); + } + /** Mark a request denied. */ async staffDeny( tx: DualStoreTx, diff --git a/apps/api/tests/agent-account-claims.test.ts b/apps/api/tests/agent-account-claims.test.ts new file mode 100644 index 00000000..224384d7 --- /dev/null +++ b/apps/api/tests/agent-account-claims.test.ts @@ -0,0 +1,245 @@ +/** + * The account-claim queue for staff and for agents (plans/claim-queue-clarity.md, + * specs/api/account-claim.md → staff queue and GET /api/agent/account-claims): + * the staff queue's member facts, the agent feed's scope, its allow-listed + * fields with no evidence and no address, and where a staff note ends up. + * + * Every person, login and address here is invented; addresses are example.org. + */ +import { afterAll, beforeAll, describe, expect, it } from 'vitest'; + +import { issueClaimPending } from '../src/auth/jwt.js'; +import { + JWT_KEY, + bearer, + createAgent, + daysAgo, + fid, + personRecord, + privateProfile, + startAgentTestEnv, + type AgentTestEnv, + type Rec, +} from './helpers/agent-fixtures.js'; + +const P = { root: 1, sam: 2, oldie: 3, merger: 4, fresh: 5, linked: 6, gone: 7 }; +const T = '2026-05-01T00:00:00.000Z'; +const R = { old: fid(901), nobody: fid(902), address: fid(903), merge: fid(904), linked: fid(905), gone: fid(906), denied: fid(907) }; +const SECRET = 'evidence-marker-do-not-leak'; + +function claim(id: string, over: Rec): Rec { + return { + id, + type: 'pre-onboarding', + claimedPersonId: null, + claimedSlug: 'x', + requesterGithubLogin: 'someone-gh', + requesterGithubId: 70000 + Number(id.slice(-3)), + requesterPersonId: null, + evidence: `${SECRET}: I worked on the example project; write to me at private-${id.slice(-3)}@example.org`, + status: 'open', + submittedAt: T, + reviewedAt: null, + reviewedBy: null, + reviewedReason: null, + ...over, + }; +} + +const CLAIMS: Rec[] = [ + claim(R.merge, { type: 'post-onboarding-merge', claimedSlug: 'merger', claimedPersonId: fid(P.merger), requesterGithubLogin: 'fresh-gh', requesterGithubId: 5005, requesterPersonId: fid(P.fresh), submittedAt: daysAgo(3) }), + claim(R.old, { claimedSlug: 'oldie', claimedPersonId: fid(P.oldie), requesterGithubLogin: 'oldie-gh', submittedAt: daysAgo(10) }), + claim(R.nobody, { claimedSlug: 'Nobody-Here', submittedAt: daysAgo(9) }), + claim(R.address, { claimedSlug: 'old.address@example.org', submittedAt: daysAgo(8) }), + claim(R.linked, { claimedSlug: 'linked', claimedPersonId: fid(P.linked), submittedAt: daysAgo(7) }), + claim(R.gone, { claimedSlug: 'gone', claimedPersonId: fid(P.gone), submittedAt: daysAgo(6) }), + claim(R.denied, { claimedSlug: 'oldie', claimedPersonId: fid(P.oldie), status: 'denied', reviewedAt: daysAgo(1), reviewedBy: fid(P.sam), reviewedReason: 'no' }), +]; + +function records(): Record { + return { + people: [ + personRecord(P.root, 'root', { accountLevel: 'administrator' }), + personRecord(P.sam, 'sam', { accountLevel: 'staff' }), + personRecord(P.oldie, 'oldie', { legacyId: 4242, createdAt: '2017-03-02T00:00:00.000Z' }), + personRecord(P.merger, 'merger', { legacyId: 4343 }), + personRecord(P.fresh, 'fresh', { createdAt: daysAgo(20), githubUserId: 5005, githubLogin: 'fresh-gh' }), + personRecord(P.linked, 'linked', { githubUserId: 6006, githubLogin: 'linked-gh' }), + personRecord(P.gone, 'gone', { deletedAt: daysAgo(2) }), + ], + projects: [{ id: fid(50), slug: 'proj', title: 'Project Proj', stage: 'testing', featured: false, createdAt: T, updatedAt: T }], + 'project-memberships': [ + { id: fid(60), projectSlug: 'proj', personSlug: 'oldie', state: 'member', isAdmin: false, muted: false, via: 'legacy', joinedAt: T, followedAt: T, createdAt: T, updatedAt: T }, + ], + }; +} + +const PROFILES = Object.entries(P).map(([slug, k]) => privateProfile(fid(k), `${slug}-profile@example.org`)); + +interface StaffItem { + requestId: string; + type: string; + claimedSlug: string; + claimedPerson: null | { slug: string; fullName: string; createdAt: string; imported: boolean; githubLogin: string | null; memberOfCount: number; isAgent: boolean }; + requesterGithubLogin: string; + requesterPerson: null | { slug: string; fullName: string; createdAt: string }; + evidence: string; +} + +interface AgentItem { + requestId: string; + type: string; + submittedAt: string; + claimedText: string | null; + resolves: boolean; + claimedPersonSlug: string | null; + requesterGithubLogin: string; +} + +describe('account-claim queue: staff view and agent feed', () => { + let env: AgentTestEnv; + let token: string; + let staff: string; + + beforeAll(async () => { + env = await startAgentTestEnv({ + records: records(), + profiles: PROFILES, + privateFiles: { 'account-claim-requests.jsonl': CLAIMS }, + }); + // Minting a grant with the new scope works (agent-grants v3). + token = (await createAgent(env, await env.cookie(P.root, 'administrator'), { slug: 'example-bot', scopes: ['account-claims:read'] })).token; + staff = await env.cookie(P.sam, 'staff'); + }, 60_000); + afterAll(async () => { + await env.close(); + }); + + const staffQueue = async () => { + const res = await env.app.inject({ method: 'GET', url: '/api/staff/account-claim/queue', cookies: { cfp_session: staff } }); + expect(res.statusCode, res.body).toBe(200); + return res.json<{ data: StaffItem[] }>().data; + }; + + it("gives staff the claimed member's facts, null when the claim names no live member", async () => { + const data = await staffQueue(); + expect(data.map((d) => d.requestId)).toEqual([R.old, R.nobody, R.address, R.linked, R.gone, R.merge]); + const by = new Map(data.map((d) => [d.requestId, d])); + expect(by.get(R.old)!.claimedPerson).toEqual({ + slug: 'oldie', + fullName: 'Test oldie', + createdAt: '2017-03-02T00:00:00.000Z', + imported: true, + githubLogin: null, + memberOfCount: 1, + isAgent: false, + }); + expect(by.get(R.old)!.requesterPerson).toBeNull(); + expect(by.get(R.nobody)!.claimedPerson).toBeNull(); + expect(by.get(R.address)!.claimedPerson).toBeNull(); + expect(by.get(R.gone)!.claimedPerson).toBeNull(); + expect(by.get(R.linked)!.claimedPerson).toMatchObject({ slug: 'linked', imported: false, githubLogin: 'linked-gh' }); + expect(by.get(R.merge)!.claimedPerson).toMatchObject({ slug: 'merger', imported: true }); + expect(by.get(R.merge)!.requesterPerson).toEqual({ slug: 'fresh', fullName: 'Test fresh', createdAt: expect.any(String) }); + // Staff still see the evidence; that is what they review. + expect(by.get(R.old)!.evidence).toContain(SECRET); + }); + + it('marks a claim naming an agent account as one in the staff view', async () => { + const claimToken = await issueClaimPending({ ghId: '8008', ghLogin: 'example-bot', ghName: 'Someone', ghEmails: [] }, [], JWT_KEY); + const sent = await env.app.inject({ + method: 'POST', + url: '/api/account-claim/request-staff-review', + remoteAddress: '10.9.0.1', + cookies: { cfp_claim: claimToken }, + payload: { claimedSlug: 'example-bot', evidence: 'That bot is me.' }, + }); + expect(sent.statusCode, sent.body).toBe(202); + const item = (await staffQueue()).find((i) => i.claimedSlug === 'example-bot'); + expect(item?.claimedPerson).toMatchObject({ slug: 'example-bot', isAgent: true }); + // Leave the queue as the other tests expect it. + const deny = await env.app.inject({ method: 'POST', url: `/api/staff/account-claim/${item!.requestId}/deny`, cookies: { cfp_session: staff }, payload: {} }); + expect(deny.statusCode, deny.body).toBe(200); + }); + + it('refuses the agent feed without the scope: another scope, staff, a member, anonymous (401)', async () => { + const other = (await createAgent(env, await env.cookie(P.root, 'administrator'), { slug: 'other-bot', scopes: ['moderation:read'] })).token; + const url = '/api/agent/account-claims'; + expect((await env.app.inject({ method: 'GET', url, ...bearer(other) })).statusCode).toBe(401); + expect((await env.app.inject({ method: 'GET', url, cookies: { cfp_session: staff } })).statusCode).toBe(401); + expect((await env.app.inject({ method: 'GET', url, cookies: { cfp_session: await env.cookie(P.root, 'administrator') } })).statusCode).toBe(401); + expect((await env.app.inject({ method: 'GET', url, cookies: { cfp_session: await env.cookie(P.oldie, 'user') } })).statusCode).toBe(401); + expect((await env.app.inject({ method: 'GET', url })).statusCode).toBe(401); + }); + + it('does not let the scope reach the staff queue', async () => { + const res = await env.app.inject({ method: 'GET', url: '/api/staff/account-claim/queue', ...bearer(token) }); + expect(res.statusCode).not.toBe(200); + expect(res.body).not.toContain(SECRET); + }); + + it('lists open requests oldest first with only the allowed fields', async () => { + const res = await env.app.inject({ method: 'GET', url: '/api/agent/account-claims', ...bearer(token) }); + expect(res.statusCode, res.body).toBe(200); + const body = res.json<{ data: AgentItem[]; metadata: { count: number; timestamp: string } }>(); + expect(body.metadata.count).toBe(6); + expect(body.data.map((d) => d.requestId)).toEqual([R.old, R.nobody, R.address, R.linked, R.gone, R.merge]); + + const allowed = ['requestId', 'type', 'submittedAt', 'claimedText', 'resolves', 'claimedPersonSlug', 'requesterGithubLogin']; + for (const item of body.data) expect(Object.keys(item).sort()).toEqual([...allowed].sort()); + + const by = new Map(body.data.map((d) => [d.requestId, d])); + expect(by.get(R.old)).toEqual({ + requestId: R.old, + type: 'pre-onboarding', + submittedAt: CLAIMS[1]!['submittedAt'], + claimedText: 'oldie', + resolves: true, + claimedPersonSlug: 'oldie', + requesterGithubLogin: 'oldie-gh', + }); + expect(by.get(R.nobody)).toMatchObject({ claimedText: 'Nobody-Here', resolves: false, claimedPersonSlug: null }); + expect(by.get(R.gone)).toMatchObject({ resolves: false, claimedPersonSlug: null }); + expect(by.get(R.merge)).toMatchObject({ type: 'post-onboarding-merge', resolves: true, claimedPersonSlug: 'merger', requesterGithubLogin: 'fresh-gh' }); + // A typed address is withheld, not passed through. + expect(by.get(R.address)).toMatchObject({ claimedText: null, resolves: false }); + }); + + it('carries no evidence, no address, no private-profile data and no person ids', async () => { + const res = await env.app.inject({ method: 'GET', url: '/api/agent/account-claims', ...bearer(token) }); + expect(res.statusCode).toBe(200); + expect(res.body).not.toContain(SECRET); + expect(res.body).not.toMatch(/@/); + expect(res.body).not.toMatch(/example\.org/); + expect(res.body).not.toMatch(/evidence|email|reason|reviewed/i); + for (const k of Object.values(P)) expect(res.body).not.toContain(fid(k)); + expect(res.body).not.toContain('5005'); + }); + + it('keeps a deny note out of the public log, and puts an approve note in it', async () => { + const deny = await env.app.inject({ + method: 'POST', + url: `/api/staff/account-claim/${R.nobody}/deny`, + cookies: { cfp_session: staff }, + payload: { reason: 'deny-note-marker' }, + }); + expect(deny.statusCode, deny.body).toBe(200); + const approve = await env.app.inject({ + method: 'POST', + url: `/api/staff/account-claim/${R.old}/approve`, + cookies: { cfp_session: staff }, + payload: { reason: 'approve-note-marker' }, + }); + expect(approve.statusCode, approve.body).toBe(200); + const log = await env.git('log', '--all', '--format=%B'); + expect(log).not.toContain('deny-note-marker'); + expect(log).toContain('Reason: approve-note-marker'); + + // Decided requests leave both feeds. + const res = await env.app.inject({ method: 'GET', url: '/api/agent/account-claims', ...bearer(token) }); + const ids = res.json<{ data: AgentItem[] }>().data.map((d) => d.requestId); + expect(ids).not.toContain(R.old); + expect(ids).not.toContain(R.nobody); + expect((await staffQueue()).map((d) => d.requestId)).not.toContain(R.old); + }); +}); diff --git a/apps/api/tests/helpers/agent-fixtures.ts b/apps/api/tests/helpers/agent-fixtures.ts index 6c4f8f93..c2e539b7 100644 --- a/apps/api/tests/helpers/agent-fixtures.ts +++ b/apps/api/tests/helpers/agent-fixtures.ts @@ -58,6 +58,8 @@ export interface AgentTestEnv { export async function startAgentTestEnv(opts: { records: Record; profiles?: Rec[]; + /** Other private-store files, by name (e.g. `account-claim-requests.jsonl`), one JSON line per record. */ + privateFiles?: Record; env?: Record; /** A logger for the app (default: none), e.g. one writing to a capture stream. */ logger?: FastifyServerOptions['logger']; @@ -81,6 +83,11 @@ export async function startAgentTestEnv(opts: { opts.profiles.map((p) => JSON.stringify(p)).join('\n') + '\n', ); } + for (const [name, recs] of Object.entries(opts.privateFiles ?? {})) { + const { writeFile } = await import('node:fs/promises'); + const { join } = await import('node:path'); + await writeFile(join(privateStore.path, name), recs.map((r) => JSON.stringify(r)).join('\n') + '\n'); + } const app = await buildApp({ serverOptions: { logger: opts.logger ?? false }, overrideEnv: { From b8327990b2a06b1b9bdc30677ec15b063f4c184c Mon Sep 17 00:00:00 2001 From: GrittyBot <30755786+codeforphilly-bot@users.noreply.github.com> Date: Tue, 1 Dec 2026 04:34:42 +0000 Subject: [PATCH 05/10] docs(specs): no approve consequence line under a warning; plan names the contract lockstep The queue card shows what approve does only when approve is possible. The plan's awaits and risks now say what the data repo must do and when: the API opens agent-grants in declared mode, so v3 is adopted on empty, fixture and legacy-import with this PR and on published at release time. Co-Authored-By: Claude Opus 5.5 --- plans/claim-queue-clarity.md | 12 ++++++++---- specs/screens/staff-account-claim-queue.md | 3 ++- 2 files changed, 10 insertions(+), 5 deletions(-) diff --git a/plans/claim-queue-clarity.md b/plans/claim-queue-clarity.md index cdd8e3bb..f5a88925 100644 --- a/plans/claim-queue-clarity.md +++ b/plans/claim-queue-clarity.md @@ -9,7 +9,8 @@ specs: - specs/api/agents.md - specs/data-model.md awaits: - - "CodeForPhilly/codeforphilly-data — adopt agent-grants/v3 from the published URL and declare it on the agent-grants sheet, before a grant with account-claims:read can be minted" + - "CodeForPhilly/codeforphilly-data — adopt agent-grants/v3 on empty, fixture and legacy-import from this PR's published contract URL and declare it on the agent-grants sheet; adopt on published at release time (docs/operations/releases.md)" + - "Ops bot's grant re-minted with account-claims:read, and a bot stream that reads GET /api/agent/account-claims (bot repo)" --- # Plan: A claim queue staff can read, find and be told about @@ -73,6 +74,9 @@ email or Slack notices from the site; the claim flow itself; the bot's stream ## Risks / unknowns -- **Contract order.** Until the data repo declares agent-grants/v3, minting a - grant with the new scope fails its contract there. Existing grants are - unaffected, so the site can deploy first. +- **Contract lockstep.** The API opens `agent-grants` in declared mode, so a + build carrying v3 does not boot against a branch that still declares v2, + and the reverse. The data repo adopts v3 on `empty`, `fixture` and + `legacy-import` while this PR is open (then the mirror's `sources.toml` + gains the v3 provenance), and on `published` right before the release + deploys ([releases.md](../docs/operations/releases.md#releases-that-change-a-schema-contract)). diff --git a/specs/screens/staff-account-claim-queue.md b/specs/screens/staff-account-claim-queue.md index c618c636..25c919a4 100644 --- a/specs/screens/staff-account-claim-queue.md +++ b/specs/screens/staff-account-claim-queue.md @@ -87,7 +87,8 @@ elsewhere. ### Decision -- A one-line consequence above the buttons: +- A one-line consequence above the buttons (left out when a warning + applies, since approve is then off and the warning says why): - Pre-onboarding: "Approve: @login signs in as `slug` from now on, with its projects and history. The old password stops working." - Merge: "Approve: `requester-slug` is merged into `slug` and deleted; its From 427bf4ec90c660eceff2f21044473b27269dcda1 Mon Sep 17 00:00:00 2001 From: GrittyBot <30755786+codeforphilly-bot@users.noreply.github.com> Date: Tue, 1 Dec 2026 04:38:44 +0000 Subject: [PATCH 06/10] feat(web): a claim queue that says who becomes whom, linked from the menu with a count Each queue card now reads as a sentence: GitHub user @login (linked to GitHub) wants to sign in as Full Name (slug) (linked to the member page), or, for a merge, which account would be merged away. Under it, the member's facts (member since, imported or not, projects, GitHub link), one warning when approve is not possible (no member has the username, already linked, an agent account), and one line on what approve does. The staff note field says where the note goes: into the public commit on approve, kept privately and not emailed on deny. The account menu's staff tools gain "Account claims" beside the members roster, with the pending count, and the menu button carries the count while any request waits. Members who are not staff never fetch the queue; the queue page sends them to the 404 page like the roster does. The mint form offers account-claims:read. Co-Authored-By: Claude Opus 5.5 --- apps/web/src/components/AppHeader.tsx | 48 ++- apps/web/src/components/admin/AgentsPanel.tsx | 2 + apps/web/src/lib/api.ts | 23 +- apps/web/src/pages/StaffAccountClaimQueue.tsx | 301 ++++++++++++------ apps/web/tests/AppHeader.test.tsx | 80 ++++- .../web/tests/StaffAccountClaimQueue.test.tsx | 178 +++++++++++ 6 files changed, 524 insertions(+), 108 deletions(-) create mode 100644 apps/web/tests/StaffAccountClaimQueue.test.tsx diff --git a/apps/web/src/components/AppHeader.tsx b/apps/web/src/components/AppHeader.tsx index 56e7021d..9731786c 100644 --- a/apps/web/src/components/AppHeader.tsx +++ b/apps/web/src/components/AppHeader.tsx @@ -1,5 +1,6 @@ import { useState } from 'react'; import { Link, NavLink, useLocation } from 'react-router'; +import { useQuery } from '@tanstack/react-query'; import { Button } from '@/components/ui/button'; import { DropdownMenu, @@ -21,6 +22,7 @@ import { SearchBox } from '@/components/SearchBox'; import { GitHubIcon } from '@/components/icons/GitHubIcon'; import { SlackIcon } from '@/components/icons/SlackIcon'; import { useAuth } from '@/hooks/useAuth'; +import { api, CLAIM_QUEUE_KEY } from '@/lib/api'; const GITHUB_URL = 'https://github.com/CodeForPhilly'; @@ -64,8 +66,25 @@ function MenuIcon() { ); } +/** + * Pending account-claim requests, for staff only (specs/behaviors/app-shell.md + * → Auth controls). Shares the queue screen's query, so a decision there + * updates the count. Members who are not staff never fetch it. + */ +function usePendingClaimCount(isStaff: boolean): number { + const q = useQuery({ + queryKey: CLAIM_QUEUE_KEY, + queryFn: () => api.staffAccountClaim.queue(), + enabled: isStaff, + staleTime: 60_000, + }); + return isStaff ? (q.data?.data.length ?? 0) : 0; +} + function AuthControls({ mobile = false }: { mobile?: boolean }) { const { person, loading, signOut } = useAuth(); + const isStaff = person?.accountLevel === 'staff' || person?.accountLevel === 'administrator'; + const pendingClaims = usePendingClaimCount(isStaff); if (loading) { return ( @@ -93,7 +112,9 @@ function AuthControls({ mobile = false }: { mobile?: boolean }) { variant="ghost" size="sm" className={`flex items-center gap-2 ${mobile ? 'w-full justify-start' : ''}`} - aria-label={`Account menu for ${person.fullName}`} + aria-label={`Account menu for ${person.fullName}${ + pendingClaims > 0 ? `, ${pendingClaims} account claim${pendingClaims === 1 ? '' : 's'} pending` : '' + }`} > {person.avatarUrl ? ( )} {person.fullName} + {pendingClaims > 0 && ( + + )} @@ -131,6 +160,23 @@ function AuthControls({ mobile = false }: { mobile?: boolean }) { Members roster + + 0 ? `Account claims, ${pendingClaims} pending` : undefined} + > + Account claims + {pendingClaims > 0 && ( + + )} + + Recent staff actions diff --git a/apps/web/src/components/admin/AgentsPanel.tsx b/apps/web/src/components/admin/AgentsPanel.tsx index 9bd4117d..ce34ce8e 100644 --- a/apps/web/src/components/admin/AgentsPanel.tsx +++ b/apps/web/src/components/admin/AgentsPanel.tsx @@ -219,6 +219,7 @@ const SCOPE_LABEL: Record = { 'slack:link': 'link members’ Slack accounts', 'projects:applications:read': 'read application events', 'projects:applications:decide': 'record an admin’s accept or close', + 'account-claims:read': 'see pending account claims (no evidence)', }; /** Mint form + the purge second confirm + the token-once dialog. */ @@ -242,6 +243,7 @@ function MintGrantDialog({ 'slack:link': false, 'projects:applications:read': false, 'projects:applications:decide': false, + 'account-claims:read': false, }); const [confirmPurge, setConfirmPurge] = useState(false); const mint = useMutation({ diff --git a/apps/web/src/lib/api.ts b/apps/web/src/lib/api.ts index d2c9193d..aaec77c4 100644 --- a/apps/web/src/lib/api.ts +++ b/apps/web/src/lib/api.ts @@ -801,13 +801,33 @@ export interface AccountClaimSessionResult { readonly accountLevel: 'user' | 'staff' | 'administrator'; } +/** + * The react-query key for the staff claim queue, shared by the queue screen + * and the account menu's pending count so a decision updates both. + */ +export const CLAIM_QUEUE_KEY = ['staff-account-claim-queue'] as const; + +/** GET /api/staff/account-claim/queue — specs/api/account-claim.md → staff queue. */ export interface AccountClaimQueueItem { readonly requestId: string; readonly type: 'pre-onboarding' | 'post-onboarding-merge'; + /** The text the requester typed. */ readonly claimedSlug: string; readonly claimedPersonId: string | null; + /** The member approve would act on, as it stands now; null when none (approve refuses). */ + readonly claimedPerson: { + readonly slug: string; + readonly fullName: string; + readonly createdAt: string; + readonly imported: boolean; + readonly githubLogin: string | null; + readonly memberOfCount: number; + readonly isAgent: boolean; + } | null; readonly requesterGithubLogin: string; readonly requesterPersonId: string | null; + /** For a merge: the account approve merges away. */ + readonly requesterPerson: { readonly slug: string; readonly fullName: string; readonly createdAt: string } | null; readonly evidence: string; readonly submittedAt: string; } @@ -949,7 +969,8 @@ export type AgentScope = | 'moderation:purge' | 'slack:link' | 'projects:applications:read' - | 'projects:applications:decide'; + | 'projects:applications:decide' + | 'account-claims:read'; /** POST /api/account/slack-link/code — specs/api/slack-link.md. */ export interface SlackLinkCode { diff --git a/apps/web/src/pages/StaffAccountClaimQueue.tsx b/apps/web/src/pages/StaffAccountClaimQueue.tsx index 18ae752d..c5ea6017 100644 --- a/apps/web/src/pages/StaffAccountClaimQueue.tsx +++ b/apps/web/src/pages/StaffAccountClaimQueue.tsx @@ -1,5 +1,11 @@ +/** + * /staff/account-claim — the staff queue of account-claim requests + * (specs/screens/staff-account-claim-queue.md). Each card says which GitHub + * user wants to sign in as which member, what approving does, and what the + * reviewer has to go on. + */ import { useEffect, useState } from 'react'; -import { useNavigate } from 'react-router'; +import { Link, useNavigate } from 'react-router'; import { useQuery, useQueryClient } from '@tanstack/react-query'; import { toast } from 'sonner'; import { @@ -13,30 +19,119 @@ import { Button } from '@/components/ui/button'; import { Textarea } from '@/components/ui/textarea'; import { Label } from '@/components/ui/label'; import { useAuth } from '@/hooks/useAuth'; -import { api, ApiError } from '@/lib/api'; -import { formatAbsoluteDate, formatRelativeTime } from '@/lib/time'; +import { api, ApiError, CLAIM_QUEUE_KEY, type AccountClaimQueueItem } from '@/lib/api'; +import { formatAbsoluteDate, formatMonthYear, formatRelativeTime } from '@/lib/time'; + +const isStaffLevel = (level: string) => level === 'staff' || level === 'administrator'; + +function GitHubUser({ login }: { login: string }) { + return ( + + @{login} + + ); +} + +function Member({ slug, fullName }: { slug: string; fullName: string }) { + return ( + <> + + {fullName} + {' '} + ({slug}) + + ); +} + +/** The request in one sentence, both sides linked. */ +function RequestSentence({ item }: { item: AccountClaimQueueItem }) { + const target = item.claimedPerson ? ( + + ) : ( + <> + the username {item.claimedSlug} + + ); + if (item.type === 'post-onboarding-merge') { + return ( + <> + GitHub user + {item.requesterPerson && ( + <> + , now signed in as{' '} + , + + )}{' '} + wants to merge into {target}. + + ); + } + return ( + <> + GitHub user wants to sign in as {target}. + + ); +} + +/** Why approve cannot work, if it cannot (one at most). */ +function blocker(item: AccountClaimQueueItem): string | null { + const m = item.claimedPerson; + if (!m) { + return 'No member has this username. Approve is not possible; deny it, and if you can tell who they are, reply through the contact in their note.'; + } + if (m.isAgent) return 'This is an agent account. It cannot be claimed.'; + if (m.githubLogin) return `This member is already linked to GitHub @${m.githubLogin}. Approve is not possible; deny it.`; + return null; +} + +/** What approve does, in one line. */ +function consequence(item: AccountClaimQueueItem): string | null { + const m = item.claimedPerson; + if (!m) return null; + if (item.type === 'post-onboarding-merge') { + const from = item.requesterPerson?.slug ?? 'their new account'; + return `Approve: ${from} is merged into ${m.slug} and deleted; its projects and posts move to ${m.slug}, and @${item.requesterGithubLogin} signs in as ${m.slug}.`; + } + return `Approve: @${item.requesterGithubLogin} signs in as ${m.slug} from now on, with its projects and history. The old password stops working.`; +} + +function MemberFacts({ m }: { m: NonNullable }) { + const facts = [ + `Member since ${formatMonthYear(m.createdAt)}`, + m.imported ? 'Imported from the old site' : 'Created on this site', + `Member of ${m.memberOfCount} project${m.memberOfCount === 1 ? '' : 's'}`, + m.githubLogin ? `Already linked to GitHub @${m.githubLogin}` : 'Not linked to GitHub', + ]; + return

{facts.join(' · ')}

; +} export function StaffAccountClaimQueue() { const { person, loading } = useAuth(); const navigate = useNavigate(); const queryClient = useQueryClient(); + const allowed = !!person && isStaffLevel(person.accountLevel); useEffect(() => { if (loading) return; if (!person) { void navigate('/login?return=/staff/account-claim', { replace: true }); return; } - if (person.accountLevel !== 'staff' && person.accountLevel !== 'administrator') { - toast.error('Staff only'); - void navigate('/', { replace: true }); + if (!isStaffLevel(person.accountLevel)) { + void navigate('/404', { replace: true }); } }, [loading, person, navigate]); const queueQ = useQuery({ - queryKey: ['staff-account-claim-queue'], + queryKey: CLAIM_QUEUE_KEY, queryFn: () => api.staffAccountClaim.queue(), - enabled: !!person && (person.accountLevel === 'staff' || person.accountLevel === 'administrator'), + enabled: allowed, }); const [pendingId, setPendingId] = useState(null); @@ -46,27 +141,16 @@ export function StaffAccountClaimQueue() { setReasons((r) => ({ ...r, [id]: val })); }; - const onApprove = async (id: string) => { + const decide = async (id: string, decision: 'approve' | 'deny') => { setPendingId(id); try { - await api.staffAccountClaim.approve(id, reasons[id] ?? undefined); - toast.success('Claim approved'); - await queryClient.invalidateQueries({ queryKey: ['staff-account-claim-queue'] }); + const reason = reasons[id]?.trim() || undefined; + if (decision === 'approve') await api.staffAccountClaim.approve(id, reason); + else await api.staffAccountClaim.deny(id, reason); + toast.success(decision === 'approve' ? 'Claim approved' : 'Claim denied'); + await queryClient.invalidateQueries({ queryKey: CLAIM_QUEUE_KEY }); } catch (err) { - toast.error(err instanceof ApiError ? err.message : 'Approve failed'); - } finally { - setPendingId(null); - } - }; - - const onDeny = async (id: string) => { - setPendingId(id); - try { - await api.staffAccountClaim.deny(id, reasons[id] ?? undefined); - toast.success('Claim denied'); - await queryClient.invalidateQueries({ queryKey: ['staff-account-claim-queue'] }); - } catch (err) { - toast.error(err instanceof ApiError ? err.message : 'Deny failed'); + toast.error(err instanceof ApiError ? err.message : decision === 'approve' ? 'Approve failed' : 'Deny failed'); } finally { setPendingId(null); } @@ -75,19 +159,22 @@ export function StaffAccountClaimQueue() { if (loading || !person) { return
Loading…
; } - if (person.accountLevel !== 'staff' && person.accountLevel !== 'administrator') { - return null; - } + if (!allowed) return null; const items = queueQ.data?.data ?? []; return (
-

Account-claim queue

+
+

Account-claim queue

+

+ Each request asks to connect a GitHub account to an existing member account. Check the + note against the member before you approve; approving lets that GitHub account sign in + as the member. +

+
- {queueQ.isLoading && ( -
Loading…
- )} + {queueQ.isLoading &&
Loading…
} {!queueQ.isLoading && items.length === 0 && ( @@ -98,78 +185,86 @@ export function StaffAccountClaimQueue() { )} - {items.map((item) => ( - - - - {item.claimedSlug} - {' '} - - ({item.type === 'pre-onboarding' ? 'pre-onboarding link' : 'post-onboarding merge'}) - - - - From{' '} - {item.requesterGithubLogin} - {item.requesterPersonId && ( - <> - {' '} - · currently{' '} - {item.requesterPersonId.slice(0, 8)}… - + {items.map((item) => { + const blocked = blocker(item); + const effect = consequence(item); + const target = item.claimedPerson?.slug ?? item.claimedSlug; + const noteId = `reason-${item.requestId}`; + const noteHelpId = `reason-help-${item.requestId}`; + return ( + + + +

+ +

+
+ + + {item.type === 'pre-onboarding' ? 'link' : 'merge'} + + {' · requested '} + + + {item.claimedPerson && } +
+ + {blocked && ( +
+ {blocked} +
)} - {' · '} - -
-
- - {!item.claimedPersonId && ( -
- The claimed slug doesn't resolve to a current Person. Approve - will return an error — deny with a note instead. +
+

Their note

+
+ {item.evidence} +
- )} -
- {item.evidence} -
-
- -