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

desktopBootstrapToken.ts

32 lines1.2 KB

1// @effect-diagnostics-next-line nodeBuiltinImport:off -- Effect's Crypto has no createHmac or timingSafeEqual.
2import * as NodeCrypto from "node:crypto";
3​
4/** Accept previous/current windows for token lifetime and the next window for WSL clock lag. */
5export const DESKTOP_BOOTSTRAP_TOKEN_WINDOW_MS = 12 * 60 * 60 * 1000;
6​
7function windowIndex(nowMs: number): number {
8 return Math.floor(nowMs / DESKTOP_BOOTSTRAP_TOKEN_WINDOW_MS);
9}
10​
11function deriveToken(secret: string, window: number): string {
12 return NodeCrypto.createHmac("sha256", secret)
13 .update(`t3-desktop-bootstrap:${window}`)
14 .digest("hex");
16​
17export function currentDesktopBootstrapToken(secret: string, nowMs: number): string {
18 return deriveToken(secret, windowIndex(nowMs));
20​
21export function isValidDesktopBootstrapToken(
22 secret: string,
23 token: string,
24 nowMs: number,
25): boolean {
26 const presented = Buffer.from(token);
27 const current = windowIndex(nowMs);
28 return [current - 1, current, current + 1].some((window) => {
29 const expected = Buffer.from(deriveToken(secret, window));
30 return expected.length === presented.length && NodeCrypto.timingSafeEqual(expected, presented);
31 });