Skip to content

Commit 6d0dbba

Browse files
committed
fix: rotate every server that shares a project's token folder
Servers that run the same project, such as the Vite plugin and pangular dev, share the private token folder. The first one to see a rotation request deleted it, so the others kept their trusted tokens while the command reported success. Each server now keeps a heartbeat and writes its own answer for a request without deleting it; the command waits for every server with a fresh heartbeat, deletes the request and answers, prints each code and says how many servers did not answer in time.
1 parent a9378ae commit 6d0dbba

4 files changed

Lines changed: 350 additions & 93 deletions

File tree

‎apps/docs/src/content/getting-started/cli.md‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -237,9 +237,9 @@ New one-time code: 482913 (expires in 5 min)
237237
Enter it in the panel to connect again.
238238
```
239239

240-
Run it in the project folder, or pass `--root`. It works with every server that runs the project: the standalone CLI, the Vite plugin and the Express hub. The running server drops the tokens it holds, stops trusting the panels and pages that used them, and makes the new code, which also ends a lock after too many wrong codes. Each panel then asks for the code again. If no server runs, the command still drops the tokens and says so. The server prints a new code when it starts.
240+
Run it in the project folder, or pass `--root`. It works with every server that runs the project: the standalone CLI, the Vite plugin and the Express hub. The running server drops the tokens it holds, stops trusting the panels and pages that used them, and makes the new code, which also ends a lock after too many wrong codes. Each panel then asks for the code again. If no server runs, the command still drops the tokens and says so. The server prints a new code when it starts. When several servers run the project, such as the Vite plugin and `pangular dev`, the command waits for each of them and prints the code of each. A server that doesn't answer within 3 seconds is counted in the output, and it keeps its tokens until you run the command again or restart it.
241241

242-
The command and the server pass the request and the code through two files in the project's private token folder (`~/.pangular-inspector/auth/<project>/`, readable by you only). The command deletes the file with the code once it printed it. See [Security](../security.md) for how the tokens are stored.
242+
The command and the servers pass the request and the codes through files in the project's private token folder (`~/.pangular-inspector/auth/<project>/`, readable by you only): a request, one answer per server, and a heartbeat per running server. The command deletes the request and the answers, which hold the codes, once it printed them. See [Security](../security.md) for how the tokens are stored.
243243

244244
## Lint export
245245

‎packages/devtools/CHANGELOG.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -180,7 +180,7 @@ What remains: `/config` exports `DEFAULT_POPUP_HOTKEY`, `PANGULAR_ACTIONS`, `PAN
180180
- `pangular dev` takes `--proxy-origin`, `--allowed-origin` and `--auth-token`.
181181
- `pangular build` refuses an `--outDir` that would delete files that are not a previous report, unless `--force` is passed.
182182
- The source scan reads Nx projects.
183-
- `pangular token --rotate` drops every trusted token of the project and prints a new one-time code from the running server (the CLI, the Vite plugin or the Express hub), which also ends a lock after too many wrong codes. `pangular token` prints how many tokens there are.
183+
- `pangular token --rotate` drops every trusted token of the project and prints a new one-time code from each running server (the CLI, the Vite plugin or the Express hub, several at once when they share the project), which also ends a lock after too many wrong codes. `pangular token` prints how many tokens there are.
184184
- The CLI start-up output names the NativeScript setup view (`?view=nativescript`) next to the Angular Native one.
185185

186186
### Performance

‎packages/devtools/src/__tests__/auth-rotate.test.ts‎

Lines changed: 150 additions & 38 deletions
Original file line numberDiff line numberDiff line change
@@ -1,18 +1,28 @@
1-
import { existsSync, mkdtempSync, readFileSync, rmSync, statSync, writeFileSync } from 'node:fs';
1+
import {
2+
existsSync,
3+
mkdtempSync,
4+
readFileSync,
5+
readdirSync,
6+
rmSync,
7+
statSync,
8+
writeFileSync,
9+
} from 'node:fs';
210
import { tmpdir } from 'node:os';
311
import { join } from 'node:path';
412
import cac from 'cac';
513
import { getTempAuthCode, verifyAuthToken } from 'devframe/node/auth';
614
import { getInternalContext } from 'devframe/node/hub-internals';
715
import { afterEach, describe, expect, it, vi } from 'vitest';
816
import {
9-
ROTATE_ANSWER_FILE,
1017
ROTATE_REQUEST_FILE,
1118
answerRotateRequest,
19+
beatTokenRotation,
1220
clearTokenFile,
1321
pollTokenRotation,
22+
rotateAnswerFile,
1423
rotateText,
1524
rotateTokens,
25+
rotateWatcherFile,
1626
tokenFileSummary,
1727
} from '../auth-rotate.ts';
1828
import { codeGuardLocked, registerCodeGuard } from '../auth-guard.ts';
@@ -78,14 +88,35 @@ describe('token file', () => {
7888
});
7989
});
8090

