Skip to content

Commit 9c2cf3e

Browse files
committed
Serve development Auth through each app without machine setup
Dex: roez7tvp (puzyggye) Remove automatic hosts, certificates, Caddy and fixed .syntax.test startup. Mount bounded same-origin developer sign-in/out and local HTTP/WebSocket routes, preserving exact cookies and individual Set-Cookie headers. Keep central Auth private on loopback and production behavior unchanged. Handle host-only HTTP/HTTPS cookie profiles, canceled mutations, refused or incomplete upgrades, malformed session answers and sanitized failures. Keep Docker safety/data and legacy option compatibility without setup. Verification: pnpm test 89/89 (actual built Auth/temp D1/gateway included), pnpm check 0 errors/0 warnings, pnpm lint, fresh frozen install with an isolated store and clean checks, independent security review/fix/confirm. Chrome 154: localhost and custom TLS-terminating test proxy sign-in/out, relative path/query return, plain/secure HttpOnly host cookies; actual failure and sign-in layouts at 1280x800 and 375x812 without overflow. No machine DNS/trust/proxy changes, paid calls, or production deployment. Remote mini consumer/HMR verification follows the consumer tasks.
1 parent cae82f7 commit 9c2cf3e

49 files changed

Lines changed: 4930 additions & 5857 deletions

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

‎CONSUMING_AUTH.md‎

Lines changed: 190 additions & 149 deletions
Large diffs are not rendered by default.

‎README.md‎

