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

utils.ts

187 lines6.4 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 NodeNet from "node:net";
10import { normalizeHostname } from "@t3tools/shared/hostClassification";
11import * as Base64Url from "effect/encoding/Base64Url";
12import * as Result from "effect/Result";
13​
14const SESSION_COOKIE_NAME = "t3_session";
15​
16/** Cookies span ports; use separate names for servers sharing a hostname. */
17export function resolveSessionCookieName(input: {
18 readonly mode: "web" | "desktop";
19 readonly port: number;
20 readonly host: string | undefined;
21 readonly instanceKey: string;
22 readonly environmentId: string;
23 readonly development: boolean;
24}): string {
25 if (input.mode === "desktop") {
26 return `${SESSION_COOKIE_NAME}_${input.port}`;
27 }
28​
29 const instanceHash = NodeCrypto.createHash("sha256")
30 .update(
31 !input.development && isRemoteReachableHost(input.host)
32 ? input.environmentId
33 : input.instanceKey,
34 )
35 .digest("hex")
36 .slice(0, 12);
37​
38 if (!input.development && isRemoteReachableHost(input.host)) {
39 return `${SESSION_COOKIE_NAME}_${instanceHash}`;
40 }
41​
42 return `${SESSION_COOKIE_NAME}_${input.port}_${instanceHash}`;
44​
45export function resolveLegacySessionCookieName(input: {
46 readonly mode: "web" | "desktop";
47 readonly host: string | undefined;
48 readonly development: boolean;
49}): string | undefined {
50 return input.mode === "web" && !input.development && isRemoteReachableHost(input.host)
51 ? SESSION_COOKIE_NAME
52 : undefined;
54​
55/**
56 * The loopback address a server given `host` listens on, or undefined when it may listen beyond
57 * this machine. Unset means 127.0.0.1. Only a loopback literal or `localhost` counts: Node listens
58 * on every interface for an empty host, and any other name resolves through DNS.
59 */
60export function loopbackBindAddress(host: string | undefined): string | undefined {
61 if (host === undefined) return "127.0.0.1";
62 const address = normalizeHostname(host);
63 if (address === "localhost") return "127.0.0.1";
64 return (NodeNet.isIPv4(address) && address.startsWith("127.")) || address === "::1"
65 ? address
66 : undefined;
68​
69export const isRemoteReachableHost = (host: string | undefined): boolean =>
70 loopbackBindAddress(host) === undefined;
71​
72export function base64UrlEncode(input: string | Uint8Array): string {
73 return typeof input === "string"
74 ? Base64Url.encode(new TextEncoder().encode(input))
75 : Base64Url.encode(input);
77​
78export function base64UrlDecodeUtf8(input: string): string {
79 return Result.getOrThrow(Base64Url.decodeString(input));
81​
82export function signPayload(payload: string, secret: Uint8Array): string {
83 return NodeCrypto.createHmac("sha256", Buffer.from(secret)).update(payload).digest("base64url");
85​
86export function timingSafeEqualBase64Url(left: string, right: string): boolean {
87 const leftBuffer = Buffer.from(left, "base64url");
88 const rightBuffer = Buffer.from(right, "base64url");
89 if (leftBuffer.length !== rightBuffer.length) {
90 return false;
91 }
92 return NodeCrypto.timingSafeEqual(leftBuffer, rightBuffer);
94​
95function normalizeNonEmptyString(value: string | null | undefined): string | undefined {
96 if (typeof value !== "string") {
97 return undefined;
98 }
99 const trimmed = value.trim();
100 return trimmed.length > 0 ? trimmed : undefined;
102​
103function normalizeIpAddress(value: string | null | undefined): string | undefined {
104 const normalized = normalizeNonEmptyString(value);
105 if (!normalized) {
106 return undefined;
107 }
108 return normalized.startsWith("::ffff:") ? normalized.slice("::ffff:".length) : normalized;
110​
111function inferDeviceType(userAgent: string | undefined): AuthClientMetadataDeviceType {
112 if (!userAgent) {
113 return "unknown";
114 }
115​
116 const normalized = userAgent.toLowerCase();
117 if (/bot|crawler|spider|slurp|curl|wget/.test(normalized)) {
118 return "bot";
119 }
120 if (/ipad|tablet/.test(normalized)) {
121 return "tablet";
122 }
123 if (/iphone|android.+mobile|mobile/.test(normalized)) {
124 return "mobile";
125 }
126 return "desktop";
128​
129function inferBrowser(userAgent: string | undefined): string | undefined {
130 if (!userAgent) {
131 return undefined;
132 }
133 const normalized = userAgent.toLowerCase();
134 if (/edg(?:e|a|ios)?\//.test(normalized)) return "Edge";
135 if (/opr\/|opios\//.test(normalized)) return "Opera";
136 if (/firefox\/|fxios\//.test(normalized)) return "Firefox";
137 if (/electron\//.test(normalized)) return "Electron";
138 if (/chrome\//.test(normalized) || /crios\//.test(normalized)) return "Chrome";
139 if (/safari\//.test(normalized) && !/chrome\//.test(normalized)) return "Safari";
140 return undefined;
142​
143function inferOs(userAgent: string | undefined): string | undefined {
144 if (!userAgent) {
145 return undefined;
146 }
147 const normalized = userAgent.toLowerCase();
148 if (/iphone|ipad|ipod/.test(normalized)) return "iOS";
149 if (/android/.test(normalized)) return "Android";
150 if (/mac os x|macintosh/.test(normalized)) return "macOS";
151 if (/windows nt/.test(normalized)) return "Windows";
152 if (/linux/.test(normalized)) return "Linux";
153 return undefined;
155​
156function readRemoteAddressFromSource(source: unknown): string | undefined {
157 if (!source || typeof source !== "object") {
158 return undefined;
159 }
160​
161 const candidate = source as {
162 readonly remoteAddress?: string | null;
163 readonly socket?: {
164 readonly remoteAddress?: string | null;
165 };
166 };
167​
168 return normalizeIpAddress(candidate.socket?.remoteAddress ?? candidate.remoteAddress);
170​
171export function deriveAuthClientMetadata(input: {
172 readonly request: HttpServerRequest.HttpServerRequest;
173 readonly presented?: AuthClientPresentationMetadata;
174}): AuthClientMetadata {
175 const userAgent = normalizeNonEmptyString(input.request.headers["user-agent"]);
176 const ipAddress = readRemoteAddressFromSource(input.request.source);
177 const os = input.presented?.os ?? inferOs(userAgent);
178 const browser = inferBrowser(userAgent);
179 return {
180 ...(input.presented?.label ? { label: input.presented.label } : {}),
181 ...(ipAddress ? { ipAddress } : {}),
182 ...(userAgent ? { userAgent } : {}),
183 deviceType: input.presented?.deviceType ?? inferDeviceType(userAgent),
184 ...(os ? { os } : {}),
185 ...(browser ? { browser } : {}),
186 };