Open History to see the last commit
1import type {
2 AuthClientMetadata,
3 AuthClientMetadataDeviceType,
4 AuthClientPresentationMetadata,
5} from "@t3tools/contracts";
6import type * as HttpServerRequest from "effect/unstable/http/HttpServerRequest";
7import * as NodeCrypto from "node:crypto";
8import * as Encoding from "effect/Encoding";
9import * as Result from "effect/Result";
10
11const SESSION_COOKIE_NAME = "t3_session";
12
13/**
14 * Cookies are scoped by host but *not* by port, so any two servers that can be
15 * live on one hostname at once need separate names — otherwise the second
16 * clobbers the first's session and both sides see "Invalid session token
17 * signature" until someone clears cookies by hand.
18 *
19 * Two populations qualify, for the same reason but from different causes:
20 *
21 * - **Dev servers** (`devUrl` set), which run several at a time across worktrees.
22 * - **Desktop**, which scans upward from 3773 for a free port and binds
23 * 127.0.0.1, so a second instance lands on a different port and the same host.
24 *
25 * Hosted deployments keep the stable production name: their public port can
26 * change between releases, and scoping it would log every user out.
27 */
28export function resolveSessionCookieName(input: {
29 readonly mode: "web" | "desktop";
30 readonly port: number;
31 readonly host: string | undefined;
32 readonly instanceKey: string;
33 readonly development: boolean;
34}): string {
35 if (input.mode === "desktop") {
36 return `${SESSION_COOKIE_NAME}_${input.port}`;
37 }
38
39 if (!input.development && isRemoteReachableHost(input.host)) {
40 return SESSION_COOKIE_NAME;
41 }
42
43 // Cookies are scoped by host, not port. Loopback development servers need an
44 // instance-specific name or parallel agents overwrite each other's session,
45 // and a server that later reuses the port receives a token signed elsewhere.
46 const instanceHash = NodeCrypto.createHash("sha256")
47 .update(input.instanceKey)
48 .digest("hex")
49 .slice(0, 12);
50 return `${SESSION_COOKIE_NAME}_${input.port}_${instanceHash}`;
51}
52
53export function isRemoteReachableHost(host: string | undefined): boolean {
54 if (host === "0.0.0.0" || host === "::" || host === "[::]") {
55 return true;
56 }
57 if (!host || host.length === 0) {
58 return false;
59 }
60 return !(
61 host === "localhost" ||
62 host === "127.0.0.1" ||
63 host === "::1" ||
64 host === "[::1]" ||
65 host.startsWith("127.")
66 );
67}
68
69export function base64UrlEncode(input: string | Uint8Array): string {
70 return typeof input === "string"
71 ? Encoding.encodeBase64Url(new TextEncoder().encode(input))
72 : Encoding.encodeBase64Url(input);
73}
74
75export function base64UrlDecodeUtf8(input: string): string {
76 return Result.getOrThrow(Encoding.decodeBase64UrlString(input));
77}
78
79export function signPayload(payload: string, secret: Uint8Array): string {
80 return NodeCrypto.createHmac("sha256", Buffer.from(secret)).update(payload).digest("base64url");
81}
82
83export function timingSafeEqualBase64Url(left: string, right: string): boolean {
84 const leftBuffer = Buffer.from(left, "base64url");
85 const rightBuffer = Buffer.from(right, "base64url");
86 if (leftBuffer.length !== rightBuffer.length) {
87 return false;
88 }
89 return NodeCrypto.timingSafeEqual(leftBuffer, rightBuffer);
90}
91
92function normalizeNonEmptyString(value: string | null | undefined): string | undefined {
93 if (typeof value !== "string") {
94 return undefined;
95 }
96 const trimmed = value.trim();
97 return trimmed.length > 0 ? trimmed : undefined;
98}
99
100function normalizeIpAddress(value: string | null | undefined): string | undefined {
101 const normalized = normalizeNonEmptyString(value);
102 if (!normalized) {
103 return undefined;
104 }
105 return normalized.startsWith("::ffff:") ? normalized.slice("::ffff:".length) : normalized;
106}
107
108function inferDeviceType(userAgent: string | undefined): AuthClientMetadataDeviceType {
109 if (!userAgent) {
110 return "unknown";
111 }
112
113 const normalized = userAgent.toLowerCase();
114 if (/bot|crawler|spider|slurp|curl|wget/.test(normalized)) {
115 return "bot";
116 }
117 if (/ipad|tablet/.test(normalized)) {
118 return "tablet";
119 }
120 if (/iphone|android.+mobile|mobile/.test(normalized)) {
121 return "mobile";
122 }
123 return "desktop";
124}
125
126function inferBrowser(userAgent: string | undefined): string | undefined {
127 if (!userAgent) {
128 return undefined;
129 }
130 const normalized = userAgent.toLowerCase();
131 if (/edg\//.test(normalized)) return "Edge";
132 if (/opr\//.test(normalized)) return "Opera";
133 if (/firefox\//.test(normalized)) return "Firefox";
134 if (/electron\//.test(normalized)) return "Electron";
135 if (/chrome\//.test(normalized) || /crios\//.test(normalized)) return "Chrome";
136 if (/safari\//.test(normalized) && !/chrome\//.test(normalized)) return "Safari";
137 return undefined;
138}
139
140function inferOs(userAgent: string | undefined): string | undefined {
141 if (!userAgent) {
142 return undefined;
143 }
144 const normalized = userAgent.toLowerCase();
145 if (/iphone|ipad|ipod/.test(normalized)) return "iOS";
146 if (/android/.test(normalized)) return "Android";
147 if (/mac os x|macintosh/.test(normalized)) return "macOS";
148 if (/windows nt/.test(normalized)) return "Windows";
149 if (/linux/.test(normalized)) return "Linux";
150 return undefined;
151}
152
153function readRemoteAddressFromSource(source: unknown): string | undefined {
154 if (!source || typeof source !== "object") {
155 return undefined;
156 }
157
158 const candidate = source as {
159 readonly remoteAddress?: string | null;
160 readonly socket?: {
161 readonly remoteAddress?: string | null;
162 };
163 };
164
165 return normalizeIpAddress(candidate.socket?.remoteAddress ?? candidate.remoteAddress);
166}
167
168export function deriveAuthClientMetadata(input: {
169 readonly request: HttpServerRequest.HttpServerRequest;
170 readonly presented?: AuthClientPresentationMetadata;
171}): AuthClientMetadata {
172 const userAgent = normalizeNonEmptyString(input.request.headers["user-agent"]);
173 const ipAddress = readRemoteAddressFromSource(input.request.source);
174 const os = input.presented?.os ?? inferOs(userAgent);
175 const browser = inferBrowser(userAgent);
176 return {
177 ...(input.presented?.label ? { label: input.presented.label } : {}),
178 ...(ipAddress ? { ipAddress } : {}),
179 ...(userAgent ? { userAgent } : {}),
180 deviceType: input.presented?.deviceType ?? inferDeviceType(userAgent),
181 ...(os ? { os } : {}),
182 ...(browser ? { browser } : {}),
183 };
184}