Lines changed: 42 additions & 46 deletions
Original file line numberDiff line numberDiff line change
@@ -93,21 +93,29 @@ pnpm dev
9393
D1, and serves `http://localhost:37960`. `pnpm preview` does the same with a production build.
9494
Both run through `scripts/local_server.js`: however they stop, they stop every process they
9595
started and start the container again, so other Syntax apps keep signing in. Neither needs
96-
secrets: the Cloudflare adapter reads the committed `local` Wrangler environment, which has a
97-
loopback URL, no shared cookie domain, and a local-only D1 database under the ignored `.wrangler/`
98-
directory. In that mode Syntax Auth replaces GitHub with a one-click local developer account (user
99-
ID `local-developer`) and answers only `localhost` and `auth.syntax.test`, the local HTTPS name
100-
that apps on `https://syntax.test` and `https://*.syntax.test` send browsers to. On
101-
`auth.syntax.test`, and on app servers' `localhost` calls that forward its cookie, sessions use the
102-
shared `.syntax.test` cookie described in `CONSUMING_AUTH.md`. Under `vite dev` (`pnpm dev`) and
103-
`vite preview` (the Docker image), a plugin in `vite.config.ts` answers every request for any other
104-
host, including `/api/health` and built files, with a plain-text 403 naming the host and the two
105-
addresses to use, before Vite's own host check or file serving. `src/hooks.server.ts` refuses
106-
other hosts the same way for every page and auth route, so `wrangler dev` (`pnpm preview`), which
107-
skips the Vite plugin, still refuses them there; it serves `/api/health` and built files to any
108-
host. In local mode, a request from an origin local Syntax Auth doesn't trust gets Better Auth's
109-
403 `INVALID_ORIGIN` with a message naming the origin and the origins it accepts.
110-
Deploys use the top-level configuration and never enable local mode.
96+
secrets, and neither changes anything else on the machine: the Cloudflare adapter reads the
97+
committed `local` Wrangler environment, which has a loopback URL, no shared cookie domain, and a
98+
local-only D1 database under the ignored `.wrangler/` directory. In that mode Syntax Auth replaces
99+
GitHub with a one-click local developer account (user ID `local-developer`) and answers only
100+
`localhost`, `127.0.0.1`, and `[::1]`. Under `vite dev` (`pnpm dev`) and `vite preview` (the Docker
101+
image), a plugin in `vite.config.ts` answers every request for any other host, including
102+
`/api/health` and built files, with a plain-text 403 naming the host and the address to use,
103+
before Vite's own host check or file serving. `src/hooks.server.ts` refuses other hosts the same
104+
way for every page and auth route, so `wrangler dev` (`pnpm preview`), which skips the Vite
105+
plugin, still refuses them there; it serves `/api/health` and built files to any host. In local
106+
mode, a request from an origin local Syntax Auth doesn't trust gets Better Auth's 403
107+
`INVALID_ORIGIN` with a message naming the origin and the origins it accepts. Deploys use the
108+
top-level configuration and never enable local mode.
109+
110+
Browsers on other addresses (a LAN or Tailscale address, or a developer's own HTTPS name) never
111+
reach this server: they sign in through their app's development proxy from `packages/auth-local`,
112+
which calls it on loopback (see `CONSUMING_AUTH.md`, "Local development"). Per request,
113+
`src/hooks.server.ts` picks host-only cookies, `__Secure-` ones for a browser on https, from the
114+
session cookie's name or from the proxy's checked `x-syntax-auth-dev-origin` header
115+
(`src/lib/server/dev_proxy.ts`), and serves local `/api/auth/*` calls before its own session
116+
lookup, so a refreshed cookie always reaches the app server that asked. A local sign-out ends the
117+
session of each session cookie the request carries, plain and `__Secure-`, and a sign-in on http
118+
expires a `__Secure-` one that would be read before it (`src/lib/server/local_session_cookies.ts`).
111119

112120
Consumer apps run the same service from the private `ghcr.io/syntaxfm/auth-local` Docker image,
113121
which `.github/workflows/local-image.yml` publishes from `main`. The image serves a production
@@ -117,31 +125,19 @@ syntaxfm members, pulls it with their GitHub CLI login without storing the token
117125
`CONSUMING_AUTH.md`. The port lives in `packages/auth-local/container.js`,
118126
`vite.config.ts`, and the `local` and `oauth-registration` envs in `wrangler.jsonc`.
119127

120-
### https://auth.syntax.test
128+
No dev server and no `syntax-auth-local` opens Docker Desktop or OrbStack, whose first run and
129+
privileged helper can show dialogs, from an AI coding agent's shell (`CLAUDECODE` or
130+
`PI_CODING_AGENT` set), over SSH (`SSH_CONNECTION` or `SSH_TTY`), in CI (`CI`), under a test runner
131+
(`NODE_TEST_CONTEXT` or `VITEST`), or outside the Mac's desktop session; if Docker isn't running,
132+
the app runs signed out and says to start Docker, then restart dev. Each of those variables counts
133+
when set at all, even to an empty string, `0`, or `false`. When Docker already runs, the local
134+
Syntax Auth container still starts. `SYNTAX_DEV_SETUP_DIALOGS=allow` at the Mac's screen lets an
135+
agent's run open Docker too; it never works over SSH, in CI, or under a test runner.
121136

