Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

utils.ts

197 lines6.5 KB

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 * Remote web servers use their persisted environment identity and omit the
20 * port, so the name survives state-directory moves and public port changes.
21 *
22 * Desktop 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 */
25export function resolveSessionCookieName(input: {
26 readonly mode: "web" | "desktop";
27 readonly port: number;
28 readonly host: string | undefined;
29 readonly instanceKey: string;
30 readonly environmentId: string;
31 readonly development: boolean;
32}): string {
33 if (input.mode === "desktop") {
34 return `${SESSION_COOKIE_NAME}_${input.port}`;
35 }
36​
37 const instanceHash = NodeCrypto.createHash("sha256")
38 .update(
39 !input.development && isRemoteReachableHost(input.host)
40 ? input.environmentId
41 : input.instanceKey,
42 )
43 .digest("hex")
44 .slice(0, 12);
45​
46 if (!input.development && isRemoteReachableHost(input.host)) {
47 return `${SESSION_COOKIE_NAME}_${instanceHash}`;
48 }
49​
50 // Cookies are scoped by host, not port. Loopback development servers need an
51 // instance-specific name or parallel agents overwrite each other's session,
52 // and a server that later reuses the port receives a token signed elsewhere.
53 return `${SESSION_COOKIE_NAME}_${input.port}_${instanceHash}`;
55​
56export function resolveLegacySessionCookieName(input: {
57 readonly mode: "web" | "desktop";
58 readonly host: string | undefined;
59 readonly development: boolean;
60}): string | undefined {
61 return input.mode === "web" && !input.development && isRemoteReachableHost(input.host)
62 ? SESSION_COOKIE_NAME
63 : undefined;
65​
66export function isRemoteReachableHost(host: string | undefined): boolean {
67 if (host === "0.0.0.0" || host === "::" || host === "[::]") {
68 return true;
69 }
70 if (!host || host.length === 0) {
71 return false;
72 }
73 return !(
74 host === "localhost" ||
75 host === "127.0.0.1" ||
76 host === "::1" ||
77 host === "[::1]" ||
78 host.startsWith("127.")
79 );
81​
82export function base64UrlEncode(input: string | Uint8Array): string {
83 return typeof input === "string"
84 ? Encoding.encodeBase64Url(new TextEncoder().encode(input))
85 : Encoding.encodeBase64Url(input);
87​
88export function base64UrlDecodeUtf8(input: string): string {
89 return Result.getOrThrow(Encoding.decodeBase64UrlString(input));
91​
92export function signPayload(payload: string, secret: Uint8Array): string {
93 return NodeCrypto.createHmac("sha256", Buffer.from(secret)).update(payload).digest("base64url");
95​
96export function timingSafeEqualBase64Url(left: string, right: string): boolean {
97 const leftBuffer = Buffer.from(left, "base64url");
98 const rightBuffer = Buffer.from(right, "base64url");
99 if (leftBuffer.length !== rightBuffer.length) {
100 return false;
101 }
102 return NodeCrypto.timingSafeEqual(leftBuffer, rightBuffer);
104​
105function normalizeNonEmptyString(value: string | null | undefined): string | undefined {
106 if (typeof value !== "string") {
107 return undefined;
108 }
109 const trimmed = value.trim();
110 return trimmed.length > 0 ? trimmed : undefined;
112​
113function normalizeIpAddress(value: string | null | undefined): string | undefined {
114 const normalized = normalizeNonEmptyString(value);
115 if (!normalized) {
116 return undefined;
117 }
118 return normalized.startsWith("::ffff:") ? normalized.slice("::ffff:".length) : normalized;
120​
121function inferDeviceType(userAgent: string | undefined): AuthClientMetadataDeviceType {
122 if (!userAgent) {
123 return "unknown";
124 }
125​
126 const normalized = userAgent.toLowerCase();
127 if (/bot|crawler|spider|slurp|curl|wget/.test(normalized)) {
128 return "bot";
129 }
130 if (/ipad|tablet/.test(normalized)) {
131 return "tablet";
132 }
133 if (/iphone|android.+mobile|mobile/.test(normalized)) {
134 return "mobile";
135 }
136 return "desktop";
138​
139function inferBrowser(userAgent: string | undefined): string | undefined {
140 if (!userAgent) {
141 return undefined;
142 }
143 const normalized = userAgent.toLowerCase();
144 if (/edg\//.test(normalized)) return "Edge";
145 if (/opr\//.test(normalized)) return "Opera";
146 if (/firefox\//.test(normalized)) return "Firefox";
147 if (/electron\//.test(normalized)) return "Electron";
148 if (/chrome\//.test(normalized) || /crios\//.test(normalized)) return "Chrome";
149 if (/safari\//.test(normalized) && !/chrome\//.test(normalized)) return "Safari";
150 return undefined;
152​
153function inferOs(userAgent: string | undefined): string | undefined {
154 if (!userAgent) {
155 return undefined;
156 }
157 const normalized = userAgent.toLowerCase();
158 if (/iphone|ipad|ipod/.test(normalized)) return "iOS";
159 if (/android/.test(normalized)) return "Android";
160 if (/mac os x|macintosh/.test(normalized)) return "macOS";
161 if (/windows nt/.test(normalized)) return "Windows";
162 if (/linux/.test(normalized)) return "Linux";
163 return undefined;
165​
166function readRemoteAddressFromSource(source: unknown): string | undefined {
167 if (!source || typeof source !== "object") {
168 return undefined;
169 }
170​
171 const candidate = source as {
172 readonly remoteAddress?: string | null;
173 readonly socket?: {
174 readonly remoteAddress?: string | null;
175 };
176 };
177​
178 return normalizeIpAddress(candidate.socket?.remoteAddress ?? candidate.remoteAddress);
180​
181export function deriveAuthClientMetadata(input: {
182 readonly request: HttpServerRequest.HttpServerRequest;
183 readonly presented?: AuthClientPresentationMetadata;
184}): AuthClientMetadata {
185 const userAgent = normalizeNonEmptyString(input.request.headers["user-agent"]);
186 const ipAddress = readRemoteAddressFromSource(input.request.source);
187 const os = input.presented?.os ?? inferOs(userAgent);
188 const browser = inferBrowser(userAgent);
189 return {
190 ...(input.presented?.label ? { label: input.presented.label } : {}),
191 ...(ipAddress ? { ipAddress } : {}),
192 ...(userAgent ? { userAgent } : {}),
193 deviceType: input.presented?.deviceType ?? inferDeviceType(userAgent),
194 ...(os ? { os } : {}),
195 ...(browser ? { browser } : {}),
196 };