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

utils.ts

139 lines4.5 KB

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