Files
hermes-control-panel/test/admin-store.integration.test.cjs
2026-06-06 01:34:52 -06:00

70 lines
2.1 KiB
JavaScript

"use strict"
const test = require("node:test")
const assert = require("node:assert/strict")
const { withTestDatabase } = require("./helpers/db-test.cjs")
const { runMigrations } = require("../lib/db.cjs")
const { createSessionToken } = require("../lib/security.cjs")
const {
createAdminSession,
validateAdminSession,
revokeAdminSession,
deleteExpiredAdminSessions
} = require("../lib/admin-store.cjs")
test("admin session lifecycle: create, validate, revoke", async (t) => {
await withTestDatabase(t, async ({ pool }) => {
await runMigrations(pool)
const { plaintext, hash } = createSessionToken()
const expiresAt = new Date(Date.now() + 3600 * 1000)
await createAdminSession(pool, hash, expiresAt)
// valid session is found
const session = await validateAdminSession(pool, hash)
assert.ok(session)
assert.equal(session.token_hash, hash)
// revoke it
await revokeAdminSession(pool, hash)
// now validation returns null
const revoked = await validateAdminSession(pool, hash)
assert.equal(revoked, null)
})
})
test("validateAdminSession returns null for expired session", async (t) => {
await withTestDatabase(t, async ({ pool }) => {
await runMigrations(pool)
const { hash } = createSessionToken()
const expiresAt = new Date(Date.now() - 1000) // already expired
await createAdminSession(pool, hash, expiresAt)
const result = await validateAdminSession(pool, hash)
assert.equal(result, null)
})
})
test("deleteExpiredAdminSessions removes expired sessions", async (t) => {
await withTestDatabase(t, async ({ pool }) => {
await runMigrations(pool)
const { hash: expiredHash } = createSessionToken()
const { hash: activeHash } = createSessionToken()
await createAdminSession(pool, expiredHash, new Date(Date.now() - 1000))
await createAdminSession(pool, activeHash, new Date(Date.now() + 3600 * 1000))
await deleteExpiredAdminSessions(pool)
const result = await pool.query("SELECT token_hash FROM admin_sessions")
const hashes = result.rows.map((r) => r.token_hash)
assert.ok(!hashes.includes(expiredHash))
assert.ok(hashes.includes(activeHash))
})
})