Skip to content

feat(chat-auth): P1 — Clerk-JWT verify + τ-metering (rebased onto C-a/C-b/C-c/#112ii), unblocks staging Clerk path - #44

Merged
supmo668 merged 7 commits into
mainfrom
mangyinm/chat-auth-p1-rebased
Jun 29, 2026
Merged

supmo668 merged 7 commits into
mainfrom
mangyinm/chat-auth-p1-rebased

Conversation

@supmo668

@supmo668 supmo668 commented Jun 29, 2026 •

Copy link
Copy Markdown

P1 chat-auth (Clerk-JWT verify + τ) reconciled onto current main f988c54 (supersedes the stale chat-auth-p1-clerk-jwt-tau off old main). #112ii timeout now wraps the P1 runResponsesAgentCommand (externalId) in both stream+non-stream; τ-record + C-b failure-terminal coexist. QG green: tsgo 0, gateway unit 546, e2e 184 (Clerk auth + τ 429 + C-b + #112ii + chat-service all coexist), sealed 60/60. WHY NOW: gating item for shrinemobile's STAGING Clerk-JWT live-reply QA (openclaw#1506) — on land, devex rebuilds staging w/ Clerk verify (currently Clerk JWTs 401, no verify code deployed). STAGING only — PROD rollout stays gated on the staging QA + principal go. @ f8e44d3. CTO lands.

Summary by CodeRabbit

  • New Features

    • Added Clerk-based sign-in support for chat and response requests.
    • Added verified external identity handling so requests can be grouped consistently across sessions.
    • Added per-user usage budgeting and retry-after rate limiting for supported chat paths.
    • Added local dev/mock tools for testing authenticated chat and streaming behavior.
  • Bug Fixes

    • Improved session and identity handling so authenticated requests use the correct scope.
    • Strengthened fail-closed behavior for invalid or missing auth tokens.

supmo668 and others added 7 commits June 25, 2026 14:09
…at-path auth, zero-dep node:crypto)

Phase A of P1 (Clerk-JWT verify + tau-metering), spec chat-endpoint-contract.md v1 section 3. Net-new src/gateway/clerk-jwt.ts: verifyClerkJwt(token,{jwksUrl,issuer,audience,now?,fetchJwks?}) -> {sub,claims}|null. RS256 via node:crypto (createPublicKey jwk + RSA-SHA256), ZERO new deps (jose NOT used). alg-confusion guard first; fail-closed never-throws; explicit non-empty-segment + required-kid guards; exact-kid JWKS match; injected-fetcher-authoritative module cache w/ one-refresh-on-unknown-kid. QG: 4 parallel reviewers, no exploitable CRITICAL/HIGH, 2 hardening fixes applied. Coverage 16/16 (src/gateway/clerk-jwt.test.ts); sealed referee 22/22 (committed separately under test-author identity). tsgo clean, oxfmt+oxlint clean on production files. NOTE: committed under cto identity due to submodule-cwd identity resolution (should be openclaw).

Stage: impl
Generated-With: Claude Code
Co-Authored-By: cto <[email protected]>
Co-Authored-By: Claude <[email protected]>
…verification onto the chat path (auth + user-scope)

Generated-With: Claude Code
Co-Authored-By: cto <[email protected]>
Co-Authored-By: Claude <[email protected]>
…ternalId (Clerk sub) into agent ctx so HTTP callers share the user graph

