import { test } from "node:test"; import assert from "node:assert/strict"; import { AUTH_STORAGE_KEY, AuthError, clearAuthSession, getAuthSession, getCaptcha, getMe, login, logout, setAuthSession, } from "../src/auth/auth.ts"; const user = { userCode: "0123456789ABCDEF0123456789ABCDEF", nickname: "用户_01234567", email: "user@example.com", }; function session() { return { token: "token-value", tokenType: "Bearer", expiresAt: Date.now() + 60_000, user, }; } test("auth storage keeps valid sessions and drops expired sessions", () => { setAuthSession(session()); assert.equal(getAuthSession()?.token, "token-value"); setAuthSession({ ...session(), expiresAt: Date.now() - 1 }); assert.equal(getAuthSession(), null); clearAuthSession(); }); test("captcha and login use the public auth endpoints without a bearer header", async (t) => { clearAuthSession(); const oldFetch = globalThis.fetch; const calls = []; globalThis.fetch = async (url, options = {}) => { calls.push({ url, options }); if (String(url).endsWith("/captcha")) return Response.json({ code: "OK", message: "success", data: { captchaCode: "challenge-1", image: "data:image/png;base64,abc", expiresIn: 120, }, }); return Response.json({ code: "OK", message: "success", data: { token: "login-token", tokenType: "Bearer", expiresIn: 86400, user }, }); }; t.after(() => { globalThis.fetch = oldFetch; clearAuthSession(); }); const captcha = await getCaptcha(); await login(" User@Example.com ", captcha.captchaCode, " aBc12 "); assert.equal(calls[0].options.credentials, "omit"); assert.equal(calls[0].options.headers.get("Authorization"), null); assert.deepEqual(JSON.parse(calls[1].options.body), { email: "user@example.com", captchaCode: "challenge-1", captchaAnswer: "aBc12", }); assert.equal(getAuthSession()?.token, "login-token"); }); test("current-user and logout use the stored bearer token", async (t) => { setAuthSession(session()); const oldFetch = globalThis.fetch; const calls = []; globalThis.fetch = async (url, options = {}) => { calls.push({ url, options }); return Response.json({ code: "OK", data: url.toString().endsWith("/me") ? user : null }); }; t.after(() => { globalThis.fetch = oldFetch; clearAuthSession(); }); assert.deepEqual(await getMe(), user); await logout(); assert.equal(calls[0].options.headers.get("Authorization"), "Bearer token-value"); assert.equal(calls[1].options.headers.get("Authorization"), "Bearer token-value"); assert.equal(getAuthSession(), null); }); test("401 auth responses clear the local session", async (t) => { setAuthSession(session()); const oldFetch = globalThis.fetch; globalThis.fetch = async () => Response.json( { code: "UNAUTHORIZED", message: "expired", data: null }, { status: 401 }, ); t.after(() => { globalThis.fetch = oldFetch; clearAuthSession(); }); await assert.rejects(getMe(), (error) => { assert.ok(error instanceof AuthError); assert.equal(error.code, "UNAUTHORIZED"); assert.equal(error.status, 401); return true; }); assert.equal(getAuthSession(), null); });