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
28 changes: 28 additions & 0 deletions docs/guide/server-routing.md
Original file line number Diff line number Diff line change
Expand Up @@ -191,6 +191,34 @@ export default defineMiddleware(async (c, next) => {

`defineMiddleware` uses Hono middleware semantics: `(c, next) => Promise<void> | 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
Expand Down
45 changes: 44 additions & 1 deletion docs/reference/api.md
Original file line number Diff line number Diff line change
Expand Up @@ -118,6 +118,49 @@ export default defineMiddleware(async (c, next) => {
function defineMiddleware(handler: MiddlewareHandler<CloudEnv>): MiddlewareHandler<CloudEnv>;
```

### `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<CloudEnv>;
```

### `defineScheduled(handler)`

Wraps a Cloudflare [Scheduled handler](https://developers.cloudflare.com/workers/runtime-apis/handlers/scheduled/) with type inference.
Expand Down Expand Up @@ -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` |
Expand Down
29 changes: 15 additions & 14 deletions packages/void/AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -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<V, R>` 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.

Expand Down Expand Up @@ -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).

Expand Down
1 change: 1 addition & 0 deletions packages/void/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,7 @@ Runtime helpers include:

- `defineHandler`
- `defineMiddleware`
- `basicAuth`
- `defineScheduled`
- `defineQueue`
- `void/db`
Expand Down
2 changes: 2 additions & 0 deletions packages/void/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1666,6 +1666,7 @@ export function voidPlugin(options?: {
export {
defineHandler,
defineMiddleware,
basicAuth,
defineScheduled,
defineRender,
defineHead,
Expand All @@ -1676,6 +1677,7 @@ export type {
CloudContext,
CloudContextVariables,
CloudEnv,
BasicAuthOptions,
RenderAssetTags,
TypedHandler,
TypedQueueHandler,
Expand Down
105 changes: 105 additions & 0 deletions packages/void/src/runtime/handler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -122,6 +122,18 @@ export type CloudContext = Context<CloudEnv>;

type HandlerFn = (c: CloudContext) => unknown | Promise<unknown>;
type MiddlewareFn = MiddlewareHandler<CloudEnv>;
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 = {
Expand Down Expand Up @@ -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<CloudEnv> {
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.
Expand Down
18 changes: 5 additions & 13 deletions packages/void/test/integration/spa-middleware-auth.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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',
});
`;

Expand Down
Loading