Skip to content

Commit 4a8400b

Browse files
committed
Name the exact setup problem and its fix when local Syntax Auth can't start
Each case now has its own message: Docker not installed, unusable, or not running (and which app was opened); gh not installed or signed out; not in, or invited to, the syntaxfm org; a token missing read:org or read:packages; the program holding the port; and the container's last log lines when it never answers. Checked each case on this Mac, with stand-in gh and open commands for the states this account can't reach.
1 parent f6ffcfa commit 4a8400b

4 files changed

Lines changed: 155 additions & 68 deletions

File tree

‎CONSUMING_AUTH.md‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -113,8 +113,9 @@ identical to production. It needs no secrets, 1Password, or GitHub OAuth App.
113113
apps may start at once: container changes are serialized by a machine-wide lock that the OS
114114
releases even if a process crashes. It opens Docker Desktop on macOS when needed, pulls newer
115115
images and swaps them in from a detached process, keeps local users and sessions in a Docker
116-
volume, and skips Vitest. If Docker is missing, the image is not accessible, or another program
117-
holds the port, it prints one warning and the app runs signed out. Apps without Vite run the
116+
volume, and skips Vitest. If Docker is missing or stopped, the image is not accessible, or
117+
another program holds the port, it prints one warning naming the exact problem and its fix, and
118+
the app runs signed out. Apps without Vite run the
118119
`syntax-auth-local` command before their dev server instead. Contributors working on Syntax Auth
119120
itself run `pnpm dev` or `pnpm preview` in this repository, which stops the container and serves
120121
the same port; other apps then use that server. When it stops, it starts the container again.

‎packages/auth-local/container.js‎

Lines changed: 82 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -56,10 +56,35 @@ export function docker(args) {
5656
return run('docker', args);
5757
}
5858

59+
/** @param {{ code: number | null, stderr: string }} result */
60+
export function is_missing_command(result) {
61+
return result.code === null && result.stderr.includes('ENOENT');
62+
}
63+
64+
/** @param {string} text */
65+
export function first_line(text) {
66+
return text.split('\n').find((line) => line.trim() !== '') ?? text;
67+
}
68+
5969
function is_access_denied(stderr) {
6070
return /unauthorized|denied|forbidden/i.test(stderr);
6171
}
6272

