| 1 | import test from "node:test"; |
| 2 | import assert from "node:assert/strict"; |
| 3 | import { mkdtempSync } from "node:fs"; |
| 4 | import { tmpdir } from "node:os"; |
| 5 | import { join } from "node:path"; |
| 6 | import { OAuthAuth } from "../src/auth/oauth.js"; |
| 7 | import { authConfig } from "../src/auth/config.js"; |
| 8 | import { StateDatabase } from "../src/persistence/stateDb.js"; |
| 9 | import { identityFromUser } from "../src/auth/client.js"; |
| 10 | |
| 11 | test("local auth session resolves identity without calling auth API", async () => |
| 12 | { |
| 13 | const dir = mkdtempSync(join(tmpdir(), "questward-auth-session-")); |
| 14 | const stateDb = new StateDatabase(join(dir, "state.sqlite")); |
| 15 | const config = { |
| 16 | ...authConfig(), |
| 17 | sessionCookie: "questward_session", |
| 18 | sessionMaxAgeSec: 3600, |
| 19 | tokenCookie: "questward_access_token" |
| 20 | }; |
| 21 | const auth = new OAuthAuth(config, { |
| 22 | async fetchMe () |
| 23 | { |
| 24 | throw new Error("auth API should not be called when local session is valid"); |
| 25 | } |
| 26 | }, stateDb); |
| 27 | |
| 28 | const sessionId = "test-session-id"; |
| 29 | stateDb.createAuthSession({ |
| 30 | sessionId, |
| 31 | authSubject: "auth:42", |
| 32 | username: "player", |
| 33 | email: "player@example.com", |
| 34 | accessToken: "remote-token", |
| 35 | expiresAtMs: Date.now() + 3600_000 |
| 36 | }); |
| 37 | |
| 38 | const identity = await auth.authenticateRequest({ |
| 39 | headers: { |
| 40 | cookie: `questward_session=${sessionId}; questward_access_token=ignored` |
| 41 | } |
| 42 | }); |
| 43 | |
| 44 | assert.equal(identity?.authSubject, "auth:42"); |
| 45 | assert.equal(identity?.username, "player"); |
| 46 | assert.equal(identity?.localSession, true); |
| 47 | }); |
| 48 | |
| 49 | test("identityFromUser ignores missing email", () => |
| 50 | { |
| 51 | const identity = identityFromUser({ id: 5, username: "player" }, "tok"); |
| 52 | assert.equal(identity.authSubject, "auth:5"); |
| 53 | assert.equal(identity.username, "player"); |
| 54 | assert.equal(identity.email, null); |
| 55 | assert.equal(identity.accessToken, "tok"); |
| 56 | }); |