Repository navigation
refactor(env): one number parser, AUTH_TRUSTED_ORIGINS for the console origins (Refs #47) - #90
Conversation
|
Pushed 🤖 Generated with Claude Code |
SoFrexs
left a comment
There was a problem hiding this comment.
Nice dedupe. I checked positiveNumberFromEnv against both removed copies: same fallback on unset/empty, same Number.isFinite / > 0 / integer checks, same messages, so build-snapshots, write-lake, prune-prevalence and lake-backlog-case behave as before. No env var is renamed and nothing else (CI, compose, rig) refers to lib/env-int. The origin parsing (scheme check, credentials/path/query refused, trailing slash and default port normalised via URL.origin, * refused) looks right. CI green; mergeable. Three accuracy issues in what the docs promise, all small:
Please fix
-
"An entry that is not an origin stops the server at start" (
docs/configuration.md:22, also the PR body) isn't what happens.lib/auth.tsis imported only byapp/api/auth/[...all]/route.tsandlib/console-session.ts, and Next 14.2 loads route modules lazily (instrumentation.tsdoesn't touch it). With a bad value the server starts; the first/api/auth/*request throws at import and answers 500, and the session lookup fails closed, so the console just bounces to/login. Either validate at boot (callauthTrustedOrigins(process.env)fromregister()ininstrumentation.tsunderNEXT_RUNTIME === "nodejs") or change the docs to "fails every auth request". I'd prefer the former, since #47 is about failing loudly. -
"Set, it is exactly the list (localhost is not added)" (
docs/configuration.md:22,docs/security-model.md:63) isn't quite true. In better-auth 1.7.5 (dist/context/helpers.mjs,getTrustedOrigins) the effective list is the base-URL origin (BETTER_AUTH_URL/…, otherwise the request's own origin) +options.trustedOrigins+BETTER_AUTH_TRUSTED_ORIGINSsplit on commas, appended unvalidated. That answers your open question (a separate name was the right choice), but the security-model doc should state the full rule and sayBETTER_AUTH_TRUSTED_ORIGINSis still honoured and not validated bylib/env.ts. -
lib/env.ts:43-45: a non-blank value with no entries (","," , ") passes the blank check, filters to nothing and returns[]: no origin and no error. It fails closed, but it's exactly the "typo silently means something" case this module exists to stop. Throw when the parsed list is empty, and add it to the bad-entry test.
Non-blocking
4. lib/env.ts:59: the 200-character condition would read better as a named predicate (isBareHttpOrigin(url)); invalid → invalidOriginError. catch { throw invalid(); } (:56) drops the URL error; pass it as { cause }.
5. Record<string, string | undefined> appears three times in lib/env.ts; a named Environment type would remove the repetition.
6. docs/deployment.md:131: the Compose server service uses an explicit environment: map, so setting the variable in .env alone does nothing there; say it goes on the server service.
7. tests/unit/env.test.ts:12-13 assert the same thing twice (default vs explicit integer: false). tests/unit/auth-trusted-origins.test.ts deletes AUTH_TRUSTED_ORIGINS in afterEach instead of restoring any previous value.
8. As you note, the auth test reads auth.options.trustedOrigins, not better-auth's decision. A cookie-bearing request with a foreign Origin to auth.handler, expecting the refusal, would pin the real behaviour.
🤖 Generated with Claude Code
|
Pushed 75f3e24, addressing the review of d85a285.
Checks run: |
SoFrexs
left a comment
There was a problem hiding this comment.
Reviewed 75f3e24b: re-read d85a285..75f3e24 and the full diff against main. Items 2-8 are done. Item 1 moved in the right direction: the value is now checked when the server comes up. But "stops the server at start" is still not what Next 14.2 does with an exception from register(). The new origin-check tests also made the first test of that file slow enough to time out here.
Earlier points
- Validate at boot: partly resolved, see the first finding.
instrumentation.ts:15callsauthTrustedOrigins(process.env)underNEXT_RUNTIME === "nodejs". The import stays inside the branch, sotests/unit/instrumentation.test.tsstill holds. - better-auth's full rule: resolved.
docs/security-model.md:63now matchesgetTrustedOriginsin better-auth 1.7.5 (dist/context/helpers.mjs:62-83): base-URL origin, then the option, thenBETTER_AUTH_TRUSTED_ORIGINS, unvalidated.docs/configuration.md:22links to it. - Empty list: resolved.
lib/env.ts:48throwslists no origin. The new test covers","," , "and",,". - Naming and cause: resolved.
isBareHttpOrigin(lib/env.ts:53),invalidOriginError(cause)with theURLerror as{ cause }. Environmenttype: resolved (lib/env.ts:8), used by all three readers.- Compose: resolved (
docs/deployment.md:131). - Tests: resolved. The duplicate assertion is gone, and
afterEachrestores the three variables it touches. - Real refusal: resolved. A cookie-bearing
POST /api/auth/sign-outgets 403 from a foreignOriginand not 403 from the configured one. I ran both. Without theNODE_ENV=productionimport they would not discriminate, because better-auth skips the check under test.
[blocker] DCO is red. 75f3e24 has no Signed-off-by trailer (d85a285 has one). Fix: git commit --amend -s --no-edit && git push --force-with-lease.
[should-fix] A bad value does not stop the server; it makes every request fail (instrumentation.ts:15, docs/configuration.md:22, PR body "A bad entry stops the server at start"). In Next 14.2.35, NextNodeServer.prepareImpl (next/dist/server/next-server.js:473-485) wraps the register() error ("An error occurred while loading instrumentation hook: …") and rethrows it. In production nobody awaits that at start. The constructor fires this.prepare().catch(err => console.error("Failed to prepare server", err)) (:437), and BaseServer.prepare keeps the rejected promise, because it resets preparedPromise only on success (base-server.js:879-888). So the process keeps listening, and every request runs await this.prepare() in handleRequest (base-server.js:430) and fails. That is every route, /api/health and the agent endpoints included. tests/unit/instrumentation.test.ts:7-8 records the same effect from the #81 lab run ("every route returned 500"). It does fail loudly, so the behaviour is acceptable. What is wrong is the promise. Either:
- make it true: in
instrumentation-node.ts, catch the validation error, log it, andprocess.exit(1)(keepprocess.exitout ofinstrumentation.ts, which is also compiled for Edge); or - say what happens: "…logs
Failed to prepare serverat start and every request answers 500", indocs/configuration.md:22,docs/security-model.md:63("validated when the server starts"), the comment atinstrumentation.ts:13-14and the PR body.
I'd take the first, since #47 is about failing loudly and a container that exits is what an orchestrator notices.
Reproduced: next build at 75f3e24b, then .next/standalone/server.js with AUTH_TRUSTED_ORIGINS=console.example.com. The server prints ✓ Ready in 320ms, then Failed to prepare server Error: An error occurred while loading instrumentation hook: AUTH_TRUSTED_ORIGINS must list … (with the Invalid URL cause, so item 4 works). It keeps running, and /api/health and /login both answer 500.
[should-fix] The first auth test now runs close to vitest's 5 s timeout and fails under load (vitest.config.ts:15, tests/unit/auth-trusted-origins.test.ts:41). Inlining better-auth makes the first import("@/lib/auth") transform the whole package. "keeps the two localhost origins when AUTH_TRUSTED_ORIGINS is unset" took 4.0 s and 4.4 s on an idle machine, against 1.5 s at d85a285. It timed out at 5000 ms in my full tests/unit run and in a run of the file while another suite was running. CI passed, but this will flake on a slow runner. Fixes, any one of them:
- a
beforeAllthat warms the import, with a longer hook timeout; - an explicit timeout on the file's tests;
- scoping the inline to this file. The global
server.deps.inlinealso slows every other file that imports better-auth.
Nits
docs/configuration.md:5-7still says variables "are read when they are used, not validated at start-up".AUTH_TRUSTED_ORIGINSis now the exception; one clause there avoids contradicting row 22.instrumentation.ts:12-15:startDecoyWatch()runs before the validation, so a bad value still installs the decoy shutdown handler and starts the table check on a server that cannot serve. Validate first: the cheap pure check before the side effects.tests/unit/auth-trusted-origins.test.ts:13-29:vi.stubEnv("NODE_ENV", "production")/vi.stubEnv("TEST", undefined)withvi.unstubAllEnvs()inafterEachreplaces theinitialsnapshot, the restore loop and theprocess.envcast.tests/unit/auth-trusted-origins.test.ts:61-65:not.toBe(403)would also pass on a 500. The request actually gets200 {"success":true}(I logged it), sotoBe(200)pins "passed the origin check" and the test name can drop "on the origin check": "accepts a cookie-bearing request from a configured Origin".
Tested (Windows host, worktree at 75f3e24b, node_modules identical to main's lockfile)
npm run typecheck: clean.npm run lint: 0 errors, 108 warnings (cap 113).npx vitest run tests/unit: 88 files, 1437 passed, 5 skipped, 1 failed: the timeout above.tests/unit/auth-trusted-origins.test.tsalone, idle machine, twice: 5/5 passed, first test 4.0 s / 4.4 s. Atd85a285: first test 1.5 s.next build+ standaloneserver.jswith a badAUTH_TRUSTED_ORIGINS: process stays up, every request 500 (above).- Read Next 14.2.35's
preparepath and better-auth 1.7.5'sgetTrustedOriginsin the installed packages. - CI on
75f3e24b:serverand bothunit-cross-osgreen,dcored.
Not verified
- No integration tests: this machine has no PostgreSQL (no Docker).
- No Docker image or Compose run; the standalone server was run directly on Windows (no database reachable, which only adds the decoy table-check error to the log).
🤖 Generated with Claude Code
…e origins (Refs #47) SV-014, first part. lib/env.ts replaces lib/env-int.ts: - positiveNumberFromEnv(env, name, fallback, { integer }) is the one parser. positiveIntFromEnv is a wrapper with the same answers and messages; build-snapshots lost its own copy (numberFromEnv), whose messages and checks are unchanged. - authTrustedOrigins(env) reads AUTH_TRUSTED_ORIGINS. Unset, empty or blank it is the two localhost origins lib/auth.ts hard-coded; set, it is exactly the listed origins. An entry that is not an http(s) origin throws at import. This is the one behaviour change, and only for a deployment that sets the variable. Docs: configuration.md, security-model.md, deployment.md, .env.example. Co-Authored-By: Claude Sonnet 5.5 <[email protected]> Signed-off-by: SherlockOmss <[email protected]>
…t, pin better-auth's refusal (Refs #47) - instrumentation.ts calls authTrustedOrigins(process.env) at start, so a bad value stops the server instead of answering 500 on the first /api/auth request. - A non-blank value with no entry ("," or " , ") throws instead of trusting no origin. - lib/env.ts: Environment type, isBareHttpOrigin predicate, invalidOriginError keeps the URL error as cause. - Tests: foreign Origin refused by auth.handler (better-auth inlined so it can be imported outside the test environment), env restored in afterEach, duplicate assertion dropped. - Docs state better-auth's full trusted-origin rule and that the compose server service needs the variable. Co-Authored-By: Claude Sonnet 5.5 <[email protected]> Signed-off-by: SherlockOmss <[email protected]>
75f3e24 to
862a7e6
Compare
|
Force-push |
…test timing out (Refs #47) A throw from register() does not stop a Next 14.2 server: it logs "Failed to prepare server" and every request answers 500. assertStartupConfig (instrumentation-node.ts) now logs the cause and exits with status 1, before the decoy side effects start. The first auth test paid for transforming better-auth inside its 5 s budget; a beforeAll warms the import with a 60 s hook timeout. The test also uses vi.stubEnv and pins 200. Co-Authored-By: Claude Sonnet 5.5 <[email protected]> Signed-off-by: SherlockOmss <[email protected]>
|
Pushed Files: Review points
Checks (Linux): Not verified
|
SoFrexs
left a comment
There was a problem hiding this comment.
Approve at d20db7bb. Every point from my review at 75f3e24b is fixed. I checked the main one by running the built server: a bad AUTH_TRUSTED_ORIGINS now makes the process exit with status 1 at start.
I re-read 75f3e24..862a7e6 and 862a7e6..d20db7b. The force-push only changed commit messages: 75f3e24b^{tree} and 862a7e6d^{tree} are the same tree (949efd2).
Earlier points
- [blocker] DCO: fixed. All three commits carry a
Signed-off-by, anddcois green. - [should-fix] A bad value did not stop the server: fixed.
assertStartupConfig(instrumentation-node.ts) logsInvalid configuration, exiting: …and callsexit(1).process.exitstays out ofinstrumentation.ts. The comment there,docs/configuration.mdanddocs/security-model.mdnow describe what actually happens. Reproduced withnext buildatd20db7bb, then.next/standalone/server.js:- With
AUTH_TRUSTED_ORIGINS=console.example.com, the server prints✓ Starting...and thenInvalid configuration, exiting: AUTH_TRUSTED_ORIGINS must list http(s)://host[:port] origins, got "console.example.com". The process exits with status 1 beforeReady. - With
AUTH_TRUSTED_ORIGINS=https://console.example.com, it reachesReadyand/loginanswers 200. - The same build also compiles the Edge side of
instrumentation.ts. That covers your "Edge bundle build not run".
- With
- [should-fix] First auth test near the 5 s timeout: fixed. A
beforeAllwarmsimport("@/lib/auth")with a 60 s hook timeout. Two runs of the file here: every test took 0.55-0.56 s, against 4.0-4.4 s at75f3e24b. The fulltests/unitrun passed, where at75f3e24bit had one timeout. - Nits: fixed.
docs/configuration.md:6names the exception.- Validation now runs before
startDecoyWatch(), and a test pins that order. vi.stubEnv/vi.unstubAllEnvsreplace the snapshot.- The test is renamed "accepts a cookie-bearing request from a configured Origin" and asserts
toBe(200).
New findings
- [nit]
tests/unit/auth-trusted-origins.test.ts:28:delete process.env.AUTH_TRUSTED_ORIGINSaftervi.unstubAllEnvs()undoes part of the restore.unstubAllEnvsalready puts back the value from before the first stub. If the runner's environment hasAUTH_TRUSTED_ORIGINSset, thedeleteremoves it for the rest of the file. Drop the line. - [nit]
tests/unit/instrumentation.test.ts:52:log.mockRestore()sits at the end of the test body, so a failed assertion leavesconsole.errormocked. Avi.restoreAllMocks()inafterEach(ascorpus-routes.test.tsdoes) always restores it.
Tested (Windows host, worktree at d20db7bb, npm ci from the branch lockfile)
npm run typecheck: clean.npm run lint: 0 errors, 108 warnings.npx vitest run tests/unit: 88 files, 1441 passed, 5 skipped, 0 failed.npx vitest run tests/unit/auth-trusted-origins.test.ts tests/unit/instrumentation.test.ts --reporter=verbose, twice: 12/12 passed both times, auth tests 0.55-0.56 s each.npx next build, thennode .next/standalone/server.jswith a bad and with a goodAUTH_TRUSTED_ORIGINS: exit status 1 and 200 respectively (above).- CI on
d20db7bb:dco,serverand bothunit-cross-osare green.gh pr view 90: mergeable, merge state clean.
Not verified
- No integration tests here: this machine has no PostgreSQL (no Docker). CI's
serverjob ran them. - No Docker image or Compose run. The standalone server ran directly on Windows with no database. That only adds the decoy table-check error to the log of the good-value run.
- No timing on a loaded or slow CI runner beyond CI's own green run.
🤖 Generated with Claude Code
Signed-off-by: SherlockOmss <[email protected]> # Conflicts: # lib/lake-backlog-case.ts
|
Pushed 1a54066 (merge of Checked: 🤖 Generated with Claude Code |
Refs #47 (SV-014, first of the two PRs the issue's delivery line asks for; what is left is listed below).
What
lib/env.tsreplaceslib/env-int.ts(whichmainalready had as the single copy of the integer parser):positiveNumberFromEnv(env, name, fallback, { integer }).positiveIntFromEnvis now a wrapper with the same answers and the same error text, sowrite-lake,prune-prevalenceandlake-backlog-casebehave as before.build-snapshotslost its own copy (numberFromEnv); its checks and messages are the same (must be a positive integer|number, got "...").authTrustedOrigins(env)readsAUTH_TRUSTED_ORIGINS, a comma-separated list ofhttp(s)://host[:port]origins, andlib/auth.tsuses it instead of the two hard-coded localhost origins.Behavior change (the only one)
AUTH_TRUSTED_ORIGINSunset, empty or blank giveshttp://localhost:3000andhttp://localhost:8443, as before.BETTER_AUTH_TRUSTED_ORIGINS(split on commas, not validated bylib/env.ts);docs/security-model.mdstates the full rule. A deployment that setsAUTH_TRUSTED_ORIGINSand still wants localhost must list it.ftp:, a path, a query, credentials,*, or a value with no entry such as,), instead of silently meaning the default.instrumentation-node.tsvalidates it first at boot, logsInvalid configuration, exiting: ...and exits with status 1 (an exception fromregister()alone would leave a Next 14.2 server listening and answering 500 everywhere); the auth module also throws at import. A trailing slash and the default port are normalized, duplicates dropped.Tests
tests/unit/env.test.ts: unset and empty fall back; a fraction is allowed unlessinteger; zero, negatives,NaN,Infinityand1e999throw with the variable and the value;positiveIntFromEnvkeeps its messages; the origin list (default, exact list, normalization, bad entries).tests/unit/auth-trusted-origins.test.ts: importslib/authwith the variable unset, set, and invalid, and readsauth.options.trustedOrigins; sends a cookie-bearingPOST /api/auth/sign-outtoauth.handlerand expects a 403 from a foreignOriginand no 403 from a configured one. better-auth skips its origin check underNODE_ENV=test, sovitest.config.tsinlines it and the test imports it withNODE_ENV=production.Checks (Linux, throwaway
postgres:15-alpine):tsc --noEmitclean; lint 0 errors, 108 warnings (limit 113); unit 1447 passed, 1 skipped; integration 456 passed, 5 skipped.Left out (so
Refs, notCloses)proxySecret(),cronSecret()andplatformOperatorIds(), and the call sites that read those ad hoc (lib/tenant.ts,lib/cron-auth.ts,lib/platform-operator.ts,lib/session-lookup.ts). Each keeps "unset fails closed" semantics that need their own tests first (cron-auth.test.tsexists; the others do not).lib/snapshot-publish.ts(paramsFromEnv).That is the "env module" PR of the issue's two-PR plan; this one is the number-parser dedupe plus the one behavior change.
Choices a reviewer can contest
AUTH_TRUSTED_ORIGINS, not better-auth's ownBETTER_AUTH_TRUSTED_ORIGINS: better-auth appends that variable, unvalidated, to its list, so it cannot be made to replace the localhost default. It is still honoured.positiveIntFromEnv, instead of the issue's(name, fallback, { integer }): it keeps the existing call sites and lets a test pass its own environment.Not verified
exit, not with a built server.🤖 Generated with Claude Code