Repository navigation
Conversation
…-core application
|
Note Reviews pausedIt looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
📝 WalkthroughWalkthroughApplication now stores modules in a protected Map and computes a dependency-aware startup order via a new resolveOrder (topological sort with cycle detection). Modules expose name/dependsOn metadata. An ApplicationBuilder with fluent withX() methods was added and used across CLI, factory, and tests to construct Applications. Changes
Sequence DiagramsequenceDiagram
participant CLI as CLI / Command
participant Builder as ApplicationBuilder
participant App as Application
participant Map as Modules Map
participant Resolver as resolveOrder()
participant Module as Module Instance
CLI->>Builder: configure modules (withX... .build())
Builder->>App: instantiate App & call addModule(name, module)
App->>Map: store module by name
CLI->>App: app.start()
App->>Resolver: resolveOrder()
Resolver->>Map: read modules (name, dependsOn)
Resolver->>Resolver: build dependency graph & topo sort
alt cycle detected
Resolver-->>App: throw AuthupError (cycle)
else
Resolver-->>App: return startOrder
loop for each module in startOrder
App->>Module: module.start(container)
end
end
Estimated code review effort🎯 4 (Complex) | ⏱️ ~45 minutes Possibly related PRs
Poem
🚥 Pre-merge checks | ✅ 3 | ❌ 2❌ Failed checks (1 warning, 1 inconclusive)
✅ Passed checks (3 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches🧪 Generate unit tests (beta)
📝 Coding Plan
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
Actionable comments posted: 2
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/app/modules/http/module.ts (1)
81-83:⚠️ Potential issue | 🔴 Critical
stop()is effectively disabled becausethis.instanceis never assigned.Line 91 exits when
this.instanceis unset, but Lines 81-83 only registerserverin the container. Without assigningthis.instanceinstart(), the HTTP server cannot be closed during shutdown/restart.🐛 Proposed fix
container.register(HTTPInjectionKey.Server, { useValue: server, }); + this.instance = server;Also applies to: 90-96
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@apps/server-core/src/app/modules/http/module.ts` around lines 81 - 83, The HTTP server instance is registered in the container but never assigned to the class field, so stop() exits early because this.instance is unset; in start() assign the created server to this.instance (e.g., this.instance = server) after creating/registering it (the block that currently calls container.register(HTTPInjectionKey.Server, { useValue: server })) so that stop() can access and close the server; ensure the same this.instance is the value used by stop()'s close logic and remove any early-return paths that check the wrong variable.
🧹 Nitpick comments (3)
apps/server-core/src/cli/commands/migration.ts (1)
50-51: UseModuleNameconstants for consistency with other modules.The inline module descriptor uses string literals
'config'and'logger'in thedependsOnarray, while all other modules in the codebase useModuleName.CONFIGandModuleName.LOGGER. SinceModuleNameis already available from the existing importfrom '../../app/index.ts', using the constants would improve consistency and maintainability.♻️ Suggested change
+import { ModuleName } from '../../app/index.ts';{ name: 'migration', - dependsOn: ['config', 'logger'], + dependsOn: [ModuleName.CONFIG, ModuleName.LOGGER], async start(container: IDIContainer): Promise<void> {🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@apps/server-core/src/cli/commands/migration.ts` around lines 50 - 51, The dependsOn array for the inline module descriptor (the module with name 'migration') uses string literals 'config' and 'logger' — replace those with the ModuleName constants (ModuleName.CONFIG and ModuleName.LOGGER) imported from '../../app/index.ts' to match project convention; update the dependsOn entry for the migration module so it references ModuleName.CONFIG and ModuleName.LOGGER instead of string literals.apps/server-core/src/app/module.ts (2)
34-36: Consider detecting duplicate module names.If two modules share the same
name, the second silently overwrites the first. This could mask configuration errors.🛡️ Proposed fix to detect duplicates
addModule(module: Module): void { + if (this.modules.has(module.name)) { + throw new AuthupError(`Duplicate module name: ${module.name}`); + } this.modules.set(module.name, module); }🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@apps/server-core/src/app/module.ts` around lines 34 - 36, The addModule method currently overwrites existing entries when a Module with the same name is added; update addModule (the addModule(module: Module): void implementation that writes to this.modules) to first detect duplicates by checking this.modules.has(module.name) and then handle it (throw a descriptive Error or log and return) instead of unconditionally calling this.modules.set; include the module.name and possibly the existing module object in the error/log message to aid debugging.
29-29: Address static analysis warning about forEach callbacks.Biome flags these callbacks for implicitly returning a value. While functionally correct (returning
void), explicit braces clarify intent.♻️ Proposed fix
- modules.forEach((module) => this.addModule(module)); + modules.forEach((module) => { this.addModule(module); });addModules(modules: Module[]): void { - modules.forEach((module) => this.addModule(module)); + modules.forEach((module) => { this.addModule(module); }); }Also applies to: 38-40
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@apps/server-core/src/app/module.ts` at line 29, The forEach callbacks implicitly return a value and trigger static-analysis warnings; change the arrow callbacks to use explicit block bodies so they return void — e.g., replace uses of modules.forEach((module) => this.addModule(module)) with a block-bodied callback modules.forEach((module) => { this.addModule(module); }); do the same for the other forEach occurrences in this file that call this.addModule (and any analogous forEach -> methodCall patterns).
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@apps/server-core/src/app/module.ts`:
- Around line 81-84: The loop that checks module.dependsOn currently ignores
missing dependencies by returning when registered.has(dep) is false; change this
to surface the problem early for the module (either throw a ValidationError or
emit a clear warning) so missing dependencies are not silently
skipped—specifically update the logic around module.dependsOn and
registered.has(dep) (the block that currently does "if (!registered.has(dep)) {
return; }") to instead either throw a descriptive error (e.g., include
module.name and the missing dep) or call the application's logger to warn, so
callers like HTTPModule that later call container.resolve(LoggerInjectionKey)
will fail fast with a helpful message.
In `@apps/server-core/src/app/modules/oauth2/module.ts`:
- Around line 53-56: The module constructor for OAuth2Module currently sets
this.dependsOn to [ModuleName.DATABASE, ModuleName.CACHE, ModuleName.CONFIG] but
omits ModuleName.IDENTITY; update the constructor (the dependsOn assignment in
OAuth2Module) to include ModuleName.IDENTITY so that IdentityModule starts
before OAuth2Module and the start() resolution of IIdentityResolver via
IdentityInjectionKey.Resolver succeeds at runtime.
---
Outside diff comments:
In `@apps/server-core/src/app/modules/http/module.ts`:
- Around line 81-83: The HTTP server instance is registered in the container but
never assigned to the class field, so stop() exits early because this.instance
is unset; in start() assign the created server to this.instance (e.g.,
this.instance = server) after creating/registering it (the block that currently
calls container.register(HTTPInjectionKey.Server, { useValue: server })) so that
stop() can access and close the server; ensure the same this.instance is the
value used by stop()'s close logic and remove any early-return paths that check
the wrong variable.
---
Nitpick comments:
In `@apps/server-core/src/app/module.ts`:
- Around line 34-36: The addModule method currently overwrites existing entries
when a Module with the same name is added; update addModule (the
addModule(module: Module): void implementation that writes to this.modules) to
first detect duplicates by checking this.modules.has(module.name) and then
handle it (throw a descriptive Error or log and return) instead of
unconditionally calling this.modules.set; include the module.name and possibly
the existing module object in the error/log message to aid debugging.
- Line 29: The forEach callbacks implicitly return a value and trigger
static-analysis warnings; change the arrow callbacks to use explicit block
bodies so they return void — e.g., replace uses of modules.forEach((module) =>
this.addModule(module)) with a block-bodied callback modules.forEach((module) =>
{ this.addModule(module); }); do the same for the other forEach occurrences in
this file that call this.addModule (and any analogous forEach -> methodCall
patterns).
In `@apps/server-core/src/cli/commands/migration.ts`:
- Around line 50-51: The dependsOn array for the inline module descriptor (the
module with name 'migration') uses string literals 'config' and 'logger' —
replace those with the ModuleName constants (ModuleName.CONFIG and
ModuleName.LOGGER) imported from '../../app/index.ts' to match project
convention; update the dependsOn entry for the migration module so it references
ModuleName.CONFIG and ModuleName.LOGGER instead of string literals.
ℹ️ Review info
⚙️ Run configuration
Configuration used: defaults
Review profile: CHILL
Plan: Pro
Run ID: c462150b-341a-472c-984a-0ba211dedadd
📒 Files selected for processing (20)
apps/server-core/src/app/module.tsapps/server-core/src/app/modules/authentication/module.tsapps/server-core/src/app/modules/cache/module.tsapps/server-core/src/app/modules/components/module.tsapps/server-core/src/app/modules/config/module.tsapps/server-core/src/app/modules/constants.tsapps/server-core/src/app/modules/database/module.tsapps/server-core/src/app/modules/http/module.tsapps/server-core/src/app/modules/identity/module.tsapps/server-core/src/app/modules/index.tsapps/server-core/src/app/modules/ldap/module.tsapps/server-core/src/app/modules/logger/module.tsapps/server-core/src/app/modules/mail/module.tsapps/server-core/src/app/modules/oauth2/module.tsapps/server-core/src/app/modules/provisioning/module.tsapps/server-core/src/app/modules/runtime/module.tsapps/server-core/src/app/modules/swagger/module.tsapps/server-core/src/app/modules/types.tsapps/server-core/src/app/modules/vault/module.tsapps/server-core/src/cli/commands/migration.ts
| module.dependsOn.forEach((dep) => { | ||
| if (!registered.has(dep)) { | ||
| return; | ||
| } |
There was a problem hiding this comment.
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash
# Check if any modules have dependencies on modules not defined in ModuleName constants
# This helps verify if silent ignore is safe
# Find all ModuleName constant values
echo "=== Defined ModuleName constants ==="
ast-grep --pattern 'ModuleName = {
$$$
}'
echo ""
echo "=== Module dependsOn declarations ==="
rg -n "dependsOn.*=" --glob "*.ts" -A3 | head -80Repository: authup/authup
Length of output: 4968
🏁 Script executed:
#!/bin/bash
# Find ModuleName definition
echo "=== ModuleName definition ==="
rg -n "ModuleName" --glob "*.ts" | grep -E "(enum|const|type).*ModuleName" | head -20
echo ""
echo "=== Full module.ts context around resolveOrder ==="
cat -n apps/server-core/src/app/module.ts | head -120Repository: authup/authup
Length of output: 4514
🏁 Script executed:
#!/bin/bash
# Check ModuleName constants
echo "=== ModuleName constants ==="
cat -n apps/server-core/src/app/modules/constants.ts
echo ""
echo "=== How Application is initialized - search for addModule/addModules calls ==="
rg -n "addModule|new Application" --glob "*.ts" -B2 -A2 | head -100Repository: authup/authup
Length of output: 3362
🏁 Script executed:
#!/bin/bash
# Check full Application factory
echo "=== Full factory.ts ==="
cat -n apps/server-core/src/app/factory.ts
echo ""
echo "=== Check if there are tests for module resolution ==="
find . -name "*.spec.ts" -o -name "*.test.ts" | xargs grep -l "resolveOrder\|circular\|dependsOn" 2>/dev/null | head -10Repository: authup/authup
Length of output: 1687
🏁 Script executed:
#!/bin/bash
# Check how HTTPModule uses its dependencies
echo "=== HTTPModule implementation ==="
cat -n apps/server-core/src/app/modules/http/module.ts | head -60
echo ""
echo "=== Check if there's any documentation or comments about optional dependencies ==="
grep -r "optional\|depend\|miss" apps/server-core/src/app/module.ts -B2 -A2
echo ""
echo "=== Check actual dependency usage in start methods ==="
rg -A20 "async start.*container" apps/server-core/src/app/modules/cache/module.tsRepository: authup/authup
Length of output: 3706
Fail fast or emit a warning for unregistered module dependencies.
When a module declares a dependency that isn't registered in the application, the dependency edge is silently skipped (lines 82-84). The module will still start, but if it tries to resolve its missing dependency from the container, it will fail at runtime with a confusing error. For example, HTTPModule depends on LOGGER but will crash when container.resolve(LoggerInjectionKey) is called if LOGGER wasn't registered. This silent failure masks configuration errors. Modules should either fail validation early or emit a clear warning if declared dependencies are missing.
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@apps/server-core/src/app/module.ts` around lines 81 - 84, The loop that
checks module.dependsOn currently ignores missing dependencies by returning when
registered.has(dep) is false; change this to surface the problem early for the
module (either throw a ValidationError or emit a clear warning) so missing
dependencies are not silently skipped—specifically update the logic around
module.dependsOn and registered.has(dep) (the block that currently does "if
(!registered.has(dep)) { return; }") to instead either throw a descriptive error
(e.g., include module.name and the missing dep) or call the application's logger
to warn, so callers like HTTPModule that later call
container.resolve(LoggerInjectionKey) will fail fast with a helpful message.
There was a problem hiding this comment.
Actionable comments posted: 2
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@apps/server-core/src/app/builder.ts`:
- Around line 54-56: The constructor currently creates an empty Map so untouched
module slots are missing when build() iterates only this.slots; update the
ApplicationBuilder constructor (or the build logic) to ensure all known/default
slots are present before build runs—either prepopulate this.slots with entries
for each module key (the same keys that factory.ts expects) or change build() to
iterate a static list of module keys and read overrides from this.slots;
reference ApplicationBuilder.constructor, this.slots, build(), and any withXxx
methods (e.g., withDatabase) so that an explicit false/override only replaces
that slot and untouched modules keep their default implementations.
- Around line 122-145: Split the current generic build method into two overloads
to prevent callers from asserting a concrete Application type when they call
build() with no args: add an overload build<T extends
Application>(ApplicationClass: new (modules?: Module[]) => T): T and a no-arg
overload build(): Application, then keep a single implementation (non-generic)
build(ApplicationClass?: new (modules?: Module[]) => Application): Application
that constructs modules the same way and returns new ApplicationClass(modules)
when provided or new Application(modules) otherwise; update the existing build
method in builder.ts (the build function and references to ApplicationClass,
Module, defaultFactories, and this.slots) to match this overload pattern so the
zero-arg path typesafe-returns Application.
ℹ️ Review info
⚙️ Run configuration
Configuration used: defaults
Review profile: CHILL
Plan: Pro
Run ID: df7e5119-483e-4a12-8966-c0aa3d768d74
📒 Files selected for processing (3)
apps/server-core/src/app/builder.tsapps/server-core/src/app/factory.tsapps/server-core/src/app/index.ts
| constructor() { | ||
| this.slots = new Map(); | ||
| } |
There was a problem hiding this comment.
The builder starts empty, so untouched modules are never defaulted.
build() only walks this.slots. With an empty constructor, new ApplicationBuilder().build() returns an empty app, and a partial override like .withDatabase(false).build() drops every untouched module as well. The current apps/server-core/src/app/factory.ts:15-33 path only works because it touches every slot first.
Suggested fix
constructor() {
- this.slots = new Map();
+ this.slots = new Map(
+ Object.keys(defaultFactories).map((name) => [name, undefined]),
+ );
}🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@apps/server-core/src/app/builder.ts` around lines 54 - 56, The constructor
currently creates an empty Map so untouched module slots are missing when
build() iterates only this.slots; update the ApplicationBuilder constructor (or
the build logic) to ensure all known/default slots are present before build
runs—either prepopulate this.slots with entries for each module key (the same
keys that factory.ts expects) or change build() to iterate a static list of
module keys and read overrides from this.slots; reference
ApplicationBuilder.constructor, this.slots, build(), and any withXxx methods
(e.g., withDatabase) so that an explicit false/override only replaces that slot
and untouched modules keep their default implementations.
There was a problem hiding this comment.
Actionable comments posted: 3
🧹 Nitpick comments (1)
apps/server-core/test/setup.ts (1)
25-32: Prefer constructing the bootstrap app insidesetup().
Applicationkeeps mutable container and startup state, so sharing one module-level instance makes repeated setup runs depend on the previous run's state. Building a fresh app insidesetup()keeps test bootstrap isolated.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@apps/server-core/test/setup.ts` around lines 25 - 32, The module-level ApplicationBuilder instance should be created inside the exported setup() function to avoid sharing mutable Application state across test runs; move the current ApplicationBuilder chain (the code that constructs app with ApplicationBuilder().withConfig().withLogger().withDatabase(new TestDatabaseModuleBase()).withProvisioning(new ProvisionerModule([ new DefaultProvisioningSource() ])).build()) into the body of setup(), create a fresh local app there, use that app for whatever initialization/setup/teardown setup() performs, and remove the module-level app variable so each call to setup() constructs and returns an isolated Application instance.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@apps/server-core/src/cli/commands/migration.ts`:
- Around line 112-145: The code currently uses a hard-coded connections array
and unconditionally calls dropDatabase/createDatabase, which can delete
unrelated local DBs; replace the fixed connections with the environment-aware
builder (use optionsBuilder.buildWithEnv() or read config.db) so you generate
migration targets from the configured deployment, and add a safety guard around
destructive operations (do not call dropDatabase/createDatabase unless a
deliberate CLI flag is provided, e.g. --force or an explicit --target that
matches the resolved DataSourceOptions.type); update the loop that uses
connections, directoryPath and calls dropDatabase/createDatabase so it iterates
only over environment-configured targets and checks the new confirmation flag
before calling dropDatabase/createDatabase.
- Around line 93-107: The DataSource creation/usage blocks must guarantee
cleanup: wrap each new DataSource(...) flow (the one that calls initialize()
then undoLastMigration()/showMigrations()/runMigrations(), and the second
instance inside the loop) in a try/finally so destroy() always runs;
specifically call await dataSource.initialize() inside the try and put await
dataSource.destroy() inside the finally, leaving the migration calls
(undoLastMigration, showMigrations, runMigrations) inside the try body so any
thrown errors still trigger destroy().
In `@apps/server-core/src/cli/commands/reset.ts`:
- Around line 24-25: The reset command calls Application.reset() but that method
is currently empty (Application.reset in module.ts) so the CLI reports success
without changing state; implement Application.reset to perform the actual
teardown/reset work (for example iterate registered modules and invoke their
reset/cleanup methods or call the same logic used by Application.stop/teardown),
and ensure the CLI path in reset.ts (where app.start() and app.reset() are
called) only returns success if Application.reset completes without error;
update Application.reset to throw on failure or return a meaningful result so
reset.ts can detect and surface errors.
---
Nitpick comments:
In `@apps/server-core/test/setup.ts`:
- Around line 25-32: The module-level ApplicationBuilder instance should be
created inside the exported setup() function to avoid sharing mutable
Application state across test runs; move the current ApplicationBuilder chain
(the code that constructs app with
ApplicationBuilder().withConfig().withLogger().withDatabase(new
TestDatabaseModuleBase()).withProvisioning(new ProvisionerModule([ new
DefaultProvisioningSource() ])).build()) into the body of setup(), create a
fresh local app there, use that app for whatever initialization/setup/teardown
setup() performs, and remove the module-level app variable so each call to
setup() constructs and returns an isolated Application instance.
ℹ️ Review info
⚙️ Run configuration
Configuration used: defaults
Review profile: CHILL
Plan: Pro
Run ID: 492ca919-6e9a-4a10-af00-c7a29b9cfd95
📒 Files selected for processing (6)
apps/server-core/src/cli/commands/healthcheck.tsapps/server-core/src/cli/commands/migration.tsapps/server-core/src/cli/commands/reset.tsapps/server-core/src/cli/commands/swagger.tsapps/server-core/test/app/factory.tsapps/server-core/test/setup.ts
| const connections : DataSourceOptions[] = [ | ||
| { | ||
| type: 'postgres', | ||
| database: 'migrations', | ||
| host: 'localhost', | ||
| port: 5432, | ||
| username: 'postgres', | ||
| password: 'start123', | ||
| }, | ||
| { | ||
| type: 'mysql', | ||
| database: 'migrations', | ||
| host: 'localhost', | ||
| port: 3306, | ||
| username: 'root', | ||
| password: 'start123', | ||
| }, | ||
| ]; | ||
|
|
||
| const baseDirectory = transformFilePath( | ||
| path.join(CODE_PATH, 'adapters', 'database', 'migrations'), | ||
| './src', | ||
| './dist', | ||
| ); | ||
|
|
||
| const timestamp = Date.now(); | ||
|
|
||
| for (let i = 0; i < connections.length; i++) { | ||
| const dataSourceOptions = optionsBuilder.buildWith(connections[i]); | ||
| const directoryPath = path.join(baseDirectory, dataSourceOptions.type); | ||
|
|
||
| await dropDatabase({ options: dataSourceOptions }); | ||
| await createDatabase({ options: dataSourceOptions, synchronize: false }); | ||
|
|
There was a problem hiding this comment.
migration generate can drop unrelated local databases.
This branch bypasses config.db / buildWithEnv() and unconditionally calls dropDatabase() for fixed localhost Postgres/MySQL targets named migrations. Running the generic generate command on a developer machine can therefore delete existing local data and generate against a schema that does not match the configured deployment.
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@apps/server-core/src/cli/commands/migration.ts` around lines 112 - 145, The
code currently uses a hard-coded connections array and unconditionally calls
dropDatabase/createDatabase, which can delete unrelated local DBs; replace the
fixed connections with the environment-aware builder (use
optionsBuilder.buildWithEnv() or read config.db) so you generate migration
targets from the configured deployment, and add a safety guard around
destructive operations (do not call dropDatabase/createDatabase unless a
deliberate CLI flag is provided, e.g. --force or an explicit --target that
matches the resolved DataSourceOptions.type); update the loop that uses
connections, directoryPath and calls dropDatabase/createDatabase so it iterates
only over environment-configured targets and checks the new confirmation flag
before calling dropDatabase/createDatabase.
| await app.start(); | ||
| await app.reset(); |
There was a problem hiding this comment.
reset still reports success without actually resetting anything.
Application.reset() is currently empty in apps/server-core/src/app/module.ts:58-60, so this path now boots the registered modules and exits 0 without changing state. That makes the command misleading and can trigger startup side effects on what looks like a reset run.
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@apps/server-core/src/cli/commands/reset.ts` around lines 24 - 25, The reset
command calls Application.reset() but that method is currently empty
(Application.reset in module.ts) so the CLI reports success without changing
state; implement Application.reset to perform the actual teardown/reset work
(for example iterate registered modules and invoke their reset/cleanup methods
or call the same logic used by Application.stop/teardown), and ensure the CLI
path in reset.ts (where app.start() and app.reset() are called) only returns
success if Application.reset completes without error; update Application.reset
to throw on failure or return a meaningful result so reset.ts can detect and
surface errors.
|
@coderabbitai review |
✅ Actions performedReview triggered.
|
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 (2)
apps/server-core/test/setup.ts (1)
45-53:⚠️ Potential issue | 🟠 MajorClean up the LDAP container on bootstrap failures.
If
app.start()orapp.stop()throws after Line 45, this function exits with the freshly started container still running. That leaves orphaned Docker containers behind on failed setup paths and can make later CI runs flaky.Suggested failure-path cleanup
const container = await containerConfig.start(); + let initialized = false; - project.provide('OPENLDAP_CONTAINER_HOST', container.getHost()); - project.provide('OPENLDAP_CONTAINER_PORT', container.getFirstMappedPort()); - - globalThis.OPENLDAP_CONTAINER = container; - - await app.start(); - await app.stop(); + try { + project.provide('OPENLDAP_CONTAINER_HOST', container.getHost()); + project.provide('OPENLDAP_CONTAINER_PORT', container.getFirstMappedPort()); + + globalThis.OPENLDAP_CONTAINER = container; + + await app.start(); + await app.stop(); + initialized = true; + } finally { + if (!initialized) { + await container.stop().catch(() => undefined); + } + }🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@apps/server-core/test/setup.ts` around lines 45 - 53, The bootstrap can leave the LDAP container running if app.start() or app.stop() throws; wrap the sequence after containerConfig.start() in a try/finally so the container is always cleaned up on failure: after calling containerConfig.start() and assigning project.provide(...) and globalThis.OPENLDAP_CONTAINER, run app.start()/app.stop() inside a try block and in the finally ensure the container is stopped/removed (call the container instance stop/remove methods or container.stop()) and clear globalThis.OPENLDAP_CONTAINER so no orphaned containers remain; reference containerConfig.start(), globalThis.OPENLDAP_CONTAINER, and app.start()/app.stop() to locate where to add the try/finally cleanup.apps/server-core/test/app/factory.ts (1)
20-24:⚠️ Potential issue | 🔴 CriticalThe factory does not consume the injected OpenLDAP endpoint coordinates.
setup.tslines 47-48 publishOPENLDAP_CONTAINER_HOSTandOPENLDAP_CONTAINER_PORTvia Vitest's provided context, butbuildTestConfig()reads only fromprocess.envthrough predefined keys inConfigEnvironmentVariableName. There are no LDAP-related environment variable keys defined in that enum, and the provided context is never synced toprocess.env. Consequently,.withLdap()at line 48 will initialize with default/stale LDAP settings, not the dynamically provisioned container endpoint.Either sync the provided values to
process.env(with appropriate key names) before callingcreateTestApplication(), or add an explicit override mechanism to the factory to consume the provided context.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@apps/server-core/test/app/factory.ts` around lines 20 - 24, buildTestConfig() currently only reads process.env via ConfigEnvironmentVariableName and therefore ignores the Vitest-provided OPENLDAP_CONTAINER_HOST/OPENLDAP_CONTAINER_PORT published in setup.ts, causing .withLdap() to use stale defaults; fix by either (A) syncing the Vitest context values to process.env under the expected keys before calling createTestApplication() (ensure the keys match ConfigEnvironmentVariableName), or (B) extend buildTestConfig() to accept an optional override object (e.g., ldapHost, ldapPort) and apply those values when normalizing the config so that .withLdap() receives the dynamically provisioned endpoint; update the test setup to pass the context through the chosen route.
♻️ Duplicate comments (2)
apps/server-core/src/cli/commands/migration.ts (2)
67-83:⚠️ Potential issue | 🟠 MajorMove
initialize()insidetryso cleanup is guaranteed.Line 71 and Line 124 call
initialize()before the guarded block. If initialization throws,destroy()is skipped. Keep bothinitialize()and migration operations insidetry, and calldestroy()infinallyonly when initialized.🔧 Proposed fix
const dataSource = new DataSource({...}); -await dataSource.initialize(); - try { + await dataSource.initialize(); // migration work... } finally { - await dataSource.destroy(); + if (dataSource.isInitialized) { + await dataSource.destroy(); + } }#!/bin/bash set -euo pipefail file="apps/server-core/src/cli/commands/migration.ts" echo "== initialize() call sites ==" rg -n "await dataSource\\.initialize\\(\\)" "$file" echo echo "== try/finally blocks around migration flows ==" nl -ba "$file" | sed -n '60,150p'Also applies to: 123-138
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@apps/server-core/src/cli/commands/migration.ts` around lines 67 - 83, The DataSource.initialize() is called before the try/finally so if initialization throws dataSource.destroy() is never called; move await dataSource.initialize() inside the try block that wraps the migration operations (the conditional using MigrationOperation.REVERT/STATUS/runMigrations()), and ensure dataSource.destroy() in the finally runs only if initialization succeeded (e.g., track an "initialized" flag after await dataSource.initialize() or check dataSource.isInitialized) so destroy is not invoked on a non-initialized DataSource; update references to dataSource.initialize(), dataSource.destroy(), and the block handling MigrationOperation to implement this change.
89-106:⚠️ Potential issue | 🔴 Critical
generatestill has destructive hard-coded DB targets and credentials.Line 89–Line 106 hard-code local Postgres/MySQL credentials, and Line 120–Line 121 unconditionally drops/recreates DBs. This can wipe unrelated local data when running
migration generate.💡 Proposed direction
- const connections: DataSourceOptions[] = [ - { type: 'postgres', database: 'migrations', host: 'localhost', ... }, - { type: 'mysql', database: 'migrations', host: 'localhost', ... }, - ]; + // Resolve migration target(s) from env/config instead of fixed localhost credentials. + const connections: DataSourceOptions[] = [optionsBuilder.buildWithEnv()]; - await dropDatabase({ options: dataSourceOptions }); - await createDatabase({ options: dataSourceOptions, synchronize: false }); + if (!context.args.force) { + throw new Error('Refusing to drop/create database without --force.'); + } + await dropDatabase({ options: dataSourceOptions, ifExist: true }); + await createDatabase({ options: dataSourceOptions, synchronize: false, ifNotExist: true });Also applies to: 120-121
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@apps/server-core/src/cli/commands/migration.ts` around lines 89 - 106, The generate command currently hard-codes local DB credentials in the connections const and unconditionally drops/recreates databases (lines referenced around the drop/recreate logic), which is dangerous; change generate to accept connection targets via CLI flags or environment variables (e.g., --db-type, --host, --port, --user, --password or a DATABASE_URL) and remove hard-coded postgres/mysql entries from the connections const, and gate any destructive operations (the unconditional drop/create) behind an explicit confirmation flag (e.g., --force) or an interactive prompt; update the code paths that perform the drop/recreate so they only run when a --force flag is passed or when a DRY_RUN/ALLOW_DESTRUCTIVE env var is true, and document the new flags in the CLI help text.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@apps/server-core/test/app/http.ts`:
- Around line 30-31: The helper currently force-casts httpServer.address() to
AddressInfo and reads port; change it to guard the return of
httpServer.address() by checking its type and nullability before using .port:
call const address = httpServer.address(); if address === null return a safe
fallback or throw a clear error; if typeof address === "string" handle the
socket-path case (use that string or a suitable base URL for socket listeners);
otherwise treat it as AddressInfo and read address.port to build baseURL; update
uses of address and baseURL accordingly so no force-cast is performed.
---
Outside diff comments:
In `@apps/server-core/test/app/factory.ts`:
- Around line 20-24: buildTestConfig() currently only reads process.env via
ConfigEnvironmentVariableName and therefore ignores the Vitest-provided
OPENLDAP_CONTAINER_HOST/OPENLDAP_CONTAINER_PORT published in setup.ts, causing
.withLdap() to use stale defaults; fix by either (A) syncing the Vitest context
values to process.env under the expected keys before calling
createTestApplication() (ensure the keys match ConfigEnvironmentVariableName),
or (B) extend buildTestConfig() to accept an optional override object (e.g.,
ldapHost, ldapPort) and apply those values when normalizing the config so that
.withLdap() receives the dynamically provisioned endpoint; update the test setup
to pass the context through the chosen route.
In `@apps/server-core/test/setup.ts`:
- Around line 45-53: The bootstrap can leave the LDAP container running if
app.start() or app.stop() throws; wrap the sequence after
containerConfig.start() in a try/finally so the container is always cleaned up
on failure: after calling containerConfig.start() and assigning
project.provide(...) and globalThis.OPENLDAP_CONTAINER, run
app.start()/app.stop() inside a try block and in the finally ensure the
container is stopped/removed (call the container instance stop/remove methods or
container.stop()) and clear globalThis.OPENLDAP_CONTAINER so no orphaned
containers remain; reference containerConfig.start(),
globalThis.OPENLDAP_CONTAINER, and app.start()/app.stop() to locate where to add
the try/finally cleanup.
---
Duplicate comments:
In `@apps/server-core/src/cli/commands/migration.ts`:
- Around line 67-83: The DataSource.initialize() is called before the
try/finally so if initialization throws dataSource.destroy() is never called;
move await dataSource.initialize() inside the try block that wraps the migration
operations (the conditional using
MigrationOperation.REVERT/STATUS/runMigrations()), and ensure
dataSource.destroy() in the finally runs only if initialization succeeded (e.g.,
track an "initialized" flag after await dataSource.initialize() or check
dataSource.isInitialized) so destroy is not invoked on a non-initialized
DataSource; update references to dataSource.initialize(), dataSource.destroy(),
and the block handling MigrationOperation to implement this change.
- Around line 89-106: The generate command currently hard-codes local DB
credentials in the connections const and unconditionally drops/recreates
databases (lines referenced around the drop/recreate logic), which is dangerous;
change generate to accept connection targets via CLI flags or environment
variables (e.g., --db-type, --host, --port, --user, --password or a
DATABASE_URL) and remove hard-coded postgres/mysql entries from the connections
const, and gate any destructive operations (the unconditional drop/create)
behind an explicit confirmation flag (e.g., --force) or an interactive prompt;
update the code paths that perform the drop/recreate so they only run when a
--force flag is passed or when a DRY_RUN/ALLOW_DESTRUCTIVE env var is true, and
document the new flags in the CLI help text.
ℹ️ Review info
⚙️ Run configuration
Configuration used: defaults
Review profile: CHILL
Plan: Pro
Run ID: 0f58d846-4e62-4c6c-8077-c0172a104588
📒 Files selected for processing (11)
apps/server-core/src/app/builder.tsapps/server-core/src/app/modules/database/module.tsapps/server-core/src/app/modules/oauth2/module.tsapps/server-core/src/cli/commands/migration.tsapps/server-core/test/app/database.tsapps/server-core/test/app/factory.tsapps/server-core/test/app/http.tsapps/server-core/test/app/index.tsapps/server-core/test/app/module.tsapps/server-core/test/setup.tsapps/server-core/test/unit/modules/provisioning.spec.ts
| const address = httpServer.address() as AddressInfo; | ||
| const baseURL = `http://localhost:${address.port}`; |
There was a problem hiding this comment.
🧩 Analysis chain
🏁 Script executed:
# First, locate and examine the test file
find . -type f -name "http.ts" -path "*/test/app/*" | head -20Repository: authup/authup
Length of output: 92
🏁 Script executed:
# Also search for the HTTP module file
find . -type f -path "*/src/app/modules/http/module.ts" | head -5Repository: authup/authup
Length of output: 106
🏁 Script executed:
cat -n ./apps/server-core/test/app/http.tsRepository: authup/authup
Length of output: 1611
🏁 Script executed:
cat -n ./apps/server-core/src/app/modules/http/module.ts | head -100Repository: authup/authup
Length of output: 3889
🏁 Script executed:
cat -n ./apps/server-core/test/app/module.tsRepository: authup/authup
Length of output: 658
Guard server.address() before reading port.
Line 30 force-casts away string | null branches without checking. If the client getter is accessed before the server listens, after shutdown, or against a socket-bound listener, this will throw or produce a malformed URL. The HTTP module at apps/server-core/src/app/modules/http/module.ts:72-79 already handles all three branches, so this helper should do the same.
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@apps/server-core/test/app/http.ts` around lines 30 - 31, The helper currently
force-casts httpServer.address() to AddressInfo and reads port; change it to
guard the return of httpServer.address() by checking its type and nullability
before using .port: call const address = httpServer.address(); if address ===
null return a safe fallback or throw a clear error; if typeof address ===
"string" handle the socket-path case (use that string or a suitable base URL for
socket listeners); otherwise treat it as AddressInfo and read address.port to
build baseURL; update uses of address and baseURL accordingly so no force-cast
is performed.
There was a problem hiding this comment.
Actionable comments posted: 1
🧹 Nitpick comments (1)
apps/server-core/test/app/database.ts (1)
61-63: Prefer omittingsetupinstead of a no-op to keep default DB existence safety.Providing a no-op overrides
DatabaseModule’s default setup behavior. Omittingsetupkeeps the “create-if-missing” fallback and reduces coupling to global setup ordering.Suggested refactor
export function createTestDatabaseModuleForSuite(): DatabaseModule { return new DatabaseModule({ prepareBuild: prepareTestBuild, - async setup() { - // do nothing — DB already exists from global setup - }, async migrate(_container, dataSource) { await dataSource.synchronize(); }, }); }🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@apps/server-core/test/app/database.ts` around lines 61 - 63, The no-op async setup method in this test subclass overrides DatabaseModule's default setup behavior and should be removed; delete the async setup() { /* do nothing */ } method so the test uses DatabaseModule's built-in create-if-missing DB setup/fallback instead of overriding it.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@apps/server-core/test/app/database.ts`:
- Around line 21-23: The module currently returns silently when config.env !==
EnvironmentName.TEST which can allow dangerous DB tear-downs if env is
misconfigured; change this to fail fast by throwing an explicit error (or
calling process.exit(1)) with a clear message that the environment is not TEST
(referencing config.env and EnvironmentName.TEST) so the process stops
immediately instead of continuing with destructive DB setup.
---
Nitpick comments:
In `@apps/server-core/test/app/database.ts`:
- Around line 61-63: The no-op async setup method in this test subclass
overrides DatabaseModule's default setup behavior and should be removed; delete
the async setup() { /* do nothing */ } method so the test uses DatabaseModule's
built-in create-if-missing DB setup/fallback instead of overriding it.
ℹ️ Review info
⚙️ Run configuration
Configuration used: defaults
Review profile: CHILL
Plan: Pro
Run ID: 3204ada7-df5c-4f2f-99a8-3ea5e52c1381
📒 Files selected for processing (2)
.claude/skills/investigate-pr-comments/SKILL.mdapps/server-core/test/app/database.ts
✅ Files skipped from review due to trivial changes (1)
- .claude/skills/investigate-pr-comments/SKILL.md
resolves #2907
Summary by CodeRabbit
Refactor
New Features
Bug Fixes