Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

desktopBootstrapToken.ts

44 lines1.8 KB

1import * as NodeCrypto from "node:crypto";
2​
3/**
4 * The desktop app and the backends it launches share one secret, delivered
5 * over the backend's bootstrap channel and never sent to the renderer. Both
6 * sides derive the bootstrap token for a time window from it, so the token the
7 * renderer holds rotates every window without the desktop having to reach a
8 * running backend. A backend accepts the previous, current and next window's
9 * token: the previous one so a token works for between one and two windows,
10 * and the next one because a WSL backend's clock can trail the Windows clock
11 * that derived the token, which would otherwise reject every fresh token for
12 * a moment after each boundary. A token is still dead two windows after it
13 * was issued.
14 */
15export const DESKTOP_BOOTSTRAP_TOKEN_WINDOW_MS = 12 * 60 * 60 * 1000;
16​
17function windowIndex(nowMs: number): number {
18 return Math.floor(nowMs / DESKTOP_BOOTSTRAP_TOKEN_WINDOW_MS);
20​
21function deriveToken(secret: string, window: number): string {
22 return NodeCrypto.createHmac("sha256", secret)
23 .update(`t3-desktop-bootstrap:${window}`)
24 .digest("hex");
26​
27/** The token the desktop hands out at `nowMs`. */
28export function currentDesktopBootstrapToken(secret: string, nowMs: number): string {
29 return deriveToken(secret, windowIndex(nowMs));
31​
32/** Whether `token` is the previous, current or next window's token at `nowMs`. */
33export function isValidDesktopBootstrapToken(
34 secret: string,
35 token: string,
36 nowMs: number,
37): boolean {
38 const presented = Buffer.from(token);
39 const current = windowIndex(nowMs);
40 return [current - 1, current, current + 1].some((window) => {
41 const expected = Buffer.from(deriveToken(secret, window));
42 return expected.length === presented.length && NodeCrypto.timingSafeEqual(expected, presented);
43 });