Closes the HTTP-memory-scope gap from P1.B: a Clerk/mobile chat turn now keys its
graph group_id on the verified user identity, unifying it with the SAME person's
other-channel graph (openclaw#834/openclaw#836) instead of forking.

Mirrors the P3 senderE164 thread: new PluginHookAgentContext.externalId (string|null);
threaded from RunEmbeddedPiAgentParams.externalId through the 3 hook-ctx sites
(run.ts before_agent_start, attempt.ts before_agent_start + agent_end) and through
AgentCommandOpts → agentCommand → runEmbeddedPiAgent; the two HTTP handlers pass
externalId: handled.externalId (the verified sub, never client-set) ?? null.

memory-graphiti: a new exported externalIdScopeKey(ctx) helper (identity.ts, reuses
deriveScopeKey) is preferred at BOTH recall (before_agent_start) and capture (agent_end)
group_id derivation when ctx.externalId is present — BEFORE the identity-DB query — so an
HTTP Clerk user sub=X and WhatsApp lp_users.external_id=X resolve the SAME group_id=X.

Behavior-preserving: channel callers carry no externalId → existing DB/derive path
byte-identical (characterization 14 + index 55 unchanged). PHI tripwire untouched (still
gates on senderE164; HTTP has none → fail-closed to Zep). 703 affected tests pass +6
(identity 5, openresponses e2e 1), tsgo 0, oxlint 0/0, sealed 60/60.

Generated-With: Claude Code
Co-Authored-By: cto <[email protected]>
Co-Authored-By: Claude <[email protected]>
…ring on the chat path (per user_scope 429 + Retry-After)

Wire a config-driven, default-OFF per-user_scope τ budget onto both chat surfaces (/v1/responses + /v1/chat/completions). The meter (tau-meter.ts) and the handler check/record seams already existed from the contract scaffold; this constructs the meter and threads it end-to-end so it actually throttles in prod.

- types.gateway.ts: GatewayTauConfig (+ tau? on GatewayAuthConfig); io.ts: OPENCLAW_TAU_* env keys.
- auth.ts: resolveTauConfig() -> ResolvedTauConfig on ResolvedGatewayAuth; present ONLY when explicitly enabled (config tau.enabled or OPENCLAW_TAU_ENABLED), else undefined -> unmetered no-op (behavior-preserving). parsePositiveIntEnv accepts decimal ints only.
- server.impl.ts: construct TauMeter once next to authRateLimiter; thread as a param and dispose() on shutdown (mirrors the rate-limiter lifecycle). server-runtime-state.ts shares the one meter across all bind-host servers (process-global budget per user_scope).
- server-http.ts: thread tauMeter into both chat handlers.
- openai-http.ts: record() a turn on both non-stream + stream completion (was check-only -> the OpenAI-compat surface enforced a budget it never debited; QG metering-evasion fix).

Contract section 9: 429 + Retry-After keyed on the server-derived user_scope (verified Clerk sub), shared across a user's consumers; unscoped requests never metered. PHI/tripwire posture untouched.

QG: sealed-referee Phase C suite (16 unit + 28 config + 8 e2e incl /v1/chat/completions metering regression lock + tauTurnCost token-cost debit). 4-reviewer adversarial QG: 1 CRIT (openai record gap) + 1 MED (dispose lifecycle) + 2 LOW fixed; zero residual CRIT/HIGH. tsgo 0, oxfmt clean, gateway unit 532/532, e2e chat lane 18/18, sealed 60/60.

Stage: impl
Generated-With: Claude Code
Co-Authored-By: cto <[email protected]>
Co-Authored-By: Claude <[email protected]>
…arness (local Clerk-JWT'd gateway for /v1/responses SSE)

scripts/dev/chat-auth-qa-preview.ts stands up the REAL gateway (startGatewayServer) with the P1 chat-auth surface wired on — Clerk-JWT verification + τ-metering — so QA can exercise the integrated mobile flow (Clerk-JWT'd POST /v1/responses -> SSE) without a deploy.

Default local mode mints a throwaway RSA keypair, serves its public JWK from a local JWKS endpoint, points gateway.auth.clerk at it, and mints a valid Clerk-shaped JWT (mirrors the tau-meter.e2e.test.ts harness — same verifier/scope/401/429 behavior as prod). --real-clerk mode reads devex's OPENCLAW_CLERK_* from env (Infisical) and expects a real Clerk session JWT.

Prints copy-paste curl for: streamed + non-streaming /v1/responses, auth fail-closed (no/bad token -> 401), τ 429 + Retry-After scope-keying, and the unscoped-never-metered legacy path. Verified live: 401 fail-closed, SSE event stream (response.created/in_progress/output_item.added), 429+Retry-After on budget exhaust, legacy-token never throttled. Dev-only harness; not shipped in the gateway runtime.

Stage: impl
Generated-With: Claude Code
Co-Authored-By: cto <[email protected]>
Co-Authored-By: Claude <[email protected]>
… — channels-free, contract-faithful /v1/responses streamed mock (shrinemobile local co-debug)

scripts/dev/chat-mock-server.ts: standalone http server (NO gateway/channels/agent — safe alongside
the live bot). Mints a local Clerk JWKS+JWT, verifies via the REAL verifyClerkJwt (401 fail-closed),
streams a deterministic mock reply matching the real handler's §2.2 SSE sequence (response.created→
in_progress→output_item.added→content_part.added→output_text.delta×N→…→completed→[DONE], full-event-
object data per the real writeSseEvent) + §2.3 stream:false envelope + 400/429(+Retry-After). Mock text
echoes input + resolved scope/session/device so the client can see scope threading. Flags: --port
--stream-delay-ms --budget --sub --legacy-token. DEV-stage tool only (test plan stage 1); not prod code.
7 tests (src/gateway/chat-mock-server.test.ts), tsgo 0, oxfmt clean. Verified: 401 + 200 stream:false +
ordered SSE live.

Generated-With: Claude Code
Co-Authored-By: cto <[email protected]>
Co-Authored-By: Claude <[email protected]>
…rebased

# Conflicts:
#	src/config/io.ts
#	src/gateway/openresponses-http.ts
@supmo668
supmo668 merged commit 2f8abc6 into main Jun 29, 2026
5 of 9 checks passed
@coderabbitai

coderabbitai Bot commented Jun 29, 2026 •

Copy link
Copy Markdown

Review Change Stack

Caution

Review failed

The pull request is closed.

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: ASSERTIVE

Plan: Pro Plus

Run ID: cf705cda-bf82-4419-9e20-9ffae0d14e98

📥 Commits

Reviewing files that changed from the base of the PR and between f988c54 and f8e44d3.

📒 Files selected for processing (38)
  • extensions/memory-graphiti/config.ts
  • extensions/memory-graphiti/identity.test.ts
  • extensions/memory-graphiti/identity.ts
  • extensions/memory-graphiti/index.ts
  • scripts/dev/chat-auth-qa-preview.ts
  • scripts/dev/chat-mock-server.ts
  • src/agents/pi-embedded-runner/run.ts
  • src/agents/pi-embedded-runner/run/attempt.ts
  • src/agents/pi-embedded-runner/run/params.ts
  • src/commands/agent.ts
  • src/commands/agent/types.ts
  • src/config/io.ts
  • src/config/types.gateway.ts
  • src/gateway/auth-clerk.test.ts
  • src/gateway/auth-tau-config.test.ts
  • src/gateway/auth.ts
  • src/gateway/chat-mock-server.test.ts
  • src/gateway/clerk-jwt.test.ts
  • src/gateway/clerk-jwt.ts
  • src/gateway/http-auth-helpers.ts
  • src/gateway/http-endpoint-helpers.test.ts
  • src/gateway/http-endpoint-helpers.ts
  • src/gateway/http-utils.test.ts
  • src/gateway/http-utils.ts
  • src/gateway/openai-http.ts
  • src/gateway/openresponses-http.e2e.test.ts
  • src/gateway/openresponses-http.ts
  • src/gateway/server-http.ts
  • src/gateway/server-runtime-state.ts
  • src/gateway/server.impl.ts
  • src/gateway/tau-meter.e2e.test.ts
  • src/gateway/tau-meter.test.ts
  • src/gateway/tau-meter.ts
  • src/plugins/types.ts
  • tests/sealed/clerk-jwt.MANIFEST.md
  • tests/sealed/clerk-jwt.sealed.test.ts
  • workstreams/openclaw/qgr/SyntropyHealth-Applications-mo-openclaw-openclaw-SyntropyHealth-Applications-qgr-pr-prep-20260626-2354-c574ff9.md
  • workstreams/openclaw/qgr/SyntropyHealth-Applications-mo-openclaw-openclaw-openclaw-qgr-iteration-complete-20260625-1410-0cbd3e0.md

Disabled knowledge base sources:

  • Linear integration is disabled

You can enable these sources in your CodeRabbit configuration.


📝 Walkthrough

Walkthrough

This PR adds RS256 Clerk JWT gateway authentication backed by a local JWKS verifier, a per-user_scope sliding-window τ-budget meter with HTTP 429 enforcement, and threads the verified externalId (Clerk sub) from gateway auth through the agent runner hook context into memory-graphiti identity resolution, where it now takes priority over the DB-based lookup.

Changes

Clerk JWT Auth + τ-Meter + externalId Pipeline

Layer / File(s) Summary
Clerk JWT verifier core
src/gateway/clerk-jwt.ts, tests/sealed/clerk-jwt.*, src/gateway/clerk-jwt.test.ts
Adds verifyClerkJwt: RS256-only, fail-closed, in-memory JWKS cache with single-refresh on unknown kid. Sealed and unit tests cover claim validation, alg confusion, malformed tokens, and JWKS fetch-call bounds.
Gateway auth types, resolution, and Clerk/τ config
src/config/types.gateway.ts, src/config/io.ts, src/gateway/auth.ts, src/gateway/auth-clerk.test.ts, src/gateway/auth-tau-config.test.ts
Adds GatewayClerkAuthConfig/GatewayTauConfig config types, resolves clerk (requires full JWKS/issuer/aud) and tau (env-gated, strict positive-integer parsing) in resolveGatewayAuth, and inserts a new clerk-jwt priority branch in authorizeGatewayConnect that is fail-closed and does not fall through to legacy token checks for JWS-shaped bearers.
τ-meter: sliding-window budget
src/gateway/tau-meter.ts, src/gateway/tau-meter.test.ts
Adds createTauMeter: per-userScope sliding-window cost accumulator with check/record/prune/dispose. Unscoped requests are always allowed. Unit tests cover exhaustion, sliding reset, independent budgets, prune, and dispose.
HTTP auth helpers: GatewayAuthResult + externalId
src/gateway/http-auth-helpers.ts, src/gateway/http-endpoint-helpers.ts, src/gateway/http-endpoint-helpers.test.ts, src/gateway/http-utils.ts, src/gateway/http-utils.test.ts
Changes authorizeGatewayBearerRequestOrReply to return GatewayAuthResult (not boolean); handleGatewayPostJsonEndpoint now returns externalId on success. Adds deriveUserScopeFromSub and a userScope-authoritative branch in resolveSessionKey that forces user:<scope> partitioning and ignores client-supplied user.
OpenResponses + OpenAI HTTP handlers
src/gateway/openresponses-http.ts, src/gateway/openai-http.ts, src/gateway/openresponses-http.e2e.test.ts
Derives userScope from handled.externalId, gates each request through tauMeter?.check, records τ spend after non-streaming completion and on streaming finalize, and passes externalId into agentCommand invocations.
Gateway server τ-meter wiring
src/gateway/server.impl.ts, src/gateway/server-runtime-state.ts, src/gateway/server-http.ts
Constructs tauMeter from resolvedAuth.tau in startGatewayServer, threads it through createGatewayRuntimeState → createGatewayHttpServer → handlers, and disposes it on shutdown.
externalId → agent runner → plugin hook context
src/plugins/types.ts, src/agents/pi-embedded-runner/run/params.ts, src/agents/pi-embedded-runner/run/attempt.ts, src/agents/pi-embedded-runner/run.ts, src/commands/agent/types.ts, src/commands/agent.ts
Adds `externalId?: string
memory-graphiti externalId identity priority
extensions/memory-graphiti/config.ts, extensions/memory-graphiti/identity.ts, extensions/memory-graphiti/identity.test.ts, extensions/memory-graphiti/index.ts
Adds externalId to GraphitiConfig, introduces externalIdScopeKey(ctx) (returns deriveScopeKey keyed on the external id or null), and updates before_agent_start/agent_end groupId derivation to prefer the external key over the DB-based identity lookup.
τ-meter e2e, chat-mock-server, and dev QA scripts
src/gateway/tau-meter.e2e.test.ts, src/gateway/chat-mock-server.test.ts, scripts/dev/chat-mock-server.ts, scripts/dev/chat-auth-qa-preview.ts, workstreams/openclaw/qgr/...
Full e2e τ-meter test suite (real gateway + local JWKS + mocked agent), exportable startChatMockServer with SSE + budget tests, and chat-auth-qa-preview dev script for local Clerk/τ QA.

Sequence Diagram(s)

sequenceDiagram
  participant Client
  participant authorizeGatewayConnect
  participant verifyClerkJwt
  participant tauMeter
  participant handleOpenResponsesHttpRequest
  participant agentCommand
  participant memoryGraphiti as memory-graphiti hooks

  Client->>authorizeGatewayConnect: Bearer JWS token
  authorizeGatewayConnect->>verifyClerkJwt: token, ResolvedClerkAuth
  verifyClerkJwt-->>authorizeGatewayConnect: {ok:true, externalId: sub}
  authorizeGatewayConnect-->>handleOpenResponsesHttpRequest: GatewayAuthResult{externalId}

  handleOpenResponsesHttpRequest->>tauMeter: check(userScope)
  tauMeter-->>handleOpenResponsesHttpRequest: {allowed:true}

  handleOpenResponsesHttpRequest->>agentCommand: {externalId}
  agentCommand->>memoryGraphiti: before_agent_start{externalId}
  memoryGraphiti->>memoryGraphiti: externalIdScopeKey(ctx) → groupId
  agentCommand-->>handleOpenResponsesHttpRequest: response + usage

  handleOpenResponsesHttpRequest->>tauMeter: record(userScope, tauTurnCost(usage))
  handleOpenResponsesHttpRequest-->>Client: 200 response
Loading

Estimated code review effort

🎯 5 (Critical) | ⏱️ ~120 minutes

Possibly related PRs

  • Syntropy-Health/openclaw#36: Both PRs modify extensions/memory-graphiti/identity.ts to derive canonical group/scope keys via deriveScopeKey; the retrieved PR introduces resolveIdentityScopeKey while this PR adds externalIdScopeKey calling the same helper.

Poem

🐇 A rabbit hops through gates of JWT,
Checks each token's kid and alg with care,
The τ-meter ticks per scope, per turn,
externalId flows to every hook in turn,
No fake Clerk key slips past this warren's stare! 🔐

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch mangyinm/chat-auth-p1-rebased

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.

@github-actions

Copy link
Copy Markdown

⚠️ Formal models conformance drift detected

The formal models extracted constants (generated/*) do not match this openclaw PR.

This check is informational (not blocking merges yet).
See the formal-models-conformance-drift artifact for the diff.

If this change is intentional, follow up by updating the formal models repo or regenerating the extracted artifacts there.

@supmo668
supmo668 deleted the mangyinm/chat-auth-p1-rebased branch October 17, 2026 17:33
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