Skip to content

feat(core): read auth configuration from environment variables#108

Merged
halvaradop merged 4 commits intomasterfrom
feat/read-config-from-envs
Mar 1, 2026
Merged

feat(core): read auth configuration from environment variables#108
halvaradop merged 4 commits intomasterfrom
feat/read-config-from-envs

Conversation

@halvaradop
Copy link
Member

@halvaradop halvaradop commented Mar 1, 2026

Description

This pull request introduces support for reading authentication configuration values from environment variables. This enhancement improves application security by reducing direct exposure of sensitive configuration values used when creating the Auth instance via the createAuth function.

The feature was initially motivated by loading TRUSTED_ORIGINS from environment variables, but the scope was expanded to support all relevant configuration values. Aura Auth now automatically resolves environment variables following these naming patterns:

  • AURA_AUTH_VALUE
  • AURA_VALUE
  • AUTH_VALUE
  • VALUE

Supported Environment Variables

  • DEBUG
  • LOG_LEVEL
  • SALT
  • SECRET
  • TRUSTED_ORIGINS
  • TRUSTED_PROXY_HEADERS

Note

Values provided via environment variables take precedence over values defined directly in the createAuth configuration. Use this behavior carefully to avoid unintended overrides.

Resources

Support configuration via:
- AUTH_DEBUG
- AUTH_LOG_LEVEL
- SALT
- SECRET
- TRUSTED_ORIGINS
- TRUSTED_PROXY_HEADERS
@vercel
Copy link

vercel bot commented Mar 1, 2026

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Actions Updated (UTC)
auth Ready Ready Preview, Comment Mar 1, 2026 9:10pm
auth-nextjs-demo Error Error Mar 1, 2026 9:10pm

@coderabbitai
Copy link

coderabbitai bot commented Mar 1, 2026

Note

Currently processing new changes in this PR. This may take a few minutes, please wait...

📥 Commits

Reviewing files that changed from the base of the PR and between a5c4dc0 and 4e2c56f.

📒 Files selected for processing (4)
  • docs/src/content/docs/configuration/env.mdx
  • packages/core/CHANGELOG.md
  • packages/core/src/index.ts
  • packages/core/src/logger.ts
 ____________________________________________________________________________________________________________________________________________________________________
< Don't gather requirements - dig for them. Requirements rarely lie on the surface. They're buried deep beneath layers of assumptions, misconceptions, and politics. >
 --------------------------------------------------------------------------------------------------------------------------------------------------------------------
  \
   \   (\__/)
       (•ㅅ•)
       /   づ

✏️ Tip: You can disable in-progress messages and the fortune message in your review settings.

📝 Walkthrough

Walkthrough

This change introduces environment-aware proxy logging and standardized environment variable resolution. It adds public helper functions for reading environment variables (getEnv, getEnvBoolean, getEnvArray), updates the logger interface to accept boolean values, replaces internal logging with environment-driven proxy logging, and refactors configuration consumers to use the new environment helpers.

Changes

Cohort / File(s) Summary
Type and Configuration Updates
packages/core/src/@types/index.ts
Broadened AuthConfig.logger type from Logger to boolean | Logger and documented AURA_AUTH_TRUSTED_PROXY_HEADERS environment variable support.
Environment Variable Helpers
packages/core/src/env.ts
Added three new public helpers: getEnv(key) resolves prioritized environment variable names (AURA_AUTH_, AURA_, AUTH_, ); getEnvBoolean(key) converts to boolean; getEnvArray(key, defaultValue) parses delimited strings into arrays.
Logging Infrastructure
packages/core/src/logger.ts
Expanded logging with RFC 5424 severity mapping, new createSyslogMessage() for syslog-compliant formatting, createLogger() for severity-filtered logging, and createProxyLogger() for environment-aware logger configuration.
Core Integration
packages/core/src/index.ts
Replaced internal logger abstraction with environment-aware proxy logging; wired environment variables for TRUSTED_PROXY_HEADERS, TRUSTED_ORIGINS, and DEBUG/LOG_LEVEL configuration via new helper functions.
Environment-Based Lookups
packages/core/src/jose.ts, packages/core/src/oauth/index.ts
Refactored SECRET, SALT, and OAuth CLIENT_ID/CLIENT_SECRET retrieval to use getEnv() instead of direct environment access.
Test Configuration and Fixtures
packages/core/test/env.test.ts, packages/core/test/presets.ts, packages/core/vitest.config.ts
Added environment variable test suite for secret retrieval; simplified test auth preset by removing custom logger configuration; added AURA_AUTH_DEBUG to test environment.
Documentation
docs/src/content/docs/api-reference/core.mdx, docs/src/content/docs/configuration/env.mdx, packages/core/CHANGELOG.md
Updated documentation to clarify environment variable lookup precedence, added runtime variables section (TRUSTED_ORIGINS, DEBUG, LOG_LEVEL), and documented new configuration patterns.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Possibly related PRs