73+
/** @param {string} login @param {{ stdout: string, stderr: string }} membership */
74+
function describe_membership_problem(login, membership) {
75+
if (membership.stdout === 'pending') {
76+
return `GitHub account ${login} has a pending invite to the syntaxfm org. Accept it at https://github.com/orgs/syntaxfm/invitation, then restart dev.`;
77+
}
78+
// gh adds a misleading admin:org hint to a 404, so check the status before any scope.
79+
if (/HTTP 404/.test(membership.stderr)) {
80+
return `GitHub account ${login} isn't in the syntaxfm org. If you're on the Syntax team, ask an org owner to add ${login}, then restart dev.`;
81+
}
82+
if (/read:org/.test(membership.stderr)) {
83+
return 'the GitHub CLI needs the read:org scope to check your syntaxfm membership. Run `gh auth refresh -h github.com -s read:org`, then restart dev.';
84+
}
85+
return `the GitHub CLI couldn't check your syntaxfm membership: ${first_line(membership.stderr)}`;
86+
}
87+
6388
async function find_docker_binary() {
6489
for (const directory of (process.env.PATH ?? '').split(delimiter)) {
6590
const candidate = join(directory, 'docker');
@@ -76,18 +101,42 @@ async function find_docker_binary() {
76101
// The image is private to the Syntax team. For a syntaxfm member, pull once with their GitHub CLI
77102
// token in a throwaway Docker config. PATH exposes only the docker binary, so Docker cannot fall
78103
// back to the OS keychain: the token is never saved, and any existing ghcr.io login is untouched.
79-
/** @returns {Promise<{ code: number | null, stdout: string, stderr: string } | null>} */
104+
// Returns why the app runs signed out (`problem`), or the pull's result.
105+
/** @returns {Promise<{ problem: string } | { result: { code: number | null, stdout: string, stderr: string } }>} */
80106
async function pull_as_syntax_team_member() {
107+
const user = await run('gh', ['api', 'user', '--jq', '.login']);
108+
if (is_missing_command(user)) {
109+
return {
110+
problem:
111+
"downloading it needs the GitHub CLI, which isn't installed. Install it (`brew install gh`, or see https://cli.github.com), run `gh auth login`, then restart dev."
112+
};
113+
}
114+
if (user.code !== 0) {
115+
return {
116+
problem: /gh auth login/.test(user.stderr)
117+
? "downloading it needs the GitHub CLI signed in, and it isn't. Run `gh auth login`, then restart dev."
118+
: `the GitHub CLI couldn't read your GitHub account: ${first_line(user.stderr)}`
119+
};
120+
}
121+
81122
const membership = await run('gh', ['api', 'user/memberships/orgs/syntaxfm', '--jq', '.state']);
82-
if (membership.code !== 0 || membership.stdout !== 'active') return null;
123+
if (membership.code !== 0 || membership.stdout !== 'active') {
124+
return { problem: describe_membership_problem(user.stdout, membership) };
125+
}
83126

84-
const [user, token, context, docker_binary] = await Promise.all([
85-
run('gh', ['api', 'user', '--jq', '.login']),
127+
const [token, context, docker_binary] = await Promise.all([
86128
run('gh', ['auth', 'token', '--hostname', 'github.com']),
87129
docker(['context', 'inspect', '--format', '{{.Endpoints.docker.Host}}']),
88130
find_docker_binary()
89131
]);
90-
if (user.code !== 0 || token.code !== 0 || context.code !== 0 || !docker_binary) return null;
132+
if (token.code !== 0) {
133+
return { problem: `the GitHub CLI couldn't give a token: ${first_line(token.stderr)}` };
134+
}
135+
if (context.code !== 0 || !docker_binary) {
136+
return {
137+
problem: `Docker's current context couldn't be read: ${first_line(context.stderr)}`
138+
};
139+
}
91140

92141
const config_directory = await mkdtemp(join(tmpdir(), 'syntax-auth-docker-config-'));
93142
const binary_directory = await mkdtemp(join(tmpdir(), 'syntax-auth-docker-bin-'));
@@ -104,29 +153,44 @@ async function pull_as_syntax_team_member() {
104153
['login', 'ghcr.io', '--username', user.stdout, '--password-stdin'],
105154
{ input: token.stdout, env }
106155
);
107-
if (login.code !== 0) return login;
108-
return await run('docker', ['pull', '--quiet', IMAGE], { env });
156+
if (login.code !== 0) return { result: login };
157+
return { result: await run('docker', ['pull', '--quiet', IMAGE], { env }) };
109158
} finally {
110159
await rm(config_directory, { recursive: true, force: true });
111160
await rm(binary_directory, { recursive: true, force: true });
112161
}
113162
}
114163

115-
/**
116-
* @returns {Promise<{ error: string | null, access_problem: 'not_syntax_team' | 'missing_read_packages' | null }>}
117-
*/
164+
/** @returns {Promise<string | null>} null once the image is downloaded, otherwise what is wrong. */
118165
export async function pull_image() {
119166
const result = await docker(['pull', '--quiet', IMAGE]);
120-
if (result.code === 0) return { error: null, access_problem: null };
121-
if (!is_access_denied(result.stderr)) return { error: result.stderr, access_problem: null };
167+
if (result.code === 0) return null;
168+
if (!is_access_denied(result.stderr)) {
169+
return `local Syntax Auth's Docker image couldn't be downloaded: ${first_line(result.stderr)}`;
170+
}
171+
172+
const team_pull = await pull_as_syntax_team_member();
173+
if ('problem' in team_pull) {
174+
return `local Syntax Auth's Docker image is private to the Syntax team, and ${team_pull.problem}`;
175+
}
176+
if (team_pull.result.code === 0) return null;
122177

123-
const team_result = await pull_as_syntax_team_member();
124-
if (!team_result) return { error: result.stderr, access_problem: 'not_syntax_team' };
125-
if (team_result.code === 0) return { error: null, access_problem: null };
178+
return is_access_denied(team_pull.result.stderr)
179+
? "your GitHub CLI token can't read the syntaxfm package registry. Run `gh auth refresh -h github.com -s read:packages`, then restart dev."
180+
: `local Syntax Auth's Docker image couldn't be downloaded: ${first_line(team_pull.result.stderr)}`;
181+
}
126182

127-
return is_access_denied(team_result.stderr)
128-
? { error: team_result.stderr, access_problem: 'missing_read_packages' }
129-
: { error: team_result.stderr, access_problem: null };
183+
/** @returns {Promise<string | null>} the program listening on the local port, like "python3 (pid 123)" */
184+
export async function find_port_holder() {
185+
const result = await run('lsof', [
186+
'-nP',
187+
`-iTCP:${SYNTAX_AUTH_LOCAL_PORT}`,
188+
'-sTCP:LISTEN',
189+
'-Fpc'
190+
]);
191+
const pid = result.stdout.match(/^p(\d+)$/m)?.[1];
192+
const command = result.stdout.match(/^c(.+)$/m)?.[1];
193+
return pid && command ? `${command} (pid ${pid})` : null;
130194
}
131195

132196
// True only when Syntax Auth itself answers, never another program that happens to use the port.

‎packages/auth-local/index.js‎

Lines changed: 68 additions & 46 deletions
Original file line numberDiff line numberDiff line change
@@ -11,23 +11,17 @@ import {
1111
SYNTAX_AUTH_LOCAL_PORT,
1212
create_container,
1313
docker,
14+
find_port_holder,
15+
first_line,
1416
get_container_state,
1517
is_healthy,
18+
is_missing_command,
1619
log,
1720
pull_image,
1821
sleep,
1922
warn,
2023
with_container_lock
2124
} from './container.js';
22-
23-
const ACCESS_MESSAGES = {
24-
not_syntax_team:
25-
'Running signed out: local Syntax Auth is for the Syntax team, via the GitHub CLI (`gh auth login`).',
26-
missing_read_packages:
27-
'Running signed out: run `gh auth refresh -h github.com -s read:packages` once, then restart dev.'
28-
};
29-
// Returned by ensure_image once it has already explained why the app runs signed out.
30-
const SIGNED_OUT = 'signed-out';
3125
const READY_TIMEOUT_MS = 180_000;
3226
const DOCKER_START_TIMEOUT_MS = 120_000;
3327
const UPDATER_PATH = fileURLToPath(new URL('./update.js', import.meta.url));
@@ -36,39 +30,59 @@ async function is_docker_running() {
3630
return (await docker(['info', '--format', '{{.ServerVersion}}'])).code === 0;
3731
}
3832

39-
// Launches Docker Desktop on macOS when it is installed but closed, then waits for the daemon.
40-
async function start_docker() {
41-
if (process.platform !== 'darwin') return false;
42-
43-
const is_launched = await new Promise((resolve) => {
44-
const child = spawn('open', ['--background', '-a', 'Docker'], { stdio: 'ignore' });
33+
/** @param {string} app */
34+
function open_app(app) {
35+
return new Promise((resolve) => {
36+
const child = spawn('open', ['--background', '-a', app], { stdio: 'ignore' });
4537
child.on('error', () => resolve(false));
4638
child.on('close', (code) => resolve(code === 0));
4739
});
48-
if (!is_launched) return false;
40+
}
4941

50-
log('Starting Docker');
51-
const deadline = Date.now() + DOCKER_START_TIMEOUT_MS;
52-
while (Date.now() < deadline) {
53-
if (await is_docker_running()) return true;
54-
await sleep(1_000);
42+
// On macOS, opens the Docker app that Docker's current context points at, then waits for it.
43+
/** @returns {Promise<string | null>} null when Docker is ready, otherwise what is wrong. */
44+
async function start_docker_app() {
45+
const context = await docker(['context', 'inspect', '--format', '{{.Endpoints.docker.Host}}']);
46+
const apps = context.stdout.includes('orbstack')
47+
? ['OrbStack', 'Docker Desktop']
48+
: ['Docker Desktop', 'OrbStack'];
49+
50+
for (const app of apps) {
51+
if (!(await open_app(app === 'Docker Desktop' ? 'Docker' : app))) continue;
52+
53+
log(`Starting ${app}`);
54+
const deadline = Date.now() + DOCKER_START_TIMEOUT_MS;
55+
while (Date.now() < deadline) {
56+
if (await is_docker_running()) return null;
57+
await sleep(1_000);
58+
}
59+
return `${app} was opened, but Docker wasn't ready after 2 minutes. Check ${app} for an error or a prompt, then restart dev.`;
60+
}
61+
return 'Docker is installed but not running, and neither Docker Desktop nor OrbStack is installed to start it. Start your Docker engine, then restart dev.';
62+
}
63+
64+
/** @returns {Promise<string | null>} null when Docker is ready, otherwise what is wrong. */
65+
async function ensure_docker() {
66+
const info = await docker(['info', '--format', '{{.ServerVersion}}']);
67+
if (info.code === 0) return null;
68+
if (is_missing_command(info)) {
69+
return "Docker isn't installed. Install Docker Desktop (https://www.docker.com/products/docker-desktop/) or OrbStack (https://orbstack.dev), then restart dev.";
70+
}
71+
if (/permission denied/i.test(info.stderr)) {
72+
return `Docker is installed, but your user can't use it (${first_line(info.stderr)}). On Linux, add yourself to the docker group (https://docs.docker.com/engine/install/linux-postinstall/), then restart dev.`;
5573
}
56-
return false;
74+
if (process.platform === 'darwin') return start_docker_app();
75+
return `Docker is installed but not running (${first_line(info.stderr)}). Start it (for example \`sudo systemctl start docker\`), then restart dev.`;
5776
}
5877

5978
// Downloads the image outside the lock, so a slow first download never makes other apps time out
6079
// waiting. Concurrent pulls of the same image are safe.
61-
/** @returns {Promise<string | null>} null when the image is available locally. */
80+
/** @returns {Promise<string | null>} null when the image is available, otherwise what is wrong. */
6281
async function ensure_image() {
6382
if ((await docker(['image', 'inspect', IMAGE])).code === 0) return null;
6483

6584
log('Downloading local Syntax Auth (first run only)');
66-
const { error, access_problem } = await pull_image();
67-
if (access_problem) {
68-
warn(ACCESS_MESSAGES[access_problem]);
69-
return SIGNED_OUT;
70-
}
71-
return error;
85+
return pull_image();
7286
}
7387

7488
/** @returns {Promise<string | null>} null when Syntax Auth is running or starting. */
@@ -84,47 +98,55 @@ async function start_container() {
8498
return result.code === 0 ? null : result.stderr;
8599
}
86100

101+
/** @param {string} error Docker's error from creating or starting the container. */
102+
async function describe_start_error(error) {
103+
if (!/address already in use|port is already allocated|ports are not available/i.test(error)) {
104+
return `the ${CONTAINER_NAME} container couldn't start: ${first_line(error)}`;
105+
}
106+
const holder = await find_port_holder();
107+
return holder
108+
? `port ${SYNTAX_AUTH_LOCAL_PORT} is in use by ${holder}, so local Syntax Auth can't start. Stop that program, then restart dev.`
109+
: `another program is using port ${SYNTAX_AUTH_LOCAL_PORT}, so local Syntax Auth can't start. Stop it, then restart dev.`;
110+
}
111+
87112
function start_updater() {
88113
const updater = spawn(process.execPath, [UPDATER_PATH], { detached: true, stdio: 'ignore' });
89114
updater.on('error', (error) => console.error('Syntax Auth updater failed to start', error));
90115
updater.unref();
91116
}
92117

118+
/** @returns {Promise<string | null>} null once Syntax Auth answers, otherwise what is wrong. */
93119
async function wait_until_ready() {
94120
const deadline = Date.now() + READY_TIMEOUT_MS;
95121

96122
while (Date.now() < deadline) {
97123
if (await is_healthy()) {
98124
log(`Ready at ${SYNTAX_AUTH_LOCAL_ORIGIN}`);
99-
return;
125+
return null;
100126
}
101127
await sleep(1_000);
102128
}
103129

104-
warn(`Not responding at ${SYNTAX_AUTH_LOCAL_ORIGIN}. Check \`docker logs ${CONTAINER_NAME}\`.`);
130+
// The container writes its server's errors to stderr, which `docker logs` passes through.
131+
const logs = await docker(['logs', '--tail', '20', CONTAINER_NAME]);
132+
return `local Syntax Auth started but isn't answering at ${SYNTAX_AUTH_LOCAL_ORIGIN} after 3 minutes. Its last log lines:\n${`${logs.stdout}\n${logs.stderr}`.trim()}`;
133+
}
134+
135+
/** @returns {Promise<string | null>} null once Syntax Auth answers, otherwise what is wrong. */
136+
async function start_and_wait() {
137+
const error = await with_container_lock(start_container);
138+
return error ? describe_start_error(error) : wait_until_ready();
105139
}
106140

107141
/** Makes sure the shared local Syntax Auth is running. Never throws. */
108142
export async function ensure_syntax_auth() {
109143
try {
110144
if (!(await is_healthy())) {
111-
if (!(await is_docker_running()) && !(await start_docker())) {
112-
warn('Docker is unavailable, so sign-in is unavailable. Install or start Docker.');
145+
const problem = (await ensure_docker()) ?? (await ensure_image()) ?? (await start_and_wait());
146+
if (problem) {
147+
warn(`Running signed out: ${problem}`);
113148
return;
114149
}
115-
116-
const error = (await ensure_image()) ?? (await with_container_lock(start_container));
117-
if (error === SIGNED_OUT) return;
118-
if (error) {
119-
warn(
120-
error.includes('address already in use')
121-
? `Another program is using port ${SYNTAX_AUTH_LOCAL_PORT}. Stop it, then restart dev.`
122-
: `Unable to start: ${error}`
123-
);
124-
return;
125-
}
126-
127-
await wait_until_ready();
128150
}
129151

130152
start_updater();

‎packages/auth-local/update.js‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -10,9 +10,9 @@ import {
1010
with_container_lock
1111
} from './container.js';
1212

13-
const pull = await pull_image();
13+
const pull_error = await pull_image();
1414

15-
if (!pull.error) {
15+
if (!pull_error) {
1616
await with_container_lock(async () => {
1717
const latest = await docker(['image', 'inspect', '--format', '{{.Id}}', IMAGE]);
1818
const state = await get_container_state();

0 commit comments

Comments
 (0)