Skip to content

Commit d26d565

Browse files
committed
fix(hub): expire session tokens on time and don't count an expired code as a guess
devframe's verifyAuthToken trusts any token left in the store, so a token's end depends on our prune. It ran hourly, so a token kept working for up to an hour past its 7 days, and it only deleted from storage, so a connection that was already trusted stayed trusted. The prune now runs when the next token expires (at least every minute) and revokes the live connections of each dropped token with devframe's revokeActiveConnectionsForToken. devframe also answers null for the right one-time code sent after it expired, and the guard counted that as a wrong guess, so a slow developer drifted toward the backoff and the lock. An attempt that carries exactly the current code is now left uncounted; every other code still counts, also after expiry.
1 parent a7cb0c6 commit d26d565

5 files changed

Lines changed: 275 additions & 28 deletions

File tree

‎apps/docs/src/content/security.md‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -92,9 +92,11 @@ Every server that asks for the code (the Vite plugin, the Express hub and the CL
9292

9393
A refused code is never compared with the real one. devframe gives you a new code after 5 wrong ones, so a client that keeps guessing can change the code you are typing at most twice a minute. If the terminal says the server stopped accepting codes and you didn't type them, something on your machine or network is guessing the code. Restart the dev server to get a new code.
9494

95+
A code lasts 5 minutes. If you type the right code after it expires, the server refuses it without counting it as a wrong code, and devframe gives you a new one. Only the code that is current when the attempt arrives is left uncounted, so a client that guesses gets no free attempts.
96+
9597
#### Trusted browsers
9698

97-
A browser that exchanges the code gets a session token, so it doesn't need the code again after a reload. The server keeps those tokens in `~/.pangular-inspector/auth/<project>/auth.json`, one folder per project (named after a hash of its path), so a token from one project doesn't open another project's server. The folder is readable by you only (mode `0700`), and the file too (`0600`). A token expires 7 days after the code was exchanged. At startup the server drops entries in the file that aren't token records, and it only trusts a token that has its own entry, so a name such as `constructor` or `toString` is never a token. To sign out every browser, delete the project's folder, or all of `~/.pangular-inspector/auth`, and restart the server.
99+
A browser that exchanges the code gets a session token, so it doesn't need the code again after a reload. The server keeps those tokens in `~/.pangular-inspector/auth/<project>/auth.json`, one folder per project (named after a hash of its path), so a token from one project doesn't open another project's server. The folder is readable by you only (mode `0700`), and the file too (`0600`). A token expires 7 days after the code was exchanged. At that moment the server drops it, and a page or panel still connected with it is no longer trusted. At startup the server drops entries in the file that aren't token records, and it only trusts a token that has its own entry, so a name such as `constructor` or `toString` is never a token. To sign out every browser, delete the project's folder, or all of `~/.pangular-inspector/auth`, and restart the server.
98100

99101
Version 0.0.7 and earlier kept the tokens in `~/.devframes/devframe/auth.json` (the Express hub and the Vite plugin) or `~/.pangular/devframe/auth.json` (the CLI), readable by other users and without expiry. Newer versions don't read those files. Delete them if no other devframe tool uses them.
100102

‎packages/devtools/CHANGELOG.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -106,6 +106,8 @@ What remains: `/config` exports `DEFAULT_POPUP_HOTKEY`, `PANGULAR_ACTIONS`, `PAN
106106
- Keep the Express hub and the overlay off in production unless `enabled: true` is passed to the hub.
107107
- Back off and lock the server after wrong one-time codes, and never compare a refused code with the real one.
108108
- Keep trusted session tokens in a `0600` file per project, and expire them after 7 days.
109+
- Expire a session token at the moment it turns 7 days old, not at the next hourly check, and stop trusting the connections that still use it. devframe trusts any token left in the store and kept already trusted connections after their token was dropped.
110+
- Don't count the right one-time code sent after it expired as a wrong guess. A slow developer no longer drifts toward the backoff and the lock. Wrong codes still count, also after the code expired.
109111
- Stop `server.allowedHosts: true` from turning off the origin checks, and warn about it.
110112
- Mask URL passwords and `Authorization` credentials (`Basic`, `Digest`, `Token`) in everything sent to the panel and to agents.
111113
- Mask more secrets: OpenAI, Anthropic, GitLab, npm, Hugging Face and SendGrid keys, Slack webhook URLs, the `Ocp-Apim-Subscription-Key` header, secret values that run past separators, secret XML elements and attributes, and token-like positional parts of TanStack Query keys and mutation variables.

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

Lines changed: 142 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,11 +12,13 @@ import {
1212
import { tmpdir } from 'node:os';
1313
import { join } from 'node:path';
1414
import { connectDevframe } from 'devframe/client';
15-
import { getTempAuthCode } from 'devframe/node/auth';
15+
import { getTempAuthCode, verifyAuthToken } from 'devframe/node/auth';
16+
import { getInternalContext } from 'devframe/node/hub-internals';
1617
import { afterEach, describe, expect, it, vi } from 'vitest';
1718
import { CodeGuard, guardedExchange } from '../auth-guard.ts';
1819
import {
1920
authStoreDir,
21+
expireAuthTokens,
2022
hardenTokenStore,
2123
pruneExpiredTokens,
2224
AUTH_TOKEN_TTL_MS,
@@ -121,6 +123,53 @@ describe('guardedExchange', () => {
121123
expect(onTrusted).toHaveBeenCalledOnce();
122124
});
123125

126+
describe("with devframe's exchange", () => {
127+
// devframe's one-time code lives 5 minutes.
128+
const CODE_TTL_MS = 5 * 60_000;
129+
let dir = '';
130+
afterEach(() => {
131+
vi.useRealTimers();
132+
if (dir) rmSync(dir, { recursive: true, force: true });
133+
});
134+
135+
function devframeContext(meta: object) {
136+
dir = mkdtempSync(join(tmpdir(), 'pangular-code-'));
137+
return { ...context(meta), host: { getStorageDir: () => dir } };
138+
}
139+
140+
it('does not count a right code that expired before it arrived as a wrong guess', () => {
141+
vi.useFakeTimers({ toFake: ['Date'] });
142+
const meta = {};
143+
const guard = new CodeGuard({ warn: vi.fn() });
144+
const handler = guardedExchange(devframeContext(meta) as never, guard);
145+
// A slow developer types the code just after it expires, more often than the lock allows.
146+
for (let i = 0; i < 60; i++) {
147+
const code = getTempAuthCode();
148+
vi.setSystemTime(Date.now() + CODE_TTL_MS + 1);
149+
expect(handler({ code, ua: '', origin: '' }).authToken).toBeNull();
150+
}
151+
expect(guard.locked).toBe(false);
152+
expect(guard.check(meta)).toBe('ok');
153+
expect(handler({ code: getTempAuthCode(), ua: '', origin: '' }).authToken).toBeTruthy();
154+
});
155+
156+
it('still counts a wrong code, also one sent after the code expired', () => {
157+
vi.useFakeTimers({ toFake: ['Date'] });
158+
const meta = {};
159+
const guard = new CodeGuard({ warn: vi.fn() });
160+
const handler = guardedExchange(devframeContext(meta) as never, guard);
161+
const wrong = (code: string) => (code === '000000' ? '000001' : '000000');
162+
handler({ code: wrong(getTempAuthCode()), ua: '', origin: '' });
163+
for (let i = 0; i < 2; i++) {
164+
const code = getTempAuthCode();
165+
vi.setSystemTime(Date.now() + CODE_TTL_MS + 1);
166+
handler({ code: wrong(code), ua: '', origin: '' });
167+
}
168+
// Three wrong guesses start the wait.
169+
expect(guard.check(meta)).toBe('backoff');
170+
});
171+
});
172+
124173
it('answers null for a call without a session or a code', () => {
125174
const exchange = vi.fn(() => 'tok');
126175
const ctx = { rpc: { ...context({}).rpc, getCurrentRpcSession: () => undefined } };
@@ -173,6 +222,78 @@ describe('pruneExpiredTokens', () => {
173222
});
174223
});
175224

225+
describe('expireAuthTokens', () => {
226+
let dir = '';
227+
afterEach(() => {
228+
vi.useRealTimers();
229+
if (dir) rmSync(dir, { recursive: true, force: true });
230+
});
231+
232+
function fakeContext(meta: Record<string, unknown>) {
233+
dir = mkdtempSync(join(tmpdir(), 'pangular-expiry-'));
234+
return {
235+
mode: 'dev',
236+
host: { getStorageDir: () => dir },
237+
// devframe's RPC host: the live connections, each with its session meta.
238+
rpc: { _rpcGroup: { clients: [{ $meta: meta }] }, broadcast: vi.fn(async () => undefined) },
239+
};
240+
}
241+
242+
it('drops a token at its exact expiry and untrusts the connections that use it', () => {
243+
vi.useFakeTimers();
244+
const start = Date.UTC(2026, 0, 1);
245+
vi.setSystemTime(start);
246+
const meta: Record<string, unknown> = { id: 'a', isTrusted: true, clientAuthToken: 'tok' };
247+
const ctx = fakeContext(meta);
248+
const storage = getInternalContext(ctx as never).storage.auth;
249+
const onPruned = vi.fn();
250+
expireAuthTokens(ctx, onPruned);
251+
// Issued half an hour after the server started, so off the hourly beat.
252+
vi.advanceTimersByTime(30 * 60_000);
253+
const issuedAt = Date.now();
254+
storage.mutate((state) => {
255+
state.trusted['tok'] = { authToken: 'tok', ua: '', origin: '', timestamp: issuedAt };
256+
});
257+
258+
vi.advanceTimersByTime(AUTH_TOKEN_TTL_MS - 1);
259+
expect(storage.value().trusted['tok']).toBeDefined();
260+
expect(meta['isTrusted']).toBe(true);
261+
262+
vi.advanceTimersByTime(1);
263+
expect(Date.now()).toBe(issuedAt + AUTH_TOKEN_TTL_MS);
264+
expect(storage.value().trusted['tok']).toBeUndefined();
265+
expect(verifyAuthToken('tok', { meta: {} } as never, storage)).toBe(false);
266+
expect(meta['isTrusted']).toBe(false);
267+
expect(meta['clientAuthToken']).toBeUndefined();
268+
expect(ctx.rpc.broadcast).toHaveBeenCalledOnce();
269+
expect(onPruned).toHaveBeenCalledOnce();
270+
});
271+
272+
it('untrusts a live connection once the prune has dropped its token', () => {
273+
vi.useFakeTimers();
274+
vi.setSystemTime(Date.UTC(2026, 0, 1));
275+
const meta: Record<string, unknown> = { id: 'a', isTrusted: true, clientAuthToken: 'tok' };
276+
const other: Record<string, unknown> = { id: 'b', isTrusted: true, clientAuthToken: 'kept' };
277+
const ctx = fakeContext(meta);
278+
ctx.rpc._rpcGroup.clients.push({ $meta: other });
279+
const storage = getInternalContext(ctx as never).storage.auth;
280+
storage.mutate((state) => {
281+
state.trusted['tok'] = { authToken: 'tok', ua: '', origin: '', timestamp: Date.now() };
282+
});
283+
expireAuthTokens(ctx);
284+
vi.advanceTimersByTime(3 * 60 * 60_000);
285+
storage.mutate((state) => {
286+
state.trusted['kept'] = { authToken: 'kept', ua: '', origin: '', timestamp: Date.now() };
287+
});
288+
// Two hours past the first token's expiry, so any schedule has pruned it by now.
289+
vi.advanceTimersByTime(AUTH_TOKEN_TTL_MS - 60 * 60_000);
290+
expect(storage.value().trusted['kept']).toBeDefined();
291+
expect(storage.value().trusted['tok']).toBeUndefined();
292+
expect(meta['isTrusted']).toBe(false);
293+
expect(other['isTrusted']).toBe(true);
294+
});
295+
});
296+
176297
describe('initPangularHub one-time code', () => {
177298
const cleanups: (() => Promise<void> | void)[] = [];
178299
afterEach(async () => {
@@ -258,6 +379,26 @@ describe('initPangularHub one-time code', () => {
258379
expect(existsSync(join(home, '.devframes', 'devframe', 'auth.json'))).toBe(false);
259380
});
260381

382+
it('stops trusting a connected client when its token expires', async () => {
383+
// The token has under two seconds left when the server starts.
384+
const issuedAt = Date.now() - AUTH_TOKEN_TTL_MS + 1500;
385+
const { connect } = await serve((home) => {
386+
const dir = authStoreDir(process.cwd(), home);
387+
mkdirSync(dir, { recursive: true });
388+
writeFileSync(
389+
join(dir, 'auth.json'),
390+
JSON.stringify({
391+
trusted: { 'expiring-token': { authToken: 'expiring-token', timestamp: issuedAt } },
392+
}),
393+
);
394+
});
395+
const client = await connect('expiring-token');
396+
expect(await client.ensureTrusted(1000)).toBe(true);
397+
await vi.waitFor(() => expect(client.isTrusted).toBe(false), { timeout: 4000 });
398+
const again = await connect('expiring-token');
399+
expect(await again.ensureTrusted(500).catch(() => false)).toBe(false);
400+
});
401+
261402
it('drops expired tokens at startup and keeps the rewritten file private', async () => {
262403
const old = Date.now() - AUTH_TOKEN_TTL_MS - 1000;
263404
let file = '';

‎packages/devtools/src/auth-guard.ts‎

Lines changed: 36 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,13 @@
1616
//
1717
// Attempts the guard refuses are not checked, so they don't rotate the code
1818
// the developer is typing either.
19-
import { exchangeTempAuthCode } from 'devframe/node/auth';
19+
//
20+
// devframe answers `null` both for a wrong code and for the right code sent
21+
// after it expired. Only a wrong code counts: an attempt is left uncounted
22+
// when it carries exactly the code that was current when it arrived, which
23+
// only the developer (or a right guess) can send, so no guess goes uncounted.
24+
import { createHash, timingSafeEqual } from 'node:crypto';
25+
import { exchangeTempAuthCode, getTempAuthCode } from 'devframe/node/auth';
2026
import { getInternalContext } from 'devframe/node/hub-internals';
2127

2228
const EXCHANGE = 'anonymous:devframe:auth:exchange';
@@ -142,13 +148,34 @@ interface GuardContext {
142148
};
143149
}
144150

145-
/** devframe's exchange: checks the code, and on a match stores and returns a new token. */
146-
export type CodeExchange = (params: ExchangeParams, session: AuthSession) => string | null;
151+
/**
152+
* devframe's exchange: checks the code, and on a match stores and returns a
153+
* new token. `'expired'` means the code was the current one but had expired,
154+
* so devframe rotated it; `null` means a wrong code.
155+
*/
156+
export type CodeExchange = (
157+
params: ExchangeParams,
158+
session: AuthSession,
159+
) => string | null | 'expired';
160+
161+
const digest = (value: string) => createHash('sha256').update(value).digest();
162+
163+
/** Compares two codes in constant time, whatever their lengths. */
164+
function sameCode(a: string, b: string): boolean {
165+
return timingSafeEqual(digest(a), digest(b));
166+
}
147167

148168
function defaultExchange(ctx: GuardContext): CodeExchange {
149169
return (params, session) => {
150170
const storage = getInternalContext(ctx as never).storage.auth;
151-
return exchangeTempAuthCode(params.code, session as never, params, storage);
171+
// The code devframe checks against. Reading it changes nothing: devframe
172+
// only creates one when there is none, as the exchange would.
173+
const current = getTempAuthCode();
174+
const authToken = exchangeTempAuthCode(params.code, session as never, params, storage);
175+
if (authToken) return authToken;
176+
// devframe accepts the current code unless it has expired, so a refused
177+
// current code was an expired one.
178+
return sameCode(params.code, current) ? 'expired' : null;
152179
};
153180
}
154181

@@ -165,15 +192,17 @@ export function guardedExchange(
165192
if (typeof params?.code !== 'string' || guard.check(session.meta) !== 'ok') {
166193
return { authToken: null };
167194
}
168-
const authToken = exchange(
195+
const result = exchange(
169196
{ code: params.code, ua: String(params.ua ?? ''), origin: String(params.origin ?? '') },
170197
session,
171198
);
172-
if (authToken) {
199+
// The right code, too late: not a guess, so neither counted nor trusted.
200+
if (result === 'expired') return { authToken: null };
201+
if (result) {
173202
guard.succeeded(session.meta);
174203
onTrusted?.();
175204
} else guard.failed(session.meta);
176-
return { authToken };
205+
return { authToken: result };
177206
};
178207
}
179208

0 commit comments

Comments
 (0)