Skip to content
Source
Sign inSign up
samwillis/one-million-boxes
Open History to see the last commit

identity-cookie.ts

139 lines3.4 KB

1const COOKIE_NAME = `boxes_identity`
2​
3export interface Identity {
4 playerId: string
5 teamId: number
6}
7​
8/**
9 * Create HMAC signature using Web Crypto API.
10 * Returns hex string truncated to 32 characters.
11 */
12async function sign(data: string, secret: string): Promise<string> {
13 const encoder = new TextEncoder()
14 const key = await crypto.subtle.importKey(
15 `raw`,
16 encoder.encode(secret),
17 { name: `HMAC`, hash: `SHA-256` },
18 false,
19 [`sign`],
20 )
21​
22 const signature = await crypto.subtle.sign(`HMAC`, key, encoder.encode(data))
23 const hex = Array.from(new Uint8Array(signature))
24 .map((b) => b.toString(16).padStart(2, `0`))
25 .join(``)
26​
27 return hex.slice(0, 32) // Truncate to 32 chars
29​
30/**
31 * Verify HMAC signature with timing-safe comparison.
32 */
33async function verify(data: string, signature: string, secret: string): Promise<boolean> {
34 const expected = await sign(data, secret)
35​
36 if (signature.length !== expected.length) return false
37​
38 // Timing-safe comparison
39 let result = 0
40 for (let i = 0; i < signature.length; i++) {
41 result |= signature.charCodeAt(i) ^ expected.charCodeAt(i)
42 }
43​
44 return result === 0
46​
47/**
48 * Generate a unique player ID using crypto.randomUUID().
49 */
50export function generatePlayerId(): string {
51 return crypto.randomUUID()
53​
54/**
55 * Generate a random team ID (0-3).
56 */
57export function generateTeamId(): number {
58 return Math.floor(Math.random() * 4)
60​
61/**
62 * Parse and verify identity cookie from cookie header.
63 * Returns { playerId, teamId } or null if invalid/missing.
64 *
65 * Cookie format: playerId.teamId.signature
66 */
67export async function parseIdentityCookie(
68 cookieHeader: string | null | undefined,
69 secret: string,
70): Promise<Identity | null> {
71 if (!cookieHeader) return null
72​
73 // Find our cookie
74 const cookies = cookieHeader.split(`;`).map((c) => c.trim())
75 const ourCookie = cookies.find((c) => c.startsWith(`${COOKIE_NAME}=`))
76​
77 if (!ourCookie) return null
78​
79 const value = ourCookie.slice(COOKIE_NAME.length + 1)
80​
81 // Format: playerId.teamId.signature
82 // playerId is UUID (36 chars with dashes)
83 // teamId is 0-3 (1 char)
84 // signature is 32 chars
85 const parts = value.split(`.`)
86​
87 if (parts.length !== 3) return null
88​
89 const [playerId, teamIdStr, sig] = parts
90​
91 // Validate UUID format
92 if (!/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(playerId)) {
93 return null
94 }
95​
96 // Validate teamId
97 const teamId = parseInt(teamIdStr, 10)
98 if (isNaN(teamId) || teamId < 0 || teamId > 3) return null
99​
100 // Verify signature covers both playerId and teamId
101 const dataToSign = `${playerId}.${teamId}`
102 const valid = await verify(dataToSign, sig, secret)
103 if (!valid) return null
104​
105 return { playerId, teamId }
107​
108/**
109 * Create signed identity cookie value.
110 * Format: playerId.teamId.signature
111 */
112export async function createIdentityCookie(
113 playerId: string,
114 teamId: number,
115 secret: string,
116): Promise<string> {
117 const dataToSign = `${playerId}.${teamId}`
118 const sig = await sign(dataToSign, secret)
119 return `${playerId}.${teamId}.${sig}`
121​
122/**
123 * Build Set-Cookie header with appropriate security attributes.
124 */
125export function buildIdentityCookieHeader(cookieValue: string, isProduction: boolean): string {
126 const parts = [
127 `${COOKIE_NAME}=${cookieValue}`,
128 `Path=/`,
129 `HttpOnly`,
130 `SameSite=Lax`,
131 `Max-Age=31536000`, // 1 year
132 ]
133​
134 if (isProduction) {
135 parts.push(`Secure`)
136 }
137​
138 return parts.join(`; `)