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 devUrl: URL | undefined;
32}): string {
33 return input.devUrl === undefined && input.mode !== "desktop"
34 ? SESSION_COOKIE_NAME
35 : `${SESSION_COOKIE_NAME}_${input.port}`;
36}
37
38export function base64UrlEncode(input: string | Uint8Array): string {
39 return typeof input === "string"
40 ? Encoding.encodeBase64Url(new TextEncoder().encode(input))
41 : Encoding.encodeBase64Url(input);
42}
43
44export function base64UrlDecodeUtf8(input: string): string {
45 return Result.getOrThrow(Encoding.decodeBase64UrlString(input));
46}
47
48export function signPayload(payload: string, secret: Uint8Array): string {
49 return NodeCrypto.createHmac("sha256", Buffer.from(secret)).update(payload).digest("base64url");
50}
51
52export function timingSafeEqualBase64Url(left: string, right: string): boolean {
53 const leftBuffer = Buffer.from(left, "base64url");
54 const rightBuffer = Buffer.from(right, "base64url");
55 if (leftBuffer.length !== rightBuffer.length) {
56 return false;
57 }
58 return NodeCrypto.timingSafeEqual(leftBuffer, rightBuffer);
59}
60
61function normalizeNonEmptyString(value: string | null | undefined): string | undefined {
62 if (typeof value !== "string") {
63 return undefined;
64 }
65 const trimmed = value.trim();
66 return trimmed.length > 0 ? trimmed : undefined;
67}
68
69function normalizeIpAddress(value: string | null | undefined): string | undefined {
70 const normalized = normalizeNonEmptyString(value);
71 if (!normalized) {
72 return undefined;
73 }
74 return normalized.startsWith("::ffff:") ? normalized.slice("::ffff:".length) : normalized;
75}
76
77function inferDeviceType(userAgent: string | undefined): AuthClientMetadataDeviceType {
78 if (!userAgent) {
79 return "unknown";
80 }
81
82 const normalized = userAgent.toLowerCase();
83 if (/bot|crawler|spider|slurp|curl|wget/.test(normalized)) {
84 return "bot";
85 }
86 if (/ipad|tablet/.test(normalized)) {
87 return "tablet";
88 }
89 if (/iphone|android.+mobile|mobile/.test(normalized)) {
90 return "mobile";
91 }
92 return "desktop";
93}
94
95function inferBrowser(userAgent: string | undefined): string | undefined {
96 if (!userAgent) {
97 return undefined;
98 }
99 const normalized = userAgent.toLowerCase();
100 if (/edg\//.test(normalized)) return "Edge";
101 if (/opr\//.test(normalized)) return "Opera";
102 if (/firefox\//.test(normalized)) return "Firefox";
103 if (/electron\//.test(normalized)) return "Electron";
104 if (/chrome\//.test(normalized) || /crios\//.test(normalized)) return "Chrome";
105 if (/safari\//.test(normalized) && !/chrome\//.test(normalized)) return "Safari";
106 return undefined;
107}
108
109function inferOs(userAgent: string | undefined): string | undefined {
110 if (!userAgent) {
111 return undefined;
112 }
113 const normalized = userAgent.toLowerCase();
114 if (/iphone|ipad|ipod/.test(normalized)) return "iOS";
115 if (/android/.test(normalized)) return "Android";
116 if (/mac os x|macintosh/.test(normalized)) return "macOS";
117 if (/windows nt/.test(normalized)) return "Windows";
118 if (/linux/.test(normalized)) return "Linux";
119 return undefined;
120}
121
122function readRemoteAddressFromSource(source: unknown): string | undefined {
123 if (!source || typeof source !== "object") {
124 return undefined;
125 }
126
127 const candidate = source as {
128 readonly remoteAddress?: string | null;
129 readonly socket?: {
130 readonly remoteAddress?: string | null;
131 };
132 };
133
134 return normalizeIpAddress(candidate.socket?.remoteAddress ?? candidate.remoteAddress);
135}
136
137export function deriveAuthClientMetadata(input: {
138 readonly request: HttpServerRequest.HttpServerRequest;
139 readonly presented?: AuthClientPresentationMetadata;
140}): AuthClientMetadata {
141 const userAgent = normalizeNonEmptyString(input.request.headers["user-agent"]);
142 const ipAddress = readRemoteAddressFromSource(input.request.source);
143 const os = input.presented?.os ?? inferOs(userAgent);
144 const browser = inferBrowser(userAgent);
145 return {
146 ...(input.presented?.label ? { label: input.presented.label } : {}),
147 ...(ipAddress ? { ipAddress } : {}),
148 ...(userAgent ? { userAgent } : {}),
149 deviceType: input.presented?.deviceType ?? inferDeviceType(userAgent),
150 ...(os ? { os } : {}),
151 ...(browser ? { browser } : {}),
152 };
153}