Skip to content
2 changes: 1 addition & 1 deletion AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,7 @@ pnpm e2e:last-failure # error-context.md of the last failed test, its last fra
- The editor server answers only to loopback host names and `ALLOWED_HOSTS` (DNS rebinding guard): a dev server reached by another name needs it.
- `EDITOR_TOKEN` (off by default; `random` makes one per start): a local editor then answers only to a browser that opened the link it prints (`?token=`, which sets an HttpOnly cookie). Dev server and e2e run without it.
- The editor's page has a Content Security Policy (`packages/server-core/src/http/shell-csp.ts`; inline scripts by hash, read from `index.html`). A local editor allows `'unsafe-eval'` (the engine's ECS is Emscripten WebAssembly, whose bindings compile strings); a hosted one does not. The e2e fixture fails a test on any CSP violation: a new kind of resource (another origin, a worker type) needs the policy changed with it.
- Hosted sessions: project grants belong to the user who opened the project (a new user or a sign-out drops them); refused tokens are not re-checked for a minute; API calls time out after 15 s; over the session cap, anonymous sessions go first. `/rpc` bodies are capped at 100 MiB, folder zips are streamed (no trash, no `nf_modules`, 1 GiB at most), and trash entries older than 30 days go when a project opens.
- Hosted sessions: project grants belong to the user who opened the project (a new user or a sign-out drops them); refused tokens are not re-checked for a minute; a request only ever resolves against the tokens it presents (it waits for a pending check of the same tokens, or for another's check to end and then gets its own), and a request without tokens signs the session out even while a check is pending; a request whose check a sign-out, a drop or another check replaced gets a signed-out session of its own (not stored, the shared session untouched, no new API call), so it runs signed out; API calls time out after 15 s; over the session cap, anonymous sessions go first. `/rpc` bodies are capped at 100 MiB, folder zips are streamed (no trash, no `nf_modules`, 1 GiB at most), and trash entries older than 30 days go when a project opens.
- To debug a failed e2e test, `pnpm e2e:last-failure` (or read `test-results/<test>/error-context.md`, and the last frame of `trace.zip`). A minified Monaco stack: rebuild code-editor with `npx vite build --sourcemap --outDir <scratch>` (same file hashes) and map the frames with `@jridgewell/trace-mapping`.
- The CLI repo needs `pnpm --filter @nanoforge-dev/config build` before `pnpm build`, and `pnpm --filter @nanoforge-dev/schematics build` for `nf new` (its root build leaves the schematics out).

Expand Down
48 changes: 36 additions & 12 deletions packages/server-core/src/session/session-store.ts
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,10 @@ interface Verification {
/** The token a refresh replaced: requests sent before the new cookie arrived still carry it. */
replaced?: string;
pending?: Promise<void>;
/** The tokens the check is for: only a request presenting them may take its answer. */
key?: string;
/** A sign-out, a drop or another check replaced this one while it ran: its answer was dropped. */
superseded?: boolean;
/** The API refused these tokens: until then, the same cookies are refused without asking. */
rejectedUntil?: number;
}
Expand Down Expand Up @@ -112,7 +116,9 @@ export class SessionStore {
this._sessions.set(session.id, session);
}
session.lastSeen = Date.now();
if (session.mode === 'ONLINE') await this._authenticate(session, cookies);
/** A request whose check was replaced while it ran gets a signed-out session of its own. */
if (session.mode === 'ONLINE' && !(await this._authenticate(session, cookies)))
return { session: this._new(), setCookies };
return { session, setCookies };
}

Expand All @@ -132,42 +138,59 @@ export class SessionStore {
this._onDidDrop.dispose();
}

