Repository navigation
feat(broker): the hosted-MCP intake flow, from Connect to a connected row (TASK-172 slice 3a) - #1995
Merged
Merged
Conversation
…nd PKCE (TASK-172) Build-order step 3's decidable half. Nothing here reaches the vendor: the authorization server is a parameter, so the slice is testable without one (connector-ops, scope note 14:24 — every step except the live lines). - The Client ID Metadata Document: client_id is the URL we serve, one redirect URI naming the entry, token_endpoint_auth_method none, the entry's scopes. - Which client id we present, in the ruling's order: CIMD, then a pre-registered per-entry key, then DCR. A dcr entry refuses until it has registered rather than inventing an id. - RFC 8707's resource on the authorization request and on both token requests, built by one function pair so they cannot drift. - PKCE S256, because a CIMD client holds no secret.
The CIMD document as a public route, mounted under `/api/integrations/connect/hosted-mcp` — deeper than `/:podId`, so an entry id can never be read as a pod id. It is unauthenticated on purpose: the authorization server fetches it before any member has consented, and it is the same document for every member. An unknown entry is a 404, not a document with empty fields: a document naming no redirect URI is still a client an AS could accept and then have nowhere to send a code. Measured: 4 route arms + 18 intake arms, (2, 22), 0 failed, 0 runtime errors; `tsc:check` clean; the 12 integrations route suites (109 tests) unchanged; eslint multiset on the touched route file identical to base (33 = 33).
The start route: entry lookup, client id in the ruling's order, authorization server discovery, PKCE + a single-use state nonce, then the pending row. Discovery runs before the row is written, so a vendor outage leaves no pending row behind — a row whose only content is a dead nonce would show the connector as mid-connect forever. The row is found by `(createdBy, config.entryId)` in the filter rather than inserted blind, because §2 allows one row per person per entry and an insert would collide with the partial unique index instead. Measured: 11 route arms (29 with the intake service), (2, 29), 0 failed, 0 runtime errors; `tsc:check` clean; the 12 integrations route suites (109 tests) unchanged; eslint on the route file 0 findings before and after.
The callback: state claim, RFC 9207 `iss`, the exchange, the pair, and §2's account-change rule. Three decisions worth naming. The state is consumed BEFORE the exchange, by `$unset` of `config.pendingAuth` rather than by the Slack callback's `claimId` — and not by preference: `config.pendingAuth` is a strict subdocument (models/Integration.ts:375), so a `claimId` written onto it would be dropped silently and no row would ever read as claimed. Consuming the subdocument is atomic on the same terms and returns the verifier in the pre-image, which is where it lives. `iss` is refused only when present and different: a vendor that sends none still had its code delivered to a redirect URI naming this entry, and treating absence as a refusal would break the vendors that do not implement RFC 9207. §2's revocation runs on an unknowable subject as well as a differing one — assuming the account is unchanged is the assumption that costs the most, and the TASK-148 guard cannot see this path because the row's `createdAt` survives the reconnect. An exchange that answers without a refresh token now drops the row's old one: `put` upserts on (row, kind), so the access half is replaced in place, but a stale refresh half would leave the mint refreshing against a retired grant and calling the failure a vendor outage. Measured: 10 callback arms + 11 route arms + 18 intake arms, (2, 21) and (13, 127) with the integrations suites, 0 failed, 0 runtime errors; `tsc:check` clean; eslint on the route file 0 findings.
…rce (TASK-172) An audit of slice 3 by mutation, which found three things the arms could not see. The document and the start route each spelled the redirect path themselves. The audit changed one and the other kept its own copy, so the arm that should have caught it passed — a document advertising a path the start route does not send is a client the vendor accepts and then refuses the code for. Both leaf names now come from one pair of constants. Two arms were tautological: they computed the expected URL with `hostedMcpApiBase()`, the function under test, so a wrong origin moved the answer and the question together. Both now assert the literal. The account-change rule had a case with no arm at all: a row carrying a credential but no recorded subject, reconnecting to a vendor that still issues no subject. Neither side has a subject, so "cannot be compared" is the only reading that is not a guess. Measured: 43 arms over 3 suites, and the ledger (/tmp/kai-172s3-ledger.py, 33 mutations) at baseline (3, 43) before every run — 32 killed, NO SURVIVORS, NO NAMED-ARM MISSES. The thirty-third is refused by the compiler rather than by an arm: `token_endpoint_auth_method: 'none'` is a literal type, so a mutation that makes it any other value cannot load. Recorded, not counted. `tsc:check` clean; eslint on both changed sources 0 findings.
…ence (TASK-172) `config` on `Integration` is a strict subdocument, and the connect commit wrote `credentialRef`, `refreshTokenRef`, `refreshGeneration`, `grantedScope`, `expiresAt` and `providerSubject` without the `config.` prefix. Mongoose kept `status` and dropped all six, so the callback would answer `connected` on a row holding no token: every later `credentialFor` call refuses `credential_missing`, `refreshGeneration` is undefined so the §10.3 fence can never win a bump, and `providerSubject` is absent so a reconnect as a different account revokes nothing. Measured on a real mongod, not reasoned about: the same `$set` applied to a real hosted-mcp row through the real model came back with all six paths undefined, with the prefixed form landing all six. The existing arms could not see this — they read back a MOCK, which records what it was handed rather than what the schema kept, and asserted the unprefixed keys as the expected shape. The guard is now the schema itself: `__tests__/utils/schemaPathGuard.js` asks whether each path a write names is declared, and both hosted-mcp write sites assert that the answer is "none undeclared". A nested object is declared by its leaves (`config.pendingAuth` is false while `config.pendingAuth.state` is true, and the object persists), which is why the predicate checks prefixes too. Proved with teeth: an undeclared key no shape assertion names (`revokedAtX`) is killed by the guard alone. 43 arms over 3 suites, 0 failed; tsc:check clean; eslint 0 findings.
…ired ref for real (TASK-172)
Three more paths in the same handler assumed the credential fields sat at the
row's top level, where `config` (a strict subdocument) keeps them:
- `consumed.credentialRef` and `consumed.providerSubject` were always
`undefined` on a real row, so `accountChanged` was always false and §2's rule —
a reconnect as a DIFFERENT account revokes the grants made against the old
account's reach — could never fire. Two unknowns were also treated as the same
account, the assumption the rule exists to refuse.
- `consumed.refreshTokenRef` was always `undefined`, so the retired-refresh
branch never ran: a vendor that stops issuing refresh tokens left the row
pointing at a grant that no longer exists, and the mint would refresh against
it and call the failure a vendor outage.
- `$set: {'config.refreshTokenRef': undefined}` does NOT clear the field:
measured on a real mongod, the old value stays on the row. The clear is now an
explicit `null`, which does.
The arms could not see any of this because the fixture — not just the calls —
carried the wrong shape: `setStoredRow` spread its overrides across the top
level, so the handler and the arms agreed on a row the database never returns.
The fixture now nests them under `config`, which is what makes the four new
mutations die in the arms that name the behaviour (M34–M37): reading the wrong
shape kills the revoke arms, and dropping the `|| null` kills the retired-refresh
arm.
Also adds the arm that NAMES the optional-`iss` rule (a callback carrying no
`iss` connects, because RFC 9207 is optional). The rule was enforced and covered
only as collateral — twelve arms failed when M33 refused an absent `iss`, and not
one of them said why that was wrong.
Ledger: 37 mutations, 36 killed, 1 NO REPORT (a TS literal type refuses the
mutant at compile time, recorded and not counted), NO SURVIVORS, NO NAMED-ARM
MISSES, NO NOT-APPLIED, baseline (3, 44) re-asserted on every run. 44 arms over
3 suites, 0 failed; tsc:check clean; lint-diff identical to base (11 errors /
2 warnings, all pre-existing classes).
…172) `$set` with `undefined` is a no-op on the strict `config` subdocument, so an exchange that returned no ID token left the PREVIOUS `providerSubject` on the row — a durable claim about which vendor account is connected. The next reconnect compared against it, read "same account", and kept grants minted under whatever account held the row in between. That is the §2 account-change rule the subject exists to enforce, and the mocked callback suite could not see it: a payload arm reading `providerSubject: undefined` is exactly as green whether the write clears the field or does nothing at all. `providerSubject || null` clears it, so the comparison is two unknowns and revokes. Witnessed against the real `Integration` schema on a real mongod (`hostedMcpConnect.storedRow.test.js`): its two arms fail on the old code and pass on the new, and a vendor that DOES issue a subject still stores it. Ledger: 38 mutations, 37 killed, 1 compiler-refused, no survivors, no named-arm misses, none unapplied; M38 restores the defect and is killed by the arm that names the claim.
…TASK-172) Vera's hold on #1995, and it is the serious class: the callback found the pending row by `config.pendingAuth.state` alone. The state is unguessable, but it is the STARTER who holds it — it travels in the authorization URL — so a starter can send that URL to somebody else, and when the victim approves on the vendor's own consent screen (which really does say "Commonly"), the code that comes back is the victim's. We would exchange it and write the victim's access and refresh tokens onto the STARTER's row, whose `createdBy` is the starter, so every trail row would correctly name the starter and the credential behind it would be somebody else's. PKCE does not catch it (it binds the code to this instance, which is what the attacker wants) and the account-change rule cannot (it needs a stored subject, and a first connect has none). The control is §10.7's cell, and it is a second secret rather than a stronger first one: `state` proves the flow EXISTS, the nonce proves the browser that FINISHES it is the one that started it. `/start` mints it alongside the state, stores it at `config.pendingAuth.browserNonce`, and hands it to the browser as an httpOnly, SameSite=Lax, Secure cookie whose path is this entry's callback — Lax and not Strict because the vendor returns by top-level GET navigation, which Strict would refuse. The callback refuses a missing cookie with `invalid_state` BEFORE it reads any row, and a cookie that does not match its row with `browser_mismatch` WITHOUT consuming the flow: a wrong browser must not be able to burn a flow that belongs to somebody else. The compare is constant-time and length-first, mirroring the Slack precedent rather than inventing one. `browserNonce` is DECLARED on `pendingAuth`, which is not a formality: that subdocument is strict, so an undeclared path is dropped in silence and the compare would read `undefined` against a real cookie while looking armed. That is the same class as the three defects this slice already fixed, one field over, and the arm that covers it is the one that feeds a row with no nonce at all. Arms: 57 over 4 suites, `(4, 57)` — the missing cookie refuses without a row read (asserted, because ORDER is the claim), a cookie from another flow is refused without consuming, a row holding no nonce is refused, the start route's cookie carries all five attributes and the same value the row holds and returns it in no JSON, and the real-mongod witness proves the refused flow is still on the row afterwards and is then finishable by its rightful browser. Ledger: 52 mutations, 51 killed, 1 compiler-refused (`token_endpoint_auth_method` is a literal type), NO SURVIVORS, NO NAMED-ARM MISSES, NO NOT-APPLIED. The four smaller findings in the hold are acknowledged and NOT in this commit: the two outbound fetches have no timeout, discovery assumes a bare-origin issuer (RFC 8414 puts the well-known segment between host and path), `buildAuthorizeUrl` appends `?` unconditionally, and the callback has no rate limiter. All four are non-blocking per the hold; they are queued as a follow-up so this walk stays about the binding.
…e 3a) `Test & Coverage` refused the previous head, and the refusal is the repo's own guard rather than a judgement call: `routeRateLimitGuard.test.js` scans every `<router>.<verb>(path, …)` registration and requires a limiter AHEAD of auth. This route file has two registrations and neither had one, so both were fresh violations (not baseline rows): `GET /:entryId/client-metadata` and `GET /:entryId/callback`. CodeQL's js/missing-rate-limiting failed on the same head for the same reason, which is what that guard is a cheap local proxy for. Both routes are public and unauthenticated on purpose — the authorization server fetches the metadata document before any member has consented, and the callback is a browser navigation from the vendor, where the httpOnly cookie is the flow binding rather than an authorization — so the limiter is the only thing in front of an unauthenticated row lookup and token exchange. Keyed by the Cloudflare-aware IP rule (`middleware/ipRateLimit.ts:49`), because `req.ip` walks to a cloudflared pod address for every external caller, which would make the whole internet one bucket (TASK-110's class). Two buckets rather than one shared limiter instance: a client that hammers the static document must not be able to spend the callback's allowance, which is the one that finishes a member's connect. Evidence: `routeRateLimitGuard` plus the four slice suites, 5 suites / 73 tests green; `tsc:check` clean; eslint 0 findings on the file; the 52-mutation ledger re-run against these exact bytes — 51 killed, 1 compiler-refused, NO SURVIVORS, NO NAMED-ARM MISSES, NO NOT-APPLIED.
…-172 slice 3a) Vera's point on the limiter commit, and it is the right shape of objection: the guard that forced the fix reads NAMES, so any number satisfies it — 60/60s on both routes passes and is wrong for one of them. `client-metadata` is fetched by the AUTHORIZATION SERVER rather than by a person, and it is one client id per instance per entry, so a vendor's handful of egress addresses fetch this document on behalf of every member. A bound tuned for humans would surface at the vendor as a client whose metadata document cannot be read, i.e. as a refused authorization for everyone at once, with nothing in our own logs pointing at a limiter. Loose on purpose at 600/60s; the document is static and holds no secret. `callback` stays at 60/60s — a browser, once per connect, on the route that validates `state` and the browser nonce and then exchanges a code. Both numbers and both reasons are in the file, because the next reader cannot recover them from a diff. The second half is that a limiter which is PRESENT is not a limiter that is ARMED, and the guard cannot tell those apart either. Three defects pass it exactly as well as the correct code: a bound nobody chose, one instance shared by two routes, and a bound tight enough to refuse a legitimate caller. New suite arms the callback at its bound (60 answered, the 61st a 429) and then serves 61 metadata requests with the callback's bucket already spent — which is the asymmetry, the separate buckets, and the vendor-facing direction in one set. Evidence, at this head: 6 suites / 75 tests green (the four slice suites plus `routeRateLimitGuard` plus the new armed-ness suite); `tsc:check` clean; eslint 0 on the route, and the new test file carries only the standard import-resolution findings a backend `__tests__` file gets for a `.ts` import (sibling suite: 6, this one: 2 — measured, not assumed). The ledger is extended to 57 mutants and re-run against these bytes: 56 killed, 1 compiler-refused (`token_endpoint_auth_method` is a literal type), NO SURVIVORS, NO NAMED-ARM MISSES, NO NOT-APPLIED — baseline now (6, 75). Two of the five new mutants are the defects above: dropping the limiter from a registration (killed by the guard, which scans the mutated file on disk) and pointing both routes at one limiter instance (killed by the spent-bucket arm, the one the guard cannot see).
samxu01
pushed a commit
that referenced
this pull request
Sep 29, 2026
…N (TASK-172) Vera's finding 75269, routed to its own PR by connector-ops 75275: the limiter that 3a added refuses in the wrong shape on one of its two routes. `publicGetRateLimit` answered `429` JSON for both. That is right for `client-metadata`, whose caller is the authorization server, and wrong for `callback`, whose caller is a browser mid-navigation — where this route's contract is that every outcome is a redirect to the page that can offer Connect again. A throttled person got raw JSON in the address bar on the one path where they are least able to work out what happened. No state was at risk (the limiter runs ahead of the row read), which is why it was not blocking. The factory now takes the refusal rather than hardcoding one: `jsonRefusal` for the server caller, `browserRefusal` — the route's own `callbackRedirect`, code `rate_limited` — for the browser. The arm is not a status assertion, because BOTH sides of the bound are 302, so the status can separate nothing: the discriminator is the `code` in the Location, asserted on the first 60 (`invalid_state`) and on the 61st (`rate_limited`). The other direction is asserted too, because the tempting fix is to change the shared handler and drag the document along with it: the document still refuses `429` JSON with no `Location`, measured to bite at request 601 — one past its own stated bound of 600, so the loop reads the real bound rather than a stale bucket. Evidence: 6 suites / 76 tests green; `tsc:check` clean; eslint 0 findings on the route. The ledger is 61 mutants on these bytes, baseline `(6, 76)` asserted before every run: 60 killed, 1 compiler-refused, NO SURVIVORS, NO NAMED-ARM MISSES, NO NOT-APPLIED. Four of the 61 are this change — the callback handed the JSON refusal at its call site, the factory ignoring the refusal it was handed, the code swapped away from `rate_limited`, and the document handed the browser refusal — all killed by the `code`/shape arms, none by `routeRateLimitGuard`, which cannot see any of them. The three earlier limiter mutants are re-anchored to the new call sites and still killed. Stacked on #1995 (`905e21b7`) because this file is not on main yet: its own delta is one hunk plus the third arm, and it collapses to that once #1995 merges and it is rebased.
samxu01
pushed a commit
that referenced
this pull request
Sep 29, 2026
…ebase onto 87c7325 The gate's non-blocking finding, folded because the entry is being touched anyway: "exactly one tracked file" is true of the union and false per string. Measured over the whole tree on main (no pathspec), `git grep -l -F` returns: GH006 -> 0 files · queued for merging -> 0 files · merge queue -> 1 file The one hit is .github/workflows/tests.yml:13, and lines 13-16 are about the merge_group trigger. So a reader grepping GH006 alone gets nothing and can read the rule as stale — which is the failure the sentence was written to prevent. Also rebased onto 87c7325 (main moved; #1995, disjoint — it does not touch this file). Text is otherwise unchanged from 9a8ec6e. Guard, CI's own invocation, --previous = 87c7325: ✓ 43 rules, numbers 1..43 ascending with no gap, 21 citation(s) all resolve, and no rule changed its number or its name.
lilyshen0722
added a commit
to thantiklermcirony/commonly
that referenced
this pull request
Oct 9, 2026
…N (TASK-172) (Team-Commonly#1999) Vera's finding 75269, routed to its own PR by connector-ops 75275: the limiter that 3a added refuses in the wrong shape on one of its two routes. `publicGetRateLimit` answered `429` JSON for both. That is right for `client-metadata`, whose caller is the authorization server, and wrong for `callback`, whose caller is a browser mid-navigation — where this route's contract is that every outcome is a redirect to the page that can offer Connect again. A throttled person got raw JSON in the address bar on the one path where they are least able to work out what happened. No state was at risk (the limiter runs ahead of the row read), which is why it was not blocking. The factory now takes the refusal rather than hardcoding one: `jsonRefusal` for the server caller, `browserRefusal` — the route's own `callbackRedirect`, code `rate_limited` — for the browser. The arm is not a status assertion, because BOTH sides of the bound are 302, so the status can separate nothing: the discriminator is the `code` in the Location, asserted on the first 60 (`invalid_state`) and on the 61st (`rate_limited`). The other direction is asserted too, because the tempting fix is to change the shared handler and drag the document along with it: the document still refuses `429` JSON with no `Location`, measured to bite at request 601 — one past its own stated bound of 600, so the loop reads the real bound rather than a stale bucket. Evidence: 6 suites / 76 tests green; `tsc:check` clean; eslint 0 findings on the route. The ledger is 61 mutants on these bytes, baseline `(6, 76)` asserted before every run: 60 killed, 1 compiler-refused, NO SURVIVORS, NO NAMED-ARM MISSES, NO NOT-APPLIED. Four of the 61 are this change — the callback handed the JSON refusal at its call site, the factory ignoring the refusal it was handed, the code swapped away from `rate_limited`, and the document handed the browser refusal — all killed by the `code`/shape arms, none by `routeRateLimitGuard`, which cannot see any of them. The three earlier limiter mutants are re-anchored to the new call sites and still killed. Stacked on Team-Commonly#1995 (`905e21b7`) because this file is not on main yet: its own delta is one hunk plus the third arm, and it collapses to that once Team-Commonly#1995 merges and it is rebased.
lilyshen0722
added a commit
to thantiklermcirony/commonly
that referenced
this pull request
Oct 9, 2026
… (a clearance binds a head the consumer can resolve) (Team-Commonly#2000) * docs(checklist): rule 42 (a queued PR refuses every push) and rule 43 (a clearance binds a head the consumer can resolve) Two rules, both earned today, appended at EOF under their own headings. Rule 42 was drafted 2026-09-28 and held while Team-Commonly#1994 claimed rule 41; that PR merged at 12:59:44Z as a20ea9b, so this is the first cycle in which the numbers were free. 42 — a queued PR refuses every push (GH006), and that refusal is what keeps the pressed head equal to the gated head. Incident: Team-Commonly#1984 was queued 95s after the % fold was asked for, so the fold became Team-Commonly#1988 — a one-line catalog change billed as a PR with a rebase and two gates. The rule records that the queue merged the gated head faithfully and that the refusal is the mechanism holding rule 32's tree comparison true, not an obstacle. 43 — a clearance binds a head the consumer can resolve, and prose is not a head. Incident: TASK-186 carried "CODE PASS @ 1a811d8" in its board title for ~32h while Team-Commonly#1988's PR held no code clearance at all; the pod line behind the claim named 5829815, a local commit the merge queue never let push, so the sha was resolvable in one clone and nowhere else. Verified through the numbering guard's own CI invocation (script extracted from origin/main, run from the repo root, --previous = the main this is based on): ✓ 43 rules, numbers 1..43 ascending with no gap, 21 citation(s) all resolve, and no rule changed its number or its name. Docs only: one file, +8 lines, no code and no tests. The guard is the test. * docs(checklist): fix both earned clauses against the ledger (rule 43's sha and spans, rule 42's file count) Sprint-review's CHANGES gate on b1515f5, all three findings confirmed by measurement rather than accepted on report. Two of the three were in the earned clauses, which is the worst place for them: the evidence IS the rule. Rule 43 named the wrong sha. The row recorded "CODE PASS @ 5829815" — the local-only commit, which is the whole point — at 06:54Z on 2026-09-28; the rule said 1a811d8, which is the head the row got RIGHT and which carried only the UX pass until a real code gate landed at 12:17:58Z. As written the example could not demonstrate its own rule: 1a811d8 is resolvable, so nothing about it is ungated. The spans were also wrong. Measured from the ledger: the row carried the claim 29.4h (06:54:19.520Z -> 12:17:58.983Z), the board title 8.7h (03:34:40.553Z -> 12:17:58.983Z, the 20.7h gap being the lag between the row and the title). The "~32h" matched neither. Added, because it is the mechanism the wrong sha came from: the title read "(UX PASS @ 1a811d8 + CODE PASS)" — it binds the sha to the UX pass and leaves the code pass bare, which is exactly how a reader collapses it into "CODE PASS @ 1a811d8". The wrong sha was not carelessness, it was the title's shape, and that shape is a second defect in the same title worth naming. Rule 42's "exactly one tracked file" was true of main and false at this head: b1515f5:.github/workflows/tests.yml plus b1515f5:docs/development/ review-checklist.md, because the rule quotes GH006 / "queued for merging" / "merge queue". Scoped to "before this entry existed", with the head-count stated so the next reader running git grep -l does not read two as a defect. Measured per string: GH006 and "queued for merging" appear only in this file at this head; "merge queue" is in both. Not changed: "95 seconds later". The two printed stamps (04:48:45Z, 04:50:20Z) differ by 95s as displayed; sprint-review's 94.3s is the same gap at sub-second precision, which the rule does not print. Guard, CI's own invocation, --previous = a20ea9b: ✓ 43 rules, numbers 1..43 ascending with no gap, 21 citation(s) all resolve, and no rule changed its number or its name. * docs(checklist): lead rule 43 with the existence question, demote the rule-32 link to a neighbour note From the gate's answer on whether 43 is a rider on 32. It is a separate rule, and the reason is rule 41's own test applied to 32: every guard 32 sends you to check passes on Team-Commonly#1988 — the head is fetchable, it never moved, and there is no merge to compare a clearance against — and the defect survives all of them. 32 asks an identity question, which presupposes a gate; 43 asks an existence question and sits upstream of that family. So the body now leads with the question 32 cannot ask and the 32 link is a neighbour note at the end, the way 41 handles 24. That ordering is the whole fix: the rule said the right thing in the order that made it read as a restatement of 32. Nothing operative changed. Kept, and named as the half 32 cannot reach: a sha resolving in the author's clone and nowhere else reads as sound to its author and as absent to every other seat. Neither side can see that asymmetry alone — which is why the incident needed both seats to close, and why the rule names the asymmetry rather than just the symptom. Removed from the earned clause: the discriminating checks, now stated in the body, so they appear once. Guard, CI's own invocation, --previous = a20ea9b: ✓ 43 rules, numbers 1..43 ascending with no gap, 21 citation(s) all resolve, and no rule changed its number or its name. * docs(checklist): rule 42's file count is per string, not per union; rebase onto 87c7325 The gate's non-blocking finding, folded because the entry is being touched anyway: "exactly one tracked file" is true of the union and false per string. Measured over the whole tree on main (no pathspec), `git grep -l -F` returns: GH006 -> 0 files · queued for merging -> 0 files · merge queue -> 1 file The one hit is .github/workflows/tests.yml:13, and lines 13-16 are about the merge_group trigger. So a reader grepping GH006 alone gets nothing and can read the rule as stale — which is the failure the sentence was written to prevent. Also rebased onto 87c7325 (main moved; Team-Commonly#1995, disjoint — it does not touch this file). Text is otherwise unchanged from 9a8ec6e. Guard, CI's own invocation, --previous = 87c7325: ✓ 43 rules, numbers 1..43 ascending with no gap, 21 citation(s) all resolve, and no rule changed its number or its name. * docs(checklist): cut rule 43 down to existence — the sha was on the remote all along ux-lead's second seat on the conclusion, and the finding is against my own rule's premise. Verified independently in a fresh clone before taking it: gh api repos/.../commits/58298156 -> resolves, parent 7f17163 git fetch origin 5829815... -> retrieves it git fetch origin 5829815 -> couldn't find remote ref advertised refs pointing at it -> 0 of 2,579 merge-base --is-ancestor 5829815 1a811d8 -> NOT an ancestor (a sibling) /pulls/1988/reviews -> 4 reviews, all commit_id=1a811d84 So "a local commit GH006 never let push" was false: the remote had it the whole time and a full-sha fetch gets it. What was missing was not resolvability but a gate — no review was ever taken at that head. Rule 43 now asks the existence question and nothing else; "absent from the reader's clone" is dropped as the test (an absence read in one clone is as clone-local as a presence read, and refs/pull/<n>/head keeps a squashed-away head fetchable), the instrument is commit_id, and --is-ancestor is named as a check that passes a spent stamp. Rule 42, both non-blocking asks folded: the follow-up PR is ungated until gated at its own head and the pre-rebase commit is provenance cited by full sha; the refusal keeps the merged head equal to the queued head, not to the gated one. Guard, CI's invocation, --previous = 87c7325: ✓ 43 rules, numbers 1..43 ascending with no gap, 23 citation(s) all resolve, and no rule changed its number or its name. * docs(checklist): rule 43's existence check is necessary and not sufficient — a review at the head can be a refusal ux-lead's re-gate, and the gap is the one my own ask left open. Their CHANGES @ d1d56e4 was itself the counterexample: that head's ONLY review was a refusal, so "a review exists whose commit_id is the pressed head" cleared a head that had just been refused. Measured before folding: Team-Commonly#1988 reviews=4 states=COMMENTED Team-Commonly#1989 reviews=10 states=COMMENTED Team-Commonly#2000 reviews=4 states=COMMENTED All 18 reviews COMMENTED; not one APPROVED or CHANGES_REQUESTED. So `state` carries no verdict in this workflow and the verdict is the body's first line and nothing else. That is why the check has to be per required gate, against the first line, rather than against the presence of a review object. Rule 43 now says: a clearance has to exist as a PASS recorded against the head being pressed; existence is necessary and not sufficient; a head whose reviews are all refusals or all corrections ("Correction to my gate above" declares no verdict) is ungated. Guard, CI's invocation, --previous = 87c7325: ✓ 43 rules, numbers 1..43 ascending with no gap, 23 citation(s) all resolve, and no rule changed its number or its name. * docs(checklist): rule 43's review counts are dated, not live — a count in a doc decays * docs(checklist): rule 43's per-gate check must name the head, not just carry its commit_id * docs(checklist): fold rule 43's re-gate — candidates not clearances, and the differing-tree witness --------- Co-authored-by: lilyshen0722 <[email protected]> Co-authored-by: Claude Opus 5.5 (1M context) <[email protected]>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
TASK-172 slice 3a — the hosted-MCP intake flow, end to end and vendor-free
Step 3 of §10 in
docs/plans/hosted-mcp-connection-scope.md: a person clicksConnect, consents at the vendor, and comes back to a connected row. This is the
whole of §4 for the half that needs no vendor account: client identity, the
authorization request, PKCE, the state nonce, discovery, the callback, the token
exchange, and the account-change rule.
Base is
mainat96cc9711, which carries #1993 — the entry module, theprojection and the drift guard are what this flow resolves against. The branch
was stacked on #1993 while it was open and is rebased now that it has landed:
git range-diff 4ae5c4d1..973a90d0 origin/main..HEADreports all eight commits=, i.e. the patches are byte-identical and every measurement below was takenagainst these bytes.
What lands
backend/services/hostedMcpIntakeService.tsbackend/routes/hostedMcpConnect.tsGET /:entryId/client-metadata,POST /:entryId/start,GET /:entryId/callbackbackend/routes/integrations.ts/connect/hosted-mcpThe shape, and why
A CIMD client is a URL, so nothing is registered anywhere. For an entry that
uses client-id-metadata,
client_idishttps://api.commonly.me/api/integrations/connect/hosted-mcp/<entry>/client-metadataand that document — public, identical for every member,
token_endpoint_auth_method: none,one redirect URI — is what the vendor fetches. An entry with a pre-registered
client reads
${ENTRY_ID}_CLIENT_ID; an entry that declaresdcris refused(
client_registration_required) rather than sent to an authorize endpoint witha client id we invented.
One redirect URI, and the path names the entry. This is the mix-up defence:
a code issued for one entry cannot be replayed at another entry's callback,
because the two do not share a callback path. The document and the start route
now take both leaf names from one pair of constants — the audit below found them
spelled twice.
PKCE S256, and it is not decoration. A public client holds no secret, so the
verifier in the row is the only thing binding the code to this instance.
RFC 8707's
resourceon all three requests — authorization, exchange,refresh — read from the entry, never a literal.
The state is spent by the claim, not by a flag. The callback looks the row up
by
config.pendingAuth.state, checks the expiry, then claims it with$unset: {'config.pendingAuth': 1}and{new: false}. A second delivery of thesame callback gets
nulland is refused asstate_consumedbefore any code isspent, and the pre-image hands back the verifier — which is the only place it
lives. This is also forced by the schema:
pendingAuthis a strict subdocumentof
{state, codeVerifier, expiresAt}, so a claim-id field like Slack's would bedropped silently and the guard would read as armed while doing nothing.
Discovery runs before the row is written, and again at the callback. An
unreachable or incomplete issuer therefore leaves no pending row behind, and the
exchange target is fetched fresh rather than cached on the row.
Reconnecting as a different account revokes the old grants. §2: the row is
one per
(person, entry), so a second consent replaces the first credential —and the grants minted from it must not survive the account that granted them.
providerSubjectfrom the ID token is the comparison; a vendor that issues nosubject is not the same account as one with a recorded subject (two unknowns
are not a match), and revocation happens before the new pair is written.
A refresh token the vendor no longer issues is dropped and revoked, not kept
next to the new access token — otherwise the mint refreshes against a retired
grant and reports the vendor as down.
The browser binding, added after Vera held the first head
The first head was refused for a real defect, and it is the serious class: the
callback found the pending row by
config.pendingAuth.statealone. The state isunguessable, but it is the STARTER who holds it — it rides in the authorization
URL — so a starter could send that URL to somebody else. The victim approves on
the vendor's own consent screen, which really does say "Commonly"; the code that
returns is the victim's; we exchange it and write the victim's access and refresh
tokens onto the STARTER's row. Every trail row would then correctly name the
starter, and the credential behind it would be somebody else's. PKCE is no
defence (it binds the code to this instance, which is what the attacker wants)
and the account-change rule cannot fire (a first connect has no stored subject).
The fix is §10.7's cell, and it is a SECOND secret rather than a stronger first
one:
stateproves the flow exists, the nonce proves the browser finishing it isthe browser that started it.
/startmints it beside the state, stores it atconfig.pendingAuth.browserNonce, and delivers it as an httpOnly,SameSite=Lax,Securecookie whose path is this entry's callback — Lax and notStrict, because the vendor returns by top-level GET navigation, which Strict
would refuse. The callback refuses a missing cookie with
invalid_statebefore it reads any row, and a cookie that does not match its row with
browser_mismatchwithout consuming the flow: a wrong browser must not beable to burn a flow that belongs to somebody else. The compare is constant-time
and length-first, mirroring
matchesSlackNonceinroutes/installables.ts.browserNonceis DECLARED onpendingAuth, which is not a formality: thatsubdocument is strict, so an undeclared path is dropped in silence and the
compare would read
undefinedagainst a real cookie while looking armed. Sameclass as the three defects this slice already fixed, one field over — and the arm
that covers it feeds the handler a row with no nonce at all.
The third item from the same hold is NOT deferred — CI gates it
The hold listed four smaller findings and marked them non-blocking. The fourth —
"the callback has no rate limiter" — is refused by the repo's own
routeRateLimitGuard, which scans every<router>.<verb>(path, …)registrationand requires a limiter ahead of auth. This file had two registrations and
neither carried one, so both were fresh violations rather than baseline rows;
CodeQL's
js/missing-rate-limitingfailed on the same head for the same reason.So that item is fixed here rather than queued.
Both routes are public and unauthenticated on purpose — the authorization
server fetches the metadata document before any member has consented, and the
callback is a browser navigation from the vendor, where the httpOnly cookie is
the flow binding rather than an authorization — which is exactly why the limiter
matters: it is the only thing in front of an unauthenticated row lookup and
token exchange. Keyed by the Cloudflare-aware IP rule
(
middleware/ipRateLimit.ts:49), sincereq.ipwalks to a cloudflared podaddress for every external caller and would make the whole internet one bucket
(TASK-110's class). Two buckets, not one shared limiter instance: a client
hammering the static document must not be able to spend the callback's
allowance, which is the one that finishes a member's connect.
The two bounds are chosen for their two callers, which the guard cannot check —
it reads names, so 60/60s on both routes satisfies it and is wrong for one of
them.
client-metadatais fetched by the authorization server rather than bya person, and it is one client id per instance per entry, so a vendor's handful of
egress addresses fetch that document on behalf of every member; a bound tuned for
humans would surface at the vendor as a client whose metadata document cannot be
read, i.e. as a refused authorization for everyone at once, with nothing in our
own logs pointing at a limiter. Loose on purpose at 600/60s.
callbackstaysat 60/60s — a browser, once per connect, on the route that validates
stateand the nonce and then exchanges a code. Both numbers and both reasons are in the
file, because a diff does not carry them.
And a limiter that is PRESENT is not one that is ARMED. The guard witnesses
presence; three defects pass it exactly as well as the correct code — a bound
nobody chose, one instance shared by two routes (which throttles the wrong
caller), and a bound tight enough to refuse a legitimate caller. So the new suite
answers the callback to its bound and asserts the 429 one past it, then serves 61
metadata requests with the callback's bucket already spent: that single set is
the asymmetry, the two separate buckets, and the vendor-facing direction.
The other three stay deferred, as non-blocking: no timeout on either outbound
fetch; discovery assumes a bare-origin issuer (RFC 8414 puts the well-knownsegment between host and path, so a path-bearing issuer would 404); and
buildAuthorizeUrlappends?unconditionally.Evidence
(4, 57), 0 failed, 0 runtime errors at the headthat carries the binding; with
routeRateLimitGuardand the armed-ness suite,6 suites / 75 tests green at the head that carries the limiters.
tsc:checkclean; eslint on the route 0 findings, and the new test file carries only the
standard import-resolution findings a backend
__tests__file gets for a.tsimport (6 in the sibling suite, 2 here — measured); the integrations-routes and
models suites (55 suites, 434 tests) green, which is what witnesses the new
schema field.
/tmp/kai-172s3-ledger.py: 57 mutations, baseline(6, 75)asserted before every run — 56 killed, NO SURVIVORS, NO NAMED-ARM MISSES, NO
NOT-APPLIED (five are the limiters: a registration with no limiter on either
route — killed by the guard, which scans the mutated file on disk — one limiter
instance shared by both routes and either bound moved in either direction, all
killed by the bound/bucket arm the guard cannot see) (14 of the 52 are the binding: the presence check, the compare,
the inversion of the compare, the stored nonce, the cookie's path,
httpOnly,Secure,Max-Age, the cookie's own name, the nonce's mint, the lengthguard, the empty-string guard and the cookie-name match). One is refused by the compiler rather than by an
arm:
token_endpoint_auth_method: 'none'is a literal type, so a mutation making itany other value cannot load the suite. Recorded, not counted as a kill.
hostedMcpApiBase(), the function under test, so a wrong origin moved theanswer and the question together. Both now assert the literal.
changing one left the other and the arm that should have caught it passed.
Both leaf names now come from one pair of constants.
a row with a credential but no recorded subject, reconnecting to a vendor
that still issues none.
What the probes found, and the arms could not
Three defects were measured against a real mongod rather than reasoned about, all
in the callback, and none was visible to an arm:
The commit named keys the schema drops in silence.
configis a strictsubdocument, and the success
$setwrotecredentialRef,refreshTokenRef,refreshGeneration,grantedScope,expiresAtandproviderSubjectwithoutthe
config.prefix: mongodb keptstatusand dropped all six, so thecallback would answer
connectedon a row holding no token at all. The same$setthrough the real model, prefixed, lands all six. Both write sites nowassert that every path they name is declared
(
backend/__tests__/utils/schemaPathGuard.js), and a key no shape assertionnames (
revokedAtX) is killed by that guard alone.The reads used the same wrong shape, so §2's account-change rule was dead
code.
consumed.credentialRef/consumed.providerSubjectareundefinedon a real row, which made
accountChangedpermanently false — a reconnect asa different account would have revoked nothing. And
$set: {'config.refreshTokenRef': undefined}does not clear the field(measured: the old value stays), so dropping a retired refresh token was a
no-op that read as a clear.
A
$setthat names a DECLARED path is still a no-op when its value isundefined.$setwithundefineddoes not clear a strict subdocumentfield; measured, the old subject stays. So an exchange that returned no ID
token left the PREVIOUS vendor account's
providerSubjecton the row — adurable claim about which account is connected — and the next reconnect
compared against it, read "same account", and kept grants minted under
whatever account had held the row in between. The read half of §2 was already
fixed above; this is the write half, and it is why the fix is
|| nullratherthan an omission at every one of the three sites.
hostedMcpConnect.storedRow.test.jsis the witness: it drives the real route against a real Mongo and reads the
row back, and its first two arms FAIL on the pre-fix code while the third —
a vendor that does issue a subject — stores it. A payload-level assertion
cannot see this class at all:
undefinedin a$setpayload reads the samewhether the store clears the field or does nothing.
The arms missed all three because the FIXTURE carried the wrong shape, not just
the calls: the row helper spread its credential overrides across the top level, so
the handler and its arms agreed on a document the database never returns. It now
nests them under
config, which is what makes the four new mutations die in thearms that name the behaviour.
Disclosed gaps
lines is measured against a stub authorization server (the fetcher is a
parameter for exactly this reason); the end-to-end run against Linear — CIMD
fetch, token lifetimes, ID token shape — needs a vendor account and is owed.
credentialForconsumption and the refresh fence, whichread
refreshGeneration. This PR writes it as0.issis refused only when present and different (RFC 9207). A vendor thatdoes not send
issis not refused for that absence.