| 1 | import { describe, expect, it } from "vite-plus/test"; |
| 2 | |
| 3 | import { |
| 4 | DESKTOP_BOOTSTRAP_TOKEN_WINDOW_MS, |
| 5 | currentDesktopBootstrapToken, |
| 6 | isValidDesktopBootstrapToken, |
| 7 | } from "./desktopBootstrapToken.ts"; |
| 8 | |
| 9 | const SECRET = "desktop-secret"; |
| 10 | const WINDOW = DESKTOP_BOOTSTRAP_TOKEN_WINDOW_MS; |
| 11 | |
| 12 | describe("desktop bootstrap token", () => { |
| 13 | it("rotates every window and stays accepted for one more", () => { |
| 14 | const issuedAt = 10 * WINDOW + 1; |
| 15 | const token = currentDesktopBootstrapToken(SECRET, issuedAt); |
| 16 | |
| 17 | expect(currentDesktopBootstrapToken(SECRET, issuedAt + WINDOW)).not.toBe(token); |
| 18 | expect(isValidDesktopBootstrapToken(SECRET, token, issuedAt)).toBe(true); |
| 19 | expect(isValidDesktopBootstrapToken(SECRET, token, issuedAt + WINDOW)).toBe(true); |
| 20 | expect(isValidDesktopBootstrapToken(SECRET, token, issuedAt + 2 * WINDOW)).toBe(false); |
| 21 | }); |
| 22 | |
| 23 | it("accepts a token from a desktop clock slightly ahead of the backend", () => { |
| 24 | // Windows crossed the boundary, the WSL clock has not yet. |
| 25 | const desktopNow = 10 * WINDOW + 500; |
| 26 | const backendNow = 10 * WINDOW - 500; |
| 27 | |
| 28 | expect( |
| 29 | isValidDesktopBootstrapToken( |
| 30 | SECRET, |
| 31 | currentDesktopBootstrapToken(SECRET, desktopNow), |
| 32 | backendNow, |
| 33 | ), |
| 34 | ).toBe(true); |
| 35 | expect( |
| 36 | isValidDesktopBootstrapToken( |
| 37 | SECRET, |
| 38 | currentDesktopBootstrapToken(SECRET, desktopNow + WINDOW), |
| 39 | backendNow, |
| 40 | ), |
| 41 | ).toBe(false); |
| 42 | }); |
| 43 | |
| 44 | it("rejects tokens derived from another secret", () => { |
| 45 | const token = currentDesktopBootstrapToken("other-secret", WINDOW); |
| 46 | |
| 47 | expect(isValidDesktopBootstrapToken(SECRET, token, WINDOW)).toBe(false); |
| 48 | expect(isValidDesktopBootstrapToken(SECRET, "short", WINDOW)).toBe(false); |
| 49 | }); |
| 50 | }); |