File size: 12,416 Bytes
9d4a3b0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
import { isHttpsRequest, requestOrigin } from "@/lib/request-origin";
import {
  benchmarkMailConfigured,
  consumeBenchmarkTicket,
  issueBenchmarkCode,
  verifyBenchmarkCode,
} from "@/lib/mailpit-public-auth";

const redisPrefix = "public-clone-auth:v1";
const sessionCookieName = "wb_public_session";
const codeTtlSeconds = 5 * 60;
const ticketTtlSeconds = 10 * 60;
const emailCooldownSeconds = 60;
const emailHourlyLimit = 6;
const ipHourlyLimit = 10;
const maxAttempts = 5;
const lockSeconds = 15 * 60;

const runtimeInstanceId = crypto.randomUUID();
const runtimeStartedAt = new Date().toISOString();
let publicStateMarker = "canonical";

type RedisResult = { result?: unknown; error?: unknown };
export class PublicCloneRateLimitError extends Error {
  constructor(public readonly retryAfter: number) {
    super("verification request rate limited");
  }
}

export class PublicCloneUnavailableError extends Error {
  constructor(message = "verification service unavailable") {
    super(message);
  }
}

function envValue(name: string) {
  return process.env[name]?.trim() || "";
}

function authMode() {
  return envValue("PUBLIC_CLONE_AUTH_MODE").toLowerCase();
}

function isLocalDevAuth() {
  return benchmarkMailConfigured() || authMode() === "local-dev";
}

function siteId() {
  return envValue("PUBLIC_CLONE_AUTH_SITE_ID") || "linkedin";
}

function siteLabel() {
  return envValue("PUBLIC_CLONE_AUTH_SITE_LABEL") || "LinkedIn";
}

function bytesToHex(bytes: Uint8Array) {
  return Array.from(bytes, (byte) => byte.toString(16).padStart(2, "0")).join("");
}

export async function sha256Hex(value: string) {
  const digest = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(value));
  return bytesToHex(new Uint8Array(digest));
}

function randomHex(bytes: number) {
  return bytesToHex(crypto.getRandomValues(new Uint8Array(bytes)));
}

function randomCode() {
  const bytes = crypto.getRandomValues(new Uint8Array(6));
  return Array.from(bytes, (byte) => String(byte % 10)).join("");
}

function readCookie(request: Request, name: string) {
  const header = request.headers.get("cookie") || "";
  for (const item of header.split(";")) {
    const separator = item.indexOf("=");
    if (separator <= 0) continue;
    if (item.slice(0, separator).trim() === name) return decodeURIComponent(item.slice(separator + 1).trim());
  }
  return "";
}

export async function publicSession(request: Request) {
  const existing = readCookie(request, sessionCookieName);
  const token = /^[A-Za-z0-9._~-]{32,160}$/.test(existing) ? existing : `${crypto.randomUUID()}${randomHex(16)}`;
  const secure = isHttpsRequest(request) ? "; Secure" : "";
  return {
    token,
    digest: await sha256Hex(token),
    cookie: `${sessionCookieName}=${encodeURIComponent(token)}; Path=/; HttpOnly; SameSite=Lax${secure}`,
  };
}

export function sameOrigin(request: Request) {
  const candidate = request.headers.get("origin") || request.headers.get("referer");
  if (!candidate) return false;
  try {
    const parsed = new URL(candidate);
    return `${parsed.protocol}//${parsed.host}` === requestOrigin(request);
  } catch {
    return false;
  }
}

export function normalizePublicEmail(value: unknown) {
  if (typeof value !== "string") throw new Error("invalid email");
  const email = value.trim().toLowerCase();
  if (
    email.length > 254 ||
    !/^[^@\s]{1,64}@[^@\s]{1,189}$/.test(email) ||
    email.split("@").length !== 2
  ) {
    throw new Error("invalid email");
  }
  const [local, domain] = email.split("@");
  if (!local || !domain || local.startsWith(".") || local.endsWith(".") || local.includes("..")) {
    throw new Error("invalid email");
  }
  if (domain.startsWith(".") || domain.endsWith(".") || !domain.includes(".")) throw new Error("invalid email");
  return email;
}

function requirePublicAuthConfig() {
  if (authMode() !== "redis-resend") {
    throw new PublicCloneUnavailableError();
  }
  const redisUrl = envValue("PUBLIC_CLONE_AUTH_REDIS_REST_URL").replace(/\/+$/, "");
  const resendUrl = envValue("PUBLIC_CLONE_AUTH_RESEND_API_URL").replace(/\/+$/, "");
  if (!redisUrl || !resendUrl) throw new PublicCloneUnavailableError();
  return { redisUrl, resendUrl };
}

