diff --git a/docs/guide/server-routing.md b/docs/guide/server-routing.md index 23cd96cc1..f44b17aa7 100644 --- a/docs/guide/server-routing.md +++ b/docs/guide/server-routing.md @@ -191,6 +191,34 @@ export default defineMiddleware(async (c, next) => { `defineMiddleware` uses Hono middleware semantics: `(c, next) => Promise | void`. +For a temporary full-site gate, use the built-in `basicAuth()` middleware with credentials from `void/env`. Void internal endpoints under `/__void` are excluded automatically so deploy migrations and dev tooling continue to work. Wrap `void/env` reads in functions so they are resolved per request after Void has bound the runtime env. + +```ts +// env.ts +import { defineEnv, string } from 'void/env'; + +export default defineEnv({ + BASIC_AUTH_USERNAME: string(), + BASIC_AUTH_PASSWORD: string(), +}); +``` + +```ts +// middleware/01.basic-auth.ts +import { basicAuth } from 'void'; +import { env } from 'void/env'; + +export default basicAuth({ + username: () => env.BASIC_AUTH_USERNAME, + password: () => env.BASIC_AUTH_PASSWORD, + realm: 'Preview', +}); +``` + +Set `BASIC_AUTH_USERNAME` and `BASIC_AUTH_PASSWORD` as local environment variables for development and production secrets before deploy. + +For app-specific bypasses such as health checks or public webhooks, compose that logic in your own middleware before calling `basicAuth()`. + Middleware can set typed context variables using `c.set()`. Augment the `CloudContextVariables` interface so downstream handlers get full type safety: ```ts diff --git a/docs/reference/api.md b/docs/reference/api.md index 38074e88a..3e12e43ca 100644 --- a/docs/reference/api.md +++ b/docs/reference/api.md @@ -118,6 +118,49 @@ export default defineMiddleware(async (c, next) => { function defineMiddleware(handler: MiddlewareHandler): MiddlewareHandler; ``` +### `basicAuth(options)` + +Built-in Basic authentication middleware for temporary site gates and pre-launch protection. Use it from `middleware/` with credentials from `void/env` to protect the whole app, or pass it to `defineHandler()` for a single route. + +Void internal endpoints under `/__void` are always excluded so deploy-time migrations, prerendering, cron/queue dispatch, and remote binding helpers still reach Void's own internal-token checks. + +When credentials come from `void/env`, wrap the reads in functions so they are resolved per request after Void has bound the runtime env. + +For app-specific bypasses such as health checks or public webhooks, compose that logic in your own middleware before calling `basicAuth()`. + +```ts +// env.ts +import { defineEnv, string } from 'void/env'; + +export default defineEnv({ + BASIC_AUTH_USERNAME: string(), + BASIC_AUTH_PASSWORD: string(), +}); +``` + +```ts +// middleware/01.basic-auth.ts +import { basicAuth } from 'void'; +import { env } from 'void/env'; + +export default basicAuth({ + username: () => env.BASIC_AUTH_USERNAME, + password: () => env.BASIC_AUTH_PASSWORD, + realm: 'Preview', +}); +``` + +**Signature:** + +```ts +function basicAuth(options: { + username: string | (() => string); + password: string | (() => string); + realm?: string | (() => string); + message?: string | (() => string); +}): MiddlewareHandler; +``` + ### `defineScheduled(handler)` Wraps a Cloudflare [Scheduled handler](https://developers.cloudflare.com/workers/runtime-apis/handlers/scheduled/) with type inference. @@ -1105,7 +1148,7 @@ This table lists app-facing imports. Exported implementation subpaths such as `v | Import path | Contents | | ------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | `void` | `voidPlugin`, handler/type re-exports, `defer`, `Deferred`, `DeferredState`, `InferProps`, `HeadDescriptor` | -| `void/handler` | `defineHandler`, `defineMiddleware`, `defineScheduled`, `defineQueue`, `defineRender`, `defineHead`, types | +| `void/handler` | `defineHandler`, `defineMiddleware`, `basicAuth`, `defineScheduled`, `defineQueue`, `defineRender`, `defineHead`, types | | `void/auth` | `defineAuth`, `getUser`, `getSession`, `requireAuth`, `AuthUser`, `AuthSession`, `AuthState` | | `void/client` | `fetch`, `fetchStream`, `FetchError`, `auth`, `createAuthClient`, `AuthUser`, `AuthSession`, `AuthState` | | `void/client/{framework}` | Same as `void/client`, with framework-specific Better Auth clients for `react`, `vue`, `svelte`, and `solid` | diff --git a/packages/void/AGENTS.md b/packages/void/AGENTS.md index bdde3ea6c..cadae8d03 100644 --- a/packages/void/AGENTS.md +++ b/packages/void/AGENTS.md @@ -23,6 +23,7 @@ Non-CF targets disable CF-only bindings (`void/db`, `void/kv`, `void/auth`, `voi - `defineHandler(fn)` — wraps a route handler `(c: CloudContext) => R`, returns `TypedHandler<{}, R>` - `defineHandler.withValidator(validators)(fn)` — validates body/query/params via Standard Schema before calling handler, returns `TypedHandler` with phantom types for codegen - `defineMiddleware(fn)` — wraps Hono middleware `(c, next) => void` +- `basicAuth(options)` — built-in Basic Auth middleware for temporary site gates; excludes Void internals under `/__void` - Handlers can return plain objects/strings (auto-converted via `convertReturnValue`) or use Hono's `c.json()` / `c.text()` directly. - Route files use **named HTTP method exports** (`export const GET`, `export const POST`, etc.) — one file per path, multiple methods per file. @@ -90,20 +91,20 @@ src/ ### Package Exports -| Subpath | What | -| ---------------- | ----------------------------------------------------------------------------------------------------------------------- | -| `void` | `voidPlugin()` named export + `defineHandler` + `defineMiddleware` + `defineHead` + `defineQueue` + `CloudContext` type | -| `void/handler` | `defineHandler()`, `defineHandler.withValidator()`, `defineMiddleware()`, `defineHead()`, types | -| `void/response` | `convertReturnValue()` | -| `void/validator` | `runValidation()`, `ValidatorSlots`, `HandlerInput` types | -| `void/routes` | Empty `RouteMap` + `WebSocketRouteMap` stubs (augmented by generated `routes.d.ts`) | -| `void/client` | Typed `fetch()` client + `fetchStream()` SSE consumer + `FetchError` | -| `void/ws` | `defineRoom()`, `defineWebSocket()`, typed `connect()`, and WebSocket context types | -| `void/db` | `db` Drizzle D1 instance (auto-wired with user schema) + `createDb()` for custom D1 bindings | -| `void/queues` | `queues` typed proxy + `QueueMap` stub interface (augmented by generated `queues.d.ts`) | -| `void/ai` | `ai` proxy — Cloudflare-native `ai.run()`/`ai.stream()`, provider-native `ai.provider().fetch()`, `ai.models()` | -| `void/log` | `logger.error/warn/info(msg, fields?)` — emits stringified JSON to `console.*` so Cloudflare Tail captures level + msg | -| `void/env` | `defineEnv()`, typed `env` proxy, built-in schema helpers (`string`, `number`, `oneOf`, …) + global Cloudflare types | +| Subpath | What | +| ---------------- | ------------------------------------------------------------------------------------------------------------------------------------- | +| `void` | `voidPlugin()` named export + `defineHandler` + `defineMiddleware` + `basicAuth` + `defineHead` + `defineQueue` + `CloudContext` type | +| `void/handler` | `defineHandler()`, `defineHandler.withValidator()`, `defineMiddleware()`, `basicAuth()`, `defineHead()`, types | +| `void/response` | `convertReturnValue()` | +| `void/validator` | `runValidation()`, `ValidatorSlots`, `HandlerInput` types | +| `void/routes` | Empty `RouteMap` + `WebSocketRouteMap` stubs (augmented by generated `routes.d.ts`) | +| `void/client` | Typed `fetch()` client + `fetchStream()` SSE consumer + `FetchError` | +| `void/ws` | `defineRoom()`, `defineWebSocket()`, typed `connect()`, and WebSocket context types | +| `void/db` | `db` Drizzle D1 instance (auto-wired with user schema) + `createDb()` for custom D1 bindings | +| `void/queues` | `queues` typed proxy + `QueueMap` stub interface (augmented by generated `queues.d.ts`) | +| `void/ai` | `ai` proxy — `ai.run()`, `ai.stream()`, `ai.models()` with auto-detected backend (service binding / HTTPS / direct) | +| `void/log` | `logger.error/warn/info(msg, fields?)` — emits stringified JSON to `console.*` so Cloudflare Tail captures level + msg | +| `void/env` | `defineEnv()`, typed `env` proxy, built-in schema helpers (`string`, `number`, `oneOf`, …) + global Cloudflare types | The CLI binary is at `dist/cli/cli.mjs` (declared in `bin` field of package.json). diff --git a/packages/void/README.md b/packages/void/README.md index 7769409ff..7e3882c2d 100644 --- a/packages/void/README.md +++ b/packages/void/README.md @@ -48,6 +48,7 @@ Runtime helpers include: - `defineHandler` - `defineMiddleware` +- `basicAuth` - `defineScheduled` - `defineQueue` - `void/db` diff --git a/packages/void/src/index.ts b/packages/void/src/index.ts index 58ce0ada2..d83274397 100644 --- a/packages/void/src/index.ts +++ b/packages/void/src/index.ts @@ -1666,6 +1666,7 @@ export function voidPlugin(options?: { export { defineHandler, defineMiddleware, + basicAuth, defineScheduled, defineRender, defineHead, @@ -1676,6 +1677,7 @@ export type { CloudContext, CloudContextVariables, CloudEnv, + BasicAuthOptions, RenderAssetTags, TypedHandler, TypedQueueHandler, diff --git a/packages/void/src/runtime/handler.ts b/packages/void/src/runtime/handler.ts index e3f250c19..055ae95c7 100644 --- a/packages/void/src/runtime/handler.ts +++ b/packages/void/src/runtime/handler.ts @@ -122,6 +122,18 @@ export type CloudContext = Context; type HandlerFn = (c: CloudContext) => unknown | Promise; type MiddlewareFn = MiddlewareHandler; +type BasicAuthOptionValue = string | (() => string); + +export interface BasicAuthOptions { + /** Username required by the Basic auth challenge. */ + username: BasicAuthOptionValue; + /** Password required by the Basic auth challenge. */ + password: BasicAuthOptionValue; + /** Browser prompt realm. Defaults to "Restricted". */ + realm?: BasicAuthOptionValue; + /** Response body for failed authentication. Defaults to "Authentication required". */ + message?: BasicAuthOptionValue; +} /** Pre-rendered asset tags injected by the SSR build. */ export type RenderAssetTags = { @@ -285,6 +297,99 @@ export function defineMiddleware( return handler; } +const basicAuthEncoder = new TextEncoder(); +const basicAuthDecoder = new TextDecoder('utf-8', { fatal: true }); + +function parseBasicAuthHeader(authorization: string | null) { + if (!authorization?.toLowerCase().startsWith('basic ')) { + return null; + } + + try { + const encoded = authorization.slice(6).trim(); + const binary = atob(encoded); + const bytes = Uint8Array.from(binary, (char) => char.charCodeAt(0)); + const decoded = basicAuthDecoder.decode(bytes); + const separator = decoded.indexOf(':'); + if (separator === -1) { + return null; + } + + return { + username: decoded.slice(0, separator), + password: decoded.slice(separator + 1), + }; + } catch { + return null; + } +} + +function timingSafeStringEqual(actual: string, expected: string) { + const actualBytes = basicAuthEncoder.encode(actual); + const expectedBytes = basicAuthEncoder.encode(expected); + let difference = actualBytes.length ^ expectedBytes.length; + + for (let i = 0; i < expectedBytes.length; i++) { + difference |= (actualBytes[i] ?? 0) ^ expectedBytes[i]; + } + + return difference === 0; +} + +function isVoidInternalPath(pathname: string) { + return pathname === '/__void' || pathname.startsWith('/__void/'); +} + +function basicAuthChallenge(realm: string, message: string) { + const escapedRealm = realm.replace(/["\\]/g, '\\$&'); + + return new Response(message, { + status: 401, + headers: { + 'Cache-Control': 'no-store', + 'WWW-Authenticate': `Basic realm="${escapedRealm}", charset="UTF-8"`, + }, + }); +} + +function resolveBasicAuthOption(value: BasicAuthOptionValue | undefined, fallback: string): string { + if (value === undefined) { + return fallback; + } + return typeof value === 'function' ? value() : value; +} + +/** + * Create Basic authentication middleware for temporary site gates and + * pre-launch protection. + * + * Void internal endpoints under `/__void` are always excluded so deploy-time + * migrations, prerendering, cron/queue dispatch, and remote binding helpers + * continue to reach Void's own internal-token checks. + */ +export function basicAuth(options: BasicAuthOptions): MiddlewareHandler { + return defineMiddleware(async (c, next) => { + if (isVoidInternalPath(c.req.path)) { + await next(); + return; + } + + const username = resolveBasicAuthOption(options.username, ''); + const password = resolveBasicAuthOption(options.password, ''); + const credentials = parseBasicAuthHeader(c.req.raw.headers.get('Authorization')); + const usernameMatches = credentials && timingSafeStringEqual(credentials.username, username); + const passwordMatches = credentials && timingSafeStringEqual(credentials.password, password); + + if (!usernameMatches || !passwordMatches) { + const realm = resolveBasicAuthOption(options.realm, 'Restricted'); + const message = resolveBasicAuthOption(options.message, 'Authentication required'); + return basicAuthChallenge(realm, message); + } + + await next(); + }); +} + /** * Identity function that provides type inference for scheduled jobs. * At runtime it simply returns the function passed to it. diff --git a/packages/void/test/integration/spa-middleware-auth.test.ts b/packages/void/test/integration/spa-middleware-auth.test.ts index 6c7156d54..3366e1868 100644 --- a/packages/void/test/integration/spa-middleware-auth.test.ts +++ b/packages/void/test/integration/spa-middleware-auth.test.ts @@ -18,20 +18,12 @@ const WRANGLER_CONFIG = join(PLAYGROUND, 'wrangler.jsonc'); const DIST = join(PLAYGROUND, 'dist'); const AUTH_HEADER = 'Basic Z3Vlc3Q6d2VkZGluZw=='; -const middlewareSource = `import { defineMiddleware } from 'void'; +const middlewareSource = `import { basicAuth } from 'void'; -export default defineMiddleware(async (c, next) => { - if (c.req.raw.headers.get('Authorization') !== '${AUTH_HEADER}') { - return new Response('Authentication required', { - status: 401, - headers: { - 'Cache-Control': 'no-store', - 'WWW-Authenticate': 'Basic realm="Preview", charset="UTF-8"', - }, - }); - } - - await next(); +export default basicAuth({ + username: 'guest', + password: 'wedding', + realm: 'Preview', }); `; diff --git a/packages/void/test/unit/basic-auth.test.ts b/packages/void/test/unit/basic-auth.test.ts new file mode 100644 index 000000000..092e5e50e --- /dev/null +++ b/packages/void/test/unit/basic-auth.test.ts @@ -0,0 +1,141 @@ +import { Hono } from 'hono'; +import { describe, expect, it } from 'vite-plus/test'; +import { env } from '../../src/runtime/env-public.ts'; +import { withRuntimeEnv } from '../../src/runtime/env.ts'; +import { basicAuth, type BasicAuthOptions, type CloudEnv } from '../../src/runtime/handler.ts'; + +function authorization(value: string) { + const bytes = new TextEncoder().encode(value); + const binary = Array.from(bytes, (byte) => String.fromCharCode(byte)).join(''); + return `Basic ${btoa(binary)}`; +} + +function createApp(options: BasicAuthOptions) { + const app = new Hono(); + + app.use('*', basicAuth(options)); + app.all('*', (c) => c.text('ok')); + + return app; +} + +describe('basicAuth', () => { + it('challenges requests without credentials', async () => { + const app = createApp({ username: 'guest', password: 'wedding', realm: 'Preview' }); + + const res = await app.request('http://localhost/'); + + expect(res.status).toBe(401); + expect(res.headers.get('Cache-Control')).toBe('no-store'); + expect(res.headers.get('WWW-Authenticate')).toBe('Basic realm="Preview", charset="UTF-8"'); + expect(await res.text()).toBe('Authentication required'); + }); + + it('challenges malformed and incorrect credentials', async () => { + const app = createApp({ username: 'guest', password: 'wedding' }); + + const malformed = await app.request('http://localhost/', { + headers: { Authorization: 'Basic not-base64' }, + }); + const wrong = await app.request('http://localhost/', { + headers: { Authorization: authorization('guest:wrong') }, + }); + + expect(malformed.status).toBe(401); + expect(wrong.status).toBe(401); + }); + + it('allows matching credentials', async () => { + const app = createApp({ username: 'guest', password: 'wedding' }); + + const res = await app.request('http://localhost/', { + headers: { Authorization: authorization('guest:wedding') }, + }); + + expect(res.status).toBe(200); + expect(await res.text()).toBe('ok'); + }); + + it('defers lazy env-backed credentials until request env is bound', async () => { + const options: BasicAuthOptions = { + username: () => env.BASIC_AUTH_USERNAME as string, + password: () => env.BASIC_AUTH_PASSWORD as string, + realm: () => env.BASIC_AUTH_REALM as string, + }; + + expect(() => createApp(options)).not.toThrow(); + + const app = createApp(options); + const unauthenticated = await withRuntimeEnv( + { + BASIC_AUTH_USERNAME: 'guest', + BASIC_AUTH_PASSWORD: 'wedding', + BASIC_AUTH_REALM: 'Preview', + }, + () => app.request('http://localhost/'), + ); + expect(unauthenticated.status).toBe(401); + expect(unauthenticated.headers.get('WWW-Authenticate')).toBe( + 'Basic realm="Preview", charset="UTF-8"', + ); + + const authenticated = await withRuntimeEnv( + { + BASIC_AUTH_USERNAME: 'guest', + BASIC_AUTH_PASSWORD: 'wedding', + BASIC_AUTH_REALM: 'Preview', + }, + () => + app.request('http://localhost/', { + headers: { Authorization: authorization('guest:wedding') }, + }), + ); + + expect(authenticated.status).toBe(200); + expect(await authenticated.text()).toBe('ok'); + }); + + it('supports UTF-8 credentials and colons in passwords', async () => { + const app = createApp({ username: 'gåst', password: 'wed:ding' }); + + const res = await app.request('http://localhost/', { + headers: { Authorization: authorization('gåst:wed:ding') }, + }); + + expect(res.status).toBe(200); + expect(await res.text()).toBe('ok'); + }); + + it('escapes the realm in the challenge header', async () => { + const app = createApp({ + username: 'guest', + password: 'wedding', + realm: 'staging "preview"', + }); + + const res = await app.request('http://localhost/'); + + expect(res.headers.get('WWW-Authenticate')).toBe( + 'Basic realm="staging \\"preview\\"", charset="UTF-8"', + ); + }); + + it('skips Void internal endpoints', async () => { + const app = createApp({ username: 'guest', password: 'wedding' }); + + const res = await app.request('http://localhost/__void/migrate', { method: 'POST' }); + + expect(res.status).toBe(200); + expect(await res.text()).toBe('ok'); + }); + + it('does not trust x-void-internal on public paths', async () => { + const app = createApp({ username: 'guest', password: 'wedding' }); + + const res = await app.request('http://localhost/', { + headers: { 'x-void-internal': 'spoofed' }, + }); + + expect(res.status).toBe(401); + }); +});