// bun test test/migrate-grant.test.ts // // The /migrate action tells the v3 registrar which identity may claim a // @coinos.io name. That name must come from the logged-in session, never from // the form, or any logged-in account could be granted someone else's name. import { beforeEach, describe, expect, mock, test } from "bun:test"; const SESSION_USER = "attacker1"; let me: any = { username: SESSION_USER }; const posts: [string, any][] = []; mock.module("$env/dynamic/private", () => ({ env: { MIGRATE_TOKEN: "t" } })); mock.module("$lib/utils", () => ({ auth: () => ({ authorization: "Bearer x" }), get: async (url: string) => { if (url !== "/me") throw new Error(`unexpected get ${url}`); if (!me) throw new Error("unauthorized"); return me; }, post: async (url: string, body: any) => { posts.push([url, body]); return {}; }, })); mock.module("@sveltejs/kit", () => ({ redirect: () => {} })); const grants: any[] = []; globalThis.fetch = (async (url: string, init: any) => { if (String(url).endsWith("/migrate-grant")) grants.push(JSON.parse(init.body)); return new Response("{}", { status: 200 }); }) as any; const { actions } = await import("../src/routes/(app)/migrate/+page.server.ts"); const run = (fields: Record) => { const form = new FormData(); for (const [k, v] of Object.entries(fields)) form.set(k, v); return actions.default({ cookies: { get: () => "x" }, request: new Request("http://x/migrate", { method: "POST", body: form }), url: new URL("http://x/migrate"), } as any); }; beforeEach(() => { me = { username: SESSION_USER }; posts.length = 0; grants.length = 0; }); describe("/migrate grant", () => { test("grants the session's own name", async () => { const r = await run({ to: "npub1me@coinos.io", username: SESSION_USER }); expect(r).toEqual({ ok: true, sent: 0, released: SESSION_USER }); expect(grants).toEqual([{ name: SESSION_USER, to: "npub1me@coinos.io" }]); }); test("ignores a username in the form that isn't the session's", async () => { const r = await run({ to: "npub1evil@coinos.io", username: "victim" }); expect(grants.map((g) => g.name)).toEqual([SESSION_USER]); expect(r.released).toBe(SESSION_USER); }); test("no session: nothing flagged, nothing granted", async () => { me = null; const r = await run({ to: "npub1evil@coinos.io", username: "victim" }); expect(r).toEqual({ error: "not logged in" }); expect(posts).toEqual([]); expect(grants).toEqual([]); }); });