private async _authenticate(session: Session, cookies: Record<string, string>): Promise<void> {
/**
* Checks the tokens a request presents. False when a sign-out, a drop or another check
* replaced the check it waited on: the session then belongs to someone else's request, and
* this one must not touch it nor be answered with it.
*/
private async _authenticate(session: Session, cookies: Record<string, string>): Promise<boolean> {
const accessToken = cookies[ACCESS_TOKEN_COOKIE];
const refreshToken = cookies[REFRESH_TOKEN_COOKIE];
if (!accessToken && !refreshToken) {
session.tokens = null;
this._setUser(session, null);
this._verifications.delete(session.id);
return;
return true;
}
const key = JSON.stringify([accessToken ?? '', refreshToken ?? '']);
const known = this._verifications.get(session.id);
if (known?.pending) return known.pending;
if (known?.pending) {
/** Other tokens wait for that check, then get their own: two at once would race on the session. */
await known.pending;
if (known.superseded) return false;
if (known.key !== key) return this._authenticate(session, cookies);
return true;
}
if (known?.rejectedUntil !== undefined) {
if (known.token === `${accessToken}\0${refreshToken}` && Date.now() < known.rejectedUntil)
return;
if (known.token === key && Date.now() < known.rejectedUntil) return true;
this._verifications.delete(session.id);
}
if (known && (accessToken === known.token || (accessToken && accessToken === known.replaced)))
return;
return true;
const presented = { accessToken: accessToken ?? '', refreshToken: refreshToken ?? '' };
/** Checked on a copy: the session keeps its verified tokens until the API accepts these. */
const candidate: Session = { ...session, tokens: presented };
const verification: Verification = { token: presented.accessToken };
const verification: Verification = { token: presented.accessToken, key };
const signOut = () => {
session.tokens = null;
this._setUser(session, null);
};
const reject = () => {
signOut();
this._verifications.set(session.id, {
token: `${accessToken}\0${refreshToken}`,
token: key,
rejectedUntil: Date.now() + REJECTED_TTL_MS,
});
};
/** A sign-out or a drop while this check ran replaced it: its answer no longer applies. */
const current = () => {
if (this._verifications.get(session.id) !== verification) verification.superseded = true;
return !verification.superseded;
};
verification.pending = this._options.verify(candidate).then(
(user) => {
delete verification.pending;
if (!current()) return;
if (!user || !candidate.tokens) return reject();
session.tokens = candidate.tokens;
this._setUser(session, user);
Expand All @@ -176,17 +199,18 @@ export class SessionStore {
},
(error: unknown) => {
delete verification.pending;
if (!current()) return;
if (error instanceof RpcError && error.code !== 'UNAVAILABLE') return reject();
if (this._verifications.get(session.id) === verification)
this._verifications.delete(session.id);
this._verifications.delete(session.id);
const verified =
session.tokens?.accessToken === presented.accessToken &&
session.tokens.refreshToken === presented.refreshToken;
if (!verified) signOut();
},
);
this._verifications.set(session.id, verification);
return verification.pending;
await verification.pending;
return !verification.superseded;
}

/**
Expand Down
158 changes: 158 additions & 0 deletions packages/server-core/test/session/session-store.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -117,6 +117,164 @@ describe('SessionStore', () => {
expect(out.session.projects.size).toBe(0);
});

it('never resolves a request against the pending check of other tokens', async () => {
const users: Record<string, { id: string; name: string }> = {
'access-ada': { id: 'ada', name: 'Ada' },
'access-bob': { id: 'bob', name: 'Bob' },
};
const asked: string[] = [];
const ada = Promise.withResolvers<undefined>();
const store = new SessionStore(env, {
verify: async (session) => {
const token = session.tokens?.accessToken ?? '';
asked.push(token);
if (token === 'access-ada') await ada.promise;
return users[token] ?? null;
},
});
const cookie = cookieOf((await store.resolve(null)).setCookies);

const first = store.resolve(`${cookie}; accessToken=access-ada; refreshToken=r`);
const second = store.resolve(`${cookie}; accessToken=access-bob; refreshToken=r`);
ada.resolve(undefined);
await first;
const bob = await second;
expect(asked).toEqual(['access-ada', 'access-bob']);
expect(bob.session.user?.id).toBe('bob');
expect(bob.session.tokens).toEqual({ accessToken: 'access-bob', refreshToken: 'r' });

await store.resolve(`${cookie}; accessToken=access-bob; refreshToken=r`);
expect(bob.session.user?.id).toBe('bob');
expect(asked).toHaveLength(2);
});

it('keeps a session signed out by a request without tokens while a check was pending', async () => {
let asked = 0;
const ada = Promise.withResolvers<undefined>();
const store = new SessionStore(env, {
verify: async () => {
asked++;
await ada.promise;
return { id: 'ada', name: 'Ada' };
},
});
const cookie = cookieOf((await store.resolve(null)).setCookies);

const check = store.resolve(`${cookie}; accessToken=access-ada; refreshToken=r`);
const out = await store.resolve(cookie);
expect(out.session.user).toBeNull();
ada.resolve(undefined);
await check;
expect(out.session.user).toBeNull();
expect(out.session.tokens).toBeNull();

const back = store.resolve(`${cookie}; accessToken=access-ada; refreshToken=r`);
await expect(back).resolves.toMatchObject({ session: { user: { id: 'ada' } } });
expect(asked).toBe(2);
});

it('answers requests whose check a sign-out replaced with a signed-out session of their own', async () => {
const asked: string[] = [];
const ada = Promise.withResolvers<undefined>();
const store = new SessionStore(env, {
verify: async (session) => {
const token = session.tokens?.accessToken ?? '';
asked.push(token);
if (token === 'access-ada') await ada.promise;
return { id: token.replace('access-', ''), name: token };
},
});
const cookie = cookieOf((await store.resolve(null)).setCookies);

const ada1 = store.resolve(`${cookie}; accessToken=access-ada; refreshToken=r`);
const ada2 = store.resolve(`${cookie}; accessToken=access-ada; refreshToken=r`);
await store.resolve(cookie);
const bob = await store.resolve(`${cookie}; accessToken=access-bob; refreshToken=r`);
bob.session.projects.add('bob-project');
ada.resolve(undefined);
for (const late of await Promise.all([ada1, ada2])) {
expect(late.session).not.toBe(bob.session);
expect(late.session.user).toBeNull();
expect(late.session.tokens).toBeNull();
}
expect(bob.session.user?.id).toBe('bob');
expect([...bob.session.projects]).toEqual(['bob-project']);
expect(asked).toEqual(['access-ada', 'access-bob']);
});

it('lets a request with other tokens wait for a check the API refuses', async () => {
const ada = Promise.withResolvers<undefined>();
const bob = Promise.withResolvers<undefined>();
const asked: string[] = [];
const store = new SessionStore(env, {
verify: async (session) => {
const token = session.tokens?.accessToken ?? '';
asked.push(token);
await (token === 'access-ada' ? ada : bob).promise;
return token === 'access-bob' ? { id: 'bob', name: 'Bob' } : null;
},
});
const cookie = cookieOf((await store.resolve(null)).setCookies);

const first = store.resolve(`${cookie}; accessToken=access-ada; refreshToken=r`);
const second = store.resolve(`${cookie}; accessToken=access-bob; refreshToken=r`);
ada.resolve(undefined);
expect((await first).session.user).toBeNull();
bob.resolve(undefined);
expect((await second).session.user?.id).toBe('bob');
expect(asked).toEqual(['access-ada', 'access-bob']);
});

it('does not ask again when an outage answers a check a sign-out replaced', async () => {
let asked = 0;
const outage = Promise.withResolvers<undefined>();
const store = new SessionStore(env, {
verify: async (session) => {
asked++;
if (session.tokens?.accessToken === 'a1') return { id: 'ada', name: 'Ada' };
await outage.promise;
throw new RpcError('UNAVAILABLE', 'API down');
},
});
const first = await store.resolve('accessToken=a1; refreshToken=r1');
const cookie = cookieOf(first.setCookies);

const check = store.resolve(`${cookie}; accessToken=a2; refreshToken=r2`);
await store.resolve(cookie);
outage.resolve(undefined);
await check;
expect(first.session.user).toBeNull();
expect(first.session.tokens).toBeNull();
expect(asked).toBe(2);
});

it('signs out a session dropped while its check was pending', async () => {
const dropped: Session[] = [];
let asked = 0;
const ada = Promise.withResolvers<undefined>();
const store = new SessionStore(env, {
verify: async (session) => {
asked++;
if (session.tokens?.accessToken !== 'access-ada') return { id: 'bob', name: 'Bob' };
await ada.promise;
return { id: 'ada', name: 'Ada' };
},
});
store.onDidDrop((session) => dropped.push(session));
const bob = await store.resolve('accessToken=access-bob; refreshToken=r');
const cookie = cookieOf(bob.setCookies);

const check = store.resolve(`${cookie}; accessToken=access-ada; refreshToken=r`);
store.prune(Date.now() + 8 * 24 * 3600 * 1000);
expect(dropped).toEqual([bob.session]);
ada.resolve(undefined);
const { session } = await check;
expect(session).not.toBe(bob.session);
expect(session.user).toBeNull();
expect(session.tokens).toBeNull();
expect(asked).toBe(2);
});

it('asks the API once about tokens it refused, and keeps signed-in users over anonymous ones', async () => {
let asked = 0;
const store = new SessionStore(env, {
Expand Down
Loading