Age: a Didit provider behind the vendor-neutral age interface. A person verifies once (ID document, passive liveness, face match) and all their linked IMVU accounts count as adult. Webhooks are checked against Didit's signatures; only "over 18" is kept. A later answer replaces an earlier one (an approval taken back is revoked). Checks are limited: one unfinished check per person, 3 in 30 days, none once verified, and a monthly cap (DIDIT_MONTHLY_LIMIT, default 30: Didit's free plan is $10 of credit a month and a check costs $0.30). The Account page gets an Age Verification card. Registration: open or closed, an admin's setting in the console (default from REGISTRATION). Closed: new accounts can only sign in until a moderator approves them (or declines, deleting the account); the website shows them a waiting page and the API treats them as signed out. Co-Authored-By: Claude Opus 5.5 <[email protected]>
276 lines
15 KiB
TypeScript
276 lines
15 KiB
TypeScript
// Age verification: the one rule, providers that check a person (a fake document-check vendor with signed webhooks,
|
|
// and Didit's adapter against a fake Didit), limits on checks, and IMVU's answers changing.
|
|
import { createHmac } from "node:crypto";
|
|
import { afterAll, beforeAll, expect, test } from "bun:test";
|
|
import { eq, openDatabase, schema, type Database } from "@t5de/db";
|
|
import { AgeService, attemptsPerPerson, type Provider } from "../src/age";
|
|
import { ageOn, diditAgeProvider } from "../src/age/didit";
|
|
import { imvuAgeProvider } from "../src/age/imvu";
|
|
import { createApp } from "../src/app";
|
|
import { createAuth } from "../src/auth";
|
|
import { ImvuClient, type ImvuUser } from "../src/imvu";
|
|
|
|
const webURL = "http://web.test";
|
|
const accounts = new Map<number, ImvuUser>();
|
|
const fakeIMVU: typeof fetch = (async (input: RequestInfo | URL) => {
|
|
const url = new URL(String(input));
|
|
const u = [...accounts.values()].find(
|
|
(u) => url.pathname === `/user/user-${u.id}` || url.searchParams.get("username")?.toLowerCase() === u.username.toLowerCase(),
|
|
);
|
|
return Response.json({
|
|
denormalized: u
|
|
? { [`https://api.imvu.com/user/user-${u.id}`]: { data: { legacy_cid: u.id, username: u.username, tagline: u.tagline, is_ageverified: u.ageVerified, is_ap: u.accessPass } } }
|
|
: {},
|
|
});
|
|
}) as typeof fetch;
|
|
|
|
// A document-check vendor: sends the person to its page, then reports by a webhook signed with a shared secret.
|
|
const webhookSecret = "vendor-secret";
|
|
const fakeVendor: Provider = {
|
|
id: "vendor",
|
|
label: "ID document",
|
|
vendor: "Vendor",
|
|
scope: "person",
|
|
start: async () => {
|
|
const ref = `session-${crypto.randomUUID()}`;
|
|
return { kind: "redirect", url: `https://vendor.test/check/${ref}`, ref };
|
|
},
|
|
webhook: async (request) => {
|
|
if (request.headers.get("x-signature") !== webhookSecret) throw new Error("bad signature");
|
|
const body = (await request.json()) as { session: string; approved: boolean; over18: boolean };
|
|
return { ref: body.session, result: body.approved ? { overEighteen: body.over18, method: "id_document" } : "failed" };
|
|
},
|
|
};
|
|
|
|
// Didit: sessions per person (an unfinished one is given again), and each session's decision.
|
|
const diditSecret = "didit-secret";
|
|
const diditSessions = new Map<string, { id: string; vendor: string; finished: boolean; decision?: unknown }>();
|
|
const fakeDidit: typeof fetch = (async (input: RequestInfo | URL, init?: RequestInit) => {
|
|
const url = new URL(String(input));
|
|
if (new Headers(init?.headers).get("x-api-key") !== "didit-key") return new Response("no key", { status: 401 });
|
|
if (init?.method === "POST" && url.pathname === "/v3/session/") {
|
|
const body = JSON.parse(String(init.body));
|
|
expect(body.workflow_id).toBe("workflow");
|
|
let s = [...diditSessions.values()].find((s) => s.vendor === body.vendor_data && !s.finished);
|
|
if (!s) {
|
|
s = { id: crypto.randomUUID(), vendor: body.vendor_data, finished: false };
|
|
diditSessions.set(s.id, s);
|
|
}
|
|
return Response.json({ session_id: s.id, url: `https://verify.didit.test/session/${s.id}`, status: "Not Started" }, { status: 201 });
|
|
}
|
|
const m = /^\/v3\/session\/([^/]+)\/decision\/$/.exec(url.pathname);
|
|
if (m && diditSessions.get(m[1]!)) return Response.json(diditSessions.get(m[1]!)!.decision ?? {});
|
|
return new Response("not found", { status: 404 });
|
|
}) as typeof fetch;
|
|
const didit = diditAgeProvider({ apiKey: "didit-key", workflowId: "workflow", webhookSecret: diditSecret, baseURL: "https://didit.test", fetch: fakeDidit });
|
|
|
|
/** A Didit webhook request, signed as Didit signs it (the raw body, or V2), or forged. */
|
|
function diditHook(body: Record<string, unknown>, sign: "raw" | "v2" | "forged" = "raw", timestamp = Math.floor(Date.now() / 1000)) {
|
|
const raw = JSON.stringify(body);
|
|
const hmac = (s: string, key = diditSecret) => createHmac("sha256", key).update(s).digest("hex");
|
|
const sortKeys = (v: unknown): unknown =>
|
|
Array.isArray(v)
|
|
? v.map(sortKeys)
|
|
: v && typeof v === "object"
|
|
? Object.fromEntries(Object.keys(v).sort().map((k) => [k, sortKeys((v as Record<string, unknown>)[k])]))
|
|
: v;
|
|
const headers: Record<string, string> = { "X-Timestamp": String(timestamp), "Content-Type": "application/json" };
|
|
if (sign === "raw") headers["X-Signature"] = hmac(raw);
|
|
if (sign === "v2") headers["X-Signature-V2"] = hmac(JSON.stringify(sortKeys(body)));
|
|
if (sign === "forged") headers["X-Signature"] = hmac(raw, "wrong");
|
|
return fetch(`${base}/api/v1/age/webhook/didit`, { method: "POST", headers, body: raw });
|
|
}
|
|
|
|
let db: Database;
|
|
let close: () => Promise<void>;
|
|
let base: string;
|
|
let age: AgeService;
|
|
let stop: () => void;
|
|
|
|
beforeAll(async () => {
|
|
({ db, close } = await openDatabase("memory"));
|
|
const auth = createAuth(db, { apiURL: "http://api.test", webURL, secret: "test-secret-test-secret-test-secret-1234", rateLimit: false });
|
|
const imvu = new ImvuClient("http://imvu.test", fakeIMVU);
|
|
age = new AgeService(db, [imvuAgeProvider(imvu), fakeVendor, didit]);
|
|
const hub = createApp({ db, auth, imvu, age, webURL });
|
|
hub.app.listen({ port: 0, hostname: "127.0.0.1" });
|
|
const server = hub.app.server as unknown as { port: number; stop: () => void };
|
|
stop = () => server.stop();
|
|
base = `http://127.0.0.1:${server.port}`;
|
|
});
|
|
|
|
afterAll(async () => {
|
|
stop();
|
|
await close();
|
|
});
|
|
|
|
async function call(cookie: { v: string }, method: string, path: string, body?: unknown, headers: Record<string, string> = {}) {
|
|
const res = await fetch(base + path, {
|
|
method,
|
|
headers: { Origin: webURL, ...(body !== undefined ? { "Content-Type": "application/json" } : {}), ...(cookie.v ? { Cookie: cookie.v } : {}), ...headers },
|
|
body: body !== undefined ? JSON.stringify(body) : undefined,
|
|
});
|
|
const set = res.headers.getSetCookie();
|
|
if (set.length) cookie.v = set.map((c) => c.split(";")[0]).join("; ");
|
|
const text = await res.text();
|
|
return { status: res.status, json: text ? JSON.parse(text) : undefined };
|
|
}
|
|
|
|
async function personWithAccounts(name: string, ids: { id: number; ageVerified?: boolean; accessPass?: boolean }[]) {
|
|
const cookie = { v: "" };
|
|
await call(cookie, "POST", "/api/auth/sign-up/email", { email: `${name}@example.test`, password: "a long password", name, username: name });
|
|
for (const a of ids) {
|
|
accounts.set(a.id, { id: a.id, username: `${name}${a.id}`, tagline: "", ageVerified: !!a.ageVerified, accessPass: !!a.accessPass, picture: null });
|
|
const started = await call(cookie, "POST", "/api/v1/account/links", { username: `${name}${a.id}` });
|
|
accounts.get(a.id)!.tagline = started.json.challenge.code;
|
|
expect((await call(cookie, "POST", `/api/v1/account/links/${a.id}/check`)).status).toBe(200);
|
|
}
|
|
return cookie;
|
|
}
|
|
|
|
const userOf = async (name: string) => (await db.select().from(schema.user)).find((u) => u.username === name)!.id;
|
|
const startedThisMonth = async () => {
|
|
const now = new Date();
|
|
const month = new Date(Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), 1));
|
|
return (await db.select().from(schema.ageCheck).where(eq(schema.ageCheck.provider, "didit"))).filter((r) => r.createdAt >= month).length;
|
|
};
|
|
|
|
const adultOf = async (cookie: { v: string }) =>
|
|
Object.fromEntries(((await call(cookie, "GET", "/api/v1/account")).json.links as any[]).map((l) => [l.imvuId, l.adult]));
|
|
|
|
test("IMVU's answer is per account, and re-checked when it expires", async () => {
|
|
const a = await personWithAccounts("ann", [{ id: 1, ageVerified: true }, { id: 2 }, { id: 3, accessPass: true }]);
|
|
expect(await adultOf(a)).toEqual({ 1: true, 2: false, 3: true });
|
|
|
|
// IMVU revokes account 1's verification; once its answer expires, the re-check sees it.
|
|
accounts.get(1)!.ageVerified = false;
|
|
await db.update(schema.ageCheck).set({ expiresAt: new Date(Date.now() - 1000) });
|
|
expect(await age.recheckDue()).toBeGreaterThanOrEqual(3);
|
|
expect(await adultOf(a)).toEqual({ 1: false, 2: false, 3: true });
|
|
});
|
|
|
|
test("a person's check covers all their accounts; webhooks must be signed", async () => {
|
|
const b = await personWithAccounts("ben", [{ id: 10 }, { id: 11 }]);
|
|
expect((await call(b, "GET", "/api/v1/age")).json.providers.map((p: any) => p.id)).toEqual(["imvu", "vendor", "didit"]);
|
|
// IMVU checks accounts, not people: it can't be started this way.
|
|
expect((await call(b, "POST", "/api/v1/age/imvu/start", { returnURL: `${webURL}/account` })).status).toBe(400);
|
|
|
|
const started = (await call(b, "POST", "/api/v1/age/vendor/start", { returnURL: `${webURL}/account` })).json;
|
|
expect(started.kind).toBe("redirect");
|
|
expect((await call(b, "GET", "/api/v1/age")).json.checks[0]).toMatchObject({ provider: "vendor", status: "pending" });
|
|
|
|
const hook = (signature: string, approved: boolean) =>
|
|
call({ v: "" }, "POST", "/api/v1/age/webhook/vendor", { session: started.ref, approved, over18: true }, { "x-signature": signature });
|
|
expect((await hook("forged", true)).status).toBe(401);
|
|
expect(await adultOf(b)).toEqual({ 10: false, 11: false });
|
|
expect((await hook(webhookSecret, true)).status).toBe(204);
|
|
expect(await adultOf(b)).toEqual({ 10: true, 11: true });
|
|
// A repeated webhook is harmless.
|
|
expect((await hook(webhookSecret, true)).status).toBe(204);
|
|
// Verified already: no more checks, with this provider or another.
|
|
const again = await call(b, "POST", "/api/v1/age/didit/start", { returnURL: `${webURL}/account` });
|
|
expect(again).toMatchObject({ status: 409, json: { error: "refused" } });
|
|
});
|
|
|
|
test("people are sent back only to the hub's website", async () => {
|
|
const e = await personWithAccounts("eve", []);
|
|
expect((await call(e, "POST", "/api/v1/age/didit/start", { returnURL: "https://evil.test/account" })).status).toBe(400);
|
|
expect((await call(e, "POST", "/api/v1/age/didit/start", { returnURL: "//evil.test/account" })).status).toBe(400);
|
|
// A path is on the website.
|
|
expect((await call(e, "POST", "/api/v1/age/didit/start", { returnURL: "/account?age=back" })).json.kind).toBe("redirect");
|
|
});
|
|
|
|
test("Didit: signed webhooks, the age on the document, and answers changed later", async () => {
|
|
const f = await personWithAccounts("fay", [{ id: 30 }]);
|
|
const started = (await call(f, "POST", "/api/v1/age/didit/start", { returnURL: `${webURL}/account?age=didit` })).json;
|
|
expect(started).toMatchObject({ kind: "redirect", url: `https://verify.didit.test/session/${started.ref}` });
|
|
// Going back to an unfinished check gives the same session, and doesn't count as another.
|
|
const resumed = (await call(f, "POST", "/api/v1/age/didit/start", { returnURL: `${webURL}/account` })).json;
|
|
expect(resumed.ref).toBe(started.ref);
|
|
expect((await call(f, "GET", "/api/v1/age")).json.checks).toHaveLength(1);
|
|
|
|
const event = (status: string, decision?: unknown) => ({
|
|
event_id: crypto.randomUUID(),
|
|
webhook_type: "status.updated",
|
|
session_id: started.ref,
|
|
status,
|
|
timestamp: Math.floor(Date.now() / 1000),
|
|
...(decision ? { decision } : {}),
|
|
});
|
|
const approved = event("Approved", { id_verifications: [{ status: "Approved", age: 31, date_of_birth: "1995-01-01" }] });
|
|
expect((await diditHook(approved, "forged")).status).toBe(401);
|
|
expect((await diditHook(approved, "raw", Math.floor(Date.now() / 1000) - 3600)).status).toBe(401); // stale
|
|
// In review: no answer yet.
|
|
expect((await diditHook(event("In Review"))).status).toBe(204);
|
|
expect((await call(f, "GET", "/api/v1/age")).json.checks[0].status).toBe("pending");
|
|
expect(await adultOf(f)).toEqual({ 30: false });
|
|
|
|
expect((await diditHook(approved, "v2")).status).toBe(204);
|
|
expect(await adultOf(f)).toEqual({ 30: true });
|
|
const [row] = await db.select().from(schema.ageCheck).where(eq(schema.ageCheck.providerRef, started.ref));
|
|
expect(row).toMatchObject({ provider: "didit", method: "id_document", status: "complete", overEighteen: true, imvuId: null });
|
|
|
|
// A reviewer at Didit declines it afterwards: the answer is taken back.
|
|
expect((await diditHook(event("Declined"))).status).toBe(204);
|
|
expect(await adultOf(f)).toEqual({ 30: false });
|
|
expect((await call(f, "GET", "/api/v1/age")).json.checks[0].status).toBe("revoked");
|
|
});
|
|
|
|
test("Didit: under 18, and a decision fetched when the webhook has none", async () => {
|
|
const g = await personWithAccounts("gus", [{ id: 40 }]);
|
|
const started = (await call(g, "POST", "/api/v1/age/didit/start", { returnURL: `${webURL}/account` })).json;
|
|
const session = diditSessions.get(started.ref)!;
|
|
session.finished = true;
|
|
session.decision = { id_verifications: [{ date_of_birth: `${new Date().getUTCFullYear() - 17}-12-31` }] };
|
|
const body = { webhook_type: "status.updated", session_id: started.ref, status: "Approved", timestamp: 0 };
|
|
expect((await diditHook(body)).status).toBe(204);
|
|
expect(await adultOf(g)).toEqual({ 40: false });
|
|
expect((await call(g, "GET", "/api/v1/age")).json.checks[0]).toMatchObject({ status: "complete", overEighteen: false });
|
|
});
|
|
|
|
test("checks are limited per person and by a provider's monthly allowance", async () => {
|
|
const h = await personWithAccounts("hal", []);
|
|
// Each abandoned check is a new one.
|
|
for (let i = 0; i < attemptsPerPerson; i++) {
|
|
const s = (await call(h, "POST", "/api/v1/age/didit/start", { returnURL: `${webURL}/account` })).json;
|
|
diditSessions.get(s.ref)!.finished = true;
|
|
const body = { webhook_type: "status.updated", session_id: s.ref, status: "Abandoned", timestamp: 0 };
|
|
expect((await diditHook(body)).status).toBe(204);
|
|
}
|
|
const limited = await call(h, "POST", "/api/v1/age/didit/start", { returnURL: `${webURL}/account` });
|
|
expect(limited).toMatchObject({ status: 409, json: { error: "refused" } });
|
|
expect(limited.json.message).toContain("30 days");
|
|
|
|
// The month's allowance is everyone's (here a service with room for one more).
|
|
const capped = new AgeService(db, [{ ...didit, monthlyLimit: (await startedThisMonth()) + 1 }]);
|
|
await personWithAccounts("ivy", []);
|
|
await personWithAccounts("joe", []);
|
|
const ivy = await capped.start({ userId: await userOf("ivy") }, "didit", `${webURL}/account`);
|
|
await expect(capped.start({ userId: await userOf("joe") }, "didit", `${webURL}/account`)).rejects.toThrow("used up");
|
|
// Ivy can still go back to hers.
|
|
expect(await capped.start({ userId: await userOf("ivy") }, "didit", `${webURL}/account`)).toEqual(ivy);
|
|
});
|
|
|
|
test("birth dates to ages", () => {
|
|
const day = new Date("2026-11-03T12:00:00Z");
|
|
expect(ageOn("2008-11-03", day)).toBe(18);
|
|
expect(ageOn("2008-11-04", day)).toBe(17);
|
|
expect(ageOn("2008-12-01", day)).toBe(17);
|
|
expect(ageOn("nonsense", day)).toBeUndefined();
|
|
});
|
|
|
|
test("a moved account takes nobody's age with it", async () => {
|
|
const c = await personWithAccounts("cal", [{ id: 20, ageVerified: true }]);
|
|
expect(await adultOf(c)).toEqual({ 20: true });
|
|
// Dee proves the account is hers; IMVU now says it isn't verified (say, the verification was the old owner's).
|
|
accounts.get(20)!.ageVerified = false;
|
|
const d = { v: "" };
|
|
await call(d, "POST", "/api/auth/sign-up/email", { email: "[email protected]", password: "a long password", name: "dee", username: "dee" });
|
|
const started = await call(d, "POST", "/api/v1/account/links", { username: "cal20" });
|
|
accounts.get(20)!.tagline = started.json.challenge.code;
|
|
expect((await call(d, "POST", "/api/v1/account/links/20/check")).json.moved).toBe(true);
|
|
expect(await adultOf(d)).toEqual({ 20: false });
|
|
const leftovers = await db.select().from(schema.ageCheck);
|
|
expect(leftovers.filter((c) => c.imvuId === 20)).toHaveLength(1);
|
|
});
|