91+
/** A trusted token on a server context, with the live connection that used it. */
92+
function trustToken(ctx: ReturnType<typeof serverContext>, token: string) {
93+
const storage = getInternalContext(ctx as never).storage.auth;
94+
storage.mutate((state) => {
95+
state.trusted[token] = { authToken: token, ua: '', origin: '', timestamp: Date.now() };
96+
});
97+
return storage;
98+
}
99+
100+
/** Runs the server's poll for each context every 10 ms, as `watchTokenRotation` does every second. */
101+
function serve(contexts: ReturnType<typeof serverContext>[], dir: string, log = vi.fn()) {
102+
const tick = () => {
103+
for (const ctx of contexts) pollTokenRotation(ctx, dir, log);
104+
};
105+
tick();
106+
const timer = setInterval(tick, 10);
107+
return () => clearInterval(timer);
108+
}
109+
110+
const REQUEST_ID = 'abcdef0123456789';
111+
81112
describe('pangular token --rotate', () => {
82-
it('drops the file tokens and says so when no server answers', async () => {
113+
it('drops the file tokens and says so when no server runs', async () => {
83114
const home = temp('pangular-home-');
84115
const root = temp('pangular-root-');
85116
const dir = privateAuthStoreDir(root, home);
86117
seedFile(dir, { a: { timestamp: Date.now() } });
87118
const result = await rotateTokens(root, { home, waitMs: 50, pollMs: 10 });
88-
expect(result).toEqual({ server: false, dropped: 1 });
119+
expect(result).toEqual({ dropped: 1, answers: [], missing: 0 });
89120
// The request is gone, so a server started later doesn't rotate.
90121
expect(existsSync(join(dir, ROTATE_REQUEST_FILE))).toBe(false);
91122
expect(rotateText(result)).toContain('No running devtools server answered');
@@ -97,30 +128,106 @@ describe('pangular token --rotate', () => {
97128
const dir = privateAuthStoreDir(root, home);
98129
const meta: Record<string, unknown> = { id: 'a', isTrusted: true, clientAuthToken: 'tok' };
99130
const ctx = serverContext(dir, meta);
100-
const storage = getInternalContext(ctx as never).storage.auth;
101-
storage.mutate((state) => {
102-
state.trusted['tok'] = { authToken: 'tok', ua: '', origin: '', timestamp: Date.now() };
103-
});
131+
const storage = trustToken(ctx, 'tok');
104132
const before = getTempAuthCode();
105-
// The server looks for requests while the command waits.
106-
const timer = setInterval(() => answerRotateRequest(ctx, dir), 10);
133+
const stop = serve([ctx], dir);
134+
let result;
107135
try {
108-
const result = await rotateTokens(root, { home, waitMs: 2000, pollMs: 10 });
109-
expect(result.server).toBe(true);
110-
if (!result.server) return;
111-
expect(result.dropped).toBe(1);
112-
expect(result.code).toMatch(/^\d+$/);
113-
expect(result.code).toBe(getTempAuthCode());
114-
expect(result.code).not.toBe(before);
115-
expect(result.expiresAt).toBeGreaterThan(Date.now());
116-
expect(rotateText(result, Date.now())).toContain(`New one-time code: ${result.code}`);
136+
result = await rotateTokens(root, { home, waitMs: 2000, pollMs: 10 });
117137
} finally {
118-
clearInterval(timer);
138+
stop();
119139
}
140+
expect(result.missing).toBe(0);
141+
expect(result.dropped).toBe(1);
142+
expect(result.answers).toHaveLength(1);
143+
const [{ code, expiresAt }] = result.answers;
144+
expect(code).toMatch(/^\d+$/);
145+
expect(code).toBe(getTempAuthCode());
146+
expect(code).not.toBe(before);
147+
expect(expiresAt).toBeGreaterThan(Date.now());
148+
expect(rotateText(result, Date.now())).toContain(`New one-time code: ${code}`);
120149
expect(verifyAuthToken('tok', { meta: {} } as never, storage)).toBe(false);
121150
expect(meta['isTrusted']).toBe(false);
122-
// The answer, which holds the code, is deleted once read.
123-
expect(existsSync(join(dir, ROTATE_ANSWER_FILE))).toBe(false);
151+
// The request and the answer, which holds the code, are deleted once read.
152+
expect(readdirSync(dir).filter((name) => name.startsWith('rotate-answer.'))).toEqual([]);
153+
expect(existsSync(join(dir, ROTATE_REQUEST_FILE))).toBe(false);
154+
});
155+
156+
it('rotates every server that shares the token folder, not only the first to see the request', async () => {
157+
const home = temp('pangular-home-');
158+
const root = temp('pangular-root-');
159+
const dir = privateAuthStoreDir(root, home);
160+
const metaA: Record<string, unknown> = { id: 'a', isTrusted: true, clientAuthToken: 'tokA' };
161+
const metaB: Record<string, unknown> = { id: 'b', isTrusted: true, clientAuthToken: 'tokB' };
162+
const a = serverContext(dir, metaA);
163+
const b = serverContext(dir, metaB);
164+
const storageA = trustToken(a, 'tokA');
165+
const storageB = trustToken(b, 'tokB');
166+
const stop = serve([a, b], dir);
167+
let result;
168+
try {
169+
result = await rotateTokens(root, { home, waitMs: 2000, pollMs: 10 });
170+
} finally {
171+
stop();
172+
}
173+
expect(result.missing).toBe(0);
174+
expect(result.answers).toHaveLength(2);
175+
// One process has one code: the second context answers with the first one's.
176+
expect(new Set(result.answers.map((answer) => answer.code)).size).toBe(1);
177+
expect(verifyAuthToken('tokA', { meta: {} } as never, storageA)).toBe(false);
178+
expect(verifyAuthToken('tokB', { meta: {} } as never, storageB)).toBe(false);
179+
expect(metaA['isTrusted']).toBe(false);
180+
expect(metaB['isTrusted']).toBe(false);
181+
});
182+
183+
it('does not let one server delete the request before another answered', () => {
184+
const dir = temp('pangular-shared-');
185+
const a = serverContext(dir, {});
186+
const b = serverContext(dir, {});
187+
writeFileSync(
188+
join(dir, ROTATE_REQUEST_FILE),
189+
JSON.stringify({ id: REQUEST_ID, at: Date.now() }),
190+
);
191+
const first = answerRotateRequest(a, dir);
192+
expect(first?.id).toBe(REQUEST_ID);
193+
expect(existsSync(join(dir, ROTATE_REQUEST_FILE))).toBe(true);
194+
expect(answerRotateRequest(b, dir)?.id).toBe(REQUEST_ID);
195+
expect(existsSync(rotateAnswerFile(dir, REQUEST_ID, first!.watcher))).toBe(true);
196+
// Each server answers a request once.
197+
expect(answerRotateRequest(a, dir)).toBeNull();
198+
});
199+
200+
it('says which running servers did not answer in time, and keeps no code for them', async () => {
201+
const home = temp('pangular-home-');
202+
const root = temp('pangular-root-');
203+
const dir = privateAuthStoreDir(root, home);
204+
const live = serverContext(dir, {});
205+
// A server with a fresh heartbeat that never answers, such as one that is busy.
206+
writeFileSync(rotateWatcherFile(dir, 'deadbeefdeadbeef'), JSON.stringify({ at: Date.now() }));
207+
// A heartbeat from a server that stopped long ago is not waited for.
208+
writeFileSync(rotateWatcherFile(dir, 'cafecafecafecafe'), JSON.stringify({ at: 0 }));
209+
const stop = serve([live], dir);
210+
let result;
211+
try {
212+
result = await rotateTokens(root, { home, waitMs: 200, pollMs: 10 });
213+
} finally {
214+
stop();
215+
}
216+
expect(result.answers).toHaveLength(1);
217+
expect(result.missing).toBe(1);
218+
const text = rotateText(result, Date.now());
219+
expect(text).toContain('New one-time code:');
220+
expect(text).toContain('1 running devtools server(s) did not answer in time');
221+
expect(existsSync(rotateWatcherFile(dir, 'cafecafecafecafe'))).toBe(false);
222+
});
223+
224+
it('keeps a heartbeat file per server', () => {
225+
const dir = temp('pangular-beat-');
226+
const ctx = serverContext(dir, {});
227+
beatTokenRotation(ctx, dir, 1234);
228+
const beats = readdirSync(dir).filter((name) => name.startsWith('rotate-watcher.'));
229+
expect(beats).toHaveLength(1);
230+
expect(JSON.parse(readFileSync(join(dir, beats[0]), 'utf8'))).toEqual({ at: 1234 });
124231
});
125232

126233
it('unlocks a code guard locked by wrong guesses', () => {
@@ -141,48 +248,53 @@ describe('pangular token --rotate', () => {
141248
registerCodeGuard(ctx2, { lockAfter: 1, warn });
142249
handlers[0].handler({ code: 'not-the-code', ua: '', origin: '' });
143250
expect(codeGuardLocked(ctx2)).toBe(true);
144-
writeFileSync(join(dir, ROTATE_REQUEST_FILE), JSON.stringify({ id: 'r1', at: Date.now() }));
145-
expect(answerRotateRequest(ctx2, dir)?.id).toBe('r1');
251+
writeFileSync(
252+
join(dir, ROTATE_REQUEST_FILE),
253+
JSON.stringify({ id: REQUEST_ID, at: Date.now() }),
254+
);
255+
expect(answerRotateRequest(ctx2, dir)?.id).toBe(REQUEST_ID);
146256
expect(codeGuardLocked(ctx2)).toBe(false);
147257
});
148258

149259
it('keeps every token and logs instead of throwing when the answer cannot be written', () => {
150260
const dir = temp('pangular-fail-');
151261
const meta: Record<string, unknown> = { id: 'a', isTrusted: true, clientAuthToken: 'tok' };
152262
const ctx = serverContext(dir, meta);
153-
const storage = getInternalContext(ctx as never).storage.auth;
154-
storage.mutate((state) => {
155-
state.trusted['tok'] = { authToken: 'tok', ua: '', origin: '', timestamp: Date.now() };
156-
});
157-
writeFileSync(join(dir, ROTATE_REQUEST_FILE), JSON.stringify({ id: 'r1', at: Date.now() }));
263+
const storage = trustToken(ctx, 'tok');
264+
writeFileSync(
265+
join(dir, ROTATE_REQUEST_FILE),
266+
JSON.stringify({ id: REQUEST_ID, at: Date.now() }),
267+
);
158268
const lines: string[] = [];
159269
const failingWrite = () => {
160270
throw new Error('ENOSPC: no space left on device');
161271
};
162-
expect(() =>
272+
const poll = () =>
163273
pollTokenRotation(
164274
ctx,
165275
dir,
166276
(line) => lines.push(line),
167277
(c, d) => answerRotateRequest(c, d, Date.now(), failingWrite),
168-
),
169-
).not.toThrow();
278+
);
279+
expect(poll).not.toThrow();
170280
expect(lines.join('')).toContain('failed, so every trusted token is kept: ENOSPC');
171281
expect(verifyAuthToken('tok', { meta: {} } as never, storage)).toBe(true);
172282
expect(meta['isTrusted']).toBe(true);
173-
// The request is gone, so the failure is not retried every second.
174-
expect(existsSync(join(dir, ROTATE_REQUEST_FILE))).toBe(false);
175-
expect(existsSync(join(dir, ROTATE_ANSWER_FILE))).toBe(false);
283+
// The server tries a request once, so the failure is not retried every second.
284+
lines.length = 0;
285+
poll();
286+
expect(lines).toEqual([]);
287+
expect(readdirSync(dir).filter((name) => name.startsWith('rotate-answer.'))).toEqual([]);
176288
});
177289

178290
it('ignores a stale or broken request', () => {
179291
const dir = temp('pangular-stale-');
180292
const ctx = serverContext(dir, {});
181-
writeFileSync(join(dir, ROTATE_REQUEST_FILE), JSON.stringify({ id: 'old', at: 0 }));
293+
writeFileSync(join(dir, ROTATE_REQUEST_FILE), JSON.stringify({ id: REQUEST_ID, at: 0 }));
182294
expect(answerRotateRequest(ctx, dir)).toBeNull();
183-
expect(existsSync(join(dir, ROTATE_REQUEST_FILE))).toBe(false);
184-
writeFileSync(join(dir, ROTATE_REQUEST_FILE), '{not json');
295+
writeFileSync(join(dir, ROTATE_REQUEST_FILE), JSON.stringify({ id: '../x', at: Date.now() }));
185296
expect(answerRotateRequest(ctx, dir)).toBeNull();
297+
writeFileSync(join(dir, ROTATE_REQUEST_FILE), '{not json');
186298
expect(answerRotateRequest(ctx, dir)).toBeNull();
187299
});
188300

0 commit comments

Comments
 (0)