122-
On macOS, `pnpm dev` also makes `https://auth.syntax.test` answer, through the same plugin
123-
(`syntax_auth({ name: 'auth' })` in `vite.config.ts`), as every Syntax app's dev server does for
124-
its own name. `CONSUMING_AUTH.md` describes each step; the first start asks for your password once
125-
(for `/etc/hosts`) and one approval (to trust Caddy's local root), and later starts ask nothing.
126-
Syntax Auth's own dev server never redirects `localhost`, because apps call it there.
137+
### Undoing the old `.syntax.test` setup
127138

128-
Setup never shows a dialog from an AI coding agent's shell (`CLAUDECODE` or `PI_CODING_AGENT`
129-
set), over SSH (`SSH_CONNECTION` or `SSH_TTY`), in CI (`CI`), under a test runner
130-
(`NODE_TEST_CONTEXT` or `VITEST`), or outside the Mac's desktop session. It then changes nothing,
131-
says why on its first line, and prints each fix, such as running
132-
`node packages/auth-local/bin.js setup auth` in Terminal at the Mac's own screen. To let an
133-
agent's run show the dialogs while you watch the screen, start it with
134-
`SYNTAX_DEV_SETUP_DIALOGS=allow` (for example `SYNTAX_DEV_SETUP_DIALOGS=allow pnpm dev`); the
135-
switch never works over SSH, in CI, or under a test runner. Each of those variables counts when
136-
set at all, even to an empty string, `0`, or `false`.
137-
138-
In the same cases no dev server (with a name or without) and no `syntax-auth-local` opens
139-
Docker Desktop or OrbStack, whose first run and privileged helper can show dialogs; if Docker
140-
isn't running, the app runs signed out and says to start Docker, then restart dev. When Docker
141-
already runs, the local Syntax Auth container still starts. `SYNTAX_DEV_SETUP_DIALOGS=allow` at
142-
the Mac's screen lets it open Docker too.
143-
144-
Setup leaves everything in place when dev stops. To undo it:
139+
Earlier versions of the plugin set up `https://*.syntax.test` names on macOS. Nothing does that
140+
any more, and nothing removes what it added. To remove it by hand:
145141

146142
```sh
147143
# The routes and certificate policy, from whichever Caddy got them:
@@ -171,14 +167,14 @@ pnpm d1:migration:create <migration-name>
171167
```
172168

173169
`pnpm test` runs the unit tests, an integration test that builds the app, serves it with
174-
`vite preview` on a free port with a temporary D1, and signs in on `localhost` and
175-
`auth.syntax.test`, and the `packages/auth-local` tests (also `pnpm --dir packages/auth-local
176-
test`). Those run setup against stand-ins for Caddy, docker, the password dialog (the real hosts
177-
script edits a temporary file), and macOS's `security`. None of them touches port 37960, the
178-
container, `.wrangler/state`, `/etc/hosts`, the keychain, or ports 80, 443, and 2019. Under a test
179-
runner, setup shows no dialog, and the package refuses to run `osascript`, `sudo`, `open`,
180-
`docker`, or a `security` command that changes the keychain, so a test that misses a stand-in
181-
fails instead of acting on your Mac.
170+
`vite preview` on a free port with a temporary D1, and signs in on `localhost` and, through the
171+
real development proxy from `packages/auth-local` in front of it, as a browser on a LAN address
172+
and on an https name, and the `packages/auth-local` tests (also `pnpm --dir packages/auth-local
173+
test`). Those run the proxy against stand-ins for local Syntax Auth, routed servers, and broken
174+
upstreams on free loopback ports, and the container start against a stand-in `docker`. None of
175+
them touches port 37960, the container, or `.wrangler/state`. Under a test runner the package
176+
refuses to run `osascript`, `sudo`, `open`, `docker`, or a `security` command that changes the
177+
keychain, so a test that misses a stand-in fails instead of acting on your machine.
182178

183179
`drizzle.config.ts` is intentionally generation-only: it declares the SQLite schema and migrations
184180
directory without inventing a local SQLite URL or storing Cloudflare credentials. Apply migrations

‎packages/auth-local/app_origin.js‎

Lines changed: 262 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,262 @@
1+
// The rules every request through an app's own address must pass before the development proxy acts
2+
// on it (gateway.js): which hosts it answers, which origins count as the app's own, where a sign-in
3+
// may return to, and which paths may go to another local server.
4+
import { isIP } from 'node:net';
5+
6+
import { SYNTAX_AUTH_LOCAL_PORT } from './container.js';
7+
8+
/** Every path the development proxy answers itself starts with this. */
9+
export const MOUNT_PATH = '/__syntax_auth';
10+
/** Lists the extra browser-facing origins of this dev server, like `https://lab.example.dev`. */
11+
export const PUBLIC_ORIGINS_VARIABLE = 'SYNTAX_AUTH_PUBLIC_ORIGINS';
12+
const MAX_RETURN_LENGTH = 2_048;
13+
14+
/**
15+
* Whether text has a space or a control character (C0, DEL, or C1), which browsers strip from URLs.
16+
* @param {string} text
17+
*/
18+
export function has_space_or_control(text) {
19+
return [...text].some((char) => {
20+
const code = char.codePointAt(0) ?? 0;
21+
return code <= 0x20 || (code >= 0x7f && code <= 0x9f);
22+
});
23+
}
24+
25+
/**
26+
* The canonical form of a browser-facing origin (`http:` or `https:`, no credentials, path, query,
27+
* or fragment; a trailing "/" is allowed), or null.
28+
* @param {unknown} value
29+
*/
30+
export function canonical_origin(value) {
31+
if (typeof value !== 'string' || has_space_or_control(value) || value.includes('\\')) return null;
32+
try {
33+
const url = new URL(value);
34+
if (url.protocol !== 'http:' && url.protocol !== 'https:') return null;
35+
if (url.username || url.password || url.search || url.hash || url.pathname !== '/') return null;
36+
if (!/^(?:\[[0-9a-f:.]+\]|[a-z0-9._-]+)$/.test(url.hostname)) return null;
37+
const given = value.toLowerCase();
38+
if (given !== url.origin && given !== `${url.origin}/`) return null;
39+
return url.origin;
40+
} catch {
41+
return null;
42+
}
43+
}
44+
45+
/**
46+
* The plugin's `public_origins` option and the SYNTAX_AUTH_PUBLIC_ORIGINS variable (separated by
47+
* commas or spaces), as canonical origins. A value that isn't an origin stops the dev server.
48+
* @param {unknown} option
49+
* @param {NodeJS.ProcessEnv} env
50+
* @returns {string[]}
51+
*/
52+
export function read_public_origins(option, env) {
53+
if (option !== undefined && !Array.isArray(option)) {
54+
throw new Error('syntax_auth(): public_origins must be an array of origins.');
55+
}
56+
const from_env = (env[PUBLIC_ORIGINS_VARIABLE] ?? '').split(/[\s,]+/).filter(Boolean);
57+
/** @type {string[]} */
58+
const origins = [];
59+
for (const [value, source] of [
60+
...(option ?? []).map((value) => [value, 'syntax_auth(): public_origins']),
61+
...from_env.map((value) => [value, PUBLIC_ORIGINS_VARIABLE])
62+
]) {
63+
const origin = canonical_origin(value);
64+
if (!origin) {
65+
throw new Error(
66+
`${source} needs origins like https://lab.example.dev or http://box.example.ts.net:5173 (http or https, no path or credentials), not ${JSON.stringify(value)}.`
67+
);
68+
}
69+
if (!origins.includes(origin)) origins.push(origin);
70+
}
71+
return origins;
72+
}
73+
74+
/**
75+
* The parts of a Host header, or null when it is anything but a host and an optional port.
76+
* @param {unknown} host_header
77+
* @returns {{ host: string, hostname: string } | null}
78+
*/
79+
export function parse_host(host_header) {
80+
if (typeof host_header !== 'string' || host_header.length === 0 || host_header.length > 255) {
81+
return null;
82+
}
83+
if (!/^(?:\[[0-9A-Fa-f:.]+\]|[A-Za-z0-9._-]+)(?::\d{1,5})?$/.test(host_header)) return null;
84+
try {
85+
const url = new URL(`http://${host_header}`);
86+
return { host: url.host, hostname: url.hostname };
87+
} catch {
88+
return null;
89+
}
90+
}
91+
92+
/**
93+
* Vite's own host rule, applied again here so the proxy answers no other host even where Vite
94+
* doesn't check (an `https` dev server, or `allowedHosts: true`): IP addresses, `localhost` and
95+
* `*.localhost`, the entries of `server.allowedHosts` (a leading "." allows a domain and every name
96+
* under it), and the hosts of the public origins.
97+
* @param {unknown} host_header
98+
* @param {readonly string[]} allowed_hosts
99+
*/
100+
export function is_allowed_host(host_header, allowed_hosts) {
101+
const parsed = parse_host(host_header);
102+
if (!parsed) return false;
103+
const { hostname } = parsed;
104+
if (hostname.startsWith('[') || isIP(hostname) === 4) return true;
105+
if (hostname === 'localhost' || hostname.endsWith('.localhost')) return true;
106+
return allowed_hosts.some((entry) => {
107+
const allowed = entry.toLowerCase();
108+
if (allowed === hostname) return true;
109+
return allowed.startsWith('.') && (allowed.slice(1) === hostname || hostname.endsWith(allowed));
110+
});
111+
}
112+
113+
/**
114+
* The origins a browser on this request's host may have: the one this connection proves (https on
115+
* a TLS connection, otherwise http), plus each configured public origin with this very host. A
116+
* forwarded-protocol header is never read: a TLS proxy in front names its https origin in
117+
* SYNTAX_AUTH_PUBLIC_ORIGINS instead.
118+
* @param {string} host_header an allowed Host header
119+
* @param {{ encrypted: boolean, public_origins: readonly string[] }} options
120+
*/
121+
export function accepted_origins(host_header, { encrypted, public_origins }) {
122+
const own = new URL(`${encrypted ? 'https' : 'http'}://${host_header}`).origin;
123+
const configured = public_origins.filter(
124+
(origin) => new URL(`${new URL(origin).protocol}//${host_header}`).origin === origin
125+
);
126+
return [...new Set([own, ...configured])];
127+
}
128+
129+
/**
130+
* The browser's origin when a state-changing request comes from this app's own pages, or why not.
131+
* Browsers send Origin on every POST and WebSocket upgrade, so a missing one is refused.
132+
* @param {import('node:http').IncomingHttpHeaders} headers
133+
* @param {readonly string[]} accepted
134+
* @returns {{ origin: string } | { problem: string }}
135+
*/
136+
export function check_origin(headers, accepted) {
137+
const origin = headers.origin;
138+
if (!origin || origin === 'null') {
139+
return { problem: 'The request has no Origin header, so it may not come from this app.' };
140+
}
141+
if (!accepted.includes(origin)) {
142+
const https_hint = origin.startsWith('https://')
143+
? ` If a TLS proxy serves this app at ${origin}, add that origin to ${PUBLIC_ORIGINS_VARIABLE} and restart dev.`
144+
: '';
145+
return {
146+
problem: `The request came from ${JSON.stringify(origin)}, but this address is ${accepted.join(' or ')}.${https_hint}`
147+
};
148+
}
149+
const site = headers['sec-fetch-site'];
150+
if (site && site !== 'same-origin') {
151+
return { problem: `The browser marked this request ${JSON.stringify(site)}, not same-origin.` };
152+
}
153+
return { origin };
154+
}
155+
156+
/**
157+
* Where a sign-in or sign-out may send the browser: a path on this same app, kept with its query
158+
* and fragment. Anything else (an absolute or protocol-relative URL, a backslash, a space or control
159+
* character browsers would strip, a path that normalizes to "//", or one of the proxy's own paths)
160+
* becomes "/".
161+
* @param {unknown} value
162+
*/
163+
export function safe_return_path(value) {
164+
if (typeof value !== 'string' || value.length === 0 || value.length > MAX_RETURN_LENGTH)
165+
return '/';
166+
if (!value.startsWith('/') || value.startsWith('//')) return '/';
167+
if (value.includes('\\') || has_space_or_control(value)) return '/';
168+
const base = 'http://return.invalid';
169+
try {
170+
const url = new URL(value, base);
171+
const path = `${url.pathname}${url.search}${url.hash}`;
172+
if (url.origin !== base || path.startsWith('//')) return '/';
173+
if (url.pathname === MOUNT_PATH || url.pathname.startsWith(`${MOUNT_PATH}/`)) return '/';
174+
return path;
175+
} catch {
176+
return '/';
177+
}
178+
}
179+
180+
/**
181+
* @typedef {{ path: string, port: number }} RouteOption
182+
* @typedef {{ path: string, port: number, prefix: string | null }} Route
183+
* `prefix` (ending in "/") for a `/*` route, null for an exact path.
184+
*/
185+
186+
const ROUTE_PATTERN =
187+
/^\/(?:[A-Za-z0-9_~-][A-Za-z0-9._~-]*\/)*(?:[A-Za-z0-9_~-][A-Za-z0-9._~-]*|\*)$/;
188+
189+
/**
190+
* The plugin's `routes` option, checked: each is an exact path or a `/prefix/*`, with plain
191+
* segments (no "." or ".." segment, no encoded characters), and a port on this computer other than
192+
* local Syntax Auth's own. A wrong route stops the dev server.
193+
* @param {unknown} routes
194+
* @returns {Route[]}
195+
*/
196+
export function parse_routes(routes) {
197+
if (routes === undefined) return [];
198+
if (!Array.isArray(routes)) {
199+
throw new Error('syntax_auth(): routes must be an array of { path, port }.');
200+
}
201+
return routes.map((route) => {
202+
const path = route?.path;
203+
const port = route?.port;
204+
if (
205+
typeof path !== 'string' ||
206+
!ROUTE_PATTERN.test(path) ||
207+
path === '/*' ||
208+
path === MOUNT_PATH ||
209+
path.startsWith(`${MOUNT_PATH}/`)
210+
) {
211+
throw new Error(
212+
`syntax_auth(): each route needs a path like '/parties/*' or '/exact/path' (plain segments, no "." or "..", not "/*" or under ${MOUNT_PATH}), not ${JSON.stringify(route)}.`
213+
);
214+
}
215+
if (!Number.isInteger(port) || port <= 0 || port >= 65_536) {
216+
throw new Error(
217+
`syntax_auth(): each route needs a port number, not ${JSON.stringify(route)}.`
218+
);
219+
}
220+
if (port === SYNTAX_AUTH_LOCAL_PORT) {
221+
throw new Error(
222+
`syntax_auth(): a route can't send paths to local Syntax Auth's port ${SYNTAX_AUTH_LOCAL_PORT}; its sign-in and sign-out already answer at ${MOUNT_PATH}/.`
223+
);
224+
}
225+
return { path, port, prefix: path.endsWith('/*') ? path.slice(0, -1) : null };
226+
});
227+
}
228+
229+
/**
230+
* The path and query of an origin-form request target ("/path?query"), or null for any other form,
231+
* such as an absolute URL that names its own destination, or "//host".
232+
* @param {unknown} target
233+
*/
234+
export function split_target(target) {
235+
if (typeof target !== 'string' || !target.startsWith('/') || target.startsWith('//')) return null;
236+
const query_start = target.indexOf('?');
237+
return query_start === -1
238+
? { path: target, query: '' }
239+
: { path: target.slice(0, query_start), query: target.slice(query_start) };
240+
}
241+
242+
/**
243+
* @param {string} path the raw path of the request target
244+
* @param {readonly Route[]} routes
245+
*/
246+
export function find_route(path, routes) {
247+
return (
248+
routes.find((route) => (route.prefix ? path.startsWith(route.prefix) : path === route.path)) ??
249+
null
250+
);
251+
}
252+
253+
/**
254+
* Whether a routed path stays inside its route on any server: no "." or ".." segment, no empty
255+
* segment, no backslash, no encoded dot, slash, or backslash, and no space or control character.
256+
* @param {string} path
257+
*/
258+
export function is_clean_path(path) {
259+
if (path.includes('\\') || path.includes('//') || has_space_or_control(path)) return false;
260+
if (/%(?:2e|2f|5c)/i.test(path)) return false;
261+
return !path.split('/').some((segment) => segment === '.' || segment === '..');
262+
}

0 commit comments

Comments
 (0)