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

utils.ts

189 lines6.1 KB

1import type {
2 AuthClientMetadata,
3 AuthClientMetadataDeviceType,
4 AuthClientPresentationMetadata,
5} from "@t3tools/contracts";
6import type * as HttpServerRequest from "effect/http/HttpServerRequest";
7// @effect-diagnostics-next-line nodeBuiltinImport:off -- Effect's Crypto has no createHmac or timingSafeEqual.
8import * as NodeCrypto from "node:crypto";
9import * as Base64Url from "effect/encoding/Base64Url";
10import * as Result from "effect/Result";
11​
12const SESSION_COOKIE_NAME = "t3_session";
13​
14/**
15 * Cookies are scoped by host but *not* by port, so any two servers that can be
16 * live on one hostname at once need separate names — otherwise the second
17 * clobbers the first's session and both sides see "Invalid session token
18 * signature" until someone clears cookies by hand.
19 */
20export function resolveSessionCookieName(input: {
21 readonly mode: "web" | "desktop";
22 readonly port: number;
23 readonly host: string | undefined;
24 readonly instanceKey: string;
25 readonly environmentId: string;
26 readonly development: boolean;
27}): string {
28 if (input.mode === "desktop") {
29 return `${SESSION_COOKIE_NAME}_${input.port}`;
30 }
31​
32 const instanceHash = NodeCrypto.createHash("sha256")
33 .update(
34 !input.development && isRemoteReachableHost(input.host)
35 ? input.environmentId
36 : input.instanceKey,
37 )
38 .digest("hex")
39 .slice(0, 12);
40​
41 if (!input.development && isRemoteReachableHost(input.host)) {
42 return `${SESSION_COOKIE_NAME}_${instanceHash}`;
43 }
44​
45 return `${SESSION_COOKIE_NAME}_${input.port}_${instanceHash}`;
47​
48export function resolveLegacySessionCookieName(input: {
49 readonly mode: "web" | "desktop";
50 readonly host: string | undefined;
51 readonly development: boolean;
52}): string | undefined {
53 return input.mode === "web" && !input.development && isRemoteReachableHost(input.host)
54 ? SESSION_COOKIE_NAME
55 : undefined;
57​
58export function isRemoteReachableHost(host: string | undefined): boolean {
59 if (host === "0.0.0.0" || host === "::" || host === "[::]") {
60 return true;
61 }
62 if (!host || host.length === 0) {
63 return false;
64 }
65 return !(
66 host === "localhost" ||
67 host === "127.0.0.1" ||
68 host === "::1" ||
69 host === "[::1]" ||
70 host.startsWith("127.")
71 );
73​
74export function base64UrlEncode(input: string | Uint8Array): string {
75 return typeof input === "string"
76 ? Base64Url.encode(new TextEncoder().encode(input))
77 : Base64Url.encode(input);
79​
80export function base64UrlDecodeUtf8(input: string): string {
81 return Result.getOrThrow(Base64Url.decodeString(input));
83​
84export function signPayload(payload: string, secret: Uint8Array): string {
85 return NodeCrypto.createHmac("sha256", Buffer.from(secret)).update(payload).digest("base64url");
87​
88export function timingSafeEqualBase64Url(left: string, right: string): boolean {
89 const leftBuffer = Buffer.from(left, "base64url");
90 const rightBuffer = Buffer.from(right, "base64url");
91 if (leftBuffer.length !== rightBuffer.length) {
92 return false;
93 }
94 return NodeCrypto.timingSafeEqual(leftBuffer, rightBuffer);
96​
97function normalizeNonEmptyString(value: string | null | undefined): string | undefined {
98 if (typeof value !== "string") {
99 return undefined;
100 }
101 const trimmed = value.trim();
102 return trimmed.length > 0 ? trimmed : undefined;
104​
105function normalizeIpAddress(value: string | null | undefined): string | undefined {
106 const normalized = normalizeNonEmptyString(value);
107 if (!normalized) {
108 return undefined;
109 }
110 return normalized.startsWith("::ffff:") ? normalized.slice("::ffff:".length) : normalized;
112​
113function inferDeviceType(userAgent: string | undefined): AuthClientMetadataDeviceType {
114 if (!userAgent) {
115 return "unknown";
116 }
117​
118 const normalized = userAgent.toLowerCase();
119 if (/bot|crawler|spider|slurp|curl|wget/.test(normalized)) {
120 return "bot";
121 }
122 if (/ipad|tablet/.test(normalized)) {
123 return "tablet";
124 }
125 if (/iphone|android.+mobile|mobile/.test(normalized)) {
126 return "mobile";
127 }
128 return "desktop";
130​
131function inferBrowser(userAgent: string | undefined): string | undefined {
132 if (!userAgent) {
133 return undefined;
134 }
135 const normalized = userAgent.toLowerCase();
136 if (/edg\//.test(normalized)) return "Edge";
137 if (/opr\//.test(normalized)) return "Opera";
138 if (/firefox\//.test(normalized)) return "Firefox";
139 if (/electron\//.test(normalized)) return "Electron";
140 if (/chrome\//.test(normalized) || /crios\//.test(normalized)) return "Chrome";
141 if (/safari\//.test(normalized) && !/chrome\//.test(normalized)) return "Safari";
142 return undefined;
144​
145function inferOs(userAgent: string | undefined): string | undefined {
146 if (!userAgent) {
147 return undefined;
148 }
149 const normalized = userAgent.toLowerCase();
150 if (/iphone|ipad|ipod/.test(normalized)) return "iOS";
151 if (/android/.test(normalized)) return "Android";
152 if (/mac os x|macintosh/.test(normalized)) return "macOS";
153 if (/windows nt/.test(normalized)) return "Windows";
154 if (/linux/.test(normalized)) return "Linux";
155 return undefined;
157​
158function readRemoteAddressFromSource(source: unknown): string | undefined {
159 if (!source || typeof source !== "object") {
160 return undefined;
161 }
162​
163 const candidate = source as {
164 readonly remoteAddress?: string | null;
165 readonly socket?: {
166 readonly remoteAddress?: string | null;
167 };
168 };
169​
170 return normalizeIpAddress(candidate.socket?.remoteAddress ?? candidate.remoteAddress);
172​
173export function deriveAuthClientMetadata(input: {
174 readonly request: HttpServerRequest.HttpServerRequest;
175 readonly presented?: AuthClientPresentationMetadata;
176}): AuthClientMetadata {
177 const userAgent = normalizeNonEmptyString(input.request.headers["user-agent"]);
178 const ipAddress = readRemoteAddressFromSource(input.request.source);
179 const os = input.presented?.os ?? inferOs(userAgent);
180 const browser = inferBrowser(userAgent);
181 return {
182 ...(input.presented?.label ? { label: input.presented.label } : {}),
183 ...(ipAddress ? { ipAddress } : {}),
184 ...(userAgent ? { userAgent } : {}),
185 deviceType: input.presented?.deviceType ?? inferDeviceType(userAgent),
186 ...(os ? { os } : {}),
187 ...(browser ? { browser } : {}),
188 };