Skip to content

fix: replace server-side cookie handling with client-side authorization code flow - #2937

Merged
tada5hi merged 4 commits into
masterfrom
2936-cookies
Mar 25, 2026
Merged

tada5hi merged 4 commits into
masterfrom
2936-cookies

Conversation

@tada5hi

@tada5hi tada5hi commented Mar 25, 2026 •

Copy link
Copy Markdown
Collaborator

closes #2936

Summary by CodeRabbit

  • New Features

    • Client auto-exchanges OAuth2 authorization codes to complete sign-in flows.
  • Improvements

    • Tighter redirect-URI validation and enforced single-use authorization codes.
    • Authorization flow now includes realm resolution when issuing app authorization codes.
  • Removals

    • Deprecated cookie-domain config removed; server and middleware no longer rely on cookie fallbacks or set auth cookies.
  • Tests

    • Added unit tests covering identity-provider authorization-code grant.
  • Documentation

    • Removed cookieDomain example config from server docs.

@coderabbitai

coderabbitai Bot commented Mar 25, 2026 •

Copy link
Copy Markdown

Caution

Review failed

The pull request is closed.

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 60ca5e4e-091c-40e2-9fca-f819e656df76

📥 Commits

Reviewing files that changed from the base of the PR and between bc4db41 and 39a5d01.

📒 Files selected for processing (2)
  • apps/client-web-slim/src/app.ts
  • packages/client-web-nuxt/src/runtime/helpers/routing-interceptor.ts

📝 Walkthrough

Walkthrough

The PR refactors OAuth2 authorization-code handling: servers stop setting auth cookies and instead issue single-use authorization codes (using a code issuer and realm resolution). Clients handle code exchange via a new store action; routing interceptors process incoming code query params and trigger the exchange.

Changes

Cohort / File(s) Summary
Client: routing & store
apps/client-web-slim/src/app.ts, packages/client-web-kit/src/core/store/create.ts, packages/client-web-nuxt/src/runtime/helpers/routing-interceptor.ts
Added client-side exchange flow: routing checks code query param and calls new exchangeAuthorizationCode(code) store action which performs token exchange and state population.
Server: identity-provider controller & types
apps/server-core/src/adapters/http/controllers/entities/identity-provider/module.ts, apps/server-core/src/adapters/http/controllers/entities/identity-provider/types.ts
Switched from issuing tokens/cookies to issuing authorization codes via codeIssuer; introduced realmRepository resolution; removed token/cookie issuance and related dependencies/options. Redirect now always includes code query param.
Server: token controller & types
apps/server-core/src/adapters/http/controllers/workflows/token/module.ts, apps/server-core/src/adapters/http/controllers/workflows/token/types.ts
Removed server-side cookie-setting from /token handler and removed TokenControllerOptions/cookie wiring from controller context. Handler now returns grant result without modifying response cookies.
Server: authorization middleware & types
apps/server-core/src/adapters/http/middleware/built-in/authorization/module.ts, apps/server-core/src/adapters/http/middleware/built-in/authorization/types.ts
Removed cookie fallback for Authorization header and removed cookie-clearing side effects; removed cookieDomain option from middleware types.
Server: config surface & wiring
apps/server-core/src/app/modules/config/constants.ts, apps/server-core/src/app/modules/config/parse.ts, apps/server-core/src/app/modules/config/read/env.ts, apps/server-core/src/app/modules/config/types.ts, apps/server-core/src/app/modules/http/modules/controller.ts, apps/server-core/src/app/modules/http/modules/middleware.ts
Deleted cookieDomain config and related wiring; updated HTTP module wiring to stop passing cookie-domain options and to provide codeIssuer + realmRepository into controllers.
Core OAuth2 / verifier changes
apps/server-core/src/core/oauth2/authorization/code-request/verifier/module.ts, apps/server-core/src/core/oauth2/authorization/module.ts, packages/core-kit/src/domains/authorization-code/entity.ts
Tightened request validation: client_id required early; stricter redirect_uri handling and explicit redirect URI presence check; authorization-code request type made client_id/redirect_uri optional at entity level.
Tests & docs
apps/server-core/test/unit/http/controllers/workflows/token/grant-idp-authorize.spec.ts, docs/src/guide/deployment/configuration-server-core.md
Added unit tests for identity-provider authorization-code grant flow; removed cookieDomain example from docs.

Sequence Diagram(s)

sequenceDiagram
    participant Browser as UserAgent (Browser)
    participant Router as Client Router
    participant Store as Client Store
    participant AppServer as App Server (IdentityProviderController)
    participant RealmRepo as RealmRepository
    participant CodeIssuer as OAuth2 CodeIssuer
    participant TokenEndpoint as TokenController

    Browser->>Router: Callback to /identity-provider/callback?code=ext-code&state=...
    Router->>Store: detect query.code -> exchangeAuthorizationCode(code)
    Store->>AppServer: POST /token (createWithAuthorizationCode) with app authorization code
    AppServer->>RealmRepo: resolve(entity.realm_id)
    AppServer->>CodeIssuer: issue(authorization code with realm in user data)
    CodeIssuer-->>AppServer: authorizationCode.id
    AppServer-->>Browser: 302 redirect back to app with ?code=<app-auth-code>
    Store->>TokenEndpoint: exchange authorization code for tokens
    TokenEndpoint-->>Store: JSON { access_token, refresh_token, expires_in } (no cookies)
    Store->>Store: applyTokenGrantResponse, resolveToken(), resolveUser()
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Possibly related PRs

"I hopped through code and left a trail of cheer,
A tiny code-crumb brought the server near.
No cookies in the breeze, just codes on the run,
I swapped a cookie for a hop — now auth is fun! 🐇"

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly summarizes the main change: replacing server-side cookie handling with authorization code flow, which is the primary objective of this changeset.
Linked Issues check ✅ Passed All key requirements from issue #2936 are met: cookie-setting logic removed from TokenController and IdentityProviderController, cookieDomain configuration removed, server-side cookie handling eliminated throughout, and authorization code flow implemented.
Out of Scope Changes check ✅ Passed All changes are directly related to the linked issue's objectives. The PR removes cookie-handling infrastructure, implements authorization code flow, updates middleware and configuration, and adds integration tests—all within scope of the stated refactoring.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ 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 2936-cookies

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 and usage tips.

@coderabbitai coderabbitai 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.

Actionable comments posted: 4

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (2)
apps/server-core/src/core/oauth2/authorization/code-request/verifier/module.ts (1)

66-72: ⚠️ Potential issue | 🔴 Critical

Redirect URI validation can be bypassed when the client has no registered redirect URI.

At Line 66, validation is skipped unless client.redirect_uri is set. Given nullable client redirect URIs, this allows arbitrary data.redirect_uri values through, which is unsafe for authorization code flows.

Suggested fix (strict redirect URI enforcement)
-        if (client.redirect_uri && data.redirect_uri) {
-            const redirectUris = client.redirect_uri.split(',');
-
-            if (!isSimpleMatch(data.redirect_uri, redirectUris)) {
-                throw OAuth2Error.redirectUriMismatch();
-            }
-        }
+        if (!client.redirect_uri || !data.redirect_uri) {
+            throw OAuth2Error.redirectUriMismatch();
+        }
+
+        const redirectUris = client.redirect_uri.split(',');
+        if (!isSimpleMatch(data.redirect_uri, redirectUris)) {
+            throw OAuth2Error.redirectUriMismatch();
+        }
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In
`@apps/server-core/src/core/oauth2/authorization/code-request/verifier/module.ts`
around lines 66 - 72, The current logic skips redirect URI validation when
client.redirect_uri is null, allowing arbitrary data.redirect_uri values; change
the verifier so that if the client has no registered redirect_uri the request is
rejected (e.g., throw OAuth2Error.redirectUriMismatch()), and otherwise parse
client.redirect_uri into redirectUris and validate data.redirect_uri with
isSimpleMatch as before—ensure you reference client.redirect_uri,
data.redirect_uri, isSimpleMatch, and OAuth2Error.redirectUriMismatch() in the
updated check so all requests require a matching registered redirect URI.
apps/server-core/src/adapters/http/controllers/entities/identity-provider/module.ts (1)

318-331: ⚠️ Potential issue | 🟠 Major

Preserve publicUrl path prefixes when rebuilding the /authorize redirect.

Line 325 uses new URL('/authorize', this.options.baseURL), which resets the path to the origin root. Since this.options.baseURL is set to config.publicUrl, if it includes a prefix such as https://example.com/auth/, this branch redirects to https://example.com/authorize instead of https://example.com/auth/authorize, breaking the IDP callback flow for path-based deployments.

Suggested fix
-            const url = new URL('/authorize', this.options.baseURL);
+            const baseURL = this.options.baseURL.endsWith('/')
+                ? this.options.baseURL
+                : `${this.options.baseURL}/`;
+            const url = new URL('authorize', baseURL);
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In
`@apps/server-core/src/adapters/http/controllers/entities/identity-provider/module.ts`
around lines 318 - 331, The redirect rebuild currently uses new
URL('/authorize', this.options.baseURL) which discards any path prefix in
this.options.baseURL; change the URL construction to preserve the base path
(e.g., create a URL from this.options.baseURL and append or join the 'authorize'
segment without a leading slash) so that if this.options.baseURL contains a path
prefix the final redirect becomes <basePath>/authorize; update the code around
where data.codeRequest, authorizationCode.id and sendRedirect are used (symbols:
this.options.baseURL, data.codeRequest, authorizationCode.id, sendRedirect) to
set searchParams on the preserved-path URL before calling sendRedirect.
🧹 Nitpick comments (2)
packages/core-kit/src/domains/authorization-code/entity.ts (1)

40-42: Consider splitting unverified vs validated authorization request types.

Making client_id and redirect_uri optional in the shared request type weakens compile-time guarantees and increases downstream mutation/guarding. A separate validated type (with required fields) would keep invariants explicit after verification.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/core-kit/src/domains/authorization-code/entity.ts` around lines 40 -
42, The current shared request type in authorization-code entity makes client_id
and redirect_uri optional (client_id, redirect_uri, realm_id), which weakens
type guarantees; introduce two explicit types such as
UnverifiedAuthorizationRequest (keeping client_id?, redirect_uri?, realm_id?)
and ValidatedAuthorizationRequest with required client_id: string and
redirect_uri: string (and realm_id as required if applicable), update any
validation function (e.g., the authorize/validate function that consumes the
unverified type) to perform runtime checks and return or narrow to
ValidatedAuthorizationRequest, and then update downstream functions to accept
ValidatedAuthorizationRequest so callers can rely on these invariants instead of
re-checking optional fields.
apps/server-core/test/unit/http/controllers/workflows/token/grant-idp-authorize.spec.ts (1)

93-185: Add regression coverage for the new callback contract.

The suite only exercises the !codeRequest path and only checks the happy-path exchange. Since this PR's contract is “no server-set token cookies plus a hand-off back through /authorize when codeRequest exists”, I'd add one test with an encoded codeRequest and one raw-response assertion that both authorize-in and POST /token omit set-cookie.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In
`@apps/server-core/test/unit/http/controllers/workflows/token/grant-idp-authorize.spec.ts`
around lines 93 - 185, Tests only cover the no-codeRequest happy path; add
regression tests that exercise the codeRequest callback contract by calling
buildIdentityProviderAuthorizePath and
buildIdentityProviderAuthorizeCallbackPath with an encoded codeRequest value and
asserting that the authorize-in response and the subsequent token exchange
(suite.client.token.createWithAuthorizationCode or a raw POST to /token) do NOT
include Set-Cookie headers; specifically, add one test that constructs a
codeRequest (encoded in the same format the server expects), sends the callback
GET to buildIdentityProviderAuthorizeCallbackPath(...)?codeRequest=..., asserts
the 302 hand-off contains the authup code, then performs the token exchange and
asserts both the authorize-in response.headers.get('set-cookie') and the token
response/raw HTTP response headers do not exist.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In
`@apps/server-core/src/app/modules/database/repositories/identity-provider/repository.ts`:
- Around line 166-169: The findRealm method currently throws a bare Error when
realmRepository.resolve(realmId) returns falsy; change this to a distinguishable
failure: either make findRealm return Promise<Realm | null> and return null when
not found (and update callers such as authorizeIn to handle the null case and
map it to the appropriate HTTP response), or create and throw a specific domain
error (e.g., RealmNotFoundError) instead of generic Error so callers can catch
and translate it; ensure the method signature and all call sites (authorizeIn
and any other callers) are updated to handle the new return type or the specific
error type.

In `@apps/server-core/src/core/entities/identity-provider/types.ts`:
- Line 18: Change the findRealm contract to return Promise<Realm | null> instead
of Promise<Realm>, update the implementation of the repository method that
currently throws when a realm is missing (the method implementing findRealm in
the identity-provider repository) to return null for not-found cases, and then
update all callers of findRealm to explicitly handle the null case and map it to
the appropriate OAuth/HTTP error instead of relying on exceptions; ensure the
Realm type remains the same and only the return signature and not-found behavior
are changed.

In `@packages/client-web-kit/src/core/store/create.ts`:
- Around line 364-373: In exchangeAuthorizationCode, reset the resolution flags
before calling resolveToken()/resolveUser() so stale state isn't reused: after
applyTokenGrantResponse(response) (or immediately before resolving), set
tokenResolved = false and userResolved = false (or call existing reset helpers
if present) and then await resolveToken(); await resolveUser(); ensuring
exchangeAuthorizationCode, applyTokenGrantResponse, resolveToken, resolveUser
and the tokenResolved/userResolved state are updated accordingly.

In `@packages/client-web-nuxt/src/runtime/helpers/routing-interceptor.ts`:
- Around line 41-48: The authorization code (variable "code") is left in the URL
after a successful exchange via this.store.exchangeAuthorizationCode, causing
redundant exchanges; after the await this.store.exchangeAuthorizationCode(code)
resolves successfully, remove the "code" query param from the current route
(e.g., via the router's replace or window.history.replaceState) so the page URL
no longer contains the code without triggering a navigation; keep the catch
behavior unchanged (only remove the param on success).

---

Outside diff comments:
In
`@apps/server-core/src/adapters/http/controllers/entities/identity-provider/module.ts`:
- Around line 318-331: The redirect rebuild currently uses new URL('/authorize',
this.options.baseURL) which discards any path prefix in this.options.baseURL;
change the URL construction to preserve the base path (e.g., create a URL from
this.options.baseURL and append or join the 'authorize' segment without a
leading slash) so that if this.options.baseURL contains a path prefix the final
redirect becomes <basePath>/authorize; update the code around where
data.codeRequest, authorizationCode.id and sendRedirect are used (symbols:
this.options.baseURL, data.codeRequest, authorizationCode.id, sendRedirect) to
set searchParams on the preserved-path URL before calling sendRedirect.

In
`@apps/server-core/src/core/oauth2/authorization/code-request/verifier/module.ts`:
- Around line 66-72: The current logic skips redirect URI validation when
client.redirect_uri is null, allowing arbitrary data.redirect_uri values; change
the verifier so that if the client has no registered redirect_uri the request is
rejected (e.g., throw OAuth2Error.redirectUriMismatch()), and otherwise parse
client.redirect_uri into redirectUris and validate data.redirect_uri with
isSimpleMatch as before—ensure you reference client.redirect_uri,
data.redirect_uri, isSimpleMatch, and OAuth2Error.redirectUriMismatch() in the
updated check so all requests require a matching registered redirect URI.

---

Nitpick comments:
In
`@apps/server-core/test/unit/http/controllers/workflows/token/grant-idp-authorize.spec.ts`:
- Around line 93-185: Tests only cover the no-codeRequest happy path; add
regression tests that exercise the codeRequest callback contract by calling
buildIdentityProviderAuthorizePath and
buildIdentityProviderAuthorizeCallbackPath with an encoded codeRequest value and
asserting that the authorize-in response and the subsequent token exchange
(suite.client.token.createWithAuthorizationCode or a raw POST to /token) do NOT
include Set-Cookie headers; specifically, add one test that constructs a
codeRequest (encoded in the same format the server expects), sends the callback
GET to buildIdentityProviderAuthorizeCallbackPath(...)?codeRequest=..., asserts
the 302 hand-off contains the authup code, then performs the token exchange and
asserts both the authorize-in response.headers.get('set-cookie') and the token
response/raw HTTP response headers do not exist.

In `@packages/core-kit/src/domains/authorization-code/entity.ts`:
- Around line 40-42: The current shared request type in authorization-code
entity makes client_id and redirect_uri optional (client_id, redirect_uri,
realm_id), which weakens type guarantees; introduce two explicit types such as
UnverifiedAuthorizationRequest (keeping client_id?, redirect_uri?, realm_id?)
and ValidatedAuthorizationRequest with required client_id: string and
redirect_uri: string (and realm_id as required if applicable), update any
validation function (e.g., the authorize/validate function that consumes the
unverified type) to perform runtime checks and return or narrow to
ValidatedAuthorizationRequest, and then update downstream functions to accept
ValidatedAuthorizationRequest so callers can rely on these invariants instead of
re-checking optional fields.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 1ec3c709-97f0-4758-b9a3-c190cca17a7b

📥 Commits

Reviewing files that changed from the base of the PR and between 23a8f13 and c72f291.

📒 Files selected for processing (22)
  • apps/client-web-slim/src/app.ts
  • apps/server-core/src/adapters/http/controllers/entities/identity-provider/module.ts
  • apps/server-core/src/adapters/http/controllers/entities/identity-provider/types.ts
  • apps/server-core/src/adapters/http/controllers/workflows/token/module.ts
  • apps/server-core/src/adapters/http/controllers/workflows/token/types.ts
  • apps/server-core/src/adapters/http/middleware/built-in/authorization/module.ts
  • apps/server-core/src/adapters/http/middleware/built-in/authorization/types.ts
  • apps/server-core/src/app/modules/config/constants.ts
  • apps/server-core/src/app/modules/config/parse.ts
  • apps/server-core/src/app/modules/config/read/env.ts
  • apps/server-core/src/app/modules/config/types.ts
  • apps/server-core/src/app/modules/database/repositories/identity-provider/repository.ts
  • apps/server-core/src/app/modules/http/modules/controller.ts
  • apps/server-core/src/app/modules/http/modules/middleware.ts
  • apps/server-core/src/core/entities/identity-provider/types.ts
  • apps/server-core/src/core/oauth2/authorization/code-request/verifier/module.ts
  • apps/server-core/src/core/oauth2/authorization/module.ts
  • apps/server-core/test/unit/http/controllers/workflows/token/grant-idp-authorize.spec.ts
  • docs/src/guide/deployment/configuration-server-core.md
  • packages/client-web-kit/src/core/store/create.ts
  • packages/client-web-nuxt/src/runtime/helpers/routing-interceptor.ts
  • packages/core-kit/src/domains/authorization-code/entity.ts
💤 Files with no reviewable changes (8)
  • apps/server-core/src/app/modules/config/read/env.ts
  • apps/server-core/src/app/modules/config/constants.ts
  • apps/server-core/src/app/modules/http/modules/middleware.ts
  • apps/server-core/src/adapters/http/middleware/built-in/authorization/types.ts
  • apps/server-core/src/app/modules/config/parse.ts
  • docs/src/guide/deployment/configuration-server-core.md
  • apps/server-core/src/app/modules/config/types.ts
  • apps/server-core/src/adapters/http/controllers/workflows/token/types.ts

@tada5hi tada5hi changed the title fix: replace server-side cookie handling with authorization code flow… fix: replace server-side cookie handling with client-side authorization code flow Mar 25, 2026
@tada5hi
tada5hi merged commit 8edb612 into master Mar 25, 2026
5 checks passed
@tada5hi
tada5hi deleted the 2936-cookies branch March 25, 2026 14:48
This was referenced Mar 24, 2026
@github-actions github-actions Bot mentioned this pull request Apr 16, 2026
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.

Refactor: Remove server-side cookie setting from /token endpoint

1 participant