Skip to content

Add user-verified personal read-only agent registration - #1052

Merged
sidneyswift merged 4 commits into
mainfrom
codex/agent-read-registration
Oct 20, 2026
Merged

sidneyswift merged 4 commits into
mainfrom
codex/agent-read-registration

Conversation

@sidneyswift

@sidneyswift sidneyswift commented Oct 20, 2026 •

Copy link
Copy Markdown
Contributor

Agents with an account holder's email can now request a personal read-only connection. Registration returns a six-digit code and a Recoup sign-in URL. No credential is issued until the account holder signs in with the matching verified email and explicitly approves.

The opt-in auth.md service-auth profile uses the existing OAuth issuer, encrypted store, grants, MCP permission checks, and Connected Agents revocation. Connections last one hour, access tokens at most five minutes, and assertion exchanges cannot extend that deadline. No refresh token, organization access, anonymous registration, or external-provider assertion trust is added.

The implementation includes atomic approval/polling transitions, five-attempt code lockout, single-use consent tickets, strict origin and input checks, bounded expiry cleanup, two token grants, token revocation, and truthful discovery/instructions. Ordinary PKCE requests retain oidc-provider's original form parsing.

Validation:

  • All 244 OAuth tests pass with the isolated PostgreSQL fixture enabled, including two provider instances sharing storage. Agent HTTP routing uses the in-memory fixture; provider and storage integration cases use PostgreSQL.
  • OAuth TypeScript and repository lint pass.
  • Tests cover code/identity binding, concurrency, expiry, scope/resource escalation, signed assertion validation, existing PKCE exchange, and revocation.
  • The configured Vercel preview passes the production build; local page collection requires the absent Privy project secret.

Deployment requires the companion database migration and chat consent page. OAUTH_AGENT_REGISTRATION_ENABLED defaults off. Apply the migration, deploy both services, enable and verify chat, then enable API and perform the account-holder read/denied-write/renew/disconnect smoke test. See docs/agent-registration.md for exact steps and rollback.

These synthetic test receipts do not establish live account-holder or named-agent-client interoperability. Merge and rollout await user approval.

Dependencies: Database #118 and App #2249.

The activation flag is read in loadOAuthConfig and gates the dispatcher in getOAuthRuntime. The Pages OAuth route applies shared/IP limits before initializing that runtime; identity registration also receives the stricter registration budgets. Regression tests pin both boundaries.

Registration, approval, polling, token-form parsing, and discovery are separate modules. Tests additionally pin the exact fifth-code lockout, malformed form rejection, upload draining, and a fixed deadline under an advancing clock. Identity infrastructure failures return a temporary error; logs contain a fixed operational event rather than credentials or provider diagnostics.

Malformed, reused, or concurrently consumed consent tickets return a client error; storage failures remain temporary errors. A failed approval revokes its entire grant family, including registration state, so subsequent polling terminates with expired_token. A partial-issuance regression test verifies this cleanup; moving the deleted registration to another status is unnecessary.

@vercel

vercel Bot commented Oct 20, 2026 •

Copy link
Copy Markdown
Contributor

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Actions Updated
api Ready Ready Preview Oct 20, 2026 4:34am UTC

Request Review

@coderabbitai

coderabbitai Bot commented Oct 20, 2026 •

Copy link
Copy Markdown

Important

  • 🔍 Trigger review

This repository does not receive automatic reviews because it has fewer than 10 stars.

⚙️ Run configuration
  • Configuration used: Repository: recoupable/api/.coderabbit.yaml
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: d7b06a8d-0175-406f-a027-ff7ec11140a8
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@cubic-dev-ai cubic-dev-ai Bot left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

1 issue found across 27 files

Confidence score: 4/5

  • The duplicate-field test in lib/oauth/agentAuth/__tests__/http.test.ts can still pass if the duplicate-parameter guard is removed, because the Zod fallback also returns 400. Use two identical claim grants plus a nonexistent claim token to isolate the guard.

You’re at about 98% of the monthly reviewed-line limit. You may want to disable incremental reviews to conserve quota. Reviews will continue until that limit is exceeded. If you need help avoiding interruptions, please contact contact@cubic.dev.

