Repository Public
1/**2 * =============================================================================3 * SP BOUCHER | SOFTWARE & RESEARCH4 * ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * Project : ORIX App Universe8 * File : tests/security.test.ts9 * Module : tests10 * Repository : https://git.spboucher.ai/orix-spboucher-ai11 * Project Website : https://www.orixlab.dev12 * Created : 2026-11-2113 * Last Modified : 2026-11-2114 *15 * Author : Simon-Pierre Boucher16 * Position : Professor of Finance17 * Institution : Université du Québec en Outaouais (UQO)18 * Organization : SP Boucher19 * Website : https://spboucher.ai20 * Git : https://git.spboucher.ai21 *22 * Preferred Contact: support@spboucher.ai23 * Development : dev@spboucher.ai24 * Support : support@spboucher.ai25 * Security/Admin : admin@spboucher.ai26 *27 * Copyright (c) 202628 * Simon-Pierre Boucher29 * All rights reserved where applicable. This file is governed by the30 * applicable project license, copyright notices and relevant law.31 * Existing third-party rights and notices remain unaffected.32 *33 * License : None specified (no license file in this repository)34 *35 * Do not embed credentials, private keys, access tokens,36 * certificates or confidential personal information.37 *38 * =============================================================================39 * END OF SP BOUCHER SOURCE HEADER40 * =============================================================================41 */4243import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";44import { existsSync } from "node:fs";45import { join } from "node:path";46import sharp from "sharp";47import { freshData, macApp, mockCookies } from "./helpers";48import { hmac, sha256 } from "@/lib/security/crypto";4950const data = freshData();51const jar = mockCookies();52let dbm: typeof import("@/lib/database/db"), session: typeof import("@/lib/auth/session"), wa: typeof import("@/lib/auth/webauthn"), cat: typeof import("@/lib/catalog");53let admin: (typeof import("@/app/api/admin/[...path]/route"))["GET"];54let csrf = "";5556const call = (method: string, path: string, opts: { body?: unknown; headers?: Record<string, string>; form?: FormData } = {}) =>57 admin(new Request(`https://orix.test/api/admin/${path}`, { method, headers: { ...(opts.form ? {} : { "content-type": "application/json" }), ...opts.headers }, body: opts.form ?? (opts.body === undefined ? undefined : JSON.stringify(opts.body)) }), { params: Promise.resolve({ path: path.split("/") }) });58const signIn = () => {59 dbm.db().prepare("INSERT OR IGNORE INTO admins (id, name, created_at) VALUES ('owner', 'Owner', ?)").run(dbm.now());60 const { token } = session.issueSession("owner");61 jar.set(session.SESSION_COOKIE, token);62 csrf = (dbm.db().prepare("SELECT csrf FROM sessions WHERE token_hash = ?").get(sha256(token)) as { csrf: string }).csrf;63 return token;64};6566beforeAll(async () => {67 dbm = await import("@/lib/database/db"); session = await import("@/lib/auth/session"); wa = await import("@/lib/auth/webauthn"); cat = await import("@/lib/catalog");68 admin = (await import("@/app/api/admin/[...path]/route")).GET;69 cat.upsertSeed(macApp());70});71afterAll(() => data.cleanup());72beforeEach(async () => { jar.clear(); (await import("@/lib/security/ratelimit")).resetRateLimits(); });7374describe("enrolment tokens", () => {75 it("are random, stored only as a hash, single-live and expiring", () => {76 const a = wa.issueEnrollToken("setup", 30);77 expect(a.raw.length).toBeGreaterThanOrEqual(43);78 const rows = dbm.db().prepare("SELECT * FROM enroll_tokens").all() as { token_hash: string }[];79 expect(JSON.stringify(rows)).not.toContain(a.raw);80 expect(rows[0].token_hash).toBe(sha256(a.raw));81 expect(wa.enrollTokenInfo(a.raw)).toEqual({ purpose: "setup" });82 const b = wa.issueEnrollToken("recovery", 30);83 expect(wa.enrollTokenInfo(a.raw)).toBeNull(); // superseded84 expect(wa.enrollTokenInfo(b.raw)).toEqual({ purpose: "recovery" });85 dbm.db().prepare("UPDATE enroll_tokens SET expires_at = ? WHERE token_hash = ?").run(new Date(Date.now() - 1000).toISOString(), sha256(b.raw));86 expect(wa.enrollTokenInfo(b.raw)).toBeNull();87 expect(wa.enrollTokenInfo("guess")).toBeNull(); expect(wa.enrollTokenInfo(undefined)).toBeNull();88 });89 it("never appear in the audit trail", () => {90 const t = wa.issueEnrollToken("setup");91 expect(JSON.stringify(dbm.db().prepare("SELECT * FROM audit").all())).not.toContain(t.raw);92 });93 it("gate passkey registration", async () => {94 await expect(wa.registrationOptions("not-a-token")).rejects.toMatchObject({ status: 403, code: "invalid_enroll_token" });95 const { raw } = wa.issueEnrollToken("setup");96 const { options, challengeId } = await wa.registrationOptions(raw);97 expect(options.rp.id).toBe("orix.test");98 expect(options.authenticatorSelection).toMatchObject({ residentKey: "required", userVerification: "required" });99 // A forged attestation is refused, and the challenge cannot be replayed afterwards.100 const forged = { id: "x", rawId: "x", type: "public-key", clientExtensionResults: {}, response: { clientDataJSON: "e30", attestationObject: "e30" } } as never;101 await expect(wa.verifyRegistration({ challengeId, response: forged, token: raw }, new Request("https://orix.test/"))).rejects.toMatchObject({ code: "registration_failed" });102 await expect(wa.verifyRegistration({ challengeId, response: forged, token: raw }, new Request("https://orix.test/"))).rejects.toMatchObject({ code: "challenge_expired" });103 expect(wa.credentialCount()).toBe(0);104 });105});106107describe("sign-in", () => {108 it("refuses an unknown passkey, records the failure and locks out after repeated attempts", async () => {109 const req = () => new Request("https://orix.test/", { headers: { "x-forwarded-for": "203.0.113.9" } });110 for (let i = 0; i < 5; i++) {111 const { challengeId } = await wa.authenticationOptions();112 await expect(wa.verifyAuthentication({ challengeId, response: { id: "unknown" } as never }, req())).rejects.toMatchObject({ status: 401, code: "login_failed" });113 }114 const { challengeId } = await wa.authenticationOptions();115 await expect(wa.verifyAuthentication({ challengeId, response: { id: "unknown" } as never }, req())).rejects.toMatchObject({ status: 429, code: "locked_out" });116 expect(jar.has(session.SESSION_COOKIE)).toBe(false);117 });118 it("binds a challenge to the browser that asked for it", async () => {119 const { challengeId } = await wa.authenticationOptions();120 jar.clear(); // another browser121 await expect(wa.verifyAuthentication({ challengeId, response: { id: "unknown" } as never }, new Request("https://orix.test/"))).rejects.toMatchObject({ code: "challenge_expired" });122 });123});124125describe("sessions", () => {126 it("expire absolutely and when idle, and are stored hashed", () => {127 const token = signIn();128 expect(session.adminFromToken(token)?.adminId).toBe("owner");129 expect(JSON.stringify(dbm.db().prepare("SELECT * FROM sessions").all())).not.toContain(token);130 expect(session.adminFromToken(token, Date.now() + (session.IDLE_MINUTES + 1) * 60_000)).toBeNull(); // idle131 expect(session.adminFromToken(token)).toBeNull(); // and it was deleted132 const t2 = signIn();133 dbm.db().prepare("UPDATE sessions SET expires_at = ? WHERE token_hash = ?").run(new Date(Date.now() - 1).toISOString(), sha256(t2));134 expect(session.adminFromToken(t2)).toBeNull();135 expect(session.adminFromToken("forged")).toBeNull(); expect(session.adminFromToken(undefined)).toBeNull();136 });137});138139describe("admin API authorization", () => {140 it("answers 401 to every route without a session", async () => {141 for (const [m, p] of [["GET", "apps"], ["GET", "apps/demo"], ["PUT", "apps/demo"], ["POST", "apps/demo/publish"], ["POST", "apps/demo/media"], ["GET", "releases"], ["POST", "releases/1/approve"], ["POST", "sync"], ["GET", "audit"], ["GET", "metrics"], ["PUT", "settings"], ["POST", "announcements"]] as const)142 expect((await call(m, p, m === "GET" ? {} : { body: {} })).status, `${m} ${p}`).toBe(401);143 });144 it("requires the CSRF token and the same origin for writes", async () => {145 signIn();146 expect((await call("GET", "apps")).status).toBe(200);147 expect((await call("POST", "apps/demo/unpublish", { body: {} })).status).toBe(403);148 expect((await call("POST", "apps/demo/unpublish", { body: {}, headers: { "x-csrf-token": "wrong" } })).status).toBe(403);149 expect((await call("POST", "apps/demo/unpublish", { body: {}, headers: { "x-csrf-token": csrf, origin: "https://evil.example" } })).status).toBe(403);150 expect((await call("POST", "apps/demo/unpublish", { body: {}, headers: { "x-csrf-token": csrf, "sec-fetch-site": "cross-site" } })).status).toBe(403);151 expect(cat.getApp("demo")).not.toBeNull(); // nothing happened152 expect((await call("POST", "apps/demo/unpublish", { body: {}, headers: { "x-csrf-token": csrf, origin: "https://orix.test" } })).status).toBe(200);153 expect(cat.getApp("demo")).toBeNull();154 expect((await call("POST", "apps/demo/publish", { body: {}, headers: { "x-csrf-token": csrf } })).status).toBe(200);155 });156 it("edits an application as a draft, validates it, and publishes on request", async () => {157 signIn(); const h = { "x-csrf-token": csrf };158 expect((await call("PUT", "apps/demo", { body: { ...macApp(), name: "ORIX Demo Pro" }, headers: h })).status).toBe(200);159 expect(cat.getApp("demo")!.app.name).toBe("ORIX Demo");160 const bad = await call("PUT", "apps/demo", { body: { ...macApp(), status: "shipping" }, headers: h });161 expect(bad.status).toBe(422); expect((await bad.json()).error.issues[0]).toContain("status");162 expect((await call("POST", "apps/demo/publish", { body: {}, headers: h })).status).toBe(200);163 expect(cat.getApp("demo")!.app.name).toBe("ORIX Demo Pro");164 expect((await call("POST", "apps", { body: { slug: "../x", name: "x" }, headers: h })).status).toBe(422);165 expect((await call("GET", "apps/..%2F..")).status).toBe(404);166 });167 it("refuses to verify a TestFlight link that is not a public invitation", async () => {168 signIn();169 const r = await call("POST", "apps/demo/testflight", { body: {}, headers: { "x-csrf-token": csrf } });170 expect(r.status).toBe(422); expect((await r.json()).error.code).toBe("no_invite");171 });172 it("requires both languages before an announcement is published", async () => {173 signIn(); const h = { "x-csrf-token": csrf };174 expect((await call("POST", "announcements", { body: { publish: "published", title_en: "Hello", body_en: "Text" }, headers: h })).status).toBe(422);175 expect((await call("POST", "announcements", { body: { publish: "published", title_en: "Hello", title_fr: "Bonjour", body_en: "Text", body_fr: "Texte", date: "2026-11-21" }, headers: h })).status).toBe(201);176 const { feed } = await import("@/lib/news");177 expect(feed("fr").some((n) => n.title === "Bonjour")).toBe(true);178 });179 it("writes an audit entry for administrative actions", () => {180 const actions = (dbm.db().prepare("SELECT action FROM audit").all() as { action: string }[]).map((a) => a.action);181 for (const a of ["app.draft_saved", "app.publish", "app.unpublish", "announcement.created", "login.failed"]) expect(actions, a).toContain(a);182 });183});184185describe("uploads", () => {186 const png = (w: number, h: number) => sharp({ create: { width: w, height: h, channels: 3, background: "#336699" } }).png().toBuffer();187 const upload = async (buf: Buffer, kind: string, name = "shot.png") => { const form = new FormData(); form.set("file", new File([new Uint8Array(buf)], name)); form.set("kind", kind); return call("POST", "apps/demo/media", { form, headers: { "x-csrf-token": csrf } }); };188 it("stores a re-encoded image under a content-hash name", async () => {189 signIn();190 const r = await upload(await png(390, 844), "screenshot", "../../evil.php");191 expect(r.status).toBe(200);192 const { file } = await r.json();193 expect(file).toMatch(/^u\/[a-f0-9]{32}\.png$/);194 expect(existsSync(join(data.dir, "uploads/demo", file.slice(2)))).toBe(true);195 const { GET } = await import("@/app/media/[slug]/[file]/route");196 const res = await GET(new Request("https://orix.test/"), { params: Promise.resolve({ slug: "demo", file: file.slice(2) }) });197 expect(res.status).toBe(200); expect(res.headers.get("content-type")).toBe("image/png"); expect(res.headers.get("x-content-type-options")).toBe("nosniff");198 expect((await GET(new Request("https://orix.test/"), { params: Promise.resolve({ slug: "demo", file: "../orix.db" }) })).status).toBe(404);199 });200 it("rejects files that are not images, whatever their name", async () => {201 signIn();202 expect((await upload(Buffer.from("<script>alert(1)</script>"), "screenshot", "x.png")).status).toBe(422);203 expect((await upload(Buffer.from("<svg xmlns='http://www.w3.org/2000/svg'><script/></svg>"), "screenshot", "x.svg")).status).toBe(422);204 expect((await upload(await png(300, 200), "icon")).status).toBe(422); // an icon must be square205 expect((await upload(await png(512, 512), "icon")).status).toBe(200);206 });207});208209describe("release webhook", () => {210 const secret = "s".repeat(40);211 const sign = (ts: string, nonce: string, body: string, key = secret) => "sha256=" + hmac(key, `${ts}.${nonce}.${body}`);212 let verify: (typeof import("@/lib/webhook"))["verifyWebhook"];213 beforeAll(async () => { verify = (await import("@/lib/webhook")).verifyWebhook; });214 const ts = () => String(Math.floor(Date.now() / 1000));215216 it("accepts a correctly signed, fresh, first-time request", () => {217 const t = ts(), n = "nonce-0000000000000001", body = '{"repo":"orix-demo"}';218 expect(verify({ secret, timestamp: t, nonce: n, signature: sign(t, n, body), body })).toEqual({ ok: true });219 });220 it("rejects a replay of the same request", () => {221 const t = ts(), n = "nonce-0000000000000002", body = "{}";222 expect(verify({ secret, timestamp: t, nonce: n, signature: sign(t, n, body), body }).ok).toBe(true);223 expect(verify({ secret, timestamp: t, nonce: n, signature: sign(t, n, body), body })).toEqual({ ok: false, reason: "replayed" });224 });225 it("rejects a bad signature, a tampered body, a stale timestamp and malformed headers", () => {226 const t = ts(), n = "nonce-0000000000000003";227 expect(verify({ secret, timestamp: t, nonce: n, signature: sign(t, n, "{}", "other-secret"), body: "{}" })).toEqual({ ok: false, reason: "bad_signature" });228 expect(verify({ secret, timestamp: t, nonce: n, signature: sign(t, n, "{}"), body: '{"repo":"x"}' })).toEqual({ ok: false, reason: "bad_signature" });229 const old = String(Math.floor(Date.now() / 1000) - 3600);230 expect(verify({ secret, timestamp: old, nonce: n, signature: sign(old, n, "{}"), body: "{}" })).toEqual({ ok: false, reason: "stale" });231 expect(verify({ secret, timestamp: null, nonce: n, signature: "x", body: "" })).toEqual({ ok: false, reason: "malformed" });232 expect(verify({ secret, timestamp: t, nonce: "short", signature: sign(t, "short", ""), body: "" })).toEqual({ ok: false, reason: "malformed" });233 });234 it("is disabled without a secret, and the endpoint says nothing useful", async () => {235 expect(verify({ secret: "", timestamp: ts(), nonce: "nonce-0000000000000004", signature: "sha256=00", body: "" })).toEqual({ ok: false, reason: "disabled" });236 vi.stubEnv("WEBHOOK_SECRET", secret);237 const { POST } = await import("@/app/api/hooks/release/route");238 const res = await POST(new Request("https://orix.test/api/hooks/release", { method: "POST", body: "{}", headers: { "x-orix-timestamp": ts(), "x-orix-nonce": "nonce-0000000000000005", "x-orix-signature": "sha256=deadbeef" } }));239 expect(res.status).toBe(401);240 vi.unstubAllEnvs();241 });242});243244describe("rate limiting", () => {245 it("throttles a client that exceeds the window", async () => {246 const { rateLimit } = await import("@/lib/security/ratelimit");247 for (let i = 0; i < 3; i++) rateLimit("t", "1.2.3.4", 3, 60);248 expect(() => rateLimit("t", "1.2.3.4", 3, 60)).toThrowError(/Too many/);249 expect(() => rateLimit("t", "5.6.7.8", 3, 60)).not.toThrow();250 });251});252