async function redisExecute(commands: unknown[][], atomic = false) {
  const { redisUrl } = requirePublicAuthConfig();
  const token = envValue("PUBLIC_CLONE_AUTH_REDIS_REST_TOKEN");
  const headers: Record<string, string> = { "content-type": "application/json", accept: "application/json" };
  if (token) headers.authorization = `Bearer ${token}`;
  const response = await fetch(`${redisUrl}/${atomic ? "multi-exec" : "pipeline"}`, {
    method: "POST",
    headers,
    body: JSON.stringify(commands),
  }).catch(() => null);
  const payload = await response?.json().catch(() => null) as RedisResult[] | null;
  if (!response?.ok || !Array.isArray(payload) || payload.length !== commands.length) {
    throw new PublicCloneUnavailableError("Redis verification state is unavailable");
  }
  return payload.map((item) => {
    if (!item || typeof item !== "object" || "error" in item) {
      throw new PublicCloneUnavailableError("Redis verification command failed");
    }
    return item.result;
  });
}

function globalKey(kind: string, scope: string) {
  return `${redisPrefix}:global:${kind}:${scope}`;
}

function scopedHash(sessionDigest: string, email: string) {
  return sha256Hex(`${siteId()}\0${sessionDigest}\0${email}`);
}

function siteKey(kind: string, scope: string) {
  return `${redisPrefix}:site:${siteId()}:${kind}:${scope}`;
}

async function consumeHourlyBudget(kind: "email-hour" | "ip-hour", scope: string, limit: number, hour: number) {
  const key = globalKey(`rate-${kind}`, `${scope}:${hour}`);
  const [count] = await redisExecute([["INCR", key], ["EXPIRE", key, 60 * 60]], true);
  const value = Number(count);
  if (!Number.isFinite(value)) throw new PublicCloneUnavailableError("Redis returned an invalid rate count");
  return value <= limit;
}

async function releaseCooldown(emailHash: string) {
  await redisExecute([["DEL", globalKey("cooldown-email", emailHash)]]).catch(() => null);
}

async function sendResendEmail(email: string, code: string, idempotencyKey: string) {
  const { resendUrl } = requirePublicAuthConfig();
  const label = siteLabel();
  const escapedLabel = label.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;");
  const payload: Record<string, unknown> = {
    to: [email],
    subject: `${label} verification code`,
    html: `<p>Your ${escapedLabel} verification code is:</p><p>${code}</p><p>This code expires in 5 minutes.</p><p>If you did not request it, you can ignore this message.</p>`,
    text: `Your ${label} verification code is:\n\n${code}\n\nThis code expires in 5 minutes.\n\nIf you did not request it, you can ignore this message.`,
    tags: [
      { name: "purpose", value: "registration" },
      { name: "site", value: siteId() },
    ],
  };
  const fromEmail = envValue("PUBLIC_CLONE_AUTH_RESEND_FROM_EMAIL");
  if (fromEmail) payload.from = fromEmail;
  const apiKey = envValue("PUBLIC_CLONE_AUTH_RESEND_API_KEY");
  const headers: Record<string, string> = {
    "content-type": "application/json",
    accept: "application/json",
    "idempotency-key": idempotencyKey,
  };
  if (apiKey) headers.authorization = `Bearer ${apiKey}`;
  const response = await fetch(resendUrl, {
    method: "POST",
    headers,
    body: JSON.stringify(payload),
  }).catch(() => null);
  const result = await response?.json().catch(() => null) as { id?: string; ok?: boolean } | null;
  if (!response?.ok || (!result?.id && result?.ok !== true)) {
    throw new PublicCloneUnavailableError("verification email delivery failed");
  }
}