Suggested labels

enhancement

Poem

🐰 A rabbit hops through env vars clear,
From AURA_AUTH to APP_NAME near,
With helpers for booleans, arrays, and strings,
The logger now learns from what config brings!
No more internal magic today,
Just proxy and proxy... in a cleaner way!

🚥 Pre-merge checks | ✅ 3
✅ Passed checks (3 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The pull request title accurately summarizes the main feature: reading authentication configuration from environment variables, which is the primary change across multiple files.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.

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

✨ Finishing Touches
  • 📝 Generate docstrings (stacked PR)
  • 📝 Generate docstrings (commit on current branch)
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch feat/read-config-from-envs

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 8

🧹 Nitpick comments (2)
packages/core/src/jose.ts (1)

24-37: Consider updating error messages to reflect all checked patterns.

The error messages reference specific env var names (AURA_AUTH_SECRET, AURA_AUTH_SALT or AUTH_SALT), but getEnv now checks multiple patterns (e.g., AURA_AUTH_SECRET, AURA_SECRET, AUTH_SECRET, SECRET). Consider updating the messages to list all valid options or use a generic phrasing like "No secret/salt found in environment variables."

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

In `@packages/core/src/jose.ts` around lines 24 - 37, Update the thrown
AuthInternalError messages in the jose initialization to reflect all env var
patterns checked by getEnv: when secret is missing (the variable referenced as
secret and set via getEnv) change the message to list all acceptable secret env
names or use a generic "No secret found in environment variables" phrasing; do
the same for the salt check (salt variable obtained via getEnv) so the
AuthInternalError for JOSE_INITIALIZATION_FAILED accurately references all salt
env options or uses a generic "No salt found in environment variables." Ensure
you update the error strings passed to AuthInternalError where secret and salt
are validated.
packages/core/test/env.test.ts (1)

5-29: Consider expanding test coverage.

The test suite only covers the env proxy directly. Consider adding tests for the new getEnv, getEnvBoolean, and getEnvArray helpers introduced in env.ts to validate the prioritized key resolution and parsing behavior.

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

In `@packages/core/test/env.test.ts` around lines 5 - 29, Add unit tests for the
new helpers getEnv, getEnvBoolean, and getEnvArray to validate prioritized key
resolution and parsing behavior: write tests that use vi.stubEnv to set fallback
and primary keys and assert getEnv returns primary when present and fallback
when primary missing (reference getEnv), tests for getEnvBoolean that verify
common truthy/falsey string values ("true","false","1","0","yes","no") and
default behavior when unset, and tests for getEnvArray that verify splitting on
commas, trimming whitespace, handling empty items, and returning an empty array
or default when unset (reference getEnvBoolean and getEnvArray to locate code
paths); use afterEach vi.unstubAllEnvs like existing tests to isolate env
changes.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@packages/core/src/env.ts`:
- Around line 48-59: getEnvArray's signature and fallbacks are incorrect: change
the generic function getEnvArray to return string[] (not <T>), type the
defaultValue as string[] = [], and simplify the body to call getEnv(key) and if
falsy return defaultValue; otherwise split on /[,;\n]+/, trim and
filter(Boolean) and return that array (remove the redundant "?? defaultValue ??
[]" chain). Keep references to getEnvArray and getEnv when making the edits.

In `@packages/core/src/index.ts`:
- Line 33: The logger is created with createProxyLogger(authConfig) but the
logger helper currently reads DEBUG/LOG_LEVEL instead of the PR-intended
AUTH_DEBUG/AUTH_LOG_LEVEL; update the logger helper
(packages/core/src/logger.ts) to read AUTH_DEBUG and AUTH_LOG_LEVEL and fall
back to DEBUG/LOG_LEVEL only if the AUTH_* vars are absent, or change
createProxyLogger usage to pass the correct env keys from authConfig; ensure
functions createProxyLogger and any internal functions that read process.env use
AUTH_DEBUG and AUTH_LOG_LEVEL as the primary sources so
createProxyLogger(authConfig) aligns with the PR contract.
- Line 32: The expression setting useProxyHeaders incorrectly treats an explicit
false from getEnvBoolean("TRUSTED_PROXY_HEADERS") as unset, so env cannot
disable authConfig.trustedProxyHeaders; update the assignment for
useProxyHeaders to prefer the environment value when present (including false)
by checking for presence/definedness of getEnvBoolean("TRUSTED_PROXY_HEADERS")
rather than using ||, e.g. retrieve the env value once via
getEnvBoolean("TRUSTED_PROXY_HEADERS") and if it is !== undefined use it,
otherwise fall back to authConfig?.trustedProxyHeaders or false; locate the
logic around getEnvBoolean, TRUSTED_PROXY_HEADERS and
authConfig?.trustedProxyHeaders where useProxyHeaders is defined to make this
change.

In `@packages/core/src/logger.ts`:
- Around line 271-273: The logger currently sets procId using process.pid which
will throw in non-Node runtimes; change the procId assignment (the "procId"
property in the logger creation) to safely check for the existence of process
and process.pid before calling toString, e.g. use a conditional/ternary that
verifies typeof process !== "undefined" and process.pid is present and then
converts to string, otherwise use a stable fallback (null/undefined or empty
string) so the logger won't crash in Bun/Deno/Edge environments.
- Around line 303-308: The syslog message can contain the literal "undefined"
because createSyslogMessage destructures appName from SyslogOptions but
createLogEntry doesn't set it; fix this by providing a safe default for appName
(e.g., '-' or a configured fallback) when building the message in
createSyslogMessage (or ensure createLogEntry always supplies appName) so that
appName is never the string "undefined" in the returned value; update the
destructuring/handling in createSyslogMessage to use that default.
- Around line 334-344: createProxyLogger incorrectly passes a boolean false into
createLogger when debug is falsy and config.logger === false; update the return
so you only forward a non-boolean logger to createLogger. Specifically, in
createProxyLogger check the type of config.logger (e.g., typeof config?.logger
=== "object" || typeof config?.logger === "function") and pass that value to
createLogger, otherwise pass undefined (or omit the argument) so createLogger is
never called with a boolean; reference createProxyLogger and createLogger to
locate the change.

In `@packages/core/src/utils.ts`:
- Around line 158-159: The exported function getEnvironmentVariables is empty
and should not be a no-op public API; either implement its intended behavior or
remove the export (or at minimum mark it as intentionally unfinished). Update
getEnvironmentVariables to return the environment map or specific vars expected
by callers (implement logic to read process.env and filter/normalize keys) or
remove the export entirely; if you must keep a placeholder, add a clear TODO
comment and make it throw a descriptive Error like "getEnvironmentVariables not
implemented" so consumers fail fast instead of receiving undefined.

In `@packages/core/test/env.test.ts`:
- Around line 23-29: Rename the unclear test title "nose" in the test function
to a descriptive name that reflects its intent (for example, "last stubbed value
overwrites previous values"); update the call to test(...) surrounding the
assertions in env.test.ts so the first argument is the new descriptive string
while leaving the body (generateSecure, vi.stubEnv,
expect(env.AURA_AUTH_SECRET).toBe(...)) unchanged.

---

Nitpick comments:
In `@packages/core/src/jose.ts`:
- Around line 24-37: Update the thrown AuthInternalError messages in the jose
initialization to reflect all env var patterns checked by getEnv: when secret is
missing (the variable referenced as secret and set via getEnv) change the
message to list all acceptable secret env names or use a generic "No secret
found in environment variables" phrasing; do the same for the salt check (salt
variable obtained via getEnv) so the AuthInternalError for
JOSE_INITIALIZATION_FAILED accurately references all salt env options or uses a
generic "No salt found in environment variables." Ensure you update the error
strings passed to AuthInternalError where secret and salt are validated.

In `@packages/core/test/env.test.ts`:
- Around line 5-29: Add unit tests for the new helpers getEnv, getEnvBoolean,
and getEnvArray to validate prioritized key resolution and parsing behavior:
write tests that use vi.stubEnv to set fallback and primary keys and assert
getEnv returns primary when present and fallback when primary missing (reference
getEnv), tests for getEnvBoolean that verify common truthy/falsey string values
("true","false","1","0","yes","no") and default behavior when unset, and tests
for getEnvArray that verify splitting on commas, trimming whitespace, handling
empty items, and returning an empty array or default when unset (reference
getEnvBoolean and getEnvArray to locate code paths); use afterEach
vi.unstubAllEnvs like existing tests to isolate env changes.

ℹ️ Review info

Configuration used: defaults

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 736ec63 and d8160ed.

📒 Files selected for processing (10)
  • packages/core/src/@types/index.ts
  • packages/core/src/env.ts
  • packages/core/src/index.ts
  • packages/core/src/jose.ts
  • packages/core/src/logger.ts
  • packages/core/src/oauth/index.ts
  • packages/core/src/utils.ts
  • packages/core/test/env.test.ts
  • packages/core/test/presets.ts
  • packages/core/vitest.config.ts
💤 Files with no reviewable changes (1)
  • packages/core/test/presets.ts

@halvaradop halvaradop added feature New functionality refactor Refactor without changing behavior labels Mar 1, 2026
Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 3

🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@docs/src/content/docs/configuration/env.mdx`:
- Around line 31-35: The warning Callout text contains grammatical errors and
unclear phrasing; update the sentence to be concise and correct by stating that
environment variables override corresponding options passed to createAuth
(specifically secret, trustedOrigins, and logger). For example, rephrase to:
"Environment variables override the corresponding options passed to createAuth
(for example: secret, trustedOrigins, and logger), so setting these environment
variables will replace the values provided in createAuth." Ensure you reference
createAuth and the option names exactly as shown.

In `@packages/core/CHANGELOG.md`:
- Line 17: The changelog line for the timingSafeEqual function is malformed: add
the missing leading bullet and a verb to make it a proper entry (e.g., "- Add
timingSafeEqual function for constant-time string comparison across runtimes.
[`#99`]"). Update the entry referencing timingSafeEqual so it reads as a full
bullet-point sentence and preserves the PR link.

In `@packages/core/src/logger.ts`:
- Around line 333-343: The current createProxyLogger function ignores a provided
custom logger because the condition (debug || Boolean(config?.logger)) returns
true when config.logger exists and causes a default syslog logger to be created;
change the branch logic so the default syslog logger is only created when debug
is true or no custom logger is provided (e.g. use if (debug || !config?.logger)
{ return createLogger({ level: (level as LogLevel) ?? "debug", log:
createSyslogMessage }) } else return typeof config?.logger === "object" ?
createLogger(config.logger) : undefined), keeping references to
createProxyLogger, AuthConfig, createLogger, createSyslogMessage and
config?.logger to locate the code.

ℹ️ Review info

Configuration used: defaults

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between d8160ed and a5c4dc0.

📒 Files selected for processing (7)
  • docs/src/content/docs/api-reference/core.mdx
  • docs/src/content/docs/configuration/env.mdx
  • packages/core/CHANGELOG.md
  • packages/core/src/env.ts
  • packages/core/src/index.ts
  • packages/core/src/logger.ts
  • packages/core/test/env.test.ts
🚧 Files skipped from review as they are similar to previous changes (2)
  • packages/core/src/env.ts
  • packages/core/test/env.test.ts

@halvaradop halvaradop merged commit e50f869 into master Mar 1, 2026
8 of 10 checks passed
@halvaradop halvaradop deleted the feat/read-config-from-envs branch March 1, 2026 21:11
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

feature New functionality refactor Refactor without changing behavior

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant