Skip to content

Commit 7305633

Browse files
committed
Make Syntax's local HTTPS names work automatically
dex v6t1ikur. Approved macOS-only setup with narrowly scoped hosts/keychain changes, proven Caddy ownership and certificate chain, local/Tailscale routes, scoped browser redirects, and accurate failure recovery. Unsupervised agent, CI, SSH and test-runner contexts never open setup dialogs or Docker. Proof: pnpm check, pnpm lint, pnpm test (94 passing); independent security/confirm reviews pass. Chrome 154 on Scott's MacBook verified trusted HTTPS sign-in to Lab, shared secure .syntax.test cookie, wss hot reload, preserved redirect path/query, nonredirected API/Auth localhost requests, prompt-free restart, Auth dev alone recreating its route, canceled certificate cleanup and 503 problem page/localhost escape at desktop/mobile widths. Fixed Docker launcher starts in 9 seconds. Hosts restored byte-for-byte, no test trust/proxy remains, Docker stopped, tunnel restored. Mini Caddy compatibility check explicitly transferred to wyl41w8a by Scott. Evidence: /tmp/sd-plan/v6-run4.log, v6-run5.log, v6-auth-alone.log, v6-run7-cancel.log, v6-chrome-check.log, v6-chrome-cancel.log, v6-chrome-shots/.
2 parents bfc6892 + 2388cc7 commit 7305633

31 files changed

Lines changed: 6852 additions & 167 deletions

‎CONSUMING_AUTH.md‎

Lines changed: 95 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -111,7 +111,10 @@ identical to production. It needs no secrets, 1Password, or GitHub OAuth App.
111111
Every dev server start then makes sure the one shared `syntax-auth` container is running,
112112
whether or not any other Syntax app is already running, without delaying the dev server. Any number of
113113
apps may start at once: container changes are serialized by a machine-wide lock that the OS
114-
releases even if a process crashes. It opens Docker Desktop on macOS when needed, pulls newer
114+
releases even if a process crashes. It opens Docker Desktop (or OrbStack) on macOS when needed
115+
and a person is at the Mac's screen (see below for when it never does), under the same lock, so
116+
the app is opened only once at a time: a second app starting meanwhile waits for that start and,
117+
if it failed or stalled, prints the same message instead of opening it again. It pulls newer
115118
images and swaps them in from a detached process, keeps local users and sessions in a Docker
116119
volume, and skips Vitest. If Docker is missing or stopped, the image is not accessible, or
117120
another program holds the port, it prints one warning naming the exact problem and its fix, and
@@ -154,7 +157,97 @@ two addresses to use instead. A request from an origin it doesn't trust gets a 4
154157
Syntax apps can also run locally on three HTTPS names, served by a local HTTPS proxy:
155158
`https://syntax.test` (the website), `https://lab.syntax.test` (Lab), and `https://auth.syntax.test`
156159
(local Syntax Auth). On those names, as in production, one cookie on the parent domain
157-
(`.syntax.test`) signs a browser in to every app:
160+
(`.syntax.test`) signs a browser in to every app.
161+
162+
Give the plugin the app's name to set its name up whenever its dev server starts (never under
163+
Vitest or in a build). `port` is where the name forwards, by default the port Vite listens on; an
164+
app whose dev server sits behind another (Lab under `alchemy dev`) passes that one. `routes` sends
165+
paths to other local servers:
166+
167+
```ts
168+
syntax_auth({ name: 'lab', port: 1337, routes: [{ path: '/parties/*', port: 1999 }] });
169+
```
170+
171+
On macOS, each start makes sure of these steps, in order, without delaying the dev server. A step
172+
that is already done is skipped, so after the first start nothing asks again:
173+
174+
1. **Hosts file.** `/etc/hosts` gets any missing `127.0.0.1` and `::1` entries for the three names,
175+
in one block marked `# >>> syntax.test` … `# <<< syntax.test`. Changing it asks for your password
176+
(or Touch ID) in a macOS dialog. A fixed script, never a file anyone could edit, then checks the
177+
file is still the one setup planned from (if another program changed it while the dialog was
178+
open, it changes nothing and says so), saves it as `/etc/hosts.syntax-test.bak`, rewrites only
179+
that block through a copy moved into place, and clears the DNS cache; an interrupted edit leaves
180+
the old file or the new one. Every byte outside the block stays as it was, CRLF line endings and
181+
a missing final newline included, and a name another line points elsewhere is left alone and
182+
reported. A damaged block (a marker without its partner, two blocks, or an altered marker line)
183+
is refused with its fix. One setup runs at a time on the machine, and a dialog left open closes
184+
after 5 minutes.
185+
2. **HTTPS proxy.** If Caddy's admin API answers on `127.0.0.1:2019` and is proven to be Caddy
186+
(it answers as Caddy's does, and the one program listening on `127.0.0.1:2019`, or on a wildcard
187+
address that covers it, is `caddy`), setup adds its routes there, first in the port 443 server,
188+
and leaves every other route alone. If a route it didn't add matches a name at any depth (inside
189+
a subroute, in a host list, or by a wildcard such as `*.syntax.test`), setup names that route and
190+
changes nothing. Otherwise it starts Syntax's
191+
own `syntax-caddy` container from the official Caddy image, pinned by digest, published on
192+
`127.0.0.1` only (ports 443, 80, and 2019), with its certificates in a Docker volume; a program
193+
already on one of those ports is named instead, and if setup can't read which programs listen,
194+
it stops rather than assume the ports are free. Each name gets a route with the `@id`
195+
`syntax-test-<name>` (`syntax-test-auth` forwards to port 37960 on every start), plus one
196+
`tls internal` certificate policy, `syntax-test-tls`. Only this computer and its tailnet
197+
(`100.64.0.0/10`) get through; any other client gets a 403. While dev runs, setup checks every
198+
15 seconds and adds the routes back if Caddy lost them (a restart or `caddy reload`).
199+
3. **Certificate trust.** Setup reads the root certificate from that Caddy's own certificate
200+
authority, checks that it issued the certificate Caddy serves for the names, and trusts it in
201+
your login keychain with one macOS approval. A root that didn't issue it is refused, with the
202+
reason. If you decline, the certificate macOS added is removed again.
203+
4. **Final check.** The names resolve to this computer, Caddy has the routes, macOS trusts the
204+
certificate, and `https://<name>` reaches this very dev server.
205+
206+
Then the dev server prints `https://<name> is ready.`, and page loads on `localhost` (or
207+
`127.0.0.1`) go to the same path on the https name; scripts' requests are never redirected. If a
208+
step fails, the dev server prints the step, what failed, and its fix, keeps running on `localhost`,
209+
and answers page loads there with a page naming the same, with a link to keep that browser on
210+
`localhost` for now. A retry (restart dev) is always safe, and a command that stalls is stopped
211+
with a message naming it.
212+
213+
Setup shows its password and approval dialogs only when a person is likely at the Mac's screen.
214+
It shows none, changes nothing, and prints each fix when dev (or `syntax-auth-local setup`)
215+
starts:
216+
217+
- from an AI coding agent's shell (`CLAUDECODE` or `PI_CODING_AGENT` set), so an agent checking
218+
a page never makes a dialog appear in front of you;
219+
- over SSH (`SSH_CONNECTION` or `SSH_TTY` set), in CI (`CI` set), or under a test runner
220+
(`NODE_TEST_CONTEXT` or `VITEST` set);
221+
- outside the Mac's desktop session (`launchctl managername` isn't `Aqua`).
222+
223+
Each of these variables counts when it is set at all, whatever its value: `CI=`, `CI=0`, and
224+
`CI=false` all mean CI. Only an unset variable is absent.
225+
226+
Its first line says which one, for example "Started from an agent shell (PI_CODING_AGENT), so
227+
setup didn't show any dialogs and changed nothing." Each fix after it is a command to run in
228+
Terminal at the Mac's own screen, such as
229+
`pnpm exec syntax-auth-local setup lab --port 1337 --route '/parties/*=1999'` (the dev server
230+
prints it with its own port and routes); `setup lab` and `setup website` need `--port`. When you
231+
are watching the screen and want an agent's run to show the dialogs, start it with
232+
`SYNTAX_DEV_SETUP_DIALOGS=allow`, for example `SYNTAX_DEV_SETUP_DIALOGS=allow pnpm dev`. That
233+
switch never works over SSH, in CI, or under a test runner.
234+
235+
In those same cases nothing opens Docker Desktop or OrbStack either, since their first run and
236+
privileged helper can show dialogs of their own: not a dev server with a name, not one without,
237+
and not `syntax-auth-local`. If Docker isn't running, the app runs signed out with a message
238+
such as "Docker isn't running, and this dev server was started from an agent shell
239+
(PI_CODING_AGENT), so it didn't open Docker Desktop or OrbStack. Start Docker Desktop (or
240+
OrbStack), then restart dev." When Docker already runs, an agent's dev server still starts the
241+
local Syntax Auth container, which shows no dialog. `SYNTAX_DEV_SETUP_DIALOGS=allow`, at the
242+
Mac's screen, lets it open Docker too.
243+
244+
On Linux and Windows setup changes nothing and says that automatic setup is macOS-only for now.
245+
There, and over SSH, in CI, under a test runner, or outside the desktop session, a named dev
246+
server also leaves Docker and the local Syntax Auth container alone: if Syntax Auth isn't
247+
running, it says to start it with `pnpm exec syntax-auth-local`. The routes stay in Caddy when dev stops; Syntax Auth's `README.md`
248+
shows how to undo every step.
249+
250+
On those names:
158251

159252
- Send browsers to `https://auth.syntax.test`, for example
160253
`https://auth.syntax.test/sign-in?return_to=<encoded app URL>`. Local Syntax Auth accepts

‎README.md‎

Lines changed: 48 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -117,6 +117,46 @@ syntaxfm members, pulls it with their GitHub CLI login without storing the token
117117
`CONSUMING_AUTH.md`. The port lives in `packages/auth-local/container.js`,
118118
`vite.config.ts`, and the `local` and `oauth-registration` envs in `wrangler.jsonc`.
119119

120+
### https://auth.syntax.test
121+
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.
127+
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:
145+
146+
```sh
147+
# The routes and certificate policy, from whichever Caddy got them:
148+
for id in syntax-test-auth syntax-test-lab syntax-test-website syntax-test-tls; do
149+
curl -X DELETE "localhost:2019/id/$id"
150+
done
151+
# Syntax's own Caddy container, if setup started one, and its certificates:
152+
docker rm --force syntax-caddy && docker volume rm syntax-caddy-data syntax-caddy-config
153+
# Trust in Caddy's root (find its SHA-1 with the first command):
154+
security find-certificate -a -Z -c "Caddy Local Authority" ~/Library/Keychains/login.keychain-db
155+
security delete-certificate -Z <sha1> ~/Library/Keychains/login.keychain-db
156+
# The hosts block (/etc/hosts.syntax-test.bak holds the file from before the last change):
157+
sudo sed -i '' '/^# >>> syntax.test: added by Syntax dev setup/,/^# <<< syntax.test$/d' /etc/hosts
158+
```
159+
120160
Useful commands:
121161

122162
```sh
@@ -130,9 +170,15 @@ pnpm db:generate
130170
pnpm d1:migration:create <migration-name>
131171
```
132172

133-
`pnpm test` runs the unit tests and an integration test that builds the app, serves it with
173+
`pnpm test` runs the unit tests, an integration test that builds the app, serves it with
134174
`vite preview` on a free port with a temporary D1, and signs in on `localhost` and
135-
`auth.syntax.test`. It never touches port 37960, the container, or `.wrangler/state`.
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.
136182

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

‎package.json‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@
99
"preview": "node scripts/local_server.js preview",
1010
"check": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json",
1111
"lint": "prettier --check . && eslint .",
12-
"test": "tsx --test 'src/**/*.test.ts'",
12+
"test": "tsx --test 'src/**/*.test.ts' 'packages/auth-local/test/*.test.js'",
1313
"format": "prettier --write .",
1414
"cf-typegen": "wrangler types",
1515
"db:generate": "drizzle-kit generate",

‎packages/auth-local/bin.js‎

Lines changed: 36 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,40 @@
11
#!/usr/bin/env node
22
// For non-Vite dev scripts: `syntax-auth-local && next dev`.
3+
// `syntax-auth-local setup <auth|lab|website> --port <port> [--route <path>=<port>]...` sets up the
4+
// https://*.syntax.test names from a terminal, for example when dev runs where nobody can answer a
5+
// dialog. See README.md.
6+
import { USAGE, parse_setup_args } from './cli.js';
7+
import { log, warn } from './container.js';
38
import { ensure_syntax_auth } from './index.js';
9+
import { SITE_LABELS, site_url } from './names.js';
10+
import { default_setup_deps, describe_result, run_setup } from './setup.js';
411

5-
await ensure_syntax_auth();
12+
const [command, ...args] = process.argv.slice(2);
13+
14+
if (command === undefined) {
15+
await ensure_syntax_auth();
16+
} else if (command === 'setup') {
17+
const parsed = parse_setup_args(args);
18+
if ('error' in parsed) {
19+
console.error(parsed.error);
20+
process.exit(1);
21+
}
22+
const { options } = parsed;
23+
const result = await run_setup(options, default_setup_deps());
24+
if (result.state === 'worked') {
25+
log(
26+
options.name === 'auth'
27+
? `${site_url('auth')} is ready.`
28+
: `Setup is done: ${site_url(options.name)} will reach ${SITE_LABELS[options.name]}'s dev server on port ${options.port} once it starts.`
29+
);
30+
} else {
31+
const [first, ...rest] = describe_result(options, result, options.port);
32+
(result.state === 'failed' ? warn : log)(
33+
[first, ...rest.map((line) => ` ${line}`)].join('\n')
34+
);
35+
}
36+
process.exit(result.state === 'failed' ? 1 : 0);
37+
} else {
38+
console.error(USAGE);
39+
process.exit(1);
40+
}

0 commit comments

Comments
 (0)