Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion apps/docs/docs/auth/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,8 @@ npx holo install auth --workos
npx holo install auth --clerk
```

When `auth` is installed, `session` is installed with it automatically because session-backed auth depends on it.
When `auth` is installed, `session` and `security` are installed with it automatically because session-backed auth
depends on cookies, CSRF/rate-limit defaults, and CORS support for separate frontend/API deployments.

## Authentication Quickstart

Expand Down
31 changes: 28 additions & 3 deletions apps/docs/docs/security.md
Original file line number Diff line number Diff line change
@@ -1,19 +1,20 @@
# Security

`@holo-js/security` is the optional package for CSRF protection and rate limiting.
`@holo-js/security` is the optional package for CSRF protection, CORS, and rate limiting.

Install it only when the app needs browser form protection or named request throttles:

```bash
npx holo install security
```

That writes `config/security.ts`, adds `@holo-js/security`, and lets core boot the package lazily only when
That writes `config/security.ts` and `config/cors.ts`, adds `@holo-js/security`, and lets core boot the package lazily only when
it is installed.

## What the package owns

- CSRF token helpers for server-rendered forms and browser clients
- CORS headers for separate frontend/API deployments
- request protection for plain routes with `protect(...)`
- named rate limiters with `limit.perMinute(...)` and `limit.perHour(...)`
- low-level `rateLimit(...)` and `clearRateLimit(...)` helpers
Expand All @@ -24,7 +25,8 @@ it is installed.

## Configuration

`config/security.ts` is the single config entrypoint:
Security uses separate config entrypoints: cross-origin rules live in `config/cors.ts`, while CSRF and rate limit settings live in
`config/security.ts`:

```ts
import { defineSecurityConfig, limit } from '@holo-js/security'
Expand Down Expand Up @@ -57,6 +59,26 @@ export default defineSecurityConfig({
})
```

`config/cors.ts` controls cross-origin API access:

Comment thread
coderabbitai[bot] marked this conversation as resolved.
```ts
import { defineCorsConfig, env } from '@holo-js/config'