export async function issuePublicRegistrationCode(
  sessionDigest: string,
  email: string,
  clientAddress: string,
): Promise<{ expiresIn: number }> {
  if (isLocalDevAuth()) {
    try {
      return await issueBenchmarkCode(siteId(), siteLabel(), sessionDigest, email);
    } catch {
      throw new PublicCloneUnavailableError("verification email delivery failed");
    }
  }

  const emailHash = await sha256Hex(email);
  const clientHash = await sha256Hex(clientAddress || "unknown");
  const cooldownKey = globalKey("cooldown-email", emailHash);
  const [reserved] = await redisExecute([["SET", cooldownKey, "1", "EX", emailCooldownSeconds, "NX"]]);
  if (reserved === null) throw new PublicCloneRateLimitError(emailCooldownSeconds);

  try {
    const hour = Math.floor(Date.now() / 3_600_000);
    const emailAllowed = await consumeHourlyBudget("email-hour", emailHash, emailHourlyLimit, hour);
    const ipAllowed = await consumeHourlyBudget("ip-hour", clientHash, ipHourlyLimit, hour);
    if (!emailAllowed || !ipAllowed) {
      await releaseCooldown(emailHash);
      throw new PublicCloneRateLimitError(60 * 60);
    }

    const code = randomCode();
    const salt = randomHex(16);
    const scope = await scopedHash(sessionDigest, email);
    const challenge = JSON.stringify({ hash: await sha256Hex(`${salt}:${code}`), salt });
    await redisExecute([
      ["SET", siteKey("challenge", scope), challenge, "EX", codeTtlSeconds],
      ["DEL", siteKey("attempts", scope)],
      ["DEL", siteKey("lock", scope)],
    ], true);
    const idempotencyKey = (await sha256Hex(`registration:${siteId()}:${scope}:${salt}`)).slice(0, 48);
    await sendResendEmail(email, code, idempotencyKey);
    return { expiresIn: codeTtlSeconds };
  } catch (error) {
    if (!(error instanceof PublicCloneRateLimitError)) await releaseCooldown(emailHash);
    throw error;
  }
}

export async function verifyPublicRegistrationCode(sessionDigest: string, email: string, code: string) {
  const scope = await scopedHash(sessionDigest, email);
  if (isLocalDevAuth()) {
    return verifyBenchmarkCode(siteId(), sessionDigest, email, code);
  }

  const challengeKey = siteKey("challenge", scope);
  const attemptsKey = siteKey("attempts", scope);
  const lockKey = siteKey("lock", scope);
  const verifiedKey = siteKey("verified", scope);
  const [locked] = await redisExecute([["GET", lockKey]]);
  if (locked !== null) return "locked";
  const [rawChallenge] = await redisExecute([["GET", challengeKey]]);
  if (rawChallenge === null) return "expired";
  const challenge = JSON.parse(String(rawChallenge)) as { salt?: string; hash?: string };
  if (!challenge.salt || !challenge.hash) throw new PublicCloneUnavailableError("stored challenge is invalid");
  if (/^[0-9]{6}$/.test(code) && await sha256Hex(`${challenge.salt}:${code}`) === challenge.hash) {
    await redisExecute([
      ["DEL", challengeKey],
      ["DEL", attemptsKey],
      ["DEL", lockKey],
      ["SET", verifiedKey, "1", "EX", ticketTtlSeconds],
    ], true);
    return "verified";
  }
  const [attempts] = await redisExecute([["INCR", attemptsKey], ["EXPIRE", attemptsKey, codeTtlSeconds]], true);
  const attemptCount = Number(attempts);
  if (attemptCount >= maxAttempts) {
    await redisExecute([
      ["SET", lockKey, "1", "EX", lockSeconds],
      ["DEL", challengeKey],
    ], true);
    return "locked";
  }
  return "invalid";
}

export async function consumePublicRegistrationTicket(sessionDigest: string, email: string) {
  const scope = await scopedHash(sessionDigest, email);
  if (isLocalDevAuth()) {
    return consumeBenchmarkTicket(siteId(), sessionDigest, email);
  }

  const [ticket] = await redisExecute([["GETDEL", siteKey("verified", scope)]]);
  return ticket === "1";
}

export async function seedPayload() {
  return { site_id: siteId(), seed_sha256: await sha256Hex(`${siteId()}:public-seed:v1`) };
}

export function runtimePayload() {
  return { site_id: siteId(), runtime_instance_id: runtimeInstanceId, started_at: runtimeStartedAt };
}

export async function statePayload() {
  return { site_id: siteId(), state_sha256: await sha256Hex(JSON.stringify({ siteId: siteId(), marker: publicStateMarker })) };
}

export async function mutateState(challenge: unknown) {
  if (typeof challenge !== "string" || !/^[a-f0-9]{64}$/.test(challenge)) throw new Error("invalid challenge");
  publicStateMarker = await sha256Hex(`mutation:${challenge}`);
  return { site_id: siteId(), challenge_sha256: await sha256Hex(challenge), state_sha256: (await statePayload()).state_sha256 };
}

export async function resetState() {
  publicStateMarker = "canonical";
  return statePayload();
}