g1t/apps/web/app/lib/github.test.ts
| 1 | import assert from "node:assert/strict"; |
| 2 | import { test } from "node:test"; |
| 3 | |
| 4 | import { INSTALL_COOKIE, STATE_COOKIE, cookie, installCookieValue, installWorkspace, newState, readCookie, sameString, stateMatches } from "./github.ts"; |
| 5 | |
| 6 | test("the state must come back exactly as it was given", () => { |
| 7 | const state = newState(); |
| 8 | assert.match(state, /^[0-9a-f]{64}$/); |
| 9 | assert.notEqual(state, newState()); |
| 10 | assert.ok(stateMatches(state, state)); |
| 11 | assert.ok(!stateMatches(state, state.slice(0, -1) + (state.endsWith("0") ? "1" : "0"))); |
| 12 | assert.ok(!stateMatches(null, state)); |
| 13 | assert.ok(!stateMatches(state, null)); |
| 14 | assert.ok(!stateMatches("", "")); |
| 15 | assert.ok(!sameString("abc", "abcd")); |
| 16 | }); |
| 17 | |
| 18 | test("cookies are read by name, and odd values are ignored", () => { |
| 19 | const header = `g1t_session=${"a".repeat(64)}; ${STATE_COOKIE}=abc123; other=x`; |
| 20 | assert.equal(readCookie(header, STATE_COOKIE), "abc123"); |
| 21 | assert.equal(readCookie(header, "missing"), null); |
| 22 | assert.equal(readCookie(`${STATE_COOKIE}=<script>`, STATE_COOKIE), null); |
| 23 | assert.equal(readCookie(null, STATE_COOKIE), null); |
| 24 | const set = cookie(STATE_COOKIE, "abc", 600); |
| 25 | assert.match(set, /HttpOnly/); |
| 26 | assert.match(set, /Secure/); |
| 27 | assert.match(set, /SameSite=Lax/); |
| 28 | assert.match(set, /Max-Age=600/); |
| 29 | }); |
| 30 | |
| 31 | test("an installation returns to the workspace it was started for", () => { |
| 32 | const state = newState(); |
| 33 | const value = installCookieValue(state, "acme"); |
| 34 | assert.equal(readCookie(`${INSTALL_COOKIE}=${value}`, INSTALL_COOKIE), value); |
| 35 | assert.equal(installWorkspace(value, state), "acme"); |
| 36 | assert.equal(installWorkspace(value, newState()), null); |
| 37 | assert.equal(installWorkspace(value, null), null); |
| 38 | assert.equal(installWorkspace(null, state), null); |
| 39 | assert.equal(installWorkspace(`${state}.`, state), null); |
| 40 | }); |