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

desktopBootstrapToken.ts

38 lines1.4 KB

1// @effect-diagnostics-next-line nodeBuiltinImport:off -- Effect's Crypto has no createHmac or timingSafeEqual.
2import * as NodeCrypto from "node:crypto";
3​
4/**
5 * A backend accepts the previous, current and next window's token: the previous
6 * one so a token works for between one and two windows, and the next one
7 * because a WSL backend's clock can trail the Windows clock that derived the
8 * token, which would otherwise reject every fresh token for a moment after each
9 * boundary.
10 */
11export const DESKTOP_BOOTSTRAP_TOKEN_WINDOW_MS = 12 * 60 * 60 * 1000;
12​
13function windowIndex(nowMs: number): number {
14 return Math.floor(nowMs / DESKTOP_BOOTSTRAP_TOKEN_WINDOW_MS);
16​
17function deriveToken(secret: string, window: number): string {
18 return NodeCrypto.createHmac("sha256", secret)
19 .update(`t3-desktop-bootstrap:${window}`)
20 .digest("hex");
22​
23export function currentDesktopBootstrapToken(secret: string, nowMs: number): string {
24 return deriveToken(secret, windowIndex(nowMs));
26​
27export function isValidDesktopBootstrapToken(
28 secret: string,
29 token: string,
30 nowMs: number,
31): boolean {
32 const presented = Buffer.from(token);
33 const current = windowIndex(nowMs);
34 return [current - 1, current, current + 1].some((window) => {
35 const expected = Buffer.from(deriveToken(secret, window));
36 return expected.length === presented.length && NodeCrypto.timingSafeEqual(expected, presented);
37 });