Prompt for AI agents (unresolved issues)

Check if these issues are valid — if so, understand the root cause of each and fix them. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. If appropriate, use sub-agents to investigate and fix each issue separately.


<file name="lib/oauth/agentAuth/__tests__/http.test.ts">

<violation number="1" location="lib/oauth/agentAuth/__tests__/http.test.ts:143">
P2: The duplicate-field case does not isolate the duplicate-parameter guard. Removing the guard still yields a 400 invalid_request through the Zod fallback. Use two identical claim grants plus a nonexistent claim token. Then the guard returns invalid_request, while without it the request reaches poll and returns expired_token.</violation>
</file>
Architecture diagram
sequenceDiagram
    participant Agent as External Agent
    participant API as OAuth API Node Dispatcher
    participant OIDC as oidc-provider
    participant Service as Agent Registration Service
    participant Store as Encrypted OAuth Store (Supabase/Postgres)
    participant Privy as Privy Identity
    participant Browser as Account Holder Browser
    participant Consent as Consent Page (Chat)
    participant Grant as MCP Grant/Access Token
    participant Connections as Connected Agents

    Note over Agent,Connections: User-Verified Personal Read-Only Agent Registration

    Agent->>API: POST /agent/identity {type: service_auth, login_hint}
    API->>API: Rate limit check (agent/identity budget)
    API->>Service: create(login_hint)
    Service->>Store: purgeAgentRegistrations() (bounded cleanup)
    alt Registration enabled
        Service->>Service: Generate claim token, attempt token, 6-digit code, opaque IDs
        Service->>Store: Encrypt + upsert registration (CAS-capable)
        Service-->>API: Registration handles, claim URL, user_code
        API-->>Agent: 200 (claim_token, user_code, verification_uri, no credentials)
    else Registration disabled
        API-->>Agent: 503 or empty
    end

    Agent-->>Browser: Show code and verification URL (out-of-band)
    Browser->>Consent: GET /oauth/claim?claim_attempt_token=...
    Consent->>Privy: Sign in (verify email)
    Privy-->>Consent: Privy identity token
    Consent->>API: POST /agent/identity/claim (Origin + Bearer Privy token)
    API->>API: Strict origin + bearer validation
    API->>Service: load(attempt, identity)
    Service->>Store: find + decrypt record
    alt Verified email matches
        Service->>Service: Issue single-use CSRF consent ticket
        Service-->>API: Consent details (context: personal, scopes, duration)
        API-->>Browser: 200 (csrf, permissions, context)
    else Email mismatch
        API-->>Browser: 403 account_mismatch
    end

    Browser->>API: POST /agent/identity/claim/complete (decision, csrf, user_code)
    API->>API: Strict origin + bearer validation again
    API->>Service: decide(attempt, decision, identity)
    Service->>Store: CAS replace (failedAttempts++, status transitions)
    alt Wrong code
        Store-->>Service: CAS success
        alt 5+ failures
            Service->>Store: Status = denied (locked)
            Service-->>API: 400 invalid_user_code
        else
            Service-->>API: 400 invalid_user_code
        end
    else Correct code + approve
        Service->>Service: Consume CSRF ticket, bind accountId + subject
        Service->>Grant: Create personal mcp:read grant (1 hour)
        Grant-->>Service: Grant saved
        Service->>Store: Final status = approved (CAS)
        Service-->>API: 200 approved
        API-->>Browser: 200
    else Deny
        Service->>Store: Status = denied
        Service-->>API: 200 denied
    end

    Agent->>API: POST /token (claim grant type, claim_token)
    API->>Service: poll(claim_token)
    loop Polling with backoff
        Service->>Store: CAS replace (lastPollAt, pollInterval)
        alt Pending
            Service-->>Agent: authorization_pending
        else Slow down
            Service-->>Agent: slow_down
        else Denied/expired
            Service-->>Agent: access_denied / expired_token
        end
    end
    Service-->>API: Issue access token (5 min) + signed identity assertion
    API-->>Agent: 200 (access_token, identity_assertion, expiry)

    opt Assertion exchange (renewal within 1 hour)
        Agent->>API: POST /token (jwt-bearer, assertion)
        API->>Service: exchange(assertion, resource, scope)
        Service->>Service: Verify signature, issuer, sub, typ, timestamps
        alt Valid + within deadline
            Service->>Grant: Issue new access token (5 min)
            API-->>Agent: 200 new access token
        else Invalid/expired
            API-->>Agent: 400 invalid_grant
        end
    end

    Progress->>API: POST /token/revocation
    API->>Service: revokeToken(access_token)
    Service->>Grant: Destroy access token
    API-->>Agent: 200 (idempotent)

    Browser->>Connections: View Disconnect
    Connections->>Grant: Revoke grant + registration + all tokens
    Connections-->>Browser: Disconnected (all credentials invalidated)