export default defineCorsConfig({
paths: ['/api/*', '/broadcasting/auth'],
origins: [
env('FRONTEND_URL', 'http://localhost:3000'),
],
methods: ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS'],
headers: ['Content-Type', 'Authorization', 'X-CSRF-TOKEN', 'X-Requested-With'],
credentials: true,
maxAge: 7200,
statefulDomains: [
env('FRONTEND_DOMAIN', 'localhost:3000'),
],
})
```

When `rateLimit.driver` is `redis`, `rateLimit.redis.connection` points to a named connection in
`config/redis.ts`.

Expand Down Expand Up @@ -96,6 +118,9 @@ Holo-JS falls back to standalone `host`, which may also be a Unix socket path.
- `csrf.header` is the header accepted for XHR and `fetch` requests.
- `csrf.cookie` stores the signed token cookie that `useForm(..., { csrf: true })` reads on the client.
- `csrf.except` skips CSRF verification for matching paths such as webhooks.
- `cors.origins` lists frontend origins allowed to call the API.
- `cors.credentials` must be true when the frontend uses cookie-backed auth with `fetch(..., { credentials: 'include' })`.
- `cors.statefulDomains` lists browser hosts that should be treated as first-party cookie clients.
- `rateLimit.driver` must be `memory`, `file`, or `redis`.
- `rateLimit.redis.connection` must reference a named shared Redis connection when `rateLimit.driver` is `redis`.
- `rateLimit.limiters` is the named limiter registry used by `validate(...)`, `protect(...)`, and
Expand Down
7 changes: 6 additions & 1 deletion packages/cli/src/cli.ts
Original file line number Diff line number Diff line change
Expand Up @@ -574,6 +574,8 @@ export function createInternalCommands(
const changed = result.updatedPackageJson
|| result.createdAuthConfig
|| result.createdSessionConfig
|| result.createdSecurityConfig
|| result.createdCorsConfig
|| result.createdUserModel
|| result.createdMigrationFiles.length > 0
|| result.updatedEnv
Expand All @@ -583,6 +585,8 @@ export function createInternalCommands(
if (result.updatedPackageJson) writeLine(context.stdout, ' - updated package.json')
if (result.createdAuthConfig) writeLine(context.stdout, ' - created config/auth.ts')
if (result.createdSessionConfig) writeLine(context.stdout, ' - created config/session.ts')
if (result.createdSecurityConfig) writeLine(context.stdout, ' - created config/security.ts')
if (result.createdCorsConfig) writeLine(context.stdout, ' - created config/cors.ts')
if (result.createdUserModel) writeLine(context.stdout, ' - created server/models/User.ts')
if (result.updatedEnv) writeLine(context.stdout, ' - updated .env')
if (result.updatedEnvExample) writeLine(context.stdout, ' - updated .env.example')
Expand Down Expand Up @@ -669,11 +673,12 @@ export function createInternalCommands(
if (target === 'security') {
const { installSecurityIntoProject } = await loadProjectScaffoldModule()
const result = await installSecurityIntoProject(context.projectRoot)
const changed = result.updatedPackageJson || result.createdSecurityConfig
const changed = result.updatedPackageJson || result.createdSecurityConfig || result.createdCorsConfig

writeLine(context.stdout, changed ? 'Installed security support.' : 'Security support is already installed.')
if (result.updatedPackageJson) writeLine(context.stdout, ' - updated package.json')
if (result.createdSecurityConfig) writeLine(context.stdout, ' - created config/security.ts')
if (result.createdCorsConfig) writeLine(context.stdout, ' - created config/cors.ts')
return
}

Expand Down
2 changes: 2 additions & 0 deletions packages/cli/src/project.ts
Original file line number Diff line number Diff line change
Expand Up @@ -103,6 +103,7 @@ import {
renderMediaConfig,
renderMailConfig,
renderCacheConfig,
renderCorsConfig,
renderSecurityConfig,
renderQueueConfig,
renderCacheEnvFiles,
Expand Down Expand Up @@ -232,6 +233,7 @@ export const projectInternals = {
renderScaffoldTsconfig,
renderVSCodeSettings,
renderCacheConfig,
renderCorsConfig,
renderQueueConfig,
renderCacheEnvFiles,
renderEnvFileContents,
Expand Down
132 changes: 127 additions & 5 deletions packages/cli/src/project/config.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,14 @@
import { mkdir, writeFile } from 'node:fs/promises'
import { createHash } from 'node:crypto'
import { mkdir, readFile, writeFile } from 'node:fs/promises'
import { dirname, extname, join, resolve } from 'node:path'
import { pathToFileURL } from 'node:url'
import {
loadConfigDirectory,
holoAppDefaults,
holoDatabaseDefaults,
loadEnvironment,
normalizeAppConfig,
normalizeDatabaseConfig,
} from '@holo-js/config'
import {
DEFAULT_HOLO_PROJECT_PATHS,
Expand All @@ -24,6 +29,117 @@ import {
resolveFirstExistingPath,
} from './runtime'

function isObject(value: unknown): value is Record<string, unknown> {
return !!value && typeof value === 'object' && !Array.isArray(value)
}

function resolveConfigExport<TConfig extends object>(moduleValue: unknown): TConfig {
if (isObject(moduleValue) && isObject(moduleValue.default)) {
return moduleValue.default as TConfig
}

if (isObject(moduleValue) && isObject(moduleValue.config)) {
return moduleValue.config as TConfig
}

if (isObject(moduleValue) && ('default' in moduleValue || 'config' in moduleValue)) {
return {} as TConfig
}

if (isObject(moduleValue)) {
return moduleValue as TConfig
}

return {} as TConfig
}

type ProjectConfigImportState = {
readonly hash: string
readonly nonce: number
}

const projectConfigImportStates = new Map<string, ProjectConfigImportState>()
let projectConfigImportLock = Promise.resolve()
let projectConfigImportNonce = 0

async function withProjectConfigImportLock<TValue>(callback: () => Promise<TValue>): Promise<TValue> {
const previousLock = projectConfigImportLock
let releaseLock = (): void => {}
projectConfigImportLock = new Promise<void>((resolveLock) => {
releaseLock = resolveLock
})

await previousLock

try {
return await callback()
} finally {
releaseLock()
}
}

function hashProjectConfigImportInputs(
fileContents: string,
environmentValues: Readonly<Record<string, string>>,
): string {
const hash = createHash('sha256').update(fileContents).update('\0')
const keys = Object.keys(environmentValues).sort()
for (const key of keys) {
hash.update(key).update('\0').update(environmentValues[key] ?? '').update('\0')
}

return hash.digest('hex').slice(0, 16)
}

async function resolveProjectConfigImportUrl(
filePath: string,
environmentValues: Readonly<Record<string, string>>,
): Promise<string> {
const fileUrl = pathToFileURL(filePath).href
const hash = hashProjectConfigImportInputs(await readFile(filePath, 'utf8'), environmentValues)
const previous = projectConfigImportStates.get(filePath)
if (previous?.hash === hash) {
return `${fileUrl}?t=${previous.nonce}`
}

projectConfigImportNonce += 1
const next = {
hash,
nonce: projectConfigImportNonce,
}
projectConfigImportStates.set(filePath, next)

return `${fileUrl}?t=${next.nonce}`
}

async function importProjectConfigFile<TConfig extends object>(
filePath: string,
environmentValues: Readonly<Record<string, string>>,
): Promise<TConfig> {
return withProjectConfigImportLock(async () => {
const previousEnvEntries = new Map<string, string | undefined>()
const importUrl = await resolveProjectConfigImportUrl(filePath, environmentValues)

try {
for (const [key, value] of Object.entries(environmentValues)) {
previousEnvEntries.set(key, process.env[key])
process.env[key] = value
}

return resolveConfigExport<TConfig>(await import(importUrl))
} finally {
for (const [key, value] of previousEnvEntries) {
if (typeof value === 'string') {
process.env[key] = value
continue
}

Reflect.deleteProperty(process.env, key)
}
}
})
}
Comment thread
coderabbitai[bot] marked this conversation as resolved.

export async function loadProjectConfig(
projectRoot: string,
options: { required?: boolean } = {},
Expand All @@ -39,12 +155,18 @@ export async function loadProjectConfig(
}
}

const loaded = await loadConfigDirectory(projectRoot, {
const databaseConfigPath = await resolveFirstExistingPath(projectRoot, DATABASE_CONFIG_FILE_NAMES)
const environment = await loadEnvironment({
cwd: projectRoot,
processEnv: process.env,
})
const app = normalizeAppConfig(await importProjectConfigFile(appConfigPath, environment.values))
const database = normalizeDatabaseConfig(databaseConfigPath
? await importProjectConfigFile(databaseConfigPath, environment.values)
: undefined)
const baseConfig = normalizeHoloProjectConfig({
paths: loaded.app.paths,
database: loaded.database,
paths: app.paths,
database,
})
const registry = await loadGeneratedProjectRegistry(projectRoot)

Expand All @@ -56,7 +178,7 @@ export async function loadProjectConfig(
models: registry.models.map(entry => entry.sourcePath),
migrations: registry.migrations.map(entry => entry.sourcePath),
seeders: registry.seeders.map(entry => entry.sourcePath),
database: loaded.database,
database,
})
: baseConfig,
}
Expand Down
2 changes: 1 addition & 1 deletion packages/cli/src/project/registry.ts
Original file line number Diff line number Diff line change
Expand Up @@ -681,7 +681,7 @@ function renderGeneratedConfigTypes(
projectRoot: string,
entries: readonly { configName: string, filePath: string }[],
): string {
const customEntries = entries.filter(entry => !['app', 'database', 'redis', 'cache', 'storage', 'queue', 'broadcast', 'notifications', 'mail', 'media', 'session', 'security', 'auth'].includes(entry.configName))
const customEntries = entries.filter(entry => !['app', 'database', 'redis', 'cache', 'cors', 'storage', 'queue', 'broadcast', 'notifications', 'mail', 'media', 'session', 'security', 'auth'].includes(entry.configName))

if (customEntries.length === 0) {
return [
Expand Down
Loading