File size: 6,546 Bytes
062a991 | 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 | import { createHash } from "node:crypto";
import { mkdirSync } from "node:fs";
import { DatabaseSync } from "node:sqlite";
import { isAbsolute, join } from "node:path";
const SITE_ID = "linkedin";
const SESSION_NAME = `__Host-${SITE_ID}-session`;
const HARBOR_REGISTRATION_EMAIL_SUFFIXES = Object.freeze([
"@linkedin.test",
"@paired.test",
]);
let database: DatabaseSync | undefined;
function db() {
if (database) return database;
const dataDir = process.env.DATA_DIR || "";
if (!isAbsolute(dataDir)) throw new Error("DATA_DIR must be absolute");
mkdirSync(dataDir, { recursive: true });
database = new DatabaseSync(join(dataDir, `${SITE_ID}.sqlite3`));
database.exec(`
PRAGMA foreign_keys = ON;
PRAGMA journal_mode = DELETE;
PRAGMA busy_timeout = 5000;
PRAGMA user_version = 1;
CREATE TABLE IF NOT EXISTS websitebench_meta (
site_id TEXT PRIMARY KEY NOT NULL,
schema_name TEXT NOT NULL
);
CREATE TABLE IF NOT EXISTS local_users (
token TEXT PRIMARY KEY NOT NULL,
email TEXT UNIQUE NOT NULL,
display_name TEXT NOT NULL,
created_at TEXT NOT NULL
);
CREATE TABLE IF NOT EXISTS business_state (
id INTEGER PRIMARY KEY CHECK (id = 1),
marker TEXT NOT NULL
);
CREATE TABLE IF NOT EXISTS mail_receipts (
id INTEGER PRIMARY KEY AUTOINCREMENT,
site_id TEXT NOT NULL,
recipient TEXT NOT NULL,
purpose TEXT NOT NULL
);
CREATE TABLE IF NOT EXISTS sandbox_payments (
id INTEGER PRIMARY KEY AUTOINCREMENT,
site_id TEXT NOT NULL,
actor_token TEXT NOT NULL,
provider TEXT NOT NULL,
outcome TEXT NOT NULL
);
`);
database.prepare(
"INSERT OR IGNORE INTO websitebench_meta(site_id, schema_name) VALUES (?, ?)",
).run(SITE_ID, `websitebench-${SITE_ID}`);
database.prepare(
"INSERT OR IGNORE INTO business_state(id, marker) VALUES (1, 'canonical')",
).run();
return database;
}
function digest(value: string) {
return createHash("sha256").update(value).digest("hex");
}
export function isHarborRegistrationEmail(value: unknown) {
if (typeof value !== "string") return false;
const email = value.trim().toLowerCase();
return HARBOR_REGISTRATION_EMAIL_SUFFIXES.some((suffix) => email.endsWith(suffix));
}
function cookieValue(request: Request) {
for (const part of (request.headers.get("cookie") || "").split(";")) {
const separator = part.indexOf("=");
if (separator > 0 && part.slice(0, separator).trim() === SESSION_NAME) {
return part.slice(separator + 1).trim();
}
}
return "";
}
export function hasHarborSession(request: Request) {
return Boolean(cookieValue(request));
}
async function deliverFormalMail(recipient: string, purpose: string) {
// Trial mail ABI (instruction.md): POST {from,to,subject,text} with the
// bearer token; absent env means this journey carries no mail duty.
const url = process.env.WEBSITEBENCH_MAIL_API_URL || "";
const token = process.env.WEBSITEBENCH_MAIL_API_TOKEN || "";
const sender =
process.env.WEBSITEBENCH_MAIL_FROM || process.env.WEBSITEBENCH_SMTP_FROM || "";
if (!url || !token || !sender) return;
try {
await fetch(url, {
method: "POST",
headers: {
authorization: `Bearer ${token}`,
"content-type": "application/json",
},
body: JSON.stringify({
from: sender,
to: recipient,
subject: `${SITE_ID} ${purpose} notice`,
text: `This ${purpose} message confirms ${recipient} on the ${SITE_ID} offline clone.`,
}),
signal: AbortSignal.timeout(8000),
});
} catch {
// The trusted mail check reads the store; a failed delivery surfaces there.
}
}
export async function harborRegister(
request: Request,
options: {
emailField: string;
nameField: string;
status: number;
mailPurpose: string | null;
},
) {
const body = await request.json().catch(() => ({})) as Record<string, unknown>;
const email = String(body[options.emailField] || "").trim().toLowerCase();
const displayName = String(body[options.nameField] || "WebsiteBench User").trim();
if (!/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(email) || !displayName) {
return Response.json({ ok: false, error: "invalid_registration" }, { status: 400 });
}
const token = digest(`${SITE_ID}\0${email}`);
try {
db().prepare(
"INSERT INTO local_users(token, email, display_name, created_at) VALUES (?, ?, ?, ?)",
).run(token, email, displayName, "2026-01-01T00:00:00Z");
} catch {
return Response.json({ ok: false, error: "account_exists" }, { status: 409 });
}
if (options.mailPurpose) {
db().prepare(
"INSERT INTO mail_receipts(site_id, recipient, purpose) VALUES (?, ?, ?)",
).run(SITE_ID, email, options.mailPurpose);
await deliverFormalMail(email, options.mailPurpose);
}
db().prepare("UPDATE business_state SET marker = ? WHERE id = 1").run(
digest(`registered:${email}`),
);
return Response.json(
{ ok: true, created: true, user: { email, name: displayName } },
{
status: options.status,
headers: {
"cache-control": "no-store",
"set-cookie": `${SESSION_NAME}=${token}; Path=/; Secure; HttpOnly; SameSite=Lax`,
},
},
);
}
export function harborSession(
request: Request,
authenticatedBody: Record<string, unknown>,
) {
const token = cookieValue(request);
const user = token
? db().prepare(
"SELECT email, display_name FROM local_users WHERE token = ?",
).get(token) as { email?: string; display_name?: string } | undefined
: undefined;
if (!user) return null;
return Response.json(
{
...authenticatedBody,
user: { email: user.email, name: user.display_name },
},
{ headers: { "cache-control": "no-store" } },
);
}
export async function harborPayment(request: Request, status: number) {
await request.arrayBuffer();
const token = cookieValue(request);
const user = token
? db().prepare("SELECT token FROM local_users WHERE token = ?").get(token)
: undefined;
if (!user) {
return Response.json(
{ ok: false, error: "authentication_required" },
{ status: 401 },
);
}
db().prepare(
"INSERT INTO sandbox_payments(site_id, actor_token, provider, outcome) VALUES (?, ?, ?, ?)",
).run(SITE_ID, token, "local-sandbox", "approved");
return Response.json(
{ ok: true, provider: "local-sandbox", outcome: "approved" },
{ status, headers: { "cache-control": "no-store" } },
);
}
|