Loading

Reply with feedback, questions, or to request a fix.

View guided diff | Turn on auto-fix | Re-trigger cubic

Comment thread docs/agent-registration.md Resolved
Comment thread lib/oauth/createRecoupOAuthProvider.ts Resolved
Comment thread lib/oauth/createRecoupOAuthProvider.ts Resolved
Comment thread lib/oauth/checkOAuthRateLimit.ts Resolved

@cubic-dev-ai cubic-dev-ai Bot left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

3 issues found across 28 files (changes from recent commits).

Confidence score: 4/5

  • In pollAgentClaim.ts, a failed completeAgentApproval leaves the registration stuck in approving, so the agent can keep receiving authorization_pending until the claim expires. Add a recovery path for that failure.
  • In docs/mcp-oauth-storage.md, the verified test count and scope don’t match the PR’s reported PostgreSQL results. Update them to reflect the migrations and verification run.
  • The command documented in docs/mcp-oauth-storage.md doesn’t run the agent HTTP registration flow against PostgreSQL; http.test.ts uses the in-memory fixture. Clarify what the command actually verifies.

You’re at about 99% of the monthly reviewed-line limit. You may want to disable incremental reviews to conserve quota. Reviews will continue until that limit is exceeded. If you need help avoiding interruptions, please contact contact@cubic.dev.

Prompt for AI agents (unresolved issues)

Check if these issues are valid — if so, understand the root cause of each and fix them. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. If appropriate, use sub-agents to investigate and fix each issue separately.


<file name="docs/mcp-oauth-storage.md">

<violation number="1" location="docs/mcp-oauth-storage.md:25">
P3: This command does not run the agent HTTP registration flow against PostgreSQL: `http.test.ts` uses the in-memory fixture, while only the two-instance test uses `createPostgresTestStore()`. Clarify that the command runs PostgreSQL-backed storage tests where supported, or wire the HTTP fixture to the durable store before claiming this coverage.</violation>

<violation number="2" location="docs/mcp-oauth-storage.md:31">
P3: The 'Verified locally' sentence still reports 49 PostgreSQL tests, but the PR description reports 229 OAuth tests passing against PostgreSQL. Update the count and the verification scope to match the migrations and the two-instance case this section now describes.</violation>
</file>

<file name="lib/oauth/agentAuth/pollAgentClaim.ts">

<violation number="1" location="lib/oauth/agentAuth/pollAgentClaim.ts:21">
P2: If `completeAgentApproval` fails after the lock, the registration stays `approving` and this branch returns `authorization_pending` until the claim expires. The agent keeps waiting up to ten minutes after the browser already got an error, and the approval cannot be retried. Move the failed lock to a terminal status, such as a CAS to `denied` in `completeAgentApproval`'s catch, so polls return `access_denied`.</violation>
</file>

Reply with feedback, questions, or to request a fix.

View guided diff | Turn on auto-fix | Re-trigger cubic

Comment thread lib/oauth/agentAuth/pollAgentClaim.ts Resolved
Comment thread lib/oauth/agentAuth/decideAgentClaim.ts Resolved
Comment thread docs/mcp-oauth-storage.md Resolved
Comment thread docs/mcp-oauth-storage.md Resolved
@sidneyswift
sidneyswift merged commit c69768b into main Oct 20, 2026
7 checks passed

This branch was successfully deployed

1 active deployment
Preview — 1b522128 Deployed Oct 20, 2026 by vercel[bot]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant