Repository navigation
feat(server-core): migrate to routup v5 + swagger split - #3030
Conversation
@ebec/http v4 renamed `Input`/`Options` to `HTTPErrorInput`/`HTTPErrorOptions`, flipped the per-error `*ErrorOptions` consts from `statusCode` to `status`, and removed the free-form `data` field from `HTTPErrorOptions`. `AuthupError.data` is a public surface used by the OAuth2 error helpers and the error middleware to forward extra payload keys, so it moves from a transitive ebec field to an explicit field on `AuthupError` itself. Callers in `apps/server-core/src/utils/error.ts` flip to the new `status` accessor on the Options consts.
|
Caution Review failedThe pull request is closed. ℹ️ Recent review info⚙️ Run configurationConfiguration used: defaults Review profile: CHILL Plan: Pro Run ID: 📒 Files selected for processing (25)
📝 WalkthroughWalkthroughComprehensive migration from routup v4 to v5 involving framework-wide refactoring of request/response handling to event-driven architecture, error type updates replacing ChangesRoutup v5 Event-Driven Framework Migration
Sequence DiagramThis PR's scope is too heterogeneous (spanning framework migration, error handling refactoring, middleware rewiring, and swagger generation changes) to visualize as a single coherent sequence. The changes constitute a framework-wide refactor affecting request/response flow, error construction, and server initialization across many disjoint code paths without a unifying primary interaction pattern suitable for sequence-diagram representation. Estimated code review effort🎯 5 (Critical) | ⏱️ ~120+ minutes Possibly related issues
Possibly related PRs
Poem
✨ Finishing Touches📝 Generate docstrings
🧪 Generate unit tests (beta)
|
There was a problem hiding this comment.
Pull request overview
Updates the monorepo’s error stack for @ebec/http v4, mainly in @authup/errors and apps/server-core, so the shared error types align with the upstream API rename/removals.
Changes:
- Bumps
@ebec/httpfrom v2 to v4 inpackages/errorsandapps/server-core. - Moves
AuthupError.dataontoAuthupErroritself and updatessanitizeError()to use the renamed option constants. - Refreshes the lockfile for the new dependency version.
Assessment: The upgrade is not yet complete: the shared AuthupError API changes break existing downstream packages that still rely on statusCode and multi-argument super(...) calls.
Reviewed changes
Copilot reviewed 5 out of 6 changed files in this pull request and generated 2 comments.
Show a summary per file
| File | Description |
|---|---|
packages/errors/src/types.ts |
Replaces old ebec option types with HTTPErrorOptions and adds explicit data to AuthupErrorOptions. |
packages/errors/src/module.ts |
Reworks AuthupError constructor/data handling for the new upstream API. |
packages/errors/package.json |
Bumps @ebec/http to v4 for the errors package. |
package-lock.json |
Updates lockfile entries for the new @ebec/http version. |
apps/server-core/src/utils/error.ts |
Switches server-side error sanitization to the new option constant shape. |
apps/server-core/package.json |
Bumps @ebec/http to v4 for server-core. |
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
| constructor(input?: AuthupErrorOptionsInput) { | ||
| super(input); | ||
|
|
||
| this.issues = []; | ||
|
|
||
| if (typeof input === 'object' && input !== null && 'data' in input) { | ||
| this.data = (input as { data?: Record<string, any> }).data; |
|
|
||
| export type AuthupErrorOptions = Options & { | ||
| codePrefix?: string | ||
| export type AuthupErrorOptions = HTTPErrorOptions & { |
There was a problem hiding this comment.
Actionable comments posted: 1
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@packages/errors/src/module.ts`:
- Around line 22-24: The current guard assigns this.data whenever input is any
non-null object with a data property, which will incorrectly pull data from
Error subclasses; update the check in the constructor (the block using input and
this.data) to exclude instances of Error (e.g., add a condition like && !(input
instanceof Error)) so that only genuine AuthupErrorOptions-like inputs populate
this.data; reference the same symbols: input, this.data, and
AuthupErrorOptions/constructor to locate and adjust the guard.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: defaults
Review profile: CHILL
Plan: Pro
Run ID: 611a6082-eb55-4c69-a29e-644cc48ee536
⛔ Files ignored due to path filters (1)
package-lock.jsonis excluded by!**/package-lock.json
📒 Files selected for processing (5)
apps/server-core/package.jsonapps/server-core/src/utils/error.tspackages/errors/package.jsonpackages/errors/src/module.tspackages/errors/src/types.ts
…lpers Bumps routup core to ^5.0.0 and the @routup/* plugin family to their v5-aligned majors. Drops @validup/adapter-routup (no v5 release exists) and replaces its 4 call sites with an inline readFromLocations helper that merges body/query/params/cookies for OAuth2 spec compliance. Server bootstrap switches from createNodeDispatcher to toNodeHandler (routup/node). Error middleware moves to defineErrorHandler returning a plain payload instead of send(res, ...). All built-in middleware (cors, logger, assets, prometheus, rate-limit, basic, authorization) moves to defineCoreHandler / fromNodeMiddleware as appropriate. Request helpers (identity, token, scopes, actor, param-id, body-realm-id) flip from req-based useRequestEnv/setRequestEnv to direct event.store reads/writes. RequestPermissionEvaluator and the permission helper mirror the same flip. ForceLoggedIn middleware classes adopt the new HandlerInterface (event) signature. Swagger middleware is stubbed with a 501 handler until phase 5 restores it via @routup/swagger-ui + @trapi/swagger. Controllers, OAuth2 grant types, and wiring modules still target the v4 dispatch shape — they're handled in phase 3.
…rver wrapper
routup v5's serve() returns a srvx Server with ready(), url, and close()
built in. The previous createHttpServer wrapper around http.Server +
manual once('listening') promise + address() parsing was needed for the
v4 dispatcher; under v5 it's pure ceremony.
apps/server-core/src/adapters/http/server/ is deleted (3 files). The
HTTPModule now boots via serve(router, { port, hostname, silent }) and
awaits server.ready(). Logging uses server.url instead of the
AddressInfo dance. The injection key types switch to a derived
HTTPServer = ReturnType<typeof serve> alias.
test/app/http.ts updates baseURL to read server.url (with the trailing
slash trimmed for compatibility with the existing client baseURL
contract).
Migrates 28 entity controllers, 8 workflow controllers, 9 OAuth2 grant files, and the http wiring modules to the v5 dispatch model: - (@DRequest req, @DResponse res) parameter pairs collapse to a single @DContext() event: IRoutupEvent argument across every method - send(res, X) is removed (no longer exported by routup); handlers return the value directly - sendCreated/sendAccepted/sendRedirect take event instead of res - useRequestParam(req, key) becomes event.params.key - useRequestBody(req, key) becomes (await readRequestBody(event)).key -- now async, cached internally by v5 - useRequestQuery, getRequestIP, getRequestHeader take event - @DRequest/@DResponse drop from imports; @DContext takes their place OAuth2 grant types (password, client-credentials, robot-credentials, refresh_token, authorize, identity) and helper utilities (extractClientCredentialsFromRequest, guessOauth2GrantTypeByRequest) become async because body extraction is now a Promise. The token controller awaits the grant type resolution before dispatching. @routup/decorators v4 has built-in body/cookie/query extractors, so the custom parameter: config in the http wiring module disappears. The v4 @routup/swagger generator can't parse @DContext()-annotated controllers, so build:swagger is dropped from the default build script until phase 5 swaps the generator for @trapi/swagger + @routup/decorators/preset. The script remains available standalone.
There was a problem hiding this comment.
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/adapters/http/middleware/built-in/error.ts (1)
34-40:⚠️ Potential issue | 🔴 Critical | 🏗️ Heavy liftChange
next.statusCodetonext.statuson lines 34 and 40.The
sanitizeErrorutility (lines 28, 30) constructsAuthupErrorinstances withstatus:parameter, aligning with@ebec/httpv4's API. However, lines 34 and 40 attempt to read fromnext.statusCode, which does not exist on the error object—this property isundefined. As a result:
- Response body carries
"statusCode": null/undefined- The 5xx range check (
undefined >= 500) always evaluates tofalse, silently suppressing server-error logging for every errorevent.response.status = undefinedfails to set the HTTP status codeChange both occurrences to use
next.status.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@apps/server-core/src/adapters/http/middleware/built-in/error.ts` around lines 34 - 40, The error handler is reading next.statusCode (which is undefined) instead of next.status; update the construction of the response object and the server-error check to use next.status (replace both uses of next.statusCode with next.status) so the response body sets "status" correctly, the 5xx range check (isServerError) works, and event.response.status is assigned a real HTTP status; verify this change around the sanitizeError/AuthupError flow and in the isServerError computation and returned response object.apps/server-core/src/adapters/http/middleware/built-in/authorization/module.ts (1)
184-226:⚠️ Potential issue | 🟠 Major | ⚡ Quick winReturn immediately after a successful Basic-auth match.
Line 190 attaches a client identity but keeps executing, unlike the user branch on Line 204. If multiple Basic auth modes are enabled, a later authenticator can overwrite the request identity/scopes and make the resolved principal depend on branch order.
Suggested fix
if (this.options.clientAuthBasic) { const authenticator = await this.clientAuthenticator.safeAuthenticate( header.username, header.password, ); if (authenticator.success) { setRequestScopes(event, [ScopeName.GLOBAL]); setRequestIdentity(event, { type: IdentityType.CLIENT, data: authenticator.data, }); + return; } } @@ if (this.options.robotAuthBasic) { const authenticated = await this.robotAuthenticator.safeAuthenticate( header.username, header.password, ); if (authenticated.success) { setRequestScopes(event, [ScopeName.GLOBAL]); setRequestIdentity(event, { type: IdentityType.ROBOT, data: authenticated.data, }); + return; } }🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@apps/server-core/src/adapters/http/middleware/built-in/authorization/module.ts` around lines 184 - 226, The client and robot Basic-auth branches (guarded by this.options.clientAuthBasic and this.options.robotAuthBasic) setRequestScopes(event, ...) and setRequestIdentity(event, ...) but do not return, allowing subsequent authenticators to overwrite the principal; update the clientAuthenticator.safeAuthenticate and robotAuthenticator.safeAuthenticate success paths to return immediately after setting scopes/identity (same as the user branch) so that once a Basic-auth match is found the middleware stops further authentication checks.
🧹 Nitpick comments (5)
apps/server-core/src/adapters/http/middleware/built-in/swagger.ts (1)
11-13: ⚡ Quick winRemove the dead
documentPathcontract from the temporary stub.The stub never reads
_input.documentPath, but the signature still forces callers to pass a path to a file that is no longer built. Dropping the unused option now makes the migration state explicit and avoids future call sites assumingswagger.jsonis still consulted.♻️ Proposed cleanup
-type SwaggerMiddlewareOptions = { - documentPath: string, -}; - /** * Phase 5 of the routup v5 migration restores the swagger UI via * `@routup/swagger-ui` + `@trapi/swagger`. Until then this plugin * mounts a 501 handler so the binary boots without the deleted * `@routup/swagger` import. */ -export async function createSwaggerMiddleware(_input: Partial<SwaggerMiddlewareOptions> = {}) : Promise<Plugin> { +export function createSwaggerMiddleware() : Plugin { return { name: '@authup/swagger-stub', install(router) { router.use(defineCoreHandler((event) => { event.response.status = 501;And the caller can become:
const middleware = createSwaggerMiddleware();Also applies to: 21-21
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@apps/server-core/src/adapters/http/middleware/built-in/swagger.ts` around lines 11 - 13, Remove the dead documentPath option from the temporary stub by deleting the SwaggerMiddlewareOptions type field and any parameter usage that expects _input.documentPath; update the createSwaggerMiddleware (and any factory/signature that references SwaggerMiddlewareOptions) to accept no options or an empty options object so callers can call createSwaggerMiddleware() directly, and remove/adjust any tests or call sites that pass a documentPath argument.apps/server-core/src/app/modules/http/module.ts (1)
72-78: ⚡ Quick winTeardown unregisters from DI before closing the server.
container.unregister(HTTPInjectionKey.Server)(line 75) runs beforeawait this.instance.close()(line 77). Any teardown code that subsequently resolvesHTTPInjectionKey.Serverfrom the container will fail unexpectedly, even though the server is still accepting connections. Closing first, then unregistering, matches the natural graceful-shutdown order and avoids the window where the container says "no server" but the server is live.♻️ Suggested fix — reverse teardown order
async teardown(container: IContainer): Promise<void> { if (!this.instance) return; - container.unregister(HTTPInjectionKey.Server); - await this.instance.close(); this.instance = undefined; + + container.unregister(HTTPInjectionKey.Server); }🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@apps/server-core/src/app/modules/http/module.ts` around lines 72 - 78, In teardown of the module (method teardown), reverse the unregister/close order: call await this.instance.close() first, then call container.unregister(HTTPInjectionKey.Server), and finally set this.instance = undefined; this ensures the server referred to by this.instance is closed before removing the HTTPInjectionKey.Server from the DI container and avoids a window where the container no longer resolves a still-running server.apps/server-core/src/adapters/http/middleware/built-in/assets.ts (1)
17-17: ⚡ Quick winMove the Vite store key into a lightweight shared module.
authorize/module.tsnow has to import the assets middleware file just to access this symbol, which also pulls the asset-wiring dependencies into controller load. A tiny shared constant module keeps the controller ↔ middleware boundary cleaner.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@apps/server-core/src/adapters/http/middleware/built-in/assets.ts` at line 17, Extract the VITE_SERVER_STORE_KEY symbol into a new tiny shared module and have both the assets middleware and authorize/module.ts import it from there instead of assets.ts; specifically, create a module that exports VITE_SERVER_STORE_KEY (the same Symbol('ViteServer')), update the export in the current assets middleware to import that constant rather than define it, and update authorize/module.ts to import VITE_SERVER_STORE_KEY from the new shared module so authorize no longer transitively pulls in the asset-wiring dependencies.apps/server-core/src/adapters/http/request/helpers/param-id.ts (1)
56-68: ⚡ Quick winNarrow
getRequestStringParamOrFailreturn type tostring.This function throws when value is missing, so
undefinedis not a valid successful return type.Proposed fix
-export function getRequestStringParamOrFail(event: IRoutupEvent, key: string) : string | undefined { +export function getRequestStringParamOrFail(event: IRoutupEvent, key: string) : string {🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@apps/server-core/src/adapters/http/request/helpers/param-id.ts` around lines 56 - 68, The return type of getRequestStringParamOrFail is too wide — it currently allows undefined even though the function throws when the value is missing; update the function signature to return string (not string | undefined) in the declaration of getRequestStringParamOrFail, leaving the implementation (which throws a ValidupError when getRequestStringParam(event, key) is undefined) intact, and ensure any callers of getRequestStringParamOrFail handle the thrown error rather than expecting undefined; use the function name getRequestStringParamOrFail and the call to getRequestStringParam(event, key) to locate the code to change.apps/server-core/src/adapters/http/controllers/entities/policy/module.ts (1)
106-123: ⚡ Quick win
@DPath('id') idis injected but unused — prefer it overevent.params.id.
const paramId = event.params.id(Line 112) re-reads the same route parameter that is already injected asidvia@DPath('id'). Theidparameter is effectively dead code, which may trigger a lint warning and is inconsistent with the rest of the method. Just useiddirectly asparamId.♻️ Proposed fix
async check( `@DPath`('id') id: string, `@DBody`() data: any, `@DContext`() event: IRoutupEvent, ): Promise<any> { - const paramId = event.params.id; + const paramId = id; let criteria: Record<string, any>;🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@apps/server-core/src/adapters/http/controllers/entities/policy/module.ts` around lines 106 - 123, The method check has an injected `@DPath`('id') parameter named id but the code ignores it and reads event.params.id into paramId; replace usages of event.params.id with the injected id (e.g. set const paramId = id or simply use id directly) so the parameter id is used and remove the redundant access to event.params.id; update any calls to realmRepository.resolve(event.params.realmId) to continue using event.params.realmId (or inject realmId if preferred) but ensure check() uses the injected id parameter rather than re-reading from event.params.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In
`@apps/server-core/src/adapters/http/controllers/entities/identity-provider/module.ts`:
- Around line 351-357: The write() method currently uses getBodyRealmID(body)
and later falls back to the caller's identity realm, which allows nested routes
to write to the wrong realm; change the realm resolution so the route param
realm takes precedence: first try to read the realm from the request route
params (the same place you get the id via getRequestParamID(event,...)), then
fall back to the request body (getBodyRealmID(body)), and only lastly use the
caller identity realm. Update both the initial realm assignment in write() and
the later fallback logic that currently uses the caller realm so all
create/update flows consistently use the route param realm when present.
In
`@apps/server-core/src/adapters/http/controllers/workflows/password-forgot/module.ts`:
- Around line 35-40: The method currently declares
Promise<PasswordForgotResponse> but returns sendAccepted(event, result) which is
a Response; remove the // `@ts-expect-error` and align the signature with
sendAccepted by changing the method return type to Promise<Response> (or remove
the explicit return type entirely) and keep the return as return
sendAccepted(event, result); reference the PasswordForgotResponse type, the
method signature in module.ts, and the sendAccepted call to locate and update
the code.
In
`@apps/server-core/src/adapters/http/controllers/workflows/token/utils/extract.ts`:
- Around line 16-25: The catch currently swallows all errors when running
TokenRequestValidator/readFromLocations and silently falls back to
useRequestToken; change the catch to only perform the header fallback for
expected validation errors from TokenRequestValidator (e.g., check err
instanceof <the validator's validation error type> or err.name ===
'ValidationError'), and rethrow any other errors so parsing/IO issues from
readFromLocations or unexpected failures are not hidden; update the try/catch
around TokenRequestValidator.run/readFromLocations to inspect the caught error
and either set token = useRequestToken(event) for validation errors or throw the
error otherwise.
In `@apps/server-core/src/adapters/http/middleware/built-in/logger.ts`:
- Around line 19-21: Formatter uses req.socket.remoteAddress without guarding
against req.socket being null; update the morgan formatter (the formatter
variable created with morgan and the tokens, req, res callback) to safely access
remoteAddress, e.g., replace direct access to req.socket.remoteAddress with a
null-safe expression such as req.socket?.remoteAddress || '-' (or req.socket &&
req.socket.remoteAddress || '-' if optional chaining isn't available) so the
fallback '-' is used when socket is null.
---
Outside diff comments:
In
`@apps/server-core/src/adapters/http/middleware/built-in/authorization/module.ts`:
- Around line 184-226: The client and robot Basic-auth branches (guarded by
this.options.clientAuthBasic and this.options.robotAuthBasic)
setRequestScopes(event, ...) and setRequestIdentity(event, ...) but do not
return, allowing subsequent authenticators to overwrite the principal; update
the clientAuthenticator.safeAuthenticate and robotAuthenticator.safeAuthenticate
success paths to return immediately after setting scopes/identity (same as the
user branch) so that once a Basic-auth match is found the middleware stops
further authentication checks.
In `@apps/server-core/src/adapters/http/middleware/built-in/error.ts`:
- Around line 34-40: The error handler is reading next.statusCode (which is
undefined) instead of next.status; update the construction of the response
object and the server-error check to use next.status (replace both uses of
next.statusCode with next.status) so the response body sets "status" correctly,
the 5xx range check (isServerError) works, and event.response.status is assigned
a real HTTP status; verify this change around the sanitizeError/AuthupError flow
and in the isServerError computation and returned response object.
---
Nitpick comments:
In `@apps/server-core/src/adapters/http/controllers/entities/policy/module.ts`:
- Around line 106-123: The method check has an injected `@DPath`('id') parameter
named id but the code ignores it and reads event.params.id into paramId; replace
usages of event.params.id with the injected id (e.g. set const paramId = id or
simply use id directly) so the parameter id is used and remove the redundant
access to event.params.id; update any calls to
realmRepository.resolve(event.params.realmId) to continue using
event.params.realmId (or inject realmId if preferred) but ensure check() uses
the injected id parameter rather than re-reading from event.params.
In `@apps/server-core/src/adapters/http/middleware/built-in/assets.ts`:
- Line 17: Extract the VITE_SERVER_STORE_KEY symbol into a new tiny shared
module and have both the assets middleware and authorize/module.ts import it
from there instead of assets.ts; specifically, create a module that exports
VITE_SERVER_STORE_KEY (the same Symbol('ViteServer')), update the export in the
current assets middleware to import that constant rather than define it, and
update authorize/module.ts to import VITE_SERVER_STORE_KEY from the new shared
module so authorize no longer transitively pulls in the asset-wiring
dependencies.
In `@apps/server-core/src/adapters/http/middleware/built-in/swagger.ts`:
- Around line 11-13: Remove the dead documentPath option from the temporary stub
by deleting the SwaggerMiddlewareOptions type field and any parameter usage that
expects _input.documentPath; update the createSwaggerMiddleware (and any
factory/signature that references SwaggerMiddlewareOptions) to accept no options
or an empty options object so callers can call createSwaggerMiddleware()
directly, and remove/adjust any tests or call sites that pass a documentPath
argument.
In `@apps/server-core/src/adapters/http/request/helpers/param-id.ts`:
- Around line 56-68: The return type of getRequestStringParamOrFail is too wide
— it currently allows undefined even though the function throws when the value
is missing; update the function signature to return string (not string |
undefined) in the declaration of getRequestStringParamOrFail, leaving the
implementation (which throws a ValidupError when getRequestStringParam(event,
key) is undefined) intact, and ensure any callers of getRequestStringParamOrFail
handle the thrown error rather than expecting undefined; use the function name
getRequestStringParamOrFail and the call to getRequestStringParam(event, key) to
locate the code to change.
In `@apps/server-core/src/app/modules/http/module.ts`:
- Around line 72-78: In teardown of the module (method teardown), reverse the
unregister/close order: call await this.instance.close() first, then call
container.unregister(HTTPInjectionKey.Server), and finally set this.instance =
undefined; this ensures the server referred to by this.instance is closed before
removing the HTTPInjectionKey.Server from the DI container and avoids a window
where the container no longer resolves a still-running server.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: defaults
Review profile: CHILL
Plan: Pro
Run ID: bdb95a7d-35f6-47e7-8e96-f83a7a1272b7
⛔ Files ignored due to path filters (1)
package-lock.jsonis excluded by!**/package-lock.json
📒 Files selected for processing (73)
apps/server-core/package.jsonapps/server-core/src/adapters/http/adapters/oauth2/authorization/module.tsapps/server-core/src/adapters/http/adapters/oauth2/grant-types/authorize.tsapps/server-core/src/adapters/http/adapters/oauth2/grant-types/client-credentials.tsapps/server-core/src/adapters/http/adapters/oauth2/grant-types/identity.tsapps/server-core/src/adapters/http/adapters/oauth2/grant-types/password.tsapps/server-core/src/adapters/http/adapters/oauth2/grant-types/refresh_token.tsapps/server-core/src/adapters/http/adapters/oauth2/grant-types/robot-credentials.tsapps/server-core/src/adapters/http/adapters/oauth2/grant-types/types.tsapps/server-core/src/adapters/http/adapters/oauth2/grant-types/utils/credentials.tsapps/server-core/src/adapters/http/adapters/oauth2/grant-types/utils/guess.tsapps/server-core/src/adapters/http/controllers/entities/client-permission/module.tsapps/server-core/src/adapters/http/controllers/entities/client-role/module.tsapps/server-core/src/adapters/http/controllers/entities/client-scope/module.tsapps/server-core/src/adapters/http/controllers/entities/client/module.tsapps/server-core/src/adapters/http/controllers/entities/identity-provide-role/module.tsapps/server-core/src/adapters/http/controllers/entities/identity-provider/module.tsapps/server-core/src/adapters/http/controllers/entities/permission-policy/module.tsapps/server-core/src/adapters/http/controllers/entities/permission/module.tsapps/server-core/src/adapters/http/controllers/entities/policy/module.tsapps/server-core/src/adapters/http/controllers/entities/realm/module.tsapps/server-core/src/adapters/http/controllers/entities/robot-permission/module.tsapps/server-core/src/adapters/http/controllers/entities/robot-role/module.tsapps/server-core/src/adapters/http/controllers/entities/robot/module.tsapps/server-core/src/adapters/http/controllers/entities/role-attribute/module.tsapps/server-core/src/adapters/http/controllers/entities/role-permission/module.tsapps/server-core/src/adapters/http/controllers/entities/role/module.tsapps/server-core/src/adapters/http/controllers/entities/scope/module.tsapps/server-core/src/adapters/http/controllers/entities/user-attribute/module.tsapps/server-core/src/adapters/http/controllers/entities/user-permission/module.tsapps/server-core/src/adapters/http/controllers/entities/user-role/module.tsapps/server-core/src/adapters/http/controllers/entities/user/module.tsapps/server-core/src/adapters/http/controllers/workflows/activate/module.tsapps/server-core/src/adapters/http/controllers/workflows/authorize/module.tsapps/server-core/src/adapters/http/controllers/workflows/jwks/handlers/read.tsapps/server-core/src/adapters/http/controllers/workflows/jwks/module.tsapps/server-core/src/adapters/http/controllers/workflows/openid/module.tsapps/server-core/src/adapters/http/controllers/workflows/password-forgot/module.tsapps/server-core/src/adapters/http/controllers/workflows/password-reset/module.tsapps/server-core/src/adapters/http/controllers/workflows/register/module.tsapps/server-core/src/adapters/http/controllers/workflows/status/module.tsapps/server-core/src/adapters/http/controllers/workflows/token/module.tsapps/server-core/src/adapters/http/controllers/workflows/token/utils/extract.tsapps/server-core/src/adapters/http/index.tsapps/server-core/src/adapters/http/middleware/built-in/assets.tsapps/server-core/src/adapters/http/middleware/built-in/authorization/factory.tsapps/server-core/src/adapters/http/middleware/built-in/authorization/module.tsapps/server-core/src/adapters/http/middleware/built-in/cors.tsapps/server-core/src/adapters/http/middleware/built-in/error.tsapps/server-core/src/adapters/http/middleware/built-in/loggedin/module.tsapps/server-core/src/adapters/http/middleware/built-in/loggedin/user.tsapps/server-core/src/adapters/http/middleware/built-in/logger.tsapps/server-core/src/adapters/http/middleware/built-in/prometheus.tsapps/server-core/src/adapters/http/middleware/built-in/rate-limit.tsapps/server-core/src/adapters/http/middleware/built-in/swagger.tsapps/server-core/src/adapters/http/request/helpers/actor.tsapps/server-core/src/adapters/http/request/helpers/body-realm-id.tsapps/server-core/src/adapters/http/request/helpers/identity.tsapps/server-core/src/adapters/http/request/helpers/index.tsapps/server-core/src/adapters/http/request/helpers/locations.tsapps/server-core/src/adapters/http/request/helpers/param-id.tsapps/server-core/src/adapters/http/request/helpers/scopes.tsapps/server-core/src/adapters/http/request/helpers/token.tsapps/server-core/src/adapters/http/request/permission/helper.tsapps/server-core/src/adapters/http/request/permission/module.tsapps/server-core/src/adapters/http/server/index.tsapps/server-core/src/adapters/http/server/module.tsapps/server-core/src/adapters/http/server/type.tsapps/server-core/src/app/modules/http/constants.tsapps/server-core/src/app/modules/http/module.tsapps/server-core/src/app/modules/http/modules/controller.tsapps/server-core/src/app/modules/http/modules/middleware.tsapps/server-core/test/app/http.ts
💤 Files with no reviewable changes (5)
- apps/server-core/src/adapters/http/server/index.ts
- apps/server-core/src/adapters/http/server/module.ts
- apps/server-core/src/adapters/http/index.ts
- apps/server-core/src/adapters/http/server/type.ts
- apps/server-core/src/app/modules/http/modules/controller.ts
✅ Files skipped from review due to trivial changes (2)
- apps/server-core/src/adapters/http/controllers/workflows/status/module.ts
- apps/server-core/src/adapters/http/controllers/workflows/openid/module.ts
| private async write(event: IRoutupEvent, options: { | ||
| updateOnly?: boolean | ||
| } = {}): Promise<any> { | ||
| let group: string; | ||
| const id = getRequestParamID(req, { isUUID: false }); | ||
| const realmId = getRequestBodyRealmID(req); | ||
| const id = getRequestParamID(event, { isUUID: false }); | ||
| const body = await readRequestBody(event); | ||
| const realmId = getBodyRealmID(body); |
There was a problem hiding this comment.
Keep the route realm authoritative in write().
Line 357 now scopes writes only from the request body, and Lines 410-413 fall back to the caller's identity realm. On nested routes like /realms/:realmId/identity-providers/:id, that means update-by-name can resolve the wrong provider, and create can land in a different realm than the route targeted.
Suggested fix
private async write(event: IRoutupEvent, options: {
updateOnly?: boolean
} = {}): Promise<any> {
let group: string;
const id = getRequestParamID(event, { isUUID: false });
const body = await readRequestBody(event);
- const realmId = getBodyRealmID(body);
+ const routeRealmId = event.params.realmId;
+ const bodyRealmId = getBodyRealmID(body);
+
+ if (routeRealmId && bodyRealmId && routeRealmId !== bodyRealmId) {
+ throw new BadRequestError('The body realm_id must match the route realm.');
+ }
+
+ const realmId = routeRealmId ?? bodyRealmId;
@@
} else {
if (!data.realm_id) {
- const identity = useRequestIdentityOrFail(event);
- data.realm_id = identity.realmId;
+ if (realmId) {
+ data.realm_id = realmId;
+ } else {
+ const identity = useRequestIdentityOrFail(event);
+ data.realm_id = identity.realmId;
+ }
}
await permissionEvaluator.evaluate({
name: PermissionName.IDENTITY_PROVIDER_CREATE,
input: new PolicyData({ [BuiltInPolicyType.ATTRIBUTES]: data }),Also applies to: 410-413
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In
`@apps/server-core/src/adapters/http/controllers/entities/identity-provider/module.ts`
around lines 351 - 357, The write() method currently uses getBodyRealmID(body)
and later falls back to the caller's identity realm, which allows nested routes
to write to the wrong realm; change the realm resolution so the route param
realm takes precedence: first try to read the realm from the request route
params (the same place you get the id via getRequestParamID(event,...)), then
fall back to the request body (getBodyRealmID(body)), and only lastly use the
caller identity realm. Update both the initial realm assignment in write() and
the later fallback logic that currently uses the caller realm so all
create/update flows consistently use the route param realm when present.
…tore error data field routup v5.0.0's fromNodeMiddleware bridge returns undefined when the wrapped node middleware calls next() without ending the response, but never invokes event.next() on the routup event. The handler contract treats that as "wait for next() or signal abort", so every request through cors/morgan/vite-dev hangs until the test fetch aborts. Replaced the three fromNodeMiddleware call sites (cors, logger, vite assets) with manual defineCoreHandler bridges that explicitly call event.next() on the pass-through path and return null when the wrapped middleware ended the response itself. Restored data extraction in AuthupError and reworked OAuth2Error, JWTError, JWKError to merge defaults with input options inside the constructor instead of relying on the dropped variadic super(...input) behavior. Added toJSON() override on OAuth2Error/JWTError so the data fields surface on the response payload, and reshaped the error middleware to consume that.
There was a problem hiding this comment.
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 (1)
apps/server-core/src/adapters/http/middleware/built-in/error.ts (1)
23-39:⚠️ Potential issue | 🟠 Major | ⚡ Quick winMask the full 5xx payload, not just the message.
Because
next.toJSON()now carries extra error data, spreading it before the 5xx check means masked server errors can still expose internaldataorissues. For 5xx responses, this should return a minimal whitelist only.Suggested fix
- const payload : Record<string, any> = { - ...next.toJSON(), - statusCode: next.statusCode, - code: `${next.code}`, - message: next.message, - issues: next.issues, - }; - const isServerError = next.statusCode >= 500 && next.statusCode < 600; + const payload : Record<string, any> = isServerError ? { + statusCode: next.statusCode, + code: `${next.code}`, + message: 'An internal server error occurred.', + } : { + ...next.toJSON(), + statusCode: next.statusCode, + code: `${next.code}`, + message: next.message, + issues: next.issues, + }; + if (isServerError) { useLogger().error(next); - - payload.message = 'An internal server error occurred.'; }🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@apps/server-core/src/adapters/http/middleware/built-in/error.ts` around lines 23 - 39, The current handler spreads next.toJSON() into payload before checking isServerError, which can leak internal fields for 5xx errors; change logic in this middleware so that when isServerError (computed from next.statusCode) you do NOT spread next.toJSON() but instead build a minimal whitelist payload (e.g., only statusCode, code as `${next.code}`, and a generic message) and still call useLogger().error(next) to record the full error; for non-5xx keep the existing behavior (include next.toJSON(), statusCode, code, message, issues) and continue to set event.response.status = payload.statusCode.
♻️ Duplicate comments (1)
apps/server-core/src/adapters/http/middleware/built-in/logger.ts (1)
19-21:⚠️ Potential issue | 🟡 Minor | ⚡ Quick winNull guard on
req.socketstill missing.The custom Morgan formatter dereferences
req.socket.remoteAddressdirectly.IncomingMessage.socketcan benull(e.g., if the underlying socket was destroyed before the formatter runs), which would throw aTypeErrorand bypass the|| '-'fallback.🛡️ Proposed fix
- req.socket.remoteAddress || '-', + req.socket?.remoteAddress || '-',🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@apps/server-core/src/adapters/http/middleware/built-in/logger.ts` around lines 19 - 21, The custom Morgan formatter (formatter variable using morgan with (tokens, req, res) => ...) dereferences req.socket.remoteAddress directly; change the expression to guard against a null socket (e.g., use optional chaining or explicit check) so that you read req.socket?.remoteAddress (or req.socket && req.socket.remoteAddress) and still fall back to '-' when that value is undefined/null, ensuring the formatter cannot throw a TypeError.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@apps/server-core/src/adapters/http/middleware/built-in/cors.ts`:
- Around line 30-41: The Promise around calling handler(node.req, node.res, ...)
must also resolve when the CORS middleware ends the response without calling the
callback (preflight OPTIONS). Update the handler invocation in the wrapper (the
Promise created where handler(node.req as any, node.res as any, (err) => { ...
})) to: 1) use a guarded resolve/reject flag to avoid double-settling; 2)
immediately check node.res.writableEnded after invoking handler and resolve if
true; and 3) keep the existing callback logic to resolve/reject if the
middleware calls it. Finally, preserve the existing branch that returns null
instead of calling event.next() when node.res.writableEnded is true.
In `@apps/server-core/src/adapters/http/middleware/built-in/error.ts`:
- Around line 15-20: Guard against non-object thrown values before accessing
cause: in the defineErrorHandler callback (the block that sets next :
AuthupError), check whether error is non-nullish and an object before reading
its cause (e.g. use optional chaining error?.cause or a type guard like error &&
typeof error === 'object' && 'cause' in error), then pass either the cause or
the original error into sanitizeError accordingly; update the branch that
currently does if (error.cause) { next = sanitizeError(error.cause) } else {
next = sanitizeError(error) } to the safe-guarded version using error?.cause or
an explicit object check to avoid re-throwing on null/primitive throws.
In `@packages/errors/src/types.ts`:
- Around line 8-12: The project still uses the legacy statusCode key while the
exported AuthupErrorOptions type (and underlying HTTPErrorOptions v4) expects
status; update all error constructors, default option objects, and test fixtures
to replace statusCode → status so the public API matches AuthupErrorOptions, and
ensure any places that build HTTP errors (error constructors/defaults and tests)
use the numeric status field and pass it through unchanged.
In `@packages/specs/src/oauth2/error.ts`:
- Line 25: The constructor for OAuth2Error currently replaces the default
payload with options.data, dropping the required OAuth2 "error" field; update
the assignment in the OAuth2Error constructor so it merges defaults with
provided data instead of replacing them (e.g., produce a merged object where the
default error: OAuth2ErrorCode.INVALID_REQUEST is used only when
options.data.error is missing). Target the OAuth2Error constructor and the
this.data assignment (currently using options.data ?? ...) and change it to
merge the default error field with options.data so custom hint/fields are
preserved while still guaranteeing the OAuth2 "error" code.
---
Outside diff comments:
In `@apps/server-core/src/adapters/http/middleware/built-in/error.ts`:
- Around line 23-39: The current handler spreads next.toJSON() into payload
before checking isServerError, which can leak internal fields for 5xx errors;
change logic in this middleware so that when isServerError (computed from
next.statusCode) you do NOT spread next.toJSON() but instead build a minimal
whitelist payload (e.g., only statusCode, code as `${next.code}`, and a generic
message) and still call useLogger().error(next) to record the full error; for
non-5xx keep the existing behavior (include next.toJSON(), statusCode, code,
message, issues) and continue to set event.response.status = payload.statusCode.
---
Duplicate comments:
In `@apps/server-core/src/adapters/http/middleware/built-in/logger.ts`:
- Around line 19-21: The custom Morgan formatter (formatter variable using
morgan with (tokens, req, res) => ...) dereferences req.socket.remoteAddress
directly; change the expression to guard against a null socket (e.g., use
optional chaining or explicit check) so that you read req.socket?.remoteAddress
(or req.socket && req.socket.remoteAddress) and still fall back to '-' when that
value is undefined/null, ensuring the formatter cannot throw a TypeError.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: defaults
Review profile: CHILL
Plan: Pro
Run ID: d6c519eb-51c5-4bdc-9fd4-c8802c10241b
📒 Files selected for processing (10)
apps/server-core/src/adapters/http/middleware/built-in/assets.tsapps/server-core/src/adapters/http/middleware/built-in/cors.tsapps/server-core/src/adapters/http/middleware/built-in/error.tsapps/server-core/src/adapters/http/middleware/built-in/logger.tsapps/server-core/src/app/modules/http/modules/middleware.tspackages/errors/src/module.tspackages/errors/src/types.tspackages/specs/src/json-web-key/error.tspackages/specs/src/json-web-token/error.tspackages/specs/src/oauth2/error.ts
🚧 Files skipped from review as they are similar to previous changes (1)
- apps/server-core/src/app/modules/http/modules/middleware.ts
Phase 5 of the routup v5 migration: - Drop @routup/swagger@^2.4.3. - Add @routup/swagger-ui@^3.0.0 for UI mounting and @trapi/swagger@^2.0.0-beta.3 + @trapi/metadata@^2.0.0-beta.3 for spec generation. - Rewrite Swagger.generate() to use @trapi/metadata + @trapi/swagger with Version.V3_2 and the @routup/decorators/preset. Pass the workspace tsconfig so transitive type resolution works. - Rewire createSwaggerMiddleware to call swaggerUI() from @routup/swagger-ui (drop the 501 stub from phase 1). - Restore npm run build:swagger to the build chain. Generated spec is OpenAPI 3.2 with 62 paths and components.securitySchemes mapped from the legacy securityDefinitions. Bumped routup pin to ^5.0.1 — upstream fixed fromNodeMiddleware / fromNodeHandler hangs (routup/routup#881). Reverted the manual defineCoreHandler bridges in cors, morgan and vite assets back to fromNodeMiddleware now that the bridge calls event.next() correctly.
- OAuth2Error.data now merges the default { error: INVALID_REQUEST } with
caller-provided fields instead of replacing it, so OAuth2Error helpers
that pass extra data (e.g. hint) still surface the required error code.
- logger middleware: guard req.socket?.remoteAddress against null sockets
destroyed before morgan runs.
- token extract: only fall back to header lookup on ValidupError (via
isValidupError duck-type check); rethrow other failures so request
parsing bugs surface instead of being swallowed.
- workflow controllers (register, password-forgot, password-reset): drop
the // @ts-expect-error workaround by replacing sendAccepted(event,
result) with the v5 idiom event.response.status = 202; return result;
This also gives @trapi/swagger the correct return type at the method
signature for richer generated documentation.
- core-http-kit RegisterResponse: widen active to boolean — service can
return active: false when emailVerificationEnabled is on.
- statusCode → status migration in the spec error files we already
touched (oauth2, json-web-token, json-web-key) and the error handler's
AuthupError reads, since @ebec/http v4 deprecated statusCode in favor
of status. The error response payload key stays statusCode for
backward compatibility with API consumers; remaining call sites in
packages/access, server-adapter-kit, and test fixtures tracked in
#3032.
Pre-existing identity-provider write() realm-scoping issue surfaced by
review tracked in #3031.
There was a problem hiding this comment.
Actionable comments posted: 3
♻️ Duplicate comments (1)
apps/server-core/src/adapters/http/middleware/built-in/error.ts (1)
15-16:⚠️ Potential issue | 🟠 Major | ⚡ Quick winGuard
errorbefore readingcause.Line 16 still assumes the thrown value is object-like. If anything throws
nullorundefined, this handler will throw again beforesanitizeError()can normalize it.Suggested fix
router.use(defineErrorHandler((error, event) => { - const next : AuthupError = sanitizeError(error.cause ?? error); + const cause = typeof error === 'object' && error !== null && 'cause' in error ? + (error as { cause?: unknown }).cause : + undefined; + const next : AuthupError = sanitizeError(cause ?? error);🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@apps/server-core/src/adapters/http/middleware/built-in/error.ts` around lines 15 - 16, The error handler assumes the thrown value is object-like by reading error.cause; guard against non-objects before accessing cause in the router.use(defineErrorHandler(...)) callback: check that error is an object (and not null) and only then read error.cause, otherwise pass error directly into sanitizeError (or wrap primitive/undefined into a normalized Error-like structure) so sanitizeError(AuthupError) never receives undefined/null; update the callback around the use of error, error.cause, sanitizeError, and AuthupError accordingly.
🧹 Nitpick comments (2)
packages/specs/src/json-web-token/error.ts (1)
10-26: 💤 Low valueRedundant
dataplumbing — parent class already handles both the type and the assignment.
AuthupErrorOptions(perpackages/errors/src/types.ts) already includesdata?: Record<string, any>, so the localJWTErrorOptionsintersection is a no-op alias.AuthupError's constructor (perpackages/errors/src/module.ts) already extractsdatafrom the options object and assignsthis.data, so the explicitif (options.data) { this.data = options.data; }block at lines 23-25 is redundant.Behavior is correct as-is; this is purely a simplification.
♻️ Proposed simplification
-import { AuthupError, type AuthupErrorOptions, ErrorCode } from '@authup/errors'; - -type JWTErrorOptions = AuthupErrorOptions & { - data?: Record<string, any> -}; +import { AuthupError, type AuthupErrorOptions, ErrorCode } from '@authup/errors'; export class JWTError extends AuthupError { - constructor(input?: JWTErrorOptions | string) { - const options : JWTErrorOptions = typeof input === 'string' ? { message: input } : (input ?? {}); + constructor(input?: AuthupErrorOptions | string) { + const options : AuthupErrorOptions = typeof input === 'string' ? { message: input } : (input ?? {}); super({ code: ErrorCode.JWT_INVALID, message: 'The JWT is invalid.', status: 400, ...options, }); - if (options.data) { - this.data = options.data; - } }🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@packages/specs/src/json-web-token/error.ts` around lines 10 - 26, The JWTError class currently defines a redundant JWTErrorOptions type and manually reassigns data that AuthupError already handles; simplify by removing the JWTErrorOptions type alias (use AuthupErrorOptions directly in the JWTError constructor signature) and delete the conditional block that sets this.data inside the JWTError constructor so construction delegates data typing and assignment to AuthupError (refer to the JWTError class and its constructor and to AuthupError/AuthupErrorOptions for locating the logic).packages/specs/src/json-web-key/error.ts (1)
11-20: ⚡ Quick winInconsistent
dataserialization vs. sibling error classes.
JWKErroracceptsAuthupErrorOptions(which carriesdata?: Record<string, any>) andAuthupError's constructor will assignthis.dataif provided, butJWKErrordoes not overridetoJSON()to surfacethis.data— unlike the sibling classes:
packages/specs/src/json-web-token/error.tslines 28-33packages/specs/src/oauth2/error.tslines 31-36Today the static factories don't pass
data, so the gap isn't observable. But any future caller (or external user) who constructsnew JWKError({ data: {...} })will silently lose those payload keys when the error middleware serializes the response. Consider either adding a paralleltoJSONoverride or removingdatasupport here for symmetry.♻️ Proposed override for consistency
export class JWKError extends AuthupError { constructor(input?: AuthupErrorOptions | string) { const options : AuthupErrorOptions = typeof input === 'string' ? { message: input } : (input ?? {}); super({ code: ErrorCode.JWK_INVALID, message: 'The JWK is invalid.', status: 400, ...options, }); } + override toJSON() { + return { + ...super.toJSON(), + ...(this.data ?? {}), + }; + } + static notFound(id?: string) {🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@packages/specs/src/json-web-key/error.ts` around lines 11 - 20, JWKError currently accepts AuthupErrorOptions including data but doesn't override toJSON so this.data won't be serialized like sibling errors; update the JWKError class to implement a toJSON() override (mirroring the pattern in json-web-token/error.ts and oauth2/error.ts) that calls the base serialization and spreads in this.data (or otherwise includes data fields) so new JWKError({ data: ... }) preserves payload when error middleware serializes responses; ensure you reference JWKError, AuthupErrorOptions, AuthupError and this.data when implementing the change.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@apps/server-core/src/adapters/http/middleware/built-in/logger.ts`:
- Around line 20-28: The Morgan token calls in the logger middleware can return
undefined and will be logged as the literal "undefined"; update the anonymous
formatter in logger.ts so each token call is normalized (e.g., const method =
tokens.method(req,res) ?? '-' etc.), substitute '-' for method/url/status when
undefined, and for tokens['response-time'] call use a variable like rt =
tokens['response-time'](req,res) and render rt === undefined ? '-' : `${rt}ms`
before joining the array; keep the same order and join logic but use these
normalized variables to avoid "undefined" in logs.
In `@apps/server-core/src/adapters/http/middleware/built-in/swagger.ts`:
- Around line 12-19: Change the function signature so documentPath is a
compile-time required option instead of relying on a runtime check: update
createSwaggerMiddleware's parameter type from Partial<SwaggerMiddlewareOptions>
to a type that requires documentPath (e.g., SwaggerMiddlewareOptions or
Partial<SwaggerMiddlewareOptions> & { documentPath: string }), remove the
runtime throw that checks for documentPath, and ensure callers (e.g., the caller
in modules/middleware.ts) continue to pass documentPath so the compiler enforces
the requirement; keep the destructuring const { documentPath, ...options } =
input and other logic unchanged.
In `@apps/server-core/src/adapters/http/swagger/module.ts`:
- Around line 88-90: The OAuth/OIDC endpoint URL construction uses new
URL('token', this.options.baseURL) which drops the base path when baseURL lacks
a trailing slash; update the construction to ensure the base URL always has a
trailing slash before calling new URL (e.g., normalize this.options.baseURL by
appending '/' when it does not end with one) wherever endpoints are built
(specifically in the swagger module that sets password.tokenUrl, and likewise in
the workflows openid module and the realm and identity-provider modules that
build authorization_endpoint, token_endpoint, jwks_uri, etc.); locate usages
around password.tokenUrl in apps/server-core/src/adapters/http/swagger/module.ts
and the OpenID endpoint builders (functions/methods that call new URL(...,
this.options.baseURL) in the controllers) and replace them with a normalized
base URL variable or helper (e.g., ensureTrailingSlash(base)) before passing to
new URL so path prefixes are preserved.
---
Duplicate comments:
In `@apps/server-core/src/adapters/http/middleware/built-in/error.ts`:
- Around line 15-16: The error handler assumes the thrown value is object-like
by reading error.cause; guard against non-objects before accessing cause in the
router.use(defineErrorHandler(...)) callback: check that error is an object (and
not null) and only then read error.cause, otherwise pass error directly into
sanitizeError (or wrap primitive/undefined into a normalized Error-like
structure) so sanitizeError(AuthupError) never receives undefined/null; update
the callback around the use of error, error.cause, sanitizeError, and
AuthupError accordingly.
---
Nitpick comments:
In `@packages/specs/src/json-web-key/error.ts`:
- Around line 11-20: JWKError currently accepts AuthupErrorOptions including
data but doesn't override toJSON so this.data won't be serialized like sibling
errors; update the JWKError class to implement a toJSON() override (mirroring
the pattern in json-web-token/error.ts and oauth2/error.ts) that calls the base
serialization and spreads in this.data (or otherwise includes data fields) so
new JWKError({ data: ... }) preserves payload when error middleware serializes
responses; ensure you reference JWKError, AuthupErrorOptions, AuthupError and
this.data when implementing the change.
In `@packages/specs/src/json-web-token/error.ts`:
- Around line 10-26: The JWTError class currently defines a redundant
JWTErrorOptions type and manually reassigns data that AuthupError already
handles; simplify by removing the JWTErrorOptions type alias (use
AuthupErrorOptions directly in the JWTError constructor signature) and delete
the conditional block that sets this.data inside the JWTError constructor so
construction delegates data typing and assignment to AuthupError (refer to the
JWTError class and its constructor and to AuthupError/AuthupErrorOptions for
locating the logic).
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: defaults
Review profile: CHILL
Plan: Pro
Run ID: b7983842-0f0d-475a-9d43-ad492bd4f357
⛔ Files ignored due to path filters (1)
package-lock.jsonis excluded by!**/package-lock.json
📒 Files selected for processing (16)
apps/server-core/package.jsonapps/server-core/src/adapters/http/controllers/workflows/password-forgot/module.tsapps/server-core/src/adapters/http/controllers/workflows/password-reset/module.tsapps/server-core/src/adapters/http/controllers/workflows/register/module.tsapps/server-core/src/adapters/http/controllers/workflows/token/utils/extract.tsapps/server-core/src/adapters/http/middleware/built-in/assets.tsapps/server-core/src/adapters/http/middleware/built-in/cors.tsapps/server-core/src/adapters/http/middleware/built-in/error.tsapps/server-core/src/adapters/http/middleware/built-in/logger.tsapps/server-core/src/adapters/http/middleware/built-in/swagger.tsapps/server-core/src/adapters/http/swagger/module.tsapps/server-core/src/app/modules/config/types.tspackages/core-http-kit/src/domains/entities/user/module.tspackages/specs/src/json-web-key/error.tspackages/specs/src/json-web-token/error.tspackages/specs/src/oauth2/error.ts
@ebec/core v1 dropped logMessage/logLevel/expose from ErrorOptions and narrowed code to string (no null), which broke the global build chain in two places: - packages/server-kit/src/crypto/json-web-token/utils.ts: drop the logMessage: true field on the fallback JWTError; the option no longer exists in v4 and behaves as a no-op anyway. - packages/access/src/policy/error/module.ts: coalesce the optional code: string | null parameter to undefined before passing to super. scripts/patch-trapi-metadata.mjs: workaround for tada5hi/trapi#821. @trapi/metadata's getInitializerValue dereferences symbol.valueDeclaration without guarding against getSymbolAtLocation returning undefined, which crashes when scanning TypeORM entity decorators with arrow-function callbacks (e.g. @Tree('closure-table', { ancestorColumnName: () => 'ancestor_id' }) on PolicyEntity). Wired in via root package.json postinstall; idempotent, removes a single line. Drop once trapi ships a fix. All 17 nx build targets and 9 nx test targets green.
…+ entity error tests Lever #1 of the phase 6 HTTP test simplification: introduce expectClientError(fn, { status?, code?, data? }) in test/utils/assertions.ts and migrate the 17 try/catch + isClientError + expect.assertions patterns scattered across: - workflows/token/grant-{client-credentials,robot-credentials,password,refresh-token,authorize}.spec.ts - entities/{role,scope,permission/checker}.spec.ts The helper: - fail-fasts when the call resolves (vs the silent-pass behaviour of the old `if (isClientError(e))` narrowing). - accepts `code` as a shorthand for `data.code` and `data` for arbitrary response.data assertions, so OAuth2 errors that carry both `code` and `error` round-trip cleanly. - consolidates ~40 LOC of boilerplate per spec into one call. All 783 tests still pass.
Lever #5 of phase 6: introduce httpRequest(suite, method, path, options) in test/utils/http.ts. Returns the native Response so callers stay explicit about status / body parsing — useful for asserting raw HTML bodies (SSR), OAuth2 redirect payloads, and RFC 6749 edge cases hapic's typed Client deletes (Basic + body credentials, missing form fields). Migrated the three raw fetch sites in grant-authorize.spec.ts as the proof. The helper accepts `form: Record<string, string>` for the common urlencoded case and auto-sets Content-Type; falls back to `body: BodyInit` for everything else.
…pectClientError Lever #3 of phase 6 (HTTP test simplification): the only remaining isClientError + try/catch + expect.assertions block was in permission/module.spec.ts; collapsed into expectClientError. The broader extraction the plan described — moving permission/policy checker tests from HTTP integration to core/ service tests — would require introducing a new PermissionCheckerService that wraps PermissionDatabaseProvider + PermissionEvaluator, since the existing HTTP tests cover the DB-backed binding/closure-tree path that the package-level evaluator tests in @authup/access don't reach. That's a distinct refactor outside this PR's scope; tracked in #3033.
There was a problem hiding this comment.
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
package.json (1)
1-76: 🛠️ Refactor suggestion | 🟠 Major | ⚡ Quick winAdd an explicit npm package manager pin for corepack.
Please add a root-level
packageManagerfield (e.g.npm@<pinned-version>) so installs are consistently driven via corepack-managed npm. This is currently missing in Line 1-76.As per coding guidelines,
package.json: Use npm with corepack as the package manager.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@package.json` around lines 1 - 76, The root package.json is missing a packageManager field required to pin corepack-managed npm; add a top-level "packageManager" key in package.json (e.g. "packageManager": "[email protected]") so installs are consistently driven via corepack-managed npm, placing it alongside "name", "version", etc.; pick and pin the npm version your CI/devs use and commit the change.
🧹 Nitpick comments (1)
apps/server-core/test/unit/http/controllers/workflows/token/grant-authorize.spec.ts (1)
280-289: ⚡ Quick winTighten this error assertion to reduce false positives.
This case currently validates only
data.error. Addingstatus(and optionally internalcode) would better lock expected behavior for the public-client PKCE validation path.Proposed assertion tightening
await expectClientError( () => suite.client.authorize.confirm({ response_type: OAuth2AuthorizationResponseType.CODE, client_id: publicClient.id, redirect_uri: 'https://example.com/redirect', scope: `${ScopeName.GLOBAL}`, state, }), - { data: { error: OAuth2ErrorCode.INVALID_REQUEST } }, + { + status: 400, + data: { error: OAuth2ErrorCode.INVALID_REQUEST }, + }, );🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@apps/server-core/test/unit/http/controllers/workflows/token/grant-authorize.spec.ts` around lines 280 - 289, Tighten the assertion in the expectClientError call around suite.client.authorize.confirm(...) by asserting the HTTP status and the internal error code in addition to data.error; specifically change the expected object to include status: 400 and data: { error: OAuth2ErrorCode.INVALID_REQUEST, code: <internal PKCE error code if present> } so the public-client PKCE validation path is fully validated (update the expectClientError call and the assertion payload used for OAuth2AuthorizationResponseType.CODE, publicClient.id, ScopeName.GLOBAL, state).
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Outside diff comments:
In `@package.json`:
- Around line 1-76: The root package.json is missing a packageManager field
required to pin corepack-managed npm; add a top-level "packageManager" key in
package.json (e.g. "packageManager": "[email protected]") so installs are consistently
driven via corepack-managed npm, placing it alongside "name", "version", etc.;
pick and pin the npm version your CI/devs use and commit the change.
---
Nitpick comments:
In
`@apps/server-core/test/unit/http/controllers/workflows/token/grant-authorize.spec.ts`:
- Around line 280-289: Tighten the assertion in the expectClientError call
around suite.client.authorize.confirm(...) by asserting the HTTP status and the
internal error code in addition to data.error; specifically change the expected
object to include status: 400 and data: { error:
OAuth2ErrorCode.INVALID_REQUEST, code: <internal PKCE error code if present> }
so the public-client PKCE validation path is fully validated (update the
expectClientError call and the assertion payload used for
OAuth2AuthorizationResponseType.CODE, publicClient.id, ScopeName.GLOBAL, state).
ℹ️ Review info
⚙️ Run configuration
Configuration used: defaults
Review profile: CHILL
Plan: Pro
Run ID: ac789086-a5d4-4abd-b66b-127c74e89d77
⛔ Files ignored due to path filters (1)
package-lock.jsonis excluded by!**/package-lock.json
📒 Files selected for processing (16)
apps/server-core/test/unit/http/controllers/entities/permission/checker.spec.tsapps/server-core/test/unit/http/controllers/entities/permission/module.spec.tsapps/server-core/test/unit/http/controllers/entities/role.spec.tsapps/server-core/test/unit/http/controllers/entities/scope.spec.tsapps/server-core/test/unit/http/controllers/workflows/token/grant-authorize.spec.tsapps/server-core/test/unit/http/controllers/workflows/token/grant-client-credentials.spec.tsapps/server-core/test/unit/http/controllers/workflows/token/grant-password.spec.tsapps/server-core/test/unit/http/controllers/workflows/token/grant-refresh-token.spec.tsapps/server-core/test/unit/http/controllers/workflows/token/grant-robot-credentials.spec.tsapps/server-core/test/utils/assertions.tsapps/server-core/test/utils/http.tsapps/server-core/test/utils/index.tspackage.jsonpackages/access/src/policy/error/module.tspackages/server-kit/src/crypto/json-web-token/utils.tsscripts/patch-trapi-metadata.mjs
💤 Files with no reviewable changes (1)
- packages/server-kit/src/crypto/json-web-token/utils.ts
- authorize controller: replace the `event.store[VITE_SERVER_STORE_KEY]
as any` cast with an `import type { ViteDevServer } from 'vite'` +
typed cast. No runtime change; restores the type-system narrowing
that the v4 → v5 controller rewrite had to bypass.
- .agents/architecture.md: rewrite the thin-controller code sample to
match v5 (`@DContext() event: IRoutupEvent`, `useRequestQuery(event)`,
`sendCreated(event, entity)`). Add a note on the `event.response.status
= 202; return entity;` idiom for typed-return ergonomics with
@trapi/swagger metadata extraction.
- .agents/testing.md: document the two new HTTP test helpers added in
phase 6 — expectClientError(fn, { status?, code?, data? }) and
httpRequest(suite, method, path, options) — with usage examples.
Lint clean (`npm run lint`), 17 nx build targets green, 9 nx test
targets green (783 server-core tests + all other workspaces). No
leftover coreHandler/errorHandler aliases, no commented-out v4
patterns in PR-touched files, no isClientError + try/catch boilerplate
in HTTP tests.
…ilerplate Address the second round of CodeRabbit feedback on PR #3030: - adapters/http/middleware/built-in/logger.ts: morgan tokens method/url/ status/response-time can return undefined (e.g. response-time on the pre-finish path or status on aborted requests). Coalesce each token to '-' before joining so the log line never contains the literal string "undefined" / "undefinedms". - adapters/http/middleware/built-in/swagger.ts: drop the runtime documentPath check by tightening the parameter type from Partial<SwaggerMiddlewareOptions> to SwaggerMiddlewareOptions itself. Caller already supplies it; the compiler now enforces it. - adapters/http/swagger/module.ts and the openid / realm / identity-provider controllers: replace `new URL(relative, this.options.baseURL).href` with a new `resolveURL(base, relative)` helper (apps/server-core/src/utils/url.ts). The native `new URL()` drops the base path component when the base lacks a trailing slash — so `new URL('token', 'https://example.com/api')` resolves to `https://example.com/token`, not `https://example.com/api/token`. Affected the swagger spec's OAuth2 tokenUrl, the well-known OpenID configuration's authorization/token/jwks/introspection/revocation/ userinfo endpoints, the per-realm OpenID configuration, and the identity-provider redirect URL. Also normalized the Docs-URL log line in app/modules/runtime/module.ts. Pre-existing on most call sites; only the swagger one was newly introduced by this PR's swagger split. Fixed inline rather than as a separate issue because the helper is a small, surgical change to files already touched by this PR. All 783 server-core tests still pass; lint clean.
|
@coderabbitai resume |
|
@coderabbitai review |
✅ Actions performedReviews resumed. |
✅ Actions performedReview triggered.
|
… at runtime Replace the custom server-core swagger plumbing with @trapi/cli's generate command. Concretely: - Drop apps/server-core/src/adapters/http/swagger/ (the Swagger class wrapper that called generateMetadata / generateSwagger / saveSwagger). - Drop apps/server-core/src/cli/commands/swagger.ts and the SwaggerModule app-bootstrap module (no more runtime spec generation; the spec is expected at dist/swagger.json by build time). - Bump @trapi/metadata + @trapi/swagger to ^2.0.0-beta.4 and add @trapi/cli@^0.1.2-beta.2 as a devDep. - Replace the build:swagger npm script with a direct trapi CLI call: trapi generate --entry-point ... --preset @routup/decorators/preset --tsconfig tsconfig.json --output dist/swagger.json --version v3.2. - createSwaggerMiddleware now also takes baseURL and forwards it to swaggerUI() so the UI's <base href> tracks the runtime publicUrl rather than being baked into the generated spec. Trade-off the migration accepts (per discussion on PR #3030): the trapi CLI doesn't currently expose flags for SwaggerGenerateData .servers / .securityDefinitions or the metadata generator's ignore / allow filters, so the produced spec ships with empty servers and empty components.securitySchemes. The auth schemes (bearer, basicAuth, oauth2 password flow) we previously baked are missing. Filed upstream at tada5hi/trapi#824 — to be recovered once the CLI grows a config-file flag or equivalent.
|
@coderabbitai review |
✅ Actions performedReview triggered.
|
There was a problem hiding this comment.
Actionable comments posted: 3
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
.agents/architecture.md (1)
298-345:⚠️ Potential issue | 🟡 Minor | ⚡ Quick winFinish the controller docs migration.
This section now describes
buildActorContext(event)and the Routup v5 handler pattern, but the earlier helper example in the same doc still showsbuildActorContext(req: Request), and the sample here still usessendCreated()/sendAccepted()right before saying typed-return style is preferred. Please make this section internally consistent so contributors only see one canonical controller pattern.As per coding guidelines, ".agents/**/*.md": "Keep the .agents directory and all corresponding files updated as the project evolves, including when making architectural changes, adding new patterns, or discovering important conventions".
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In @.agents/architecture.md around lines 298 - 345, The doc is inconsistent: replace the old helper signature buildActorContext(req: Request) with buildActorContext(event: IRoutupEvent) everywhere, and standardize the controller example to the preferred typed-return pattern by removing sendCreated/sendAccepted usages and instead setting event.response.status = 201/202 and returning the entity; update any references/examples (e.g. the earlier helper example and the sample that mentions sendCreated/sendAccepted) to reference buildActorContext, IRoutupEvent, and the register/password-forgot/password-reset controllers as canonical examples so contributors see one consistent Routup v5 controller pattern.
🧹 Nitpick comments (2)
apps/server-core/src/adapters/http/controllers/workflows/authorize/module.ts (1)
66-66: 💤 Low valueTighten
Promise<any>return types.Both handlers can be typed precisely now that they return concrete payloads —
confirmreturns{ url: string }andservereturns the rendered HTML string. This improves call-site safety and documents the new contracts introduced by the routup v5 migration.♻️ Proposed typing
- async confirm(`@DContext`() event: IRoutupEvent): Promise<any> { + async confirm(`@DContext`() event: IRoutupEvent): Promise<{ url: string }> { @@ - async serve(`@DContext`() event: IRoutupEvent): Promise<any> { + async serve(`@DContext`() event: IRoutupEvent): Promise<string> {Also applies to: 90-90
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@apps/server-core/src/adapters/http/controllers/workflows/authorize/module.ts` at line 66, The handlers use broad Promise<any> return types; tighten them by updating confirm's signature to return Promise<{ url: string }> (since it returns an object with a url) and update serve's signature to return Promise<string> (since it returns rendered HTML), i.e., replace Promise<any> on the methods confirm and serve in the authorize module with these precise return types and adjust any local typings/returns to match those shapes (functions: confirm, serve).scripts/patch-trapi-metadata.mjs (1)
54-59: ⚡ Quick winAdd a warning for the silent no-target case.
When both candidate paths are absent (e.g.,
@trapi/metadatais hoisted to a different location), the script exits silently (patched === 0,skipped === 0). The missing patch won't surface until the swagger-generation step fails with a cryptic crash, making it hard to trace back to the unpatched file.🛡️ Proposed fix
if (patched > 0) { console.log(`[patch-trapi-metadata] patched ${patched} file${patched === 1 ? '' : 's'}.`); } if (skipped > 0 && patched === 0) { console.log('[patch-trapi-metadata] already patched.'); } +if (patched === 0 && skipped === 0) { + console.warn('[patch-trapi-metadata] `@trapi/metadata` not found at expected paths — patch was not applied.'); +}🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@scripts/patch-trapi-metadata.mjs` around lines 54 - 59, Add a warning branch for the silent no-target case: when both patched === 0 and skipped === 0, log a clear warning (e.g., console.warn) that no candidate `@trapi/metadata` files were found/targeted so the patch did not run, and include contextual hints (like the paths you searched or advise that the package may be hoisted) so the missing patch is discovered earlier; place this check alongside the existing patched/skipped checks in scripts/patch-trapi-metadata.mjs where patched and skipped are evaluated.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@apps/server-core/package.json`:
- Line 24: The npm script "build:swagger" uses single quotes around the
--entry-point and --name arguments which breaks on Windows cmd.exe; update the
"build:swagger" script (the trapi generate invocation) to use escaped double
quotes for those arguments (e.g., \"...\") so the glob and API title are passed
correctly on Windows while preserving the rest of the command.
In `@apps/server-core/src/adapters/http/controllers/workflows/openid/module.ts`:
- Around line 58-62: The discovery document incorrectly sets revocation_endpoint
to the same URL as token_endpoint; update the revocation_endpoint construction
(the resolveURL(baseURL, 'token') call) to point to the correct revocation path
used by the handler (e.g., resolveURL(baseURL, 'token/revoke')) so
revocation_endpoint is distinct from token_endpoint and matches the
TokenController's revoke handler.
In
`@apps/server-core/test/unit/http/controllers/workflows/token/grant-robot-credentials.spec.ts`:
- Line 19: The top-level Mocha/Jest test suite label for
grant-robot-credentials.spec.ts is incorrectly "refresh-token" (a stale
copy/paste); update the describe(...) call in this file to use the correct suite
name "robot-credentials" so test output and CI reports reflect the intended
suite (look for the describe(...) invocation at the top of the file and change
its string).
---
Outside diff comments:
In @.agents/architecture.md:
- Around line 298-345: The doc is inconsistent: replace the old helper signature
buildActorContext(req: Request) with buildActorContext(event: IRoutupEvent)
everywhere, and standardize the controller example to the preferred typed-return
pattern by removing sendCreated/sendAccepted usages and instead setting
event.response.status = 201/202 and returning the entity; update any
references/examples (e.g. the earlier helper example and the sample that
mentions sendCreated/sendAccepted) to reference buildActorContext, IRoutupEvent,
and the register/password-forgot/password-reset controllers as canonical
examples so contributors see one consistent Routup v5 controller pattern.
---
Nitpick comments:
In
`@apps/server-core/src/adapters/http/controllers/workflows/authorize/module.ts`:
- Line 66: The handlers use broad Promise<any> return types; tighten them by
updating confirm's signature to return Promise<{ url: string }> (since it
returns an object with a url) and update serve's signature to return
Promise<string> (since it returns rendered HTML), i.e., replace Promise<any> on
the methods confirm and serve in the authorize module with these precise return
types and adjust any local typings/returns to match those shapes (functions:
confirm, serve).
In `@scripts/patch-trapi-metadata.mjs`:
- Around line 54-59: Add a warning branch for the silent no-target case: when
both patched === 0 and skipped === 0, log a clear warning (e.g., console.warn)
that no candidate `@trapi/metadata` files were found/targeted so the patch did not
run, and include contextual hints (like the paths you searched or advise that
the package may be hoisted) so the missing patch is discovered earlier; place
this check alongside the existing patched/skipped checks in
scripts/patch-trapi-metadata.mjs where patched and skipped are evaluated.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: defaults
Review profile: CHILL
Plan: Pro
Run ID: 136efc67-36ab-43f8-a22c-9de7a49e651f
⛔ Files ignored due to path filters (1)
package-lock.jsonis excluded by!**/package-lock.json
📒 Files selected for processing (42)
.agents/architecture.md.agents/testing.mdapps/server-core/package.jsonapps/server-core/src/adapters/http/controllers/entities/identity-provider/module.tsapps/server-core/src/adapters/http/controllers/entities/realm/module.tsapps/server-core/src/adapters/http/controllers/workflows/authorize/module.tsapps/server-core/src/adapters/http/controllers/workflows/openid/module.tsapps/server-core/src/adapters/http/index.tsapps/server-core/src/adapters/http/middleware/built-in/logger.tsapps/server-core/src/adapters/http/middleware/built-in/swagger.tsapps/server-core/src/adapters/http/swagger/index.tsapps/server-core/src/adapters/http/swagger/module.tsapps/server-core/src/adapters/http/swagger/type.tsapps/server-core/src/app/builder.tsapps/server-core/src/app/factory.tsapps/server-core/src/app/modules/constants.tsapps/server-core/src/app/modules/http/modules/middleware.tsapps/server-core/src/app/modules/index.tsapps/server-core/src/app/modules/runtime/module.tsapps/server-core/src/app/modules/swagger/index.tsapps/server-core/src/app/modules/swagger/module.tsapps/server-core/src/cli/commands/index.tsapps/server-core/src/cli/commands/swagger.tsapps/server-core/src/cli/module.tsapps/server-core/src/utils/index.tsapps/server-core/src/utils/url.tsapps/server-core/test/unit/http/controllers/entities/permission/checker.spec.tsapps/server-core/test/unit/http/controllers/entities/permission/module.spec.tsapps/server-core/test/unit/http/controllers/entities/role.spec.tsapps/server-core/test/unit/http/controllers/entities/scope.spec.tsapps/server-core/test/unit/http/controllers/workflows/token/grant-authorize.spec.tsapps/server-core/test/unit/http/controllers/workflows/token/grant-client-credentials.spec.tsapps/server-core/test/unit/http/controllers/workflows/token/grant-password.spec.tsapps/server-core/test/unit/http/controllers/workflows/token/grant-refresh-token.spec.tsapps/server-core/test/unit/http/controllers/workflows/token/grant-robot-credentials.spec.tsapps/server-core/test/utils/assertions.tsapps/server-core/test/utils/http.tsapps/server-core/test/utils/index.tspackage.jsonpackages/access/src/policy/error/module.tspackages/server-kit/src/crypto/json-web-token/utils.tsscripts/patch-trapi-metadata.mjs
💤 Files with no reviewable changes (14)
- apps/server-core/src/adapters/http/swagger/type.ts
- apps/server-core/src/app/modules/constants.ts
- apps/server-core/src/app/modules/index.ts
- apps/server-core/src/cli/commands/index.ts
- apps/server-core/src/cli/commands/swagger.ts
- apps/server-core/src/app/modules/swagger/index.ts
- apps/server-core/src/adapters/http/swagger/index.ts
- apps/server-core/src/app/factory.ts
- apps/server-core/src/adapters/http/index.ts
- apps/server-core/src/app/builder.ts
- apps/server-core/src/cli/module.ts
- apps/server-core/src/app/modules/swagger/module.ts
- apps/server-core/src/adapters/http/swagger/module.ts
- packages/server-kit/src/crypto/json-web-token/utils.ts
✅ Files skipped from review due to trivial changes (1)
- .agents/testing.md
| "build:server:js": "tsdown", | ||
| "build:server": "npm run build:server:js && npm run build:server:types", | ||
| "build:swagger": "npm run cli -- swagger generate", | ||
| "build:swagger": "trapi generate --entry-point 'src/adapters/http/controllers/**/*.ts' --preset @routup/decorators/preset --tsconfig tsconfig.json --output dist/swagger.json --version v3.2 --name 'API Documentation'", |
There was a problem hiding this comment.
🧩 Analysis chain
🌐 Web query:
Does npm runon Windowscmd.exetreat single quotes inpackage.json scripts as literal characters, and are double quotes the portable way to pass quoted CLI arguments?
💡 Result:
Yes: on Windows, npm run runs your package.json script in the default shell cmd.exe, and cmd.exe does not treat single quotes '...' as quoting syntax. As a result, single quotes tend to be passed through literally or be interpreted as part of multiple tokens rather than “single parameter” quoting, so single-quoted CLI arguments in scripts often break. For example, switching a script that used ' quotes to use escaped double quotes (") fixes the problem when running under npm run on Windows [1][2]. Also, double quotes are generally the more portable way to pass quoted CLI arguments across shells, especially for Windows cmd.exe. Many cross-platform npm-script examples recommend using double quotes for arguments because sh supports single quotes but Windows does not; consequently, you need to escape double quotes inside the JSON string (e.g. "value") in package.json [2]. Caveat: npm’s argument passing can still remove/normalize quotes depending on how you structure the command/-- usage, so for “pass-through” arguments you should use npm run <script> -- <args> to ensure args are forwarded as intended [3].
Citations:
- 1: https://stackoverflow.com/questions/37500744/how-to-properly-run-a-npm-script-with-arguments/37501023
- 2: https://exploringjs.com/nodejs-shell-scripting/ch_package-scripts.html
- 3: npm run removes quotes from given parameters npm/npm#7743
Use double quotes in the npm script for Windows portability.
The single-quoted --entry-point and --name arguments fail on Windows under cmd.exe, which does not recognize single quotes as quoting syntax. The quotes are passed literally to trapi generate, breaking the glob pattern and including literal quotes in the API title. Use escaped double quotes instead.
Portable script change
- "build:swagger": "trapi generate --entry-point 'src/adapters/http/controllers/**/*.ts' --preset `@routup/decorators/preset` --tsconfig tsconfig.json --output dist/swagger.json --version v3.2 --name 'API Documentation'",
+ "build:swagger": "trapi generate --entry-point \"src/adapters/http/controllers/**/*.ts\" --preset `@routup/decorators/preset` --tsconfig tsconfig.json --output dist/swagger.json --version v3.2 --name \"API Documentation\"",📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| "build:swagger": "trapi generate --entry-point 'src/adapters/http/controllers/**/*.ts' --preset @routup/decorators/preset --tsconfig tsconfig.json --output dist/swagger.json --version v3.2 --name 'API Documentation'", | |
| "build:swagger": "trapi generate --entry-point \"src/adapters/http/controllers/**/*.ts\" --preset `@routup/decorators/preset` --tsconfig tsconfig.json --output dist/swagger.json --version v3.2 --name \"API Documentation\"", |
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@apps/server-core/package.json` at line 24, The npm script "build:swagger"
uses single quotes around the --entry-point and --name arguments which breaks on
Windows cmd.exe; update the "build:swagger" script (the trapi generate
invocation) to use escaped double quotes for those arguments (e.g., \"...\") so
the glob and API title are passed correctly on Windows while preserving the rest
of the command.
| token_endpoint: resolveURL(baseURL, 'token'), | ||
|
|
||
| introspection_endpoint: new URL('token/introspect', this.options.baseURL).href, | ||
| introspection_endpoint: resolveURL(baseURL, 'token/introspect'), | ||
|
|
||
| revocation_endpoint: new URL('token', this.options.baseURL).href, | ||
| revocation_endpoint: resolveURL(baseURL, 'token'), |
There was a problem hiding this comment.
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash
# Find the revocation route registration to confirm the correct path
rg -n --type=ts -C3 'revoc' apps/server-core/src/Repository: authup/authup
Length of output: 1569
🏁 Script executed:
rg -n --type=ts 'token.*revok|revok.*endpoint' apps/server-core/src/ -A 2 -B 2Repository: authup/authup
Length of output: 1443
🏁 Script executed:
# Search for route/handler definitions for token revocation
rg -n --type=ts -i 'router\.(post|put|delete).*revok|revok.*handler|revocation.*route' apps/server-core/src/Repository: authup/authup
Length of output: 39
🏁 Script executed:
# Look for all token-related route paths to understand the structure
rg -n --type=ts 'router\.(post|put|delete).*['\''"].*token' apps/server-core/src/ -A 1 | head -30Repository: authup/authup
Length of output: 39
🏁 Script executed:
cat -n apps/server-core/src/adapters/http/controllers/workflows/token/module.ts | head -200Repository: authup/authup
Length of output: 8965
🏁 Script executed:
# Search for router definitions in token module
rg -n 'router\.' apps/server-core/src/adapters/http/controllers/workflows/token/module.ts -A 2 | head -50Repository: authup/authup
Length of output: 39
revocation_endpoint resolves to the same URL as token_endpoint
Both line 58 and line 62 call resolveURL(baseURL, 'token'). However, the actual token revocation handler is registered at /token/revoke (see TokenController line 173), not /token. Per RFC 7009, the revocation endpoint must be distinct from the token endpoint. Clients that autodiscover via this discovery document will fail to revoke tokens.
introspection_endpoint is correctly set to token/introspect, so this is a copy-paste oversight.
Suggested fix
- revocation_endpoint: resolveURL(baseURL, 'token'),
+ revocation_endpoint: resolveURL(baseURL, 'token/revoke'),📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| token_endpoint: resolveURL(baseURL, 'token'), | |
| introspection_endpoint: new URL('token/introspect', this.options.baseURL).href, | |
| introspection_endpoint: resolveURL(baseURL, 'token/introspect'), | |
| revocation_endpoint: new URL('token', this.options.baseURL).href, | |
| revocation_endpoint: resolveURL(baseURL, 'token'), | |
| token_endpoint: resolveURL(baseURL, 'token'), | |
| introspection_endpoint: resolveURL(baseURL, 'token/introspect'), | |
| revocation_endpoint: resolveURL(baseURL, 'token/revoke'), |
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@apps/server-core/src/adapters/http/controllers/workflows/openid/module.ts`
around lines 58 - 62, The discovery document incorrectly sets
revocation_endpoint to the same URL as token_endpoint; update the
revocation_endpoint construction (the resolveURL(baseURL, 'token') call) to
point to the correct revocation path used by the handler (e.g.,
resolveURL(baseURL, 'token/revoke')) so revocation_endpoint is distinct from
token_endpoint and matches the TokenController's revoke handler.
| import { createFakeRobot, expectClientError } from '../../../../../utils'; | ||
| import { createTestApplication } from '../../../../../app'; | ||
|
|
||
| describe('refresh-token', () => { |
There was a problem hiding this comment.
describe label is stale — reads 'refresh-token' instead of 'robot-credentials'
Likely a copy-paste artifact from grant-refresh-token.spec.ts; this will show up as the wrong suite name in test output and CI reports.
🔧 Proposed fix
-describe('refresh-token', () => {
+describe('robot-credentials', () => {📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| describe('refresh-token', () => { | |
| describe('robot-credentials', () => { |
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In
`@apps/server-core/test/unit/http/controllers/workflows/token/grant-robot-credentials.spec.ts`
at line 19, The top-level Mocha/Jest test suite label for
grant-robot-credentials.spec.ts is incorrectly "refresh-token" (a stale
copy/paste); update the describe(...) call in this file to use the correct suite
name "robot-credentials" so test output and CI reports reflect the intended
suite (look for the describe(...) invocation at the top of the file and change
its string).
- Rename AuthupErrorOptionsInput to AuthupErrorInput, mirror HTTPErrorInput shape (string | options); drop Error from union - Make AuthupError.data readonly and consolidate response payload in toJSON via super.toJSON() + spread extras - Align JWTError, JWKError, OAuth2Error, PermissionError on the new input type and pass data through super() instead of post-construction mutation - Replace toOAuth2Error mutation with fresh OAuth2Error construction; update tests - Replace ! non-null assertions in jwks handlers with type-predicate filters - Hoist vite type-only import in assets middleware to top level - Drop pointless async on createSwaggerMiddleware (swaggerUI is sync) - Switch error middleware to next.toJSON() for the canonical payload shape
There was a problem hiding this comment.
Actionable comments posted: 1
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
apps/server-core/src/adapters/http/controllers/workflows/jwks/module.ts (1)
72-78:⚠️ Potential issue | 🟠 Major | ⚡ Quick winRestore realm-aware filtering in
getOneJwks.Line 72 drops event context, so the lookup at Lines 74-77 cannot apply
realmId(unlikegetManyJwksat Lines 39-45). This can return a key from a different realm when realm scoping is expected.Suggested fix
- async getOneJwks(`@DPath`('id') id: string): Promise<any> { + async getOneJwks( + `@DContext`() event: IRoutupEvent, + `@DPath`('id') id: string, + ): Promise<any> { + const realmId = getRequestStringParam(event, 'realmId'); const entity = await this.repository.findOne({ where: { type: In([JWKType.RSA, JWKType.EC]), id, + ...(realmId ? { realm_id: realmId } : {}), }, });🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@apps/server-core/src/adapters/http/controllers/workflows/jwks/module.ts` around lines 72 - 78, getOneJwks currently omits the realm filter so repository.findOne({ where: { type: In([JWKType.RSA, JWKType.EC]), id } }) can return keys from other realms; restore realm-aware filtering by retrieving the current realm id the same way getManyJwks does (use the same event/request context helper used there) and add realmId to the where clause for findOne (i.e., include realmId alongside type and id) so the lookup is scoped to the request's realm.
♻️ Duplicate comments (1)
apps/server-core/src/adapters/http/middleware/built-in/error.ts (1)
15-16:⚠️ Potential issue | 🟠 Major | ⚡ Quick winGuard
errorbefore reading.causein the handler.Line 16 can throw again if the thrown value is
null/undefined, becauseerror.causeis accessed unguarded inside the error middleware.Suggested fix
router.use(defineErrorHandler((error, event) => { - const next : AuthupError = sanitizeError(error.cause ?? error); + const cause = (typeof error === 'object' && error !== null && 'cause' in error) ? + (error as { cause?: unknown }).cause : + undefined; + const next : AuthupError = sanitizeError(cause ?? error);🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@apps/server-core/src/adapters/http/middleware/built-in/error.ts` around lines 15 - 16, The error handler reads error.cause unguarded which will throw if the thrown value is null/undefined; update the router.use(defineErrorHandler(...)) callback to first guard the incoming error (e.g. check error !== null && error !== undefined and typeof error === 'object') before accessing .cause, and pass sanitizeError(error.cause ?? error) only after that guard (or compute a safeCause variable from (error as any)?.cause with a conditional fallback to error). Ensure you update references in the same function (router.use, defineErrorHandler, sanitizeError) so no property access occurs on null/undefined.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In
`@apps/server-core/src/adapters/http/controllers/workflows/jwks/handlers/read.ts`:
- Line 46: The JWKS handler changed shape by returning an object `{ keys }` but
callers like getCerts() and the forwarded getJwksRouteHandler(...) expect a
Promise<OAuth2JsonWebKey[]>; update the handler in read.ts to return the raw
keys array (not wrapped) or alternatively update getCerts() and its forwarding
of getJwksRouteHandler to accept the `{ keys }` shape—preferably revert read.ts
to return the array so getCerts(), getJwksRouteHandler, and callers remain
compatible.
---
Outside diff comments:
In `@apps/server-core/src/adapters/http/controllers/workflows/jwks/module.ts`:
- Around line 72-78: getOneJwks currently omits the realm filter so
repository.findOne({ where: { type: In([JWKType.RSA, JWKType.EC]), id } }) can
return keys from other realms; restore realm-aware filtering by retrieving the
current realm id the same way getManyJwks does (use the same event/request
context helper used there) and add realmId to the where clause for findOne
(i.e., include realmId alongside type and id) so the lookup is scoped to the
request's realm.
---
Duplicate comments:
In `@apps/server-core/src/adapters/http/middleware/built-in/error.ts`:
- Around line 15-16: The error handler reads error.cause unguarded which will
throw if the thrown value is null/undefined; update the
router.use(defineErrorHandler(...)) callback to first guard the incoming error
(e.g. check error !== null && error !== undefined and typeof error === 'object')
before accessing .cause, and pass sanitizeError(error.cause ?? error) only after
that guard (or compute a safeCause variable from (error as any)?.cause with a
conditional fallback to error). Ensure you update references in the same
function (router.use, defineErrorHandler, sanitizeError) so no property access
occurs on null/undefined.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: defaults
Review profile: CHILL
Plan: Pro
Run ID: 8898416a-c050-4e99-9c8b-4a9be6a5da81
📒 Files selected for processing (14)
apps/server-core/src/adapters/http/controllers/workflows/jwks/handlers/read.tsapps/server-core/src/adapters/http/controllers/workflows/jwks/module.tsapps/server-core/src/adapters/http/middleware/built-in/assets.tsapps/server-core/src/adapters/http/middleware/built-in/error.tsapps/server-core/src/adapters/http/middleware/built-in/swagger.tsapps/server-core/src/app/modules/http/modules/middleware.tsapps/server-core/src/core/oauth2/helpers/erorr.tsapps/server-core/test/unit/core/oauth2/helpers/error.spec.tspackages/access/src/permission/error/module.tspackages/errors/src/module.tspackages/errors/src/types.tspackages/specs/src/json-web-key/error.tspackages/specs/src/json-web-token/error.tspackages/specs/src/oauth2/error.ts
| const keys = await Promise.all(promises); | ||
|
|
||
| return send(res, { keys }); | ||
| return { keys }; |
There was a problem hiding this comment.
Align JWKS collection response shape with callers.
Line 46 now returns { keys }, but apps/server-core/src/adapters/http/controllers/entities/realm/module.ts (provided snippet, Lines 137-141) still exposes getCerts() as Promise<OAuth2JsonWebKey[]> and forwards getJwksRouteHandler(...) directly. Please align the caller contract (or keep the previous shape) to avoid breaking response expectations.
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In
`@apps/server-core/src/adapters/http/controllers/workflows/jwks/handlers/read.ts`
at line 46, The JWKS handler changed shape by returning an object `{ keys }` but
callers like getCerts() and the forwarded getJwksRouteHandler(...) expect a
Promise<OAuth2JsonWebKey[]>; update the handler in read.ts to return the raw
keys array (not wrapped) or alternatively update getCerts() and its forwarding
of getJwksRouteHandler to accept the `{ keys }` shape—preferably revert read.ts
to return the array so getCerts(), getJwksRouteHandler, and callers remain
compatible.
|
@coderabbitai review |
✅ Actions performedReview triggered.
|
…turns - Replace `return sendCreated(event, entity)` with `event.response.status = 201; return entity;` and the equivalent for 202 across all entity + workflow controllers, so @trapi/swagger can extract the response shape from the method signature - For no-body 202 responses (activate, token revoke), set status and `return null;` (routup's toResponse handles null as an empty-body Response; returning undefined would hang the handler) - Promote `pickStringParam` in HTTPOAuth2AuthorizeGrant from a free function to a `protected` method on the class
@trapi/[email protected] ships the `if (!symbol) return;` guard upstream (tada5hi/trapi#821), so the local workaround is no longer needed.
@ebec/http v4 renamed
Input/OptionstoHTTPErrorInput/HTTPErrorOptions, flipped the per-error*ErrorOptionsconsts fromstatusCodetostatus, and removed the free-formdatafield fromHTTPErrorOptions.AuthupError.datais a public surface used by the OAuth2 error helpers and the error middleware to forward extra payload keys, so it moves from a transitive ebec field to an explicit field onAuthupErroritself. Callers inapps/server-core/src/utils/error.tsflip to the newstatusaccessor on the Options consts.Summary by CodeRabbit
New Features
Improvements
Bug Fixes