diff --git a/.planning/phases/32.2-mcp-oauth-with-administrator-subjects/32.2-RESEARCH.md b/.planning/phases/32.2-mcp-oauth-with-administrator-subjects/32.2-RESEARCH.md new file mode 100644 index 00000000..2d2ec241 --- /dev/null +++ b/.planning/phases/32.2-mcp-oauth-with-administrator-subjects/32.2-RESEARCH.md @@ -0,0 +1,665 @@ +# Phase 32.2: MCP OAuth with administrator subjects - Research + +**Researched:** 2026-11-20 +**Domain:** OAuth 2.1 authorization server (wristband + sm-oauthserver-plugin), MCP resource (pier), cabana admin API / admin SPA, nginx wiring of a consumer app +**Confidence:** HIGH for the code seams (read this session); MEDIUM for SPA/cookie behaviour on a real cross-site connector; LOW for exact Claude-connector behaviour (not probed) + + +## User Constraints (from CONTEXT.md) + +### Locked Decisions +- **D-01:** On a backend-mode application, the OAuth sign-in authenticates an administrator (`backend_users`). No frontend user and no account link is involved; the grant subject is the administrator. +- **D-02:** It is a mode of `sm-oauthserver-plugin`, not a new framework module. Code stores, PKCE, refresh rotation, replay-family revocation, the Clients and Branding screens and pruning are reused. Every change to the plugin is additive. `sm-oauthserver-plugin`, `sm-user-plugin`, `sm-journal-plugin` and the framework are shared by many apps, so no breaking changes. — **Reversibility:** costly — the mode becomes a public config key and a grant shape other apps may adopt. +- **D-03:** Consent lives in the **admin SPA** (boardwalk, `admin/`) as a route under the admin prefix (working shape `//connect?request=…`), not as a Go-rendered page and not in Nuxt. Reason: the admin cookie `summer_admin` is `Path=`, `SameSite=Strict` (`modules/cabana/auth.go` `sessionCookie`). It never reaches `/oauth/mcp/authorize` at the root, and it isn't sent on the cross-site navigation from the MCP client. A route inside the SPA gets it on its same-origin API fetches, and the SPA router already sends an anonymous visitor to login with `?redirect=` and back (`admin/src/app/router.ts` `safeRedirect`). Login gates (2FA, Turnstile) therefore apply unchanged. +- **D-04:** wristband's MCP authorize handoff, currently hard-wired to `{issuer}/connect?request=` (`modules/wristband/authorize.go`), becomes configurable so backend mode can point it at the admin SPA route. The default stays `/connect`. — **Reversibility:** costly — wristband option and oauthserver config key are public API. +- **D-05:** The consent screen is a **standalone full-screen card** like `LoginView` (no sidebar or top bar). It shows the client name, the redirect host, the scope checkboxes and the refresh choice, with Allow and Deny. +- **D-06:** The consent screen shows the signed-in administrator ("Signed in as ()") with a **"use another account"** action. That action signs out and goes back to login with the same redirect, like the 19.4 OIDC switch-account flow. +- **D-07:** The mode is **exclusive per application for now**: a config key on `golem15.oauthserver` (working name `mcp.subject`, values `user` (default) and `backend`). One issuer, one `/mcp` resource, one consent surface per app. Pick a config shape that doesn't block coexisting modes later (see Deferred). — **Reversibility:** costly — config key name and values become part of the plugin's contract. +- **D-08:** `sm-oauthserver-plugin` keeps `Requires() = ["golem15.user"]` in backend mode. grzyby mounts golem15.user anyway, and the core plugin's dependency graph stays untouched. +- **D-09:** The scopes on consent are the **cabana token-scope catalog**, the same as `g15_` personal-token creation (`modules/cabana/token_scopes.go`: `*`, `admin:read` and the plugin-declared `TokenScopes()` such as the Journal's). A backend-mode grant gets the same `bouncer.ScopeLimit` a personal token with those scopes would (`cabana.ScopeLimitFor`). An OAuth agent and a `g15_` token with equal scopes therefore see and can call the same tools. This differs from today's linked-admin grants, which carry no scope limit (`modules/pier/backend_guard.go` `principal` applies the limit only when `ClientID == ""`). That existing behaviour must not change for user-mode grants. In backend mode the advertised `scopes_supported` (wristband metadata and pier's protected-resource metadata) come from this catalog. +- **D-10:** `offline_access` appears as a **"Stay connected" checkbox, ticked by default**, as in 32.1's `/connect`. Unticked, the agent gets no refresh token and re-consents when the access token expires. +- **D-11:** Scopes the administrator can't use (they lack the scope's permissions) are **hidden** from the consent screen. A request that asked for them gets only what is ticked and granted. +- **D-12:** Each administrator lists and revokes their own MCP connections in a **My account section** (`pact.HasAccountContributions`). A superuser, or an administrator holding a new oauthserver permission, can see and revoke any administrator's connections on the existing oauthserver admin screens. +- **D-13:** An administrator's MCP grants (access and refresh tokens) are revoked, and their open MCP sessions ended (`pact.MCPSubjectChanged`), on: **delete, deactivate, password change, role or permission change** (including the role's own permissions changing) and **"sign out everywhere"** where cabana offers it. Role and permission changes revoke the grants rather than only re-listing tools. +- **D-14:** sm-grzybyfunkcjonalne-app mounts `golem15.oauthserver` in backend mode with only the MCP authorization server enabled (no OIDC provider surface), keeps `allow_personal_tokens: true`, routes `/.well-known/oauth-authorization-server`, `/.well-known/oauth-protected-resource` and `/oauth/mcp/*` to the Go binary, and documents it in DEPLOY.md. Proof: on a local stack, an MCP client completes discovery, dynamic registration, admin sign-in, consent and a Journal tool call. The production deploy is not part of this phase. + +### Claude's Discretion +- How backend-mode grants are stored. The current tables have `user_id INTEGER NOT NULL REFERENCES users(id)` on access tokens, auth codes and consents (`updates/202610190001_create_golem15_oauthserver_tables.go`). Options: nullable `user_id` via an additive migration with the readers that assume it hardened, or companion rows keyed on `backend_user_id`. Constraints: additive only, user-mode rows and queries unchanged, and the per-user advisory lock and revocation cascade keep working. +- How pier represents an administrator-only grant (for example `pact.MCPGrant` with `UserID` 0 and `BackendUserID` set, resolved straight to the `backend` subject, with no `MCPLinkedBackendResolver` lookup). Additive to `pact`. +- Where the consent JSON API lives (oauthserver routes under the admin API, authenticated by the cabana guard) and how the framework SPA route renders a consent screen whose data a plugin serves. The admin SPA can't load plugin Vue code, so the screen is framework code against a JSON contract. +- The name of the new "manage any administrator's MCP connections" permission and its default role (none, like `golem15.users.manage_backend_links`). +- Whether `*` and `admin:read` are shown as plain scope checkboxes or as "full access" / "read only" presets above the plugin scopes. + +### Deferred Ideas (OUT OF SCOPE) +- **Both subject modes on one application** (for example the demo offering member and administrator connectors, through two resources or a choice at authorize). Exclusive per app for now (D-07); the config shape should leave room for it. +- **Production deploy of grzybyfunkcjonalne.pl with OAuth on** and a live check with the Claude connector: after the phase, on the user's go-ahead. +- **Backend mode without golem15.user** for apps that mount no user plugin (D-08 keeps the dependency). +- Reviewed todos not folded: "Benchmark Płytarium on WinterCMS vs SummerCMS", "Record PHP OIDC parity against WavePath", "Earlier phase gate scripts still name consuming applications", "Translate Messages as a Nuxt i18n JSON editor". + + + +## Phase Requirements + +No REQ-IDs are assigned (ROADMAP: "Requirements: TBD"). The five ROADMAP success criteria act as requirements; this research labels them SC-1..SC-5. + +| ID | Description | Research Support | +|----|-------------|------------------| +| SC-1 | Backend mode: authorize → admin login → SPA consent; grant carries `BackendUserID`, no frontend user; mode off = all existing flows/tests unchanged | §Storage recommendation, §wristband seams, §Admin SPA consent, §Pitfalls 1-6 | +| SC-2 | pier resolves the grant straight to the `backend` subject, capped by cabana permissions and granted scopes like a scope-limited `g15_` token | §pier seams, §Code Examples (identity, backend guard) | +| SC-3 | Revoke (My account list), delete/deactivate/password change ends tokens and sessions | §D-13 revocation map, §My account | +| SC-4 | grzyby mounts oauthserver in backend mode, proxy routes OAuth paths, local MCP client proof; `g15_` still works | §grzyby wiring, §Local proof | +| SC-5 | READMEs, docs/, DEPLOY.md; unit tests last plan; patch tags | §Release mechanics, §Validation Architecture | + + +## Summary + +The MCP OAuth flow is already subject-agnostic at the protocol layer: wristband carries the "user id" as an opaque `uint` through `IssueCode` → `MarkIssued` → code exchange → `Mint` / refresh `Create`, and refuses only a code with a nil user (`modules/wristband/token.go:248`). Everything that interprets that id as a frontend user lives in `sm-oauthserver-plugin` (store, verifier, cascade, consent controllers) and in pier (`resolveOAuth` rejects `grant.UserID == 0`, `modules/pier/identity.go:210`). Backend mode can therefore be built by (1) letting the plugin pass the administrator id as wristband's opaque subject id and persist it as `user_id NULL, backend_user_id = ` per row, (2) a backend branch in the verifier and refresh check that loads the admin through `cabana.BackendPrincipal` and applies its `tokens_valid_after` cutoff, and (3) a pier branch that turns a backend-only grant into a `backend` subject with the cabana scope limit and no read/write ceiling. + +The recommended storage is **nullable `user_id` on access tokens, refresh tokens and consents, plus `backend_user_id` on consents with a partial unique index** (one additive migration). Every user-mode query filters on `user_id = ?` / `IN ?`, so `NULL` rows are invisible to them; the only readers that see all rows (verifier by hash, refresh by hash, prune, the client authorizations partial) are few and listed below. Companion tables would duplicate the wristband store, the verifier lookup, lineage revocation and pruning for no safety gain. + +Three framework seams are missing today and must be added additively: a wristband consent-handoff path and default-scope option, a cabana-owned admin consent endpoint backed by a new pact provider interface (the SPA cannot load plugin code and plugin routes cannot read the `summer_admin` cookie: `cabana.ResolveBackend` is "never the admin cookie"), and a per-row "items" extension of `pact.AccountContribution` (today a section is only a status line and fixed buttons, so per-connection revoke does not fit). D-13 needs one new in-transaction cabana event: password changes fire no MCP event today, and role/permission changes only re-list tools. + +**Primary recommendation:** Nullable `user_id` + per-row backend subject in the existing tables; a cabana `{api}/mcp/consent/{request}` endpoint that delegates to a published `pact.MCPAdminConsent` provider; pier keys a backend-only grant on a new `pact.MCPGrant` subject marker and applies `cabana.ScopeLimitFor` through a new `pact.MCPSubject` flag; revocation through a new in-transaction `cabana` "admin access revoked" event mirroring sm-user-plugin's `AccessRevokedEvent`. + +## Architectural Responsibility Map + +| Capability | Primary Tier | Secondary Tier | Rationale | +|------------|-------------|----------------|-----------| +| RFC 8414 metadata, DCR, authorize, token, PKCE, refresh rotation | API (wristband, mounted by oauthserver) | — | Unchanged protocol code; only handoff URL and default scopes become options | +| Subject binding of codes/tokens (admin vs user) | Database / Storage (oauthserver `MCPStore`) | API | wristband's id is opaque; the store decides per row | +| Admin sign-in, 2FA/Turnstile | API (cabana auth) + Browser (admin SPA LoginView) | — | Reused unchanged (D-03) | +| Consent screen | Browser (admin SPA `ConnectView`) | API (cabana consent endpoint → oauthserver provider) | Cookie is `Path=`, `SameSite=Strict`; only same-origin SPA fetches carry it | +| Scope catalog, "hide what you can't use", scope validation | API (cabana) | — | cabana owns the token-scope catalog and `scopeOverlaps`; unexported today | +| Token verification at `/mcp` | API (oauthserver `MCPTokenVerifier`) | API (pier) | Verifier answers `pact.MCPGrant`; pier builds the identity | +| Tool listing/calls capped by admin permissions + scopes | API (pier backend guard + cabana) | — | Same path as `g15_` tokens | +| Revocation on admin changes | API (cabana fires, oauthserver listens) | Database | cabana owns admin lifecycle; oauthserver owns grant rows | +| Session teardown | API (pier `handleEvent`) | Store (memory/redis fan-out) | Existing `pact.MCPSubjectChanged` path | +| My account connections list | Browser (AccountView) + API (cabana contributions) | oauthserver (items provider) | Framework renders, plugin supplies data | +| Proxy routing of OAuth paths | CDN/edge (nginx in grzyby `deploy/nginx`) | — | Nuxt answers everything else | + +## Standard Stack + +No new dependencies. Everything is standard library, existing modules, or packages already in `.planning/research/STACK.md` / the plugin's go.mod. + +### Core (existing, versions from go.mod files read this session) +| Library | Version | Purpose | Why Standard | +|---------|---------|---------|--------------| +| `git.golem15.com/golem15/summercms` | v0.6.6 tagged; HEAD = `v0.6.6-4-g6c44946d` [VERIFIED: git describe] | pact, pier, wristband, cabana, boardwalk | The framework | +| `sm-oauthserver-plugin` | v0.1.7, HEAD = v0.1.7 (go.work has an uncommitted change by another session; leave it) [VERIFIED: git describe/status] | MCP + OIDC authorization server | D-02 | +| `sm-user-plugin` | v0.1.21 latest tag; oauthserver go.mod requires v0.1.17 [VERIFIED: git tag, go.mod] | `Requires()` dependency (D-08) | unchanged | +| `gorm.io/gorm` | v1.31.2 [VERIFIED: sm-oauthserver-plugin/go.mod] | Store | existing | +| `go-gormigrate/gormigrate/v2` | v2.1.7 | Additive migration | existing | +| `github.com/modelcontextprotocol/go-sdk` | v1.8.0 (indirect) | pier transport | existing | +| Admin SPA: vue 3.5.35, vitest 3.2.7, openapi-fetch, playwright 1.60.0 | [VERIFIED: admin/package.json] | Consent route + tests | existing | +| swag v1.16.6 via `go run` in `scripts/check-admin-openapi.sh` | [VERIFIED: script line 31] | Typed admin API contract | existing pipeline | + +### Alternatives Considered +| Instead of | Could Use | Tradeoff | +|------------|-----------|----------| +| Nullable `user_id` | Companion tables keyed on `backend_user_id` | Needs a second `wristband.Backend`, a two-table verifier lookup, duplicated lineage revoke/prune; rejected | +| Cabana-owned consent endpoint | Plugin route under the admin prefix with the `backend` middleware | Plugin routes mount before `cabana.Activate` (`modules/surf/router.go:753`), `interactiveOnly`/`requireAjax` are unexported, the plugin would hard-code the API base; rejected | +| New in-tx cabana event for D-13 | oauthserver listening to `*pact.MCPSubjectChanged` (after commit) | Covers delete/deactivate/permissions but not password change, not atomic, listener errors only logged; use as defense in depth only | + +**Installation:** none. + +## Package Legitimacy Audit + +No external packages are installed by this phase. **Packages removed due to [SLOP] verdict:** none. **Packages flagged [SUS]:** none. + +## Architecture Patterns + +### System Architecture Diagram + +``` +MCP client (Claude connector / script) + │ 1. POST /mcp (no bearer) ──► pier ─► 401 WWW-Authenticate resource_metadata=… + │ 2. GET /.well-known/oauth-protected-resource[/mcp] ──► pier PRM + │ scopes_supported ◄── verifier.MCPScopesSupported() ◄── cabana catalog (backend mode) + │ 3. GET /.well-known/oauth-authorization-server ──► wristband Metadata (same scope slice) + │ 4. POST /oauth/mcp/register ──► wristband Register (DCR, kind=mcp client) + │ 5. Browser: GET /oauth/mcp/authorize?…PKCE…&resource=… + │ └─► wristband Authorize: validate client/redirect/PKCE/scopes/resource + │ → CreatePending (mcp_codes, user_id NULL) + │ → 302 {issuer}{ConsentPath}?request= (backend mode: //connect) + ▼ +Admin SPA (boardwalk, //connect) + ├─ not signed in? router → //login?redirect=/connect?request=… (2FA/Turnstile unchanged) → back + ├─ GET {prefix}/api/v1/mcp/consent/{request} (cookie summer_admin, X-Requested-With) + │ cabana: guard → principal → provider.Show(adminID, request) + │ → requested ∩ catalog ∩ scopeOverlaps(admin) (D-11) + labels + ├─ "use another account": POST /auth/logout → login?redirect=same (D-06) + └─ POST {prefix}/api/v1/mcp/consent/{request} {decision, scopes, offline_access} + cabana: validate scopes (validateTokenScopes) → provider.Decide(adminID, …) + oauthserver: WithinBackendGrantsLock(admin) { + wristband.IssueCode(ctx+backendSubject, request, adminID, scopes) + → MarkIssued: user_id NULL, backend_user_id = admin + record consent row (user_id NULL, backend_user_id, client_id) } + → {redirect_uri: ?code=…&iss=…&state=…} + SPA: window.location.assign(redirect_uri) (NOT safeRedirect) + ▼ +MCP client: POST /oauth/mcp/token (code + verifier + resource) + wristband Token → ByCodeHashForUpdate (backend lock shared) → Mint/Create (user_id NULL, backend_user_id) + ▼ +POST /mcp Authorization: Bearer oas_at_… + pier.resolveOAuth → verifier.MCPVerifyToken + backend row: cabana.BackendPrincipal(admin) nil? → invalid; created_at < tokens_valid_after? → invalid + → MCPGrant{UserID:0, BackendUserID:admin, Subject:"backend", Scopes} + → Identity{Frontend:nil, Backend:{Guard:"backend", UserID:admin, ClientID, TokenID, ScopeLimited:true}, + ceiling:false, Binding:"oauth:backend::"} + → backendGuard.principal: BackendPrincipal + ScopeLimitFor(scopes, method) (D-09) + → tools/list, tools/call (Journal tools, guard "backend") + +Revocation: cabana admin delete/deactivate/password/role/permission save + → in-tx event (new) → oauthserver revokes backend rows in same tx + → after commit: MCPSubjectChanged{Guard:"backend", UserID:admin, Kind:revoked, ClientID} per client + → pier.handleEvent ends matching sessions +``` + +### Recommended file layout (new/changed) + +``` +summercms.go/ +├── modules/pact/mcp.go # MCPGrant.Subject (+const), MCPSubject.ScopeLimited, MCPAdminConsent provider + view/decision types + errors +├── modules/pact/capabilities.go # AccountContribution.Items / ItemActions (additive) +├── modules/wristband/server.go # Options.ConsentPath, Options.DefaultScopes +├── modules/wristband/authorize.go # use them (defaults keep PHP bytes) +├── modules/pier/identity.go # backend-only grant branch +├── modules/pier/backend_guard.go # scope limit when subject.ScopeLimited +├── modules/cabana/mcp_consent.go # GET/POST {api}/mcp/consent/{request} (new) +├── modules/cabana/token_scopes_export.go # TokenScopeNames(app), grantable view for consent (new exports) +├── modules/cabana/admin_events.go # BackendAccessRevokedEvent (new), fired from users admin/account/commands +├── modules/cabana/account_contributions.go # items list + item action route +├── modules/cabana/admin_openapi.go # swag annotations for the new endpoints +├── admin/src/views/ConnectView.vue # standalone card (new) +├── admin/src/app/router.ts # { path: '/connect', name: 'connect', component: ConnectView } (no shell, not public) +├── admin/src/components/account/AccountContributions.vue # render items + per-item actions +├── admin/openapi/admin.json, admin/src/api/schema.d.ts # regenerated +└── modules/boardwalk/dist # rebuilt and committed +sm-oauthserver-plugin/ +├── updates/2026112xxxxx_add_golem15_oauthserver_backend_subjects.go +├── classes/mcp_store.go # per-row backend subject +├── classes/mcp_backend_subject.go # WithBackendSubject ctx, backend grants lock, revokeBackendGrants (new) +├── classes/mcp_verifier.go # backend branch +├── classes/backend_cascade.go # listener for the cabana event (new) +├── controllers/mcp_admin_consent.go # implements pact.MCPAdminConsent (new) +├── controllers/mcp_connections.go # admin list screen of backend connections (new) +├── account.go # HasAccountContributions (new) +├── admin_permissions.go / admin_navigation.go # new permission + side menu +├── servers.go / routes.go / config/config.yaml # mcp.subject, mcp.consent_path, oidc.enabled +sm-grzybyfunkcjonalne-app/ +├── summer.yaml, .gitmodules, go.mod, go.work # add golem15.oauthserver +├── plugins/golem15/oauthserver (submodule) +├── config/golem15.oauthserver.yaml, config/mcp.yaml +├── deploy/nginx/*.conf # OAuth locations +├── scripts/smoke-mcp-oauth.sh (or Go test) # local proof +└── DEPLOY.md +``` + +### Pattern 1: Per-row backend subject in the existing store (storage recommendation) + +**What:** wristband keeps passing one opaque `uint`. In backend mode the consent provider calls `IssueCode(ctx, request, adminID, …)` with `ctx = classes.WithBackendSubject(ctx)`. The store writes `user_id = NULL, backend_user_id = adminID`. On the code exchange and refresh lookup the store reads the row; `user_id IS NULL AND backend_user_id IS NOT NULL` marks a backend row, the record's `UserID` is filled with `backend_user_id`, and `Mint`/`Create` in that transaction write the same shape. + +**Why this works with wristband** [VERIFIED: modules/wristband/token.go:248,262,276,351,365]: the exchange requires only `rec.UserID != nil` and forwards `*rec.UserID` to `tx.Mint` and into the refresh record; refresh forwards `rec.UserID`. wristband never loads a user. + +**Current schema** [VERIFIED: sm-oauthserver-plugin/updates/202610190001_create_golem15_oauthserver_tables.go:74,92,106,112,128; 202610190003…:23; 202610230001…:20-22]: +- auth_codes (OIDC): `user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,` (line 74) — not touched. +- access_tokens: `user_id INTEGER NOT NULL,` (line 92) — no FK. +- consents: `user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,` (line 106), `CONSTRAINT oas_consents_user_client_unique UNIQUE (user_id, client_id)` (line 112). +- refresh_tokens: `user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,` (line 128). +- mcp_codes: `user_id INTEGER NULL REFERENCES users(id) ON DELETE CASCADE,` (line 23 of 202610190003) — already nullable. +- `ALTER TABLE golem15_oauthserver_mcp_codes ADD COLUMN backend_user_id INTEGER NULL`, same for access_tokens and refresh_tokens (202610230001 lines 20-22). Consents have no `backend_user_id`. + +**Migration (one file, raw SQL like the others):** +```sql +ALTER TABLE golem15_oauthserver_access_tokens ALTER COLUMN user_id DROP NOT NULL; +ALTER TABLE golem15_oauthserver_refresh_tokens ALTER COLUMN user_id DROP NOT NULL; +ALTER TABLE golem15_oauthserver_consents ALTER COLUMN user_id DROP NOT NULL; +ALTER TABLE golem15_oauthserver_consents ADD COLUMN backend_user_id INTEGER NULL; +CREATE UNIQUE INDEX oas_consents_backend_client_unique + ON golem15_oauthserver_consents (backend_user_id, client_id) WHERE user_id IS NULL; +CREATE INDEX oas_tokens_backend_client_idx ON golem15_oauthserver_access_tokens (backend_user_id, client_id) WHERE user_id IS NULL; +CREATE INDEX oas_refresh_backend_client_idx ON golem15_oauthserver_refresh_tokens (backend_user_id, client_id) WHERE user_id IS NULL; +-- every row names a subject; a uint zero written by mistake is refused +ALTER TABLE golem15_oauthserver_access_tokens ADD CONSTRAINT oas_tokens_subject_check CHECK ((user_id IS NOT NULL AND user_id > 0) OR backend_user_id IS NOT NULL) NOT VALID; +ALTER TABLE golem15_oauthserver_refresh_tokens ADD CONSTRAINT oas_refresh_subject_check CHECK (user_id IS NOT NULL OR backend_user_id IS NOT NULL) NOT VALID; +ALTER TABLE golem15_oauthserver_consents ADD CONSTRAINT oas_consents_subject_check CHECK (user_id IS NOT NULL OR backend_user_id IS NOT NULL) NOT VALID; +``` +Rollback: `DELETE … WHERE user_id IS NULL` on the three tables (backend grants cannot survive a down migration; say so in the comment), drop constraints/indexes/column, `SET NOT NULL`. `NOT VALID` keeps the migration from scanning or failing on historic rows. `backend_user_id` gets no FK, matching 202610230001 and because backend users are only soft-deleted (`modules/cabana/backend_users_admin.go` FormAfterDelete comment: "a backend user is never hard-deleted"). + +**Reader inventory (sm-oauthserver-plugin, non-test) and what each needs:** + +| Reader | Filter | Sees backend rows? | Action | +|--------|--------|--------------------|--------| +| `classes/mcp_store.go` `MarkIssued` | writes `"user_id": userID` | writes them | backend ctx → `user_id: nil`, `backend_user_id: id` | +| `mcp_store.go` `ByCodeHashForUpdate` | owner `Select("user_id")` into `*uint`; locks user | yes | also select `backend_user_id`; backend row → backend lock (shared); fill record `UserID` from `backend_user_id`; remember subject kind on `mcpTx` | +| `mcp_store.go` `Create` (refresh), `Mint` | `UserID: rec.UserID` | writes | backend tx → omit `user_id` (`Omit("user_id")` or column map), set `backend_user_id` regardless of the `backend` scope (today `backendBinding` requires that scope) | +| `mcp_store.go` `ByTokenHashForUpdate` + `refreshUserUsable` | `PrincipalByID(user)` | yes | backend row → `cabana.BackendPrincipal` + `issuedBeforeCutoff(created_at, principal.TokensValidAfter)`; no ban check (admins have none) | +| `mcp_store.go` `refreshRecord` | `UserID: m.UserID` | yes | backend row → `UserID = *m.BackendUserID` | +| `classes/mcp_verifier.go` `MCPVerifyToken` | `PrincipalByID(token.UserID)` | yes | backend branch (see Code Examples) | +| `classes/cascade.go` `purge`, `revokeUserGrants` | `user_id = ?` / `IN ?` | no | unchanged | +| `controllers/authorizations.go` (frontend authorized apps) | `s.user_id = ?` | no | unchanged | +| `controllers/mcp_consent_api.go` | jwt.auth frontend | — | do not mount in backend mode (Pitfall 4) | +| `controllers/clients.go` `authorizations` partial | `client_id = ?` | yes (UserID 0 → user not found → skipped) | OIDC clients only (`ListExtendQuery` `kind = oidc`); backend consents are MCP, so no change needed | +| `console/prune.go` `PruneExpired` | expiry only | yes | correct as is | +| `classes/oidc_store.go` consents | `user_id = ? AND client_id = ?`, `ON CONFLICT (user_id, client_id)` | no | unchanged | +| `updates/…backfill_…mcp_consents.go` | scans all live MCP tokens | only on a fresh DB, before any backend row exists | unchanged; it already ran everywhere else | +| `models.*` `UserID uint` | GORM scan | NULL → 0 | keep `uint` (GORM's uint setter ignores a nil `**uint`, [VERIFIED: ~/go/pkg/mod/gorm.io/gorm@v1.31.2/schema/field.go:696-706 `case **uint: if data != nil && *data != nil { … SetUint(…) }`]); do not change exported field types | + +No other repository reads the oauthserver tables (grep of sibling repos found only the plugin's own files) [VERIFIED: grep this session]. + +**Advisory lock:** today `userGrantsLockKey` is `"golem15_oauthserver_user_grants:" + id` and `lockUserGrantsShared` returns early for id 0 [VERIFIED: classes/mcp_backend_binding.go]. Add a parallel `backendGrantsLockKey` (`"golem15_oauthserver_backend_grants:" + id`), `lockBackendGrantsShared`, `LockBackendGrants`, `WithinBackendGrantsLock` (same join-the-tx trick through `grantsTxKey`, so `MCPStore.WithinTx` reuses the tx). Separate namespace means admin 7 and user 7 never contend and never cross-serialize. + +### Pattern 2: pier backend-only grant + +**What:** `pact.MCPGrant` gains `Subject string` (const `pact.MCPGrantSubjectBackend = "backend"`; empty = the frontend user, today's meaning). The verifier sets it with `UserID: 0`, `BackendUserID: admin`. `resolveOAuth` branches before the `grant.UserID == 0` refusal. + +Current code [VERIFIED: modules/pier/identity.go:209-231]: `if err != nil || grant.UserID == 0 { return Identity{}, ErrUnauthorized }`, `Binding: "oauth:" + grant.ClientID + ":" + strconv.FormatUint(uint64(grant.UserID), 10)`, `ceiling: true`, `id.Backend = r.consentedBackendSubject(…)`. + +Backend branch requirements: +- `Frontend: nil` even when a frontend guard is registered (grzyby mounts golem15.user, so `r.frontendGuard` is set). A frontend subject with UserID 0 would be wrong. +- `Binding: "oauth:backend:" + clientID + ":" + adminID` — with UserID 0 the current format would put every admin of one client on `oauth::0` (Pitfall 2). +- `ceiling: false` — like an admin personal token; writes are governed by the scope limit's methods. With `ceiling: true` every non-read-only Journal tool would be hidden because `write` is not a cabana scope (`modules/pier/identity.go:80-82` `return !id.ceiling || slices.Contains(id.Scopes, "write")`). +- `Backend: &pact.MCPSubject{Guard: BackendGuard, UserID: admin, Scopes, ClientID, TokenID, ScopeLimited: true}`. +- `consentedBackend` not used; `refreshBackend` already returns early when `Frontend == nil` (`modules/pier/events.go:288-293`), so link events never touch it. + +**Scope limit:** current condition [VERIFIED: modules/pier/backend_guard.go:110] `if subject.ClientID == "" && subject.TokenID != 0 {` → becomes `if (subject.ClientID == "" && subject.TokenID != 0) || subject.ScopeLimited {`. User-mode linked grants never set `ScopeLimited`, so their behaviour is unchanged (D-09). `errScopeUnavailable` then also covers a backend grant whose scopes all disappeared. + +**Sessions:** `revokedMatch` with `ClientID` already matches `id.subjectFor("backend")` with that client [VERIFIED: modules/pier/events.go:80-94], so the plugin fires `MCPSubjectChanged{Guard: "backend", UserID: admin, Kind: revoked, ClientID}` per revoked client and nothing in pier changes. Include `ScopeLimited` in `fingerprint()` for completeness. + +**PRM:** no pier change. `mountPRM` copies `MCPAdvertisedScopes.MCPScopesSupported()` when non-empty [VERIFIED: modules/pier/prm.go:37-40]; the plugin's verifier returns the backend-mode slice. + +### Pattern 3: wristband options (D-04, plus default scopes) + +Current [VERIFIED: modules/wristband/authorize.go:187] `spa := s.opts.Issuer + "/connect?request=" + rfc3986Escape(requestID)` and [authorize.go:250] the empty-scope fallback `return []string{"read"}, ""`. + +Add to `Options` (zero value keeps PHP bytes, `DefaultOptions` unchanged): +- `ConsentPath string` — appended to `Issuer`; empty means `"/connect"`. Backend mode sets `cabana.AdminPrefix(app) + "/connect"` (`/gfadmin/connect` on grzyby; `modules/cabana/prefix.go` `AdminPrefix` reads `backend.uri`, callable at Boot). +- `DefaultScopes []string` — the scopes an authorize request with no data scope gets; empty means `["read"]`. Backend mode must set it, because `read` is not a cabana scope (Pitfall 3). Recommended value: the catalog's data scopes (everything advertised except `offline_access`); the consent screen then lets the admin narrow, which matches the MCP spec's "request all scopes_supported, let the user decide at consent" strategy [CITED: modelcontextprotocol.io/specification/2025-11-25/basic/authorization "Scope Selection Strategy"]. + +Scopes themselves need no wristband change: `NewServers` already sets `mcpOpts.ScopesSupported = scopes` and the verifier gets the same slice [VERIFIED: sm-oauthserver-plugin/servers.go NewServers]. Backend mode swaps the slice for `cabana catalog names + "offline_access"`. cabana names such as `*`, `admin:read`, `journal`, `journal:read` are valid RFC 6749 scope tokens (`%x21 / %x23-5B / %x5D-7E`) [ASSUMED from RFC 6749 §3.3 grammar]. + +**Catalog timing:** oauthserver builds its servers in `Boot`; `cabana.Activate` (which compiles the registry used by `ScopeLimitFor`) runs later at route assembly (`modules/surf/router.go:753`). But `party.Activated` is published before any `Register`/`Boot` (`modules/party/registry.go` activate: `app.Publish(Activated(ordered))` precedes the Register loop), and cabana already compiles a standalone catalog from it for CLI commands (`modules/cabana/token_commands.go` `tokenCatalogForApp` → `compileTokenCatalog(plugins)`). Export `cabana.TokenScopeNames(app *backpack.App) ([]string, error)` on top of `tokenCatalogForApp` (catalog order: `*`, `admin:read`, then plugin scopes). Constants [VERIFIED: modules/cabana/token_scopes.go:14-15] `scopeAll = "*"`, `scopeAdminRead = "admin:read"`. + +### Pattern 4: Cabana-owned consent endpoint + pact provider (discretion item "where the consent JSON lives") + +Why cabana: the SPA's API base is `{prefix}/api/v1` (`modules/cabana/prefix.go` `adminAPIVersion = "/api/v1"`); the cookie is `Path: s.adminPrefix()`, `HttpOnly`, `SameSite: http.SameSiteStrictMode` [VERIFIED: modules/cabana/auth.go sessionCookie]; plugin-side `cabana.ResolveBackend` reads "the Authorization Bearer header only (admin JWT or g15_ personal API token — never the admin cookie)" [VERIFIED: modules/cabana/token_guard.go ResolveBackend comment]. The admin group is `r.GroupRaw(api, []string{"backend", "locale.from-principal"}, …)` with `interactiveOnly(requireAjax(…))` wrappers [VERIFIED: modules/cabana/http.go:335-347]. Mounting the consent routes there gives cookie auth, CSRF header, interactive-only (no `g15_` tokens) and swag/openapi typing for free. + +Contract (recommended, mirrors `controllers/mcp_consent_api.go` minus the link fields): +``` +GET {api}/mcp/consent/{request} + 200 {data: {request_id, client:{name, redirect_host, logo_url}, admin:{login, name, email}, + scopes:[{name, label, description}], // requested ∩ catalog ∩ scopeOverlaps(admin) (D-11) + offline_access: bool, // requested + consent_required: bool, expires_at}} + 404 request_not_found (missing/expired/used/foreign/no provider), 401 +POST {api}/mcp/consent/{request} body {decision:"allow"|"deny", scopes:[…], offline_access: bool} + 200 {data: {redirect_uri}} 422 no_grantable_scopes 404 request_not_found +``` +pact interface (provider published by oauthserver in backend mode; cabana answers 404 when none is published): +```go +type MCPAdminConsent interface { + MCPAdminConsentShow(ctx context.Context, adminID uint, requestID string) (MCPAdminConsentRequest, error) + MCPAdminConsentDecide(ctx context.Context, adminID uint, requestID string, d MCPAdminConsentDecision) (redirectURI string, err error) +} +// ErrMCPConsentNotFound, ErrMCPConsentNoScopes sentinel errors +``` +cabana does the scope policy (it owns the catalog): filter requested scopes with `scopeOverlaps`, and on allow run the same normalisation as token creation (`validateTokenScopes`: `*` collapses the set to `["*"]`, unknown or not-overlapping names refused) [VERIFIED: modules/cabana/api_tokens.go validateTokenScopes]. Submitted scopes outside requested ∩ grantable are dropped, not errors (D-11). The provider only resolves the pending request (wristband `PendingRequest`), issues the code under the backend grants lock and records the consent. + +### Pattern 5: Admin SPA consent route + +- Route: `{ path: '/connect', name: 'connect', component: ConnectView }` with no `meta.shell` (standalone card) and no `meta.public` (so `beforeEach` sends anonymous visitors to `{ name: 'login', query: { redirect: to.fullPath } }`) [VERIFIED: admin/src/app/router.ts:92-104]. `/connect` is a single segment, so it does not collide with `/:vendor/:plugin/:controller`. +- Login round trip: `LoginView` does `router.replace(safeRedirect(route.query.redirect) ?? '/')` [VERIFIED: admin/src/views/LoginView.vue:34]; `safeRedirect` accepts `/connect?request=…` (single leading slash). Any MFA/Turnstile step inside the login flow is reused as is. +- After the decision the SPA navigates to the **server-issued** `redirect_uri` with `window.location.assign`. Never route it through `safeRedirect` (it rejects absolute URLs; the URI is trusted because wristband validated it against the registered list). +- "Use another account": `POST {api}/auth/logout`, clear `currentUser`, `router.replace({ name: 'login', query: { redirect: '/connect?request=' + id } })`. +- Scope UI: reuse the `ApiTokenCreateDialog` rule that ticking `*` disables the others (`starChecked`, admin/src/components/account/ApiTokenCreateDialog.vue:64,149-177). Recommendation for the discretion item: **plain checkboxes with that rule**, labels from the catalog, so the consent mirrors `g15_` token creation exactly (the D-09 mental model). "Stay connected" checkbox ticked by default, shown when `offline_access` was requested. +- `boardwalk` serves `index.html` for client-side routes (`modules/boardwalk/boardwalk.go` header comment: "falls back to index.html for client-side routes"), so `/gfadmin/connect` loads without a cookie; the cookie rides on the SPA's same-origin API fetches. +- Release gate: rebuild `modules/boardwalk/dist` and pass `scripts/check-admin-dist.sh`; regenerate types with `scripts/check-admin-openapi.sh` and pass `--check`. + +### Pattern 6: My account connections (D-12) + +`pact.AccountContribution` today is `Name, Label, Description, Status func(ctx, adminID) (string, error), Actions []AccountAction` and `AccountActionInput` carries only `AdminID` [VERIFIED: modules/pact/capabilities.go:599-650]. The list endpoint returns status + fixed buttons [VERIFIED: modules/cabana/account_contributions.go:98-158]. A per-connection list with revoke does not fit. Add additively: +```go +// on AccountContribution +Items func(ctx context.Context, adminID uint) ([]AccountItem, error) `json:"-"` +ItemActions []AccountItemAction +type AccountItem struct { ID, Title, Subtitle string; Meta []string } +type AccountItemAction struct { Name, Label, Confirm string; Danger bool; Permissions []string + Run func(ctx context.Context, in AccountItemActionInput) (AccountActionResult, error) `json:"-"` } +type AccountItemActionInput struct { AdminID uint; ItemID string } +``` +Route `POST /account/contributions/{name}/items/{item}/actions/{action}` in the same group, run in a transaction like section actions. `AccountContributions.vue` renders items under the section. The oauthserver item ID is the client_id; revoke deletes the admin's consent and the pair's codes/tokens under `LockBackendGrants` and fires the per-client revoked event after commit (mirror of `controllers/authorizations.go` `revoke`). + +Admin-wide view: the existing Clients screen lists OIDC clients only (`ListExtendQuery` `kind = ?` oidc) [VERIFIED: controllers/clients.go:70-79]. Add a side-menu "MCP connections" list over backend consents (`backend_user_id IS NOT NULL AND user_id IS NULL`), relation columns to the admin and client (cabana list columns support `relation`/`select`, `modules/cabana/list_schema.go:68-69`), a "Revoke" record action and bulk action. Permission: **`golem15.oauthserver.manage_mcp_connections`**, no default role (superusers pass cabana checks anyway), label under the existing `golem15.oauthserver::lang.plugin.tab`. The main navigation item already requires `golem15.oauthserver.*`. + +### D-13 revocation map + +| Trigger | Where in cabana | Today | Needed | +|---------|-----------------|-------|--------| +| Delete admin | `usersAdmin.FormAfterDelete` sets `tokens_valid_after = revocationCutoff()` and fires `MCPSubjectDeleted` (after commit) | verifier would need the cutoff; sessions already end | new in-tx event → revoke rows; verifier cutoff as defense in depth | +| Deactivate | lifecycle action: `is_activated: false, tokens_valid_after: revocationCutoff()` + `MCPSubjectDeleted` | same | same | +| Password set by another admin | `FormBeforeUpdate`: `user.TokensValidAfter = &cutoff` when `storePassword` changed; **no event** | — | event (fire from FormAfterUpdate on a flag set in BeforeUpdate) | +| Own password change | `account.go` `accountUpdate`: `updates["tokens_valid_after"] = now.Truncate(time.Second)`; **no event** | — | event | +| `admin:reset-password` command | `commands.go`: password + `tokens_valid_after` cutoff; **no event** | — | event | +| Role / own permissions / superuser flip | `usersAdmin.FormAfterUpdate` fires `MCPSubjectPermissions` | re-list only | event with reason permissions → revoke (D-13 says revoke) | +| Role's permissions change | `rolesAdmin.FormAfterUpdate` fires `MCPSubjectPermissions` for holders | re-list only | event for holders | +| "Sign out everywhere" | not offered by cabana (no route found; `logout` is per-token) | — | none; document "not offered" | + +[VERIFIED: modules/cabana/backend_users_admin.go:219-234, 284-289, 767-845; account.go:287-390; commands.go:150-165; backend_roles_admin.go:179-199; grep for everywhere/sign-out] + +Recommended event, mirroring sm-user-plugin `AccessRevokedEvent{UserIDs []uint; Before time.Time; Reason string; Tx *gorm.DB}` [VERIFIED: sm-user-plugin/classes/events.go:112-117]: +```go +// modules/cabana +type BackendAccessRevokedEvent struct { + AdminIDs []uint + Before time.Time + Reason string // deleted, deactivated, password_changed, password_set, password_reset, permissions + Tx *gorm.DB +} +``` +Fired synchronously inside the save's transaction (`TxFromContext`) through `app.Events.Fire`; a listener error rolls the save back, as the user-plugin pattern does. oauthserver's listener revokes the admins' backend rows (tokens revoked, consents and unused codes deleted) under `lockBackendGrants`, then `lagoon.AfterCommit` fires `MCPSubjectChanged{Guard: "backend", UserID, Kind: revoked, ClientID}` per touched client. Keep the existing cabana `MCPSubjectChanged` emissions untouched (they also serve user-mode linked grants and `g15_` sessions). + +Defense in depth: the verifier and refresh check refuse a backend token with `created_at` before the admin's `tokens_valid_after` (`issuedBeforeCutoff`, already used for users), and `cabana.BackendPrincipal` answers nil for a deleted or deactivated admin [VERIFIED: modules/cabana/token_resolver.go BackendPrincipal comment]. So even a missed event cannot leave a usable token after delete, deactivate or password change; pier re-verifies the bearer on every request [VERIFIED: identity.go Identity comment "Every request resolves its own Identity from its bearer"]. + +### Anti-Patterns to Avoid +- **Writing `user_id = 0` for backend rows.** access_tokens has no FK, so a GORM `Create` with `UserID: 0` silently stores 0 instead of NULL. Use `Omit("user_id")`/column maps; the CHECK above catches it. +- **Reusing `backendBinding(scopes, id)` for backend rows.** It returns nil unless the scopes contain `backend` [VERIFIED: classes/mcp_backend_binding.go backendBinding]; backend-mode scopes never do. +- **Mounting the user-mode `/oauth/mcp/requests/*` routes in backend mode** (Pitfall 4). +- **Plugin Vue code or plugin routes under the admin prefix** for consent (see Pattern 4). +- **Changing `UserID uint` model fields to pointers** — an exported API change for no gain. + +## Don't Hand-Roll + +| Problem | Don't Build | Use Instead | Why | +|---------|-------------|-------------|-----| +| Scope → route-method limit | new limit logic | `cabana.ScopeLimitFor` | identical to `g15_` tokens by construction (D-09) | +| Scopes an admin may grant | permission matching in the plugin | cabana `scopeOverlaps` / `validateTokenScopes` (export thin wrappers or keep them behind the cabana endpoint) | the token dialog's rules, incl. `*` collapsing | +| Admin loading, deactivated/deleted check | SQL on backend_users | `cabana.BackendPrincipal` (+ `TokensValidAfter`) | same answer the guard uses | +| Session teardown | custom pier hooks | `pact.MCPSubjectChanged` with `ClientID` | `revokedMatch` already handles it | +| Commit-time side effects | goroutines | `lagoon.AfterCommit` / `userclasses.FireSubjectEventAfterCommit` | rollback-safe | +| PKCE/DCR/refresh replay | anything | wristband | byte-exact PHP contract | +| Login, 2FA, Turnstile on the consent path | a second login page | admin SPA `LoginView` + router redirect | D-03 | + +**Key insight:** the only genuinely new logic is the per-row subject switch and the backend branches; everything else is wiring existing, already-tested pieces through additive seams. + +## Common Pitfalls + +### Pitfall 1: The pending row is owned by everyone until issued +**What goes wrong:** `lookupOwnedPending` treats `pending.UserID == nil` as owned by every caller and compares `*pending.UserID != userID` otherwise [VERIFIED: wristband/consent.go]. In backend mode the "userID" is an admin id; in user mode it is a user id. Fine while the modes are exclusive, but a backend-mode app must not also expose the frontend consent routes, or a frontend user could consent to an admin's pending request with their own id. +**How to avoid:** backend mode mounts only metadata/authorize/register/token; the consent path is the cabana endpoint only. + +### Pitfall 2: Binding collision for UserID 0 +**What goes wrong:** `"oauth:" + clientID + ":" + "0"` for every admin of one client → sessions shared across admins. +**How to avoid:** distinct backend binding format; test two admins on one client get distinct bindings. + +### Pitfall 3: Empty-scope fallback is `read` +**What goes wrong:** a client that sends no `scope` gets `["read"]` (authorize.go:250), which no cabana scope matches; consent shows nothing and `ScopeLimitFor` answers known 0. +**How to avoid:** `Options.DefaultScopes` set in backend mode. + +### Pitfall 4: Frontend consent routes in backend mode +**What goes wrong:** `MCPConsentShow/Decide` behind `jwt.auth` would let any frontend user of the app finish a pending backend-mode request as a user-subject grant. +**How to avoid:** do not mount them when `mcp.subject: backend`; a test asserts 404. + +### Pitfall 5: Read/write ceiling hides write tools +**What goes wrong:** OAuth identities set `ceiling: true`; cabana scopes never include `write`, so every non-read-only tool disappears. +**How to avoid:** `ceiling: false` for backend-only grants; the scope limit's methods do the capping. + +### Pitfall 6: OIDC surface still mounted +**What goes wrong:** `Routes` always mounts OIDC discovery, JWKS, `/oauth/authorize`, `/oauth/token`, `/oauth/userinfo` and the authorized-apps routes [VERIFIED: sm-oauthserver-plugin/routes.go]. D-14 wants no OIDC surface; MCP clients also probe `/.well-known/openid-configuration` as a fallback [CITED: MCP authorization spec, "Authorization Server Metadata Discovery"]. +**How to avoid:** additive `oidc.enabled` (default true) key; grzyby sets false. The nginx vhost routes only the MCP paths anyway. + +### Pitfall 7: SameSite=Strict on the cross-site redirect chain +**What goes wrong:** the top-level navigation from the connector's site to `/gfadmin/connect` does not carry the Strict cookie; a server-side check on that request would see "anonymous". +**How to avoid:** the SPA shell is public and the session is read by the SPA's same-origin API fetch (D-03). A localhost proof is same-site and cannot exercise this; flag the live connector check for the deploy step [ASSUMED: browser SameSite semantics for subresource fetches from a same-origin document]. + +### Pitfall 8: `tokens_valid_after` granularity +**What goes wrong:** cabana's `revocationCutoff()` is `now + 1s`, and `issuedBeforeCutoff` refuses `createdAt < cutoff + 1s`, so a consent completed within about two seconds after an admin-set password or deactivation/reactivation would be refused. +**How to avoid:** acceptable; tests must sleep past the window or use a clock seam. + +### Pitfall 9: Revocation event fired outside the transaction +**What goes wrong:** firing the new cabana event after commit makes the oauthserver revocation non-atomic and its errors silent. +**How to avoid:** fire with the save's `Tx` (as sm-user-plugin does), and keep the verifier cutoff check. + +### Pitfall 10: Docker-backed and MCP-tagged tests are skipped silently +**What goes wrong:** `go test -short` skips testcontainers tests; pier is linked only with `-tags summercms_mcp` (`modules/surf/pier_on.go:1`). A full flow test without the tag never mounts `/mcp`. +**How to avoid:** run the backend-mode end-to-end test with `-tags summercms_mcp` and without `-short`. + +## Code Examples + +### Verifier backend branch (sm-oauthserver-plugin) +```go +// Source: pattern of classes/mcp_verifier.go MCPVerifyToken (read this session) +if token.UserID == 0 && token.BackendUserID != nil { // user_id NULL scans as 0 + admin, err := cabana.BackendPrincipal(ctx, v.App, *token.BackendUserID) + if err != nil { + return pact.MCPGrant{}, err + } + if admin == nil || issuedBeforeCutoff(token.CreatedAt, admin.TokensValidAfter) { + return pact.MCPGrant{}, pact.ErrMCPTokenInvalid + } + v.stamp(ctx, db, token.ID, now) + return pact.MCPGrant{ + UserID: 0, BackendUserID: *token.BackendUserID, Subject: pact.MCPGrantSubjectBackend, + ClientID: token.ClientID, TokenID: token.ID, + Scopes: slices.Clone(stringsOf(token.Scopes)), ExpiresAt: *token.ExpiresAt, + }, nil +} +// … existing user path unchanged +``` +`cabana.BackendPrincipal` errors with `ErrUnauthenticated` when cabana is not activated; that is a fail-closed 401, which is correct. + +### pier identity branch +```go +// Source: modules/pier/identity.go resolveOAuth (read this session), additive branch +grant, err := verifier.MCPVerifyToken(ctx, raw) +if err != nil { + return Identity{}, ErrUnauthorized +} +if grant.Subject == pact.MCPGrantSubjectBackend { + if grant.UserID != 0 || grant.BackendUserID == 0 { + return Identity{}, ErrUnauthorized + } + scopes := append([]string(nil), grant.Scopes...) + return Identity{ + Scopes: scopes, + Binding: "oauth:backend:" + grant.ClientID + ":" + strconv.FormatUint(uint64(grant.BackendUserID), 10), + ExpiresAt: grant.ExpiresAt, + TokenKind: TokenKindOAuth, + Backend: &pact.MCPSubject{Guard: BackendGuard, UserID: grant.BackendUserID, Scopes: scopes, + ClientID: grant.ClientID, TokenID: grant.TokenID, ScopeLimited: true}, + }, nil +} +if grant.UserID == 0 { + return Identity{}, ErrUnauthorized +} +// … existing user path unchanged +``` + +### oauthserver config (backend mode, grzyby) +```yaml +# config/golem15.oauthserver.yaml +oidc: + enabled: false +mcp: + enabled: true + subject: backend # user (default) | backend + # consent_path: "" # empty: /connect in backend mode, /connect in user mode + resource: http://127.0.0.1:8096/mcp # must equal mcp.resource of config/mcp.yaml; production via env +``` +Existing keys read today: `golem15.oauthserver.mcp.enabled`, `golem15.oauthserver.mcp.resource` [VERIFIED: sm-oauthserver-plugin/servers.go:126-127]; `mcp_scopes` filters declared member scopes and should be ignored (or refused) in backend mode. The port 8096 is the vhost's upstream (`proxy_pass http://127.0.0.1:8096;`) [VERIFIED: deploy/nginx/grzybyfunkcjonalne-staging.conf:182]. + +### nginx locations to add (grzyby, both vhosts) +```nginx +location = /.well-known/oauth-authorization-server { auth_basic off; limit_except GET HEAD { deny all; } proxy_pass http://127.0.0.1:8096; … same proxy headers … } +location ^~ /oauth/mcp/ { auth_basic off; limit_except GET POST { deny all; } client_max_body_size 64k; proxy_pass http://127.0.0.1:8096; … } +``` +The two PRM locations and `/mcp` exist already (staging.conf:175-224). Exact locations are needed because a `location ~ /\.` dotfile rule answers 404 for `/.well-known/*` otherwise (staging.conf:195-196 comment and :254). `/gfadmin` is already proxied (staging.conf:122). No `add_header` in the new locations (`scripts/check-deploy.sh` fails on one, DEPLOY.md:239). `auth_basic off` is required because the connector fetches metadata, register and token server-to-server. + +## Local proof (SC-4) + +grzyby runs as one Go binary locally (Nuxt is not needed for the OAuth paths; app.url pointing at the Go port serves `/gfadmin`, `/mcp`, `/.well-known/*`, `/oauth/mcp/*`). Recommended: `scripts/smoke-mcp-oauth.sh` (bash + curl + openssl, no new deps): +1. `POST /mcp` without bearer → 401 and `resource_metadata`. +2. `GET /.well-known/oauth-protected-resource/mcp` → `authorization_servers`, `scopes_supported` contains `journal`. +3. `GET /.well-known/oauth-authorization-server` → endpoints; `GET /.well-known/openid-configuration` → 404 (OIDC off). +4. `POST /oauth/mcp/register` (redirect `http://127.0.0.1:/cb`, auth method none). +5. PKCE: `verifier=$(openssl rand -base64 48 | tr '+/' '-_' | tr -d '=\n')`, challenge = `printf %s "$verifier" | openssl dgst -sha256 -binary | base64 | tr '+/' '-_' | tr -d '='`. +6. `GET /oauth/mcp/authorize?…&resource=…` → 302 to `/gfadmin/connect?request=`. +7. Admin login: `POST /gfadmin/api/v1/auth/login` with `X-Requested-With`, cookie jar (the login handler sets the cookie when the CSRF header is present; `modules/cabana/http.go` comment "without it the response is a Bearer body and no cookie is set"). +8. `GET`/`POST /gfadmin/api/v1/mcp/consent/` with the jar and `X-Requested-With` → `redirect_uri` with `code`. +9. `POST /oauth/mcp/token` (code, verifier, resource) → `oas_at_…` (+ refresh when ticked). +10. MCP `initialize` → `notifications/initialized` → `tools/list` (Journal tools present) → `tools/call journal_show_post`. +11. Regression: the same with a `g15_` token. +12. Revocation: change the admin's password via `PUT /gfadmin/api/v1/account` → next `/mcp` call 401. + +A Claude connector run is part of the deferred deploy check. + +## Release mechanics + +- Order (CLAUDE.md, memory): framework commits → plugin commits (development through `go.work` replace) → at phase completion only: framework tag = next free patch on `master` (v0.6.6 now; phase 35 may take v0.6.7 first — pick the next free one at tag time) → plugin `go.mod` `require git.golem15.com/golem15/summercms vX.Y.Z` (today v0.6.0 with `replace => ../summercms.go`) → plugin tag **v0.1.8** → grzyby: add submodule `plugins/golem15/oauthserver` (`url = git@git.golem15.com:golem15/sm-oauthserver-plugin.git`, `branch = master`), `go.work use ./plugins/golem15/oauthserver`, `go.mod require sm-oauthserver-plugin v0.1.8` + `replace … => ./plugins/golem15/oauthserver`, bump `summercms` require (today v0.6.1) — plugin pushed first, pointer bump as its own commit. +- Changelog posts the same day for the framework tag and the plugin tag (`../sm-summercmsio-app/scripts/changelog-post.py`). No push/tag without the user's go-ahead. +- sm-bm-app (oauthserver v0.1.7, summercms v0.6.4) and sm-demo-app (v0.1.6, v0.6.1) are not bumped in this phase; verify them against the new plugin with a scratch `go.work` replace. + +## State of the Art + +| Old Approach | Current Approach | When Changed | Impact | +|--------------|------------------|--------------|--------| +| MCP clients rely on DCR | Spec 2025-11-25: Client ID Metadata Documents preferred, DCR "MAY", kept for backwards compatibility | MCP spec 2025-11-25 | wristband offers DCR only; clients that support CIMD fall back to DCR when `client_id_metadata_document_supported` is absent [CITED: modelcontextprotocol.io/specification/2025-11-25/basic/authorization] | +| Client picks scopes | Use `scope` from WWW-Authenticate, else all PRM `scopes_supported` | same | consent receives the whole catalog; DefaultScopes matters only for clients that send none | + +## Assumptions Log + +| # | Claim | Section | Risk if Wrong | +|---|-------|---------|---------------| +| A1 | cabana scope names (`*`, `journal:read`) are acceptable to Claude/ChatGPT connectors as scope tokens | Pattern 3 | connector refuses or drops `*`; mitigate by offering `admin:read`/plugin scopes and testing at deploy | +| A2 | SameSite=Strict cookie is sent on the SPA's same-origin fetch after a cross-site redirect chain | Pitfall 7 | consent always shows login; would need a re-navigation trick; only checkable live | +| A3 | The Claude connector requests `offline_access` when advertised | Pattern 5 | "Stay connected" never shown; tokens expire hourly | +| A4 | cabana list relation columns can join consents→clients via `client_id` string references | Pattern 6 | the admin screen needs a ListExtendQuery join or a partial instead | +| A5 | Firing a new cabana event synchronously inside admin saves has no ordering conflict with existing FormAfterUpdate hooks | D-13 map | minor rework of hook placement | +| A6 | No other app relies on `Options` zero values producing `/connect` other than through `DefaultOptions` | Pattern 3 | none if empty-means-default is kept | + +## Open Questions + +1. **Show consent when already consented?** The user-mode contract has `consent_required`; vue-oauth-layer omits scopes when consent is stored. Recommendation: always show the card for admins (one click), keep the field for parity. +2. **Keep `oidc.enabled` as a new key or tie OIDC off to `mcp.subject: backend`?** Recommendation: separate key (default true); coupling would block the deferred coexistence. +3. **`mcp_scopes` in backend mode:** ignore or fail boot? Recommendation: fail boot with a clear message when set together with `subject: backend`. +4. **"Sign out everywhere":** cabana offers none today. Recommendation: document; if added later it fires the new event with its own reason. + +## Environment Availability + +| Dependency | Required By | Available | Version | Fallback | +|------------|------------|-----------|---------|----------| +| Go | all Go code/tests | ✓ | go1.27.2 | — | +| Node / npm | admin SPA build/tests | ✓ | v24.22.0 / 12.2.1, `admin/node_modules` present | — | +| Docker | testcontainers Postgres tests | ✓ | 29.9.1, daemon reachable | `sudo -u golem` if the group list is stale (CLAUDE.md) | +| swag | openapi script | via `go run …@v1.16.6` | — | — | +| openssl, curl | local proof script | assumed present [ASSUMED] | — | a Go test instead | + +**Missing dependencies with no fallback:** none. + +## Validation Architecture + +### Test Framework +| Property | Value | +|----------|-------| +| Framework | Go `testing` (+ testcontainers Postgres), vitest 3.2.7 (+ browser config with playwright) | +| Config file | per-package `TestMain` (`sm-oauthserver-plugin/testmain_test.go` with `flag.Parse()` + `testing.Short()`); `admin/vitest.config*.ts` | +| Quick run command | `go test -short ./modules/pier ./modules/wristband ./modules/cabana ./modules/pact` (framework); `cd ../sm-oauthserver-plugin && go test -short ./...` | +| Full suite command | `go vet ./... && go test ./... && go test -tags summercms_mcp ./modules/pier ./modules/surf`; `cd ../sm-oauthserver-plugin && go test ./... && go test -tags summercms_mcp ./...`; `npm --prefix admin run typecheck && npm --prefix admin run test && npm --prefix admin run test:browser`; `scripts/check-admin-openapi.sh --check && scripts/check-admin-dist.sh`; `summer docs:build --check` | + +### Success criteria → tests +| ID | Behavior | Type | Command | File exists? | +|----|----------|------|---------|-------------| +| SC-1 | `ConsentPath`/`DefaultScopes` defaults keep `/connect` and `read`; set values used | unit | `go test -short ./modules/wristband -run 'TestAuthorize(ConsentPath|DefaultScopes)'` | ❌ new | +| SC-1 | backend mode authorize → 302 `//connect`; user consent routes 404; OIDC routes 404 with `oidc.enabled: false` | integration (docker) | `cd ../sm-oauthserver-plugin && go test ./ -run TestBackendMode` | ❌ new | +| SC-1 | consent endpoint: anon 401, foreign/expired 404, hidden scopes, `*` collapse, allow → redirect with code, deny → access_denied | integration | `go test ./modules/cabana -run TestMCPAdminConsent` (fake provider) + plugin `-run TestBackendConsent` | ❌ new | +| SC-1 | rows: `user_id IS NULL`, `backend_user_id` set on code, access, refresh, consent; migration up/down | integration | plugin `go test ./ -run 'TestBackendSubjectMigration|TestBackendGrantRows'` | ❌ new | +| SC-1 | mode off: existing suites unchanged | regression | plugin `go test ./...`; sm-bm-app `go test ./...` with scratch go.work replace | ✅ | +| SC-1 | ConnectView: renders card, switch account, Allow/Deny navigation, router sends anon to login | unit (vitest) | `npm --prefix admin run test -- tests/views/ConnectView.test.ts tests/app/router.test.ts` | ❌ new (router ✅) | +| SC-2 | backend grant → backend subject, no frontend subject, distinct binding, ceiling off, ScopeLimit applied; user-mode linked grant unchanged | unit | `go test -short ./modules/pier -run 'TestBackendOnlyGrant|TestLinkedGrantNoScopeLimit'` | ❌ new | +| SC-2 | `journal:read` grant lists read tools only; `journal` lists write tools; equals `g15_` token with same scopes | integration (docker, MCP tag) | plugin `go test -tags summercms_mcp ./ -run TestBackendGrantToolsMatchPersonalToken` | ❌ new | +| SC-3 | My account items list + revoke ends one client's sessions | unit + integration | `go test ./modules/cabana -run TestAccountContributionItems`; plugin `-run TestBackendRevokeFromAccount` | ❌ new | +| SC-3 | delete/deactivate/password (own, set, CLI)/role/role-permissions → tokens revoked + MCPSubjectChanged per client; verifier refuses pre-cutoff token | integration | `go test ./modules/cabana -run TestBackendAccessRevokedEvent`; plugin `-run TestBackendCascade` | ❌ new | +| SC-4 | local stack proof | smoke (manual-run script) | `cd ../sm-grzybyfunkcjonalne-app && scripts/build.sh && scripts/smoke-mcp-oauth.sh` | ❌ new | +| SC-4 | vhost contains the OAuth locations, no add_header | static | `cd ../sm-grzybyfunkcjonalne-app && scripts/check-deploy.sh` | ✅ (extend) | +| SC-5 | docs identifiers and snippets | static | `summer docs:build --check` | ✅ | + +### Sampling Rate +- **Per task commit:** the quick command of the touched repo. +- **Per wave merge:** the full suite of the touched repo. +- **Phase gate:** all full suites green, `check-admin-openapi.sh --check`, `check-admin-dist.sh`, the grzyby smoke, before `/msd-verify-work`. + +### Wave 0 Gaps +- [ ] Plugin harness helper that boots with `mcp.subject: backend` and a backend user (extend `harness_test.go` `bootOAuthWith`). +- [ ] A pier test fake verifier returning a backend grant (existing helpers in `modules/pier/helpers_test.go`). +- [ ] `admin/tests/views/ConnectView.test.ts` fixtures for the new endpoint. +- [ ] `scripts/smoke-mcp-oauth.sh` in grzyby. + +## Security Domain + +### Applicable ASVS Categories +| ASVS Category | Applies | Standard Control | +|---------------|---------|-----------------| +| V2 Authentication | yes | cabana login (2FA/Turnstile) reused; PKCE S256 enforced by wristband | +| V3 Session Management | yes | `summer_admin` HttpOnly/Strict cookie; `tokens_valid_after` cutoff on OAuth tokens; refresh rotation + replay family revocation | +| V4 Access Control | yes | `cabana.Allows` + `ScopeLimitFor`; consent scopes ⊆ requested ∩ grantable; per-admin locks | +| V5 Input Validation | yes | wristband client/redirect/resource validation; cabana `validateTokenScopes`; capped JSON bodies | +| V6 Cryptography | yes | existing token hashing (SHA-256 of 32 random bytes); no new crypto | + +### Known Threat Patterns +| Pattern | STRIDE | Standard Mitigation | +|---------|--------|---------------------| +| CSRF on consent allow | Tampering | `requireAjax` + Strict cookie + interactive-only | +| Open redirect via consent | Spoofing | wristband exact redirect match; SPA navigates only to the server-issued URI | +| Frontend user hijacking a backend pending request | Elevation | backend mode does not mount user consent routes (Pitfall 4) | +| Scope escalation (granting scopes the admin lacks) | Elevation | cabana filters with `scopeOverlaps` and re-validates on decide | +| Grant outliving a password change/deactivation | Elevation | in-tx revocation + verifier cutoff check | +| Cross-admin session reuse | Information disclosure | per-admin binding key | +| Phishing via client name | Spoofing | show redirect host (MCP spec MUST) [CITED: MCP authorization spec "Localhost Redirect URI Risks"] | + +## Suggested plan split (lean, for the planner to confirm with the user) + +1. **Framework seams** (summercms.go): pact additions, wristband options, pier backend-only branch + scope flag, cabana `TokenScopeNames`, consent endpoint + swag, `BackendAccessRevokedEvent` at every site, account contribution items API; module READMEs and docs/services/oauth-server.md, mcp.md, backend/admin-spa.md, users-and-permissions.md, plugins/registration.md in the same commits. Smoke tests only. +2. **Admin SPA** (summercms.go `admin/`): ConnectView + route, switch account, items rendering in AccountContributions, regenerated openapi/types, rebuilt `modules/boardwalk/dist`. Can run in parallel with 3 once 1 lands. +3. **sm-oauthserver-plugin backend mode**: config keys (`mcp.subject`, `mcp.consent_path`, `oidc.enabled`), migration, per-row store, backend locks, verifier/refresh branch, consent provider, cabana-event listener, My account section, MCP connections screen + permission, README. +4. **grzyby wiring + local proof**: submodule, summer.yaml, config, nginx, smoke script, DEPLOY.md. +5. **Unit tests + release checkpoint** (project rule: tests last): the Validation Architecture tests across the three repos, regression runs for sm-bm-app, tags (framework next patch, plugin v0.1.8), pointer bump, changelog posts — on the user's go-ahead. + +## Project Constraints (from CLAUDE.md) + +- One Go module; new code in existing modules; no new module needed (beach-name rule not triggered). +- Standard library first; no new dependency without a decision note (none needed). +- YAML via goccy/go-yaml only. +- Docs: exported API, config key or CLI change updates the module README and `docs/` in the same commit; every identifier in docs must exist; Go code blocks in docs/READMEs are `src=` references (`summer docs:sync`). +- Admin changes: rebuild and commit `modules/boardwalk/dist`, pass `scripts/check-admin-dist.sh`; openapi via `scripts/check-admin-openapi.sh`. +- Keep `go vet ./...` and `go test ./...` green at every commit; Docker tests skip under `-short` with `flag.Parse()` + `testing.Short()`. +- Framework code never names a consuming application. +- Core plugins shared across apps: no breaking changes (user, oauthserver, journal). +- Plugin commit first, then the app pointer bump as a separate commit; tags only at phase completion on the default branch, next patch by default; changelog post the same day; no push/tag/deploy without the user's go-ahead. +- No co-author tags; stage files by path; leave other sessions' uncommitted edits (e.g. `sm-oauthserver-plugin/go.work`, `.planning/state.json`). +- Lean planning: present plan count and scopes before writing PLAN.md; unit tests are the last plan; STATE.md via `msd_run query state.*`; g15office comment when the phase advances. + +## Sources + +### Primary (HIGH confidence, read this session) +- summercms.go: `modules/wristband/{authorize,server,consent,stores,token}.go`, `modules/pier/{identity,backend_guard,events,prm}.go`, `modules/pact/{mcp,capabilities}.go`, `modules/cabana/{auth,prefix,token_guard,token_resolver,token_scopes,api_tokens,account,account_contributions,account_tokens,backend_users_admin,backend_roles_admin,subject_events,record_events,commands,http,registry,token_commands}.go`, `modules/party/registry.go`, `modules/surf/router.go`, `admin/src/app/router.ts`, `admin/src/views/LoginView.vue`, `admin/package.json`, `scripts/check-admin-{dist,openapi}.sh` +- sm-oauthserver-plugin: `plugin.go`, `servers.go`, `routes.go`, `admin*.go`, `config/config.yaml`, `updates/*`, `models/*`, `classes/{mcp_store,mcp_verifier,mcp_backend_binding,cascade,subject_events,mcp_scopes}.go`, `controllers/{mcp_consent_api,authorizations,clients}.go`, `console/prune.go`, `go.mod` +- sm-grzybyfunkcjonalne-app: `summer.yaml`, `config/{mcp,backend,app}.yaml`, `.gitmodules`, `go.mod`, `go.work`, `deploy/nginx/grzybyfunkcjonalne-staging.conf`, `DEPLOY.md` +- sm-user-plugin `classes/events.go`; sm-journal-plugin `token_scopes.go`, `mcp.go`; sm-bm-app `config/golem15.oauthserver.yaml` +- gorm v1.31.2 `schema/field.go` (module cache) + +### Secondary (MEDIUM) +- MCP Authorization spec 2025-11-25 (WebFetch): scope selection, discovery order, DCR/CIMD, redirect-host display + +### Tertiary (LOW) +- Connector behaviour for `*` scopes and `offline_access` (A1, A3): not probed + +## Metadata + +**Confidence breakdown:** +- Standard stack: HIGH — no new packages; versions read from go.mod/tags. +- Architecture: HIGH for Go seams (code read); MEDIUM for SPA cookie behaviour on a real cross-site connector. +- Pitfalls: HIGH — each tied to a read line of code. + +**Process note:** the research-plan/research-store seam was not used; all findings come from direct file reads and one spec fetch. + +**Research date:** 2026-11-20 +**Valid until:** 2026-12-20 (other sessions are changing cabana and the plugin; re-check `git log` of cabana, pier and sm-oauthserver-plugin before executing) diff --git a/.planning/phases/32.2-mcp-oauth-with-administrator-subjects/32.2-VALIDATION.md b/.planning/phases/32.2-mcp-oauth-with-administrator-subjects/32.2-VALIDATION.md new file mode 100644 index 00000000..178dcf67 --- /dev/null +++ b/.planning/phases/32.2-mcp-oauth-with-administrator-subjects/32.2-VALIDATION.md @@ -0,0 +1,90 @@ +--- +phase: "32.2" +slug: "mcp-oauth-with-administrator-subjects" +# status lifecycle: draft (seeded by plan-phase) → validated (set by validate-phase §6) +# audit-milestone §5.5 distinguishes NOT-VALIDATED (draft) from PARTIAL (validated + nyquist_compliant: false) (#2117) +status: draft +nyquist_compliant: false +wave_0_complete: false +created: "2026-11-20" +--- + +# Phase 32.2 — Validation Strategy + +> Per-phase validation contract for feedback sampling during execution. + +--- + +## Test Infrastructure + +| Property | Value | +|----------|-------| +| **Framework** | go test (+ testcontainers Postgres), vitest (+ browser config) | +| **Config file** | per-package `TestMain` (`sm-oauthserver-plugin/testmain_test.go`); `admin/vitest.config*.ts` | +| **Quick run command** | `go test -short ./modules/pier ./modules/wristband ./modules/cabana ./modules/pact`; `go -C ../sm-oauthserver-plugin test -short ./...` | +| **Full suite command** | `go vet ./... && go test ./... && go test -tags summercms_mcp ./modules/pier ./modules/surf`; `go -C ../sm-oauthserver-plugin test ./... && go -C ../sm-oauthserver-plugin test -tags summercms_mcp ./...`; `npm --prefix admin run typecheck && npm --prefix admin run test && npm --prefix admin run test:browser`; `scripts/check-admin-openapi.sh --check && scripts/check-admin-dist.sh`; `go run ./cmd/summer docs:build --check` | +| **Estimated runtime** | ~60 s quick, ~6 min full (Docker) | + +--- + +## Sampling Rate + +- **After every task commit:** Run the quick command of the touched repo +- **After every plan wave:** Run the full suite of the touched repo +- **Before `/msd-verify-work`:** All full suites green, plus `check-admin-openapi.sh --check`, `check-admin-dist.sh` and the grzyby smoke script +- **Max feedback latency:** 60 seconds (quick loop) + +--- + +## Per-Task Verification Map + +Filled by the planner per task; source map from RESEARCH.md §Validation Architecture: + +| Criterion | Behavior | Test Type | Automated Command | File Exists | Status | +|-----------|----------|-----------|-------------------|-------------|--------| +| SC-1 | wristband `ConsentPath`/`DefaultScopes` defaults unchanged, set values used | unit | `go test -short ./modules/wristband -run 'TestAuthorize(ConsentPath\|DefaultScopes)'` | ❌ W0 | ⬜ pending | +| SC-1 | backend mode authorize → admin `/connect`; user consent + OIDC routes absent | integration | `go -C ../sm-oauthserver-plugin test ./ -run TestBackendMode` | ❌ W0 | ⬜ pending | +| SC-1 | admin consent endpoint (401/404/hidden scopes/allow/deny) | integration | `go test ./modules/cabana -run TestMCPAdminConsent`; plugin `-run TestBackendConsent` | ❌ W0 | ⬜ pending | +| SC-1 | backend grant rows + migration up/down | integration | plugin `go test ./ -run 'TestBackendSubjectMigration\|TestBackendGrantRows'` | ❌ W0 | ⬜ pending | +| SC-1 | mode off: existing suites unchanged | regression | plugin `go test ./...`; sm-bm-app `go test ./...` | ✅ | ⬜ pending | +| SC-1 | ConnectView + router | unit | `npm --prefix admin run test -- tests/views/ConnectView.test.ts tests/app/router.test.ts` | ❌ W0 | ⬜ pending | +| SC-2 | pier backend-only grant, ScopeLimit; linked grant unchanged | unit | `go test -short ./modules/pier -run 'TestBackendOnlyGrant\|TestLinkedGrantNoScopeLimit'` | ❌ W0 | ⬜ pending | +| SC-2 | tools match a `g15_` token with equal scopes | integration | plugin `go test -tags summercms_mcp ./ -run TestBackendGrantToolsMatchPersonalToken` | ❌ W0 | ⬜ pending | +| SC-3 | My account items + revoke | unit + integration | `go test ./modules/cabana -run TestAccountContributionItems`; plugin `-run TestBackendRevokeFromAccount` | ❌ W0 | ⬜ pending | +| SC-3 | delete/deactivate/password/role cascade + verifier cutoff | integration | `go test ./modules/cabana -run TestBackendAccessRevokedEvent`; plugin `-run TestBackendCascade` | ❌ W0 | ⬜ pending | +| SC-4 | local stack proof | smoke | `cd ../sm-grzybyfunkcjonalne-app && scripts/smoke-mcp-oauth.sh` | ❌ W0 | ⬜ pending | +| SC-4 | vhost OAuth locations | static | `cd ../sm-grzybyfunkcjonalne-app && scripts/check-deploy.sh` | ✅ (extend) | ⬜ pending | +| SC-5 | docs identifiers and snippets | static | `go run ./cmd/summer docs:build --check` | ✅ | ⬜ pending | + +*Status: ⬜ pending · ✅ green · ❌ red · ⚠️ flaky* + +--- + +## Wave 0 Requirements + +- [ ] Plugin harness helper booting with `mcp.subject: backend` and a backend user (extend `harness_test.go` `bootOAuthWith`) +- [ ] pier fake verifier returning a backend grant (`modules/pier/helpers_test.go`) +- [ ] `admin/tests/views/ConnectView.test.ts` fixtures for the new endpoint +- [ ] `scripts/smoke-mcp-oauth.sh` in sm-grzybyfunkcjonalne-app + +--- + +## Manual-Only Verifications + +| Behavior | Requirement | Why Manual | Test Instructions | +|----------|-------------|------------|-------------------| +| `SameSite=Strict` admin cookie on a real cross-site connector redirect chain | SC-1, SC-4 | Local proof is same-site | After deploy (out of phase), add the connector in Claude and sign in | +| Claude connector handling of `*` and `offline_access` | SC-4 | Needs the live connector | Same live check | + +--- + +## Validation Sign-Off + +- [ ] All tasks have `` verify or Wave 0 dependencies +- [ ] Sampling continuity: no 3 consecutive tasks without automated verify +- [ ] Wave 0 covers all MISSING references +- [ ] No watch-mode flags +- [ ] Feedback latency < 60s +- [ ] `nyquist_compliant: true` set in frontmatter + +**Approval:** pending