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

utils.ts

184 lines5.9 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/** Cookies span ports; use separate names for servers sharing a hostname. */
15export function resolveSessionCookieName(input: {
16 readonly mode: "web" | "desktop";
17 readonly port: number;
18 readonly host: string | undefined;
19 readonly instanceKey: string;
20 readonly environmentId: string;
21 readonly development: boolean;
22}): string {
23 if (input.mode === "desktop") {
24 return `${SESSION_COOKIE_NAME}_${input.port}`;
25 }
26​
27 const instanceHash = NodeCrypto.createHash("sha256")
28 .update(
29 !input.development && isRemoteReachableHost(input.host)
30 ? input.environmentId
31 : input.instanceKey,
32 )
33 .digest("hex")
34 .slice(0, 12);
35​
36 if (!input.development && isRemoteReachableHost(input.host)) {
37 return `${SESSION_COOKIE_NAME}_${instanceHash}`;
38 }
39​
40 return `${SESSION_COOKIE_NAME}_${input.port}_${instanceHash}`;
42​
43export function resolveLegacySessionCookieName(input: {
44 readonly mode: "web" | "desktop";
45 readonly host: string | undefined;
46 readonly development: boolean;
47}): string | undefined {
48 return input.mode === "web" && !input.development && isRemoteReachableHost(input.host)
49 ? SESSION_COOKIE_NAME
50 : undefined;
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 );
68​
69export function base64UrlEncode(input: string | Uint8Array): string {
70 return typeof input === "string"
71 ? Base64Url.encode(new TextEncoder().encode(input))
72 : Base64Url.encode(input);
74​
75export function base64UrlDecodeUtf8(input: string): string {
76 return Result.getOrThrow(Base64Url.decodeString(input));
78​
79export function signPayload(payload: string, secret: Uint8Array): string {
80 return NodeCrypto.createHmac("sha256", Buffer.from(secret)).update(payload).digest("base64url");
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);
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;
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;
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";
125​
126function inferBrowser(userAgent: string | undefined): string | undefined {
127 if (!userAgent) {
128 return undefined;
129 }
130 const normalized = userAgent.toLowerCase();
131 if (/edg(?:e|a|ios)?\//.test(normalized)) return "Edge";
132 if (/opr\/|opios\//.test(normalized)) return "Opera";
133 if (/firefox\/|fxios\//.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;
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;
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);
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 };