feat(tests): add unit and integration test suite (node:test)
Adds 215 tests across three tiers using node:test + node:assert/strict (no new test framework dependencies): - test/tools/ — middleware and utility tests (token, hash, authenticate, jsonBody, convertError, validators) - test/shared/ — DbInterface/BackendDbInterface contract suites reusable across backends (users, abodes, residents, apikeys, sessions, auth) - test/backends/sqlite/ — SQLite-private tests (sql builder, WrappedDb, migrator) + shared suites via SqliteInterface - test/backends/api/ — ApiInterface unit tests + shared suites via a live Koa server backed by SQLite Also fixes four bugs uncovered by the tests: - ApiInterface: path params leaked into query string (slice(1) fix) - ApiInterface: calling res.json() on 204 No Content responses - SqliteInterface.updateResident: missing comma in SET clause - WrappedBetterSqlite3Db: readonly:undefined rejected by better-sqlite3 Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,273 @@
|
||||
import { describe, it } from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import { authenticate } from "../../src/webapi/middleware/authenticate.js";
|
||||
import type { BackendDbInterface } from "../../src/db/types/DbInterface.js";
|
||||
import type { ClientUser } from "../../src/db/types/User.js";
|
||||
import type { ClientApikey } from "../../src/db/types/Apikey.js";
|
||||
import {
|
||||
ConflictAbodeError,
|
||||
NotAuthorizedAbodeError,
|
||||
NotFoundAbodeError,
|
||||
} from "../../src/db/types/errors.js";
|
||||
|
||||
const MOCK_USER: ClientUser = {
|
||||
uid: "11111111-1111-1111-1111-111111111111",
|
||||
email: "test@example.com",
|
||||
name: "Test User",
|
||||
flags: {},
|
||||
created_at: "2024-01-01T00:00:00Z",
|
||||
updated_at: "2024-01-01T00:00:00Z",
|
||||
};
|
||||
|
||||
const MOCK_APIKEY: ClientApikey = {
|
||||
kid: "22222222-2222-2222-2222-222222222222",
|
||||
uid: MOCK_USER.uid,
|
||||
name: "Test Key",
|
||||
permissions: {},
|
||||
created_at: "2024-01-01T00:00:00Z",
|
||||
expires_at: null,
|
||||
};
|
||||
|
||||
function makeMockDb(
|
||||
overrides: Partial<BackendDbInterface> = {}
|
||||
): BackendDbInterface {
|
||||
return {
|
||||
readonly: false,
|
||||
backend: true,
|
||||
name: "mock",
|
||||
close: async () => {},
|
||||
listUsers: async () => [],
|
||||
getUserById: async () => { throw new NotFoundAbodeError(); },
|
||||
deleteUserById: async () => {},
|
||||
createUser: async () => MOCK_USER,
|
||||
updateUser: async () => MOCK_USER,
|
||||
getUserByEmail: async () => { throw new NotFoundAbodeError(); },
|
||||
listAbodes: async () => [],
|
||||
getAbodeById: async () => { throw new NotFoundAbodeError(); },
|
||||
deleteAbodeById: async () => {},
|
||||
createAbode: async () => ({ aid: "a", name: "A", created_at: "", created_by: null, updated_at: "", updated_by: null }),
|
||||
updateAbode: async () => ({ aid: "a", name: "A", created_at: "", created_by: null, updated_at: "", updated_by: null }),
|
||||
listResidents: async () => [],
|
||||
getResidentById: async () => { throw new NotFoundAbodeError(); },
|
||||
deleteResidentById: async () => {},
|
||||
createResident: async () => ({ uid: "", aid: "", flags: {}, created_at: "", created_by: null, updated_at: "", updated_by: null }),
|
||||
updateResident: async () => ({ uid: "", aid: "", flags: {}, created_at: "", created_by: null, updated_at: "", updated_by: null }),
|
||||
listResidentsByUserId: async () => [],
|
||||
listResidentsByAbodeId: async () => [],
|
||||
listUsersByAbodeId: async () => [],
|
||||
listAbodesByUserId: async () => [],
|
||||
listNotes: async () => [],
|
||||
getNoteById: async () => { throw new NotFoundAbodeError(); },
|
||||
deleteNoteById: async () => {},
|
||||
createNote: async () => { throw new Error("unimplemented"); },
|
||||
updateNote: async () => { throw new Error("unimplemented"); },
|
||||
listNotesByAbodeId: async () => [],
|
||||
listNotesByUserId: async () => [],
|
||||
deleteSessionsByUser: async () => {},
|
||||
listApikeysByUser: async () => [],
|
||||
getApikeyById: async () => { throw new NotFoundAbodeError(); },
|
||||
createApikey: async () => [MOCK_APIKEY, "at_" + "0".repeat(32) as `at_${string}`],
|
||||
deleteApikeyById: async () => {},
|
||||
getUserByLogin: async () => { throw new NotFoundAbodeError(); },
|
||||
getUserBySession: async () => { throw new NotFoundAbodeError(); },
|
||||
createSession: async () => `as_${"0".repeat(32)}`,
|
||||
getUserByApikey: async () => { throw new NotFoundAbodeError(); },
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
type MockCtx = {
|
||||
headers: Record<string, string>;
|
||||
cookieJar: Record<string, string>;
|
||||
clearedCookies: Set<string>;
|
||||
status: number;
|
||||
body: unknown;
|
||||
user?: ClientUser;
|
||||
session?: unknown;
|
||||
get(header: string): string;
|
||||
cookies: {
|
||||
get(name: string): string | undefined;
|
||||
set(name: string, value: string, opts?: unknown): void;
|
||||
};
|
||||
};
|
||||
|
||||
function makeMockCtx(headerOverrides: Record<string, string> = {}, cookieOverrides: Record<string, string> = {}): MockCtx {
|
||||
const clearedCookies = new Set<string>();
|
||||
const ctx: MockCtx = {
|
||||
headers: headerOverrides,
|
||||
cookieJar: cookieOverrides,
|
||||
clearedCookies,
|
||||
status: 200,
|
||||
body: null,
|
||||
user: undefined,
|
||||
session: undefined,
|
||||
get(header: string) {
|
||||
return this.headers[header] ?? this.headers[header.toLowerCase()] ?? "";
|
||||
},
|
||||
cookies: {
|
||||
get(name: string) {
|
||||
return cookieOverrides[name];
|
||||
},
|
||||
set(name: string, value: string, opts?: unknown) {
|
||||
if (value === "" || (opts && (opts as { expires?: Date }).expires?.getFullYear()! < 2000)) {
|
||||
clearedCookies.add(name);
|
||||
}
|
||||
},
|
||||
},
|
||||
};
|
||||
return ctx;
|
||||
}
|
||||
|
||||
async function runMiddleware(
|
||||
db: BackendDbInterface,
|
||||
ctx: MockCtx
|
||||
): Promise<boolean> {
|
||||
let nextCalled = false;
|
||||
const mw = authenticate(db);
|
||||
await mw(ctx as any, async () => { nextCalled = true; });
|
||||
return nextCalled;
|
||||
}
|
||||
|
||||
describe("authenticate middleware", () => {
|
||||
describe("Basic auth", () => {
|
||||
it("valid credentials → sets user and session, calls next", async () => {
|
||||
const db = makeMockDb({ getUserByLogin: async () => MOCK_USER });
|
||||
const encoded = btoa("test@example.com:password");
|
||||
const ctx = makeMockCtx({ Authorization: `Basic ${encoded}` });
|
||||
const next = await runMiddleware(db, ctx);
|
||||
assert.equal(next, true);
|
||||
assert.deepEqual(ctx.user, MOCK_USER);
|
||||
assert.deepEqual(ctx.session, { source: "basic" });
|
||||
});
|
||||
|
||||
it("malformed base64 → 400", async () => {
|
||||
const db = makeMockDb();
|
||||
const ctx = makeMockCtx({ Authorization: "Basic !!not-base64!!" });
|
||||
await runMiddleware(db, ctx);
|
||||
assert.equal(ctx.status, 400);
|
||||
});
|
||||
|
||||
it("missing colon in decoded value → 400", async () => {
|
||||
const db = makeMockDb();
|
||||
const ctx = makeMockCtx({ Authorization: "Basic " + btoa("nocolon") });
|
||||
await runMiddleware(db, ctx);
|
||||
assert.equal(ctx.status, 400);
|
||||
});
|
||||
|
||||
it("wrong password (NotAuthorizedAbodeError) → 401 invalid_password", async () => {
|
||||
const db = makeMockDb({
|
||||
getUserByLogin: async () => { throw new NotAuthorizedAbodeError(); },
|
||||
});
|
||||
const ctx = makeMockCtx({ Authorization: "Basic " + btoa("user:wrong") });
|
||||
await runMiddleware(db, ctx);
|
||||
assert.equal(ctx.status, 401);
|
||||
assert.deepEqual((ctx.body as any)?.error, "invalid_password");
|
||||
});
|
||||
|
||||
it("unknown user (NotFoundAbodeError) → 401 unknown_user", async () => {
|
||||
const db = makeMockDb({
|
||||
getUserByLogin: async () => { throw new NotFoundAbodeError(); },
|
||||
});
|
||||
const ctx = makeMockCtx({ Authorization: "Basic " + btoa("nobody:pass") });
|
||||
await runMiddleware(db, ctx);
|
||||
assert.equal(ctx.status, 401);
|
||||
assert.deepEqual((ctx.body as any)?.error, "unknown_user");
|
||||
});
|
||||
|
||||
it("ConflictAbodeError (#unset password) → 401 user_not_loggable", async () => {
|
||||
const db = makeMockDb({
|
||||
getUserByLogin: async () => { throw new ConflictAbodeError(); },
|
||||
});
|
||||
const ctx = makeMockCtx({ Authorization: "Basic " + btoa("user:pass") });
|
||||
await runMiddleware(db, ctx);
|
||||
assert.equal(ctx.status, 401);
|
||||
assert.deepEqual((ctx.body as any)?.error, "user_not_loggable");
|
||||
});
|
||||
|
||||
it("uses X-Abode-Authorization header when Authorization is absent", async () => {
|
||||
const db = makeMockDb({ getUserByLogin: async () => MOCK_USER });
|
||||
const encoded = btoa("test@example.com:password");
|
||||
const ctx = makeMockCtx({ "X-Abode-Authorization": `Basic ${encoded}` });
|
||||
const next = await runMiddleware(db, ctx);
|
||||
assert.equal(next, true);
|
||||
assert.ok(ctx.user);
|
||||
});
|
||||
});
|
||||
|
||||
describe("Bearer (API key)", () => {
|
||||
const validToken = `at_${"a".repeat(32)}` as `at_${string}`;
|
||||
|
||||
it("valid at_ token → sets user and apikey session, calls next", async () => {
|
||||
const db = makeMockDb({
|
||||
getUserByApikey: async () => [MOCK_USER, MOCK_APIKEY],
|
||||
});
|
||||
const ctx = makeMockCtx({ Authorization: `Bearer ${validToken}` });
|
||||
const next = await runMiddleware(db, ctx);
|
||||
assert.equal(next, true);
|
||||
assert.deepEqual(ctx.user, MOCK_USER);
|
||||
assert.deepEqual(ctx.session, { source: "apikey", key: MOCK_APIKEY });
|
||||
});
|
||||
|
||||
it("invalid/expired at_ token → 401 invalid_apikey", async () => {
|
||||
const db = makeMockDb({
|
||||
getUserByApikey: async () => { throw new NotFoundAbodeError(); },
|
||||
});
|
||||
const ctx = makeMockCtx({ Authorization: `Bearer ${validToken}` });
|
||||
await runMiddleware(db, ctx);
|
||||
assert.equal(ctx.status, 401);
|
||||
assert.deepEqual((ctx.body as any)?.error, "invalid_apikey");
|
||||
});
|
||||
|
||||
it("bearer token without at_ prefix → 401 unrecognized_bearer", async () => {
|
||||
const db = makeMockDb();
|
||||
const ctx = makeMockCtx({ Authorization: "Bearer not-an-apikey-token" });
|
||||
await runMiddleware(db, ctx);
|
||||
assert.equal(ctx.status, 401);
|
||||
assert.deepEqual((ctx.body as any)?.error, "unrecognized_bearer");
|
||||
});
|
||||
});
|
||||
|
||||
describe("session cookie", () => {
|
||||
const validToken = `as_${"b".repeat(32)}`;
|
||||
|
||||
it("valid session cookie → sets user and session, calls next", async () => {
|
||||
const db = makeMockDb({
|
||||
getUserBySession: async () => MOCK_USER,
|
||||
});
|
||||
const ctx = makeMockCtx({}, { abode_session: validToken });
|
||||
const next = await runMiddleware(db, ctx);
|
||||
assert.equal(next, true);
|
||||
assert.deepEqual(ctx.user, MOCK_USER);
|
||||
assert.deepEqual(ctx.session, { source: "session" });
|
||||
});
|
||||
|
||||
it("invalid session token format clears cookie and falls through to 401", async () => {
|
||||
const db = makeMockDb();
|
||||
const ctx = makeMockCtx({}, { abode_session: "not-a-session-token" });
|
||||
await runMiddleware(db, ctx);
|
||||
assert.ok(ctx.clearedCookies.has("abode_session"), "cookie should be cleared");
|
||||
assert.equal(ctx.status, 401);
|
||||
});
|
||||
|
||||
it("expired/unknown session token clears cookie and returns 401", async () => {
|
||||
const db = makeMockDb({
|
||||
getUserBySession: async () => { throw new NotFoundAbodeError(); },
|
||||
});
|
||||
const ctx = makeMockCtx({}, { abode_session: validToken });
|
||||
await runMiddleware(db, ctx);
|
||||
assert.ok(ctx.clearedCookies.has("abode_session"), "cookie should be cleared");
|
||||
assert.equal(ctx.status, 401);
|
||||
});
|
||||
});
|
||||
|
||||
describe("no auth", () => {
|
||||
it("no credentials → 401 not_authenticated", async () => {
|
||||
const db = makeMockDb();
|
||||
const ctx = makeMockCtx();
|
||||
const next = await runMiddleware(db, ctx);
|
||||
assert.equal(next, false);
|
||||
assert.equal(ctx.status, 401);
|
||||
assert.deepEqual((ctx.body as any)?.error, "not_authenticated");
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,74 @@
|
||||
import { describe, it } from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import { convertError } from "../../src/webapi/middleware/convertError.js";
|
||||
import {
|
||||
NotFoundAbodeError,
|
||||
NotAuthorizedAbodeError,
|
||||
ConflictAbodeError,
|
||||
InvalidAbodeError,
|
||||
ReadonlyAbodeError,
|
||||
} from "../../src/db/types/errors.js";
|
||||
|
||||
function makeCtx() {
|
||||
return { status: 200, body: null as unknown };
|
||||
}
|
||||
|
||||
async function runWithError(err: unknown) {
|
||||
const ctx = makeCtx();
|
||||
await convertError(ctx as any, async () => {
|
||||
throw err;
|
||||
});
|
||||
return ctx;
|
||||
}
|
||||
|
||||
describe("convertError middleware", () => {
|
||||
it("does not interfere when next succeeds", async () => {
|
||||
const ctx = makeCtx();
|
||||
let nextCalled = false;
|
||||
await convertError(ctx as any, async () => { nextCalled = true; });
|
||||
assert.equal(nextCalled, true);
|
||||
assert.equal(ctx.status, 200);
|
||||
});
|
||||
|
||||
it("NotFoundAbodeError → 404 not_found", async () => {
|
||||
const ctx = await runWithError(new NotFoundAbodeError());
|
||||
assert.equal(ctx.status, 404);
|
||||
assert.deepEqual(ctx.body, { ok: false, error: "not_found" });
|
||||
});
|
||||
|
||||
it("NotAuthorizedAbodeError → 401 not_authorized", async () => {
|
||||
const ctx = await runWithError(new NotAuthorizedAbodeError());
|
||||
assert.equal(ctx.status, 401);
|
||||
assert.deepEqual(ctx.body, { ok: false, error: "not_authorized" });
|
||||
});
|
||||
|
||||
it("ConflictAbodeError → 409 conflict", async () => {
|
||||
const ctx = await runWithError(new ConflictAbodeError());
|
||||
assert.equal(ctx.status, 409);
|
||||
assert.deepEqual(ctx.body, { ok: false, error: "conflict" });
|
||||
});
|
||||
|
||||
it("InvalidAbodeError → 400 invalid", async () => {
|
||||
const ctx = await runWithError(new InvalidAbodeError());
|
||||
assert.equal(ctx.status, 400);
|
||||
assert.deepEqual(ctx.body, { ok: false, error: "invalid" });
|
||||
});
|
||||
|
||||
it("ReadonlyAbodeError → 403 readonly", async () => {
|
||||
const ctx = await runWithError(new ReadonlyAbodeError());
|
||||
assert.equal(ctx.status, 403);
|
||||
assert.deepEqual(ctx.body, { ok: false, error: "readonly" });
|
||||
});
|
||||
|
||||
it("unknown Error → 500 unknown", async () => {
|
||||
const ctx = await runWithError(new Error("something went wrong"));
|
||||
assert.equal(ctx.status, 500);
|
||||
assert.deepEqual(ctx.body, { ok: false, error: "unknown" });
|
||||
});
|
||||
|
||||
it("non-Error thrown → 500 unknown", async () => {
|
||||
const ctx = await runWithError("string error");
|
||||
assert.equal(ctx.status, 500);
|
||||
assert.deepEqual(ctx.body, { ok: false, error: "unknown" });
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,39 @@
|
||||
import { describe, it } from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import { hashPassword, validatePassword } from "../../src/util/hash.js";
|
||||
|
||||
describe("hashPassword", () => {
|
||||
it("returns a string in PHC/argon2 format", async () => {
|
||||
const hash = await hashPassword("secret");
|
||||
assert.ok(hash.startsWith("$argon2"), `expected argon2 hash, got: ${hash}`);
|
||||
assert.ok(hash.includes("$"), "has delimiter");
|
||||
});
|
||||
|
||||
it("two hashes of the same password differ (random salt)", async () => {
|
||||
const [h1, h2] = await Promise.all([
|
||||
hashPassword("same-password"),
|
||||
hashPassword("same-password"),
|
||||
]);
|
||||
assert.notEqual(h1, h2, "hashes should differ due to random salt");
|
||||
});
|
||||
});
|
||||
|
||||
describe("validatePassword", () => {
|
||||
it("returns true for matching password and hash", async () => {
|
||||
const hash = await hashPassword("correct-password");
|
||||
const result = await validatePassword("correct-password", hash);
|
||||
assert.equal(result, true);
|
||||
});
|
||||
|
||||
it("returns false for wrong password", async () => {
|
||||
const hash = await hashPassword("correct-password");
|
||||
const result = await validatePassword("wrong-password", hash);
|
||||
assert.equal(result, false);
|
||||
});
|
||||
|
||||
it("returns false for a completely different password", async () => {
|
||||
const hash = await hashPassword("original-password");
|
||||
const result = await validatePassword("different-password", hash);
|
||||
assert.equal(result, false);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,140 @@
|
||||
import { describe, it, before, after } from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import Koa from "koa";
|
||||
import KoaRouter from "@koa/router";
|
||||
import { createServer } from "node:http";
|
||||
import type { AddressInfo } from "node:net";
|
||||
import { jsonBody } from "../../src/webapi/middleware/jsonBody.js";
|
||||
|
||||
async function request(
|
||||
url: string,
|
||||
opts: { method?: string; body?: unknown; contentType?: string } = {}
|
||||
): Promise<{ status: number; body: unknown }> {
|
||||
const method = opts.method ?? "POST";
|
||||
const bodyStr =
|
||||
opts.body !== undefined ? JSON.stringify(opts.body) : undefined;
|
||||
const headers: Record<string, string> = {};
|
||||
if (bodyStr !== undefined) {
|
||||
headers["Content-Type"] = opts.contentType ?? "application/json";
|
||||
headers["Content-Length"] = String(bodyStr.length);
|
||||
}
|
||||
const res = await fetch(url, { method, headers, body: bodyStr });
|
||||
const text = await res.text();
|
||||
let parsed: unknown;
|
||||
try { parsed = JSON.parse(text); } catch { parsed = text; }
|
||||
return { status: res.status, body: parsed };
|
||||
}
|
||||
|
||||
async function makeTestServer() {
|
||||
const failValidator = Object.assign(
|
||||
(_obj: unknown): _obj is never => false,
|
||||
{
|
||||
errors: [{ message: "required" }] as unknown[],
|
||||
schema: { $id: "test-schema", title: "Test", description: "" },
|
||||
}
|
||||
);
|
||||
|
||||
const app = new Koa();
|
||||
const router = new KoaRouter();
|
||||
|
||||
router.post("/echo", jsonBody(), async (ctx) => {
|
||||
ctx.status = 200;
|
||||
ctx.body = { ok: true, received: ctx.request.body };
|
||||
});
|
||||
|
||||
router.post(
|
||||
"/fail-validate",
|
||||
jsonBody({ validate: failValidator as any }),
|
||||
async (ctx) => {
|
||||
ctx.status = 200;
|
||||
ctx.body = { ok: true };
|
||||
}
|
||||
);
|
||||
|
||||
router.post(
|
||||
"/with-params/:uid",
|
||||
jsonBody({ includeParams: ["uid"] }),
|
||||
async (ctx) => {
|
||||
ctx.status = 200;
|
||||
ctx.body = { ok: true, body: ctx.request.body };
|
||||
}
|
||||
);
|
||||
|
||||
app.use(router.routes());
|
||||
app.use(router.allowedMethods());
|
||||
|
||||
const server = createServer(app.callback());
|
||||
await new Promise<void>((resolve) => server.listen(0, "127.0.0.1", resolve));
|
||||
const { port } = server.address() as AddressInfo;
|
||||
const url = `http://127.0.0.1:${port}`;
|
||||
const close = () =>
|
||||
new Promise<void>((resolve, reject) =>
|
||||
server.close((err) => (err ? reject(err) : resolve()))
|
||||
);
|
||||
return { url, close };
|
||||
}
|
||||
|
||||
describe("jsonBody middleware", () => {
|
||||
let url: string;
|
||||
let closeServer: () => Promise<void>;
|
||||
|
||||
before(async () => {
|
||||
({ url, close: closeServer } = await makeTestServer());
|
||||
});
|
||||
|
||||
after(() => closeServer());
|
||||
|
||||
it("no Content-Type → 200 with empty body (bodyparser sets body to {})", async () => {
|
||||
const res = await fetch(url + "/echo", { method: "POST" });
|
||||
const json = await res.json();
|
||||
assert.equal(res.status, 200);
|
||||
assert.deepEqual(json.received, {});
|
||||
});
|
||||
|
||||
it("invalid JSON with Content-Type: application/json → 400 from bodyparser", async () => {
|
||||
const res = await fetch(url + "/echo", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: "not-valid-json",
|
||||
});
|
||||
assert.equal(res.status, 400);
|
||||
});
|
||||
|
||||
it("valid JSON body → 200 with echoed body", async () => {
|
||||
const res = await request(url + "/echo", { body: { hello: "world" } });
|
||||
assert.equal(res.status, 200);
|
||||
assert.deepEqual((res.body as any).received, { hello: "world" });
|
||||
});
|
||||
|
||||
it("failing validator → 400 jsonchema_validation_failed with schema and errors", async () => {
|
||||
const res = await request(url + "/fail-validate", { body: { any: "thing" } });
|
||||
assert.equal(res.status, 400);
|
||||
assert.equal((res.body as any).error, "jsonchema_validation_failed");
|
||||
assert.ok((res.body as any).schema, "response includes schema");
|
||||
assert.ok(Array.isArray((res.body as any).errors), "response includes errors");
|
||||
});
|
||||
|
||||
it("includeParams: param absent from body → merged in", async () => {
|
||||
const res = await request(url + "/with-params/user-42", {
|
||||
body: { other: "field" },
|
||||
});
|
||||
assert.equal(res.status, 200);
|
||||
assert.equal((res.body as any).body?.uid, "user-42");
|
||||
});
|
||||
|
||||
it("includeParams: param present with matching value → ok", async () => {
|
||||
const res = await request(url + "/with-params/user-42", {
|
||||
body: { uid: "user-42" },
|
||||
});
|
||||
assert.equal(res.status, 200);
|
||||
});
|
||||
|
||||
it("includeParams: mismatching param value → 400 mismatch_params", async () => {
|
||||
const res = await request(url + "/with-params/user-42", {
|
||||
body: { uid: "different-uid" },
|
||||
});
|
||||
assert.equal(res.status, 400);
|
||||
assert.equal((res.body as any).error, "mismatch_params");
|
||||
assert.equal((res.body as any).param, "uid");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,86 @@
|
||||
import { describe, it } from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import {
|
||||
createSessionToken,
|
||||
createApikeyToken,
|
||||
isSessionToken,
|
||||
isApikeyToken,
|
||||
} from "../../src/util/token.js";
|
||||
|
||||
describe("createSessionToken", () => {
|
||||
it("starts with 'as_'", () => {
|
||||
const token = createSessionToken();
|
||||
assert.ok(token.startsWith("as_"), `expected as_ prefix, got: ${token}`);
|
||||
});
|
||||
|
||||
it("has 35 chars total (as_ + 32 hex)", () => {
|
||||
const token = createSessionToken();
|
||||
assert.equal(token.length, 35);
|
||||
});
|
||||
|
||||
it("suffix is all hex characters", () => {
|
||||
const token = createSessionToken();
|
||||
const hex = token.slice(3);
|
||||
assert.ok(/^[0-9a-f]{32}$/.test(hex), `not all hex: ${hex}`);
|
||||
});
|
||||
|
||||
it("produces different tokens on each call", () => {
|
||||
const tokens = new Set(Array.from({ length: 10 }, createSessionToken));
|
||||
assert.equal(tokens.size, 10, "all tokens should be unique");
|
||||
});
|
||||
});
|
||||
|
||||
describe("createApikeyToken", () => {
|
||||
it("starts with 'at_'", () => {
|
||||
const token = createApikeyToken();
|
||||
assert.ok(token.startsWith("at_"), `expected at_ prefix, got: ${token}`);
|
||||
});
|
||||
|
||||
it("has 35 chars total (at_ + 32 hex)", () => {
|
||||
const token = createApikeyToken();
|
||||
assert.equal(token.length, 35);
|
||||
});
|
||||
|
||||
it("suffix is all hex characters", () => {
|
||||
const token = createApikeyToken();
|
||||
const hex = token.slice(3);
|
||||
assert.ok(/^[0-9a-f]{32}$/.test(hex), `not all hex: ${hex}`);
|
||||
});
|
||||
|
||||
it("produces different tokens on each call", () => {
|
||||
const tokens = new Set(Array.from({ length: 10 }, createApikeyToken));
|
||||
assert.equal(tokens.size, 10, "all tokens should be unique");
|
||||
});
|
||||
});
|
||||
|
||||
describe("isSessionToken", () => {
|
||||
it("returns true for as_ prefixed strings", () => {
|
||||
assert.equal(isSessionToken("as_" + "a".repeat(32)), true);
|
||||
});
|
||||
|
||||
it("returns false for at_ prefixed strings", () => {
|
||||
assert.equal(isSessionToken("at_abc"), false);
|
||||
});
|
||||
|
||||
it("returns false for empty string", () => {
|
||||
assert.equal(isSessionToken(""), false);
|
||||
});
|
||||
|
||||
it("returns false for plain strings", () => {
|
||||
assert.equal(isSessionToken("hello"), false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("isApikeyToken", () => {
|
||||
it("returns true for at_ prefixed strings", () => {
|
||||
assert.equal(isApikeyToken("at_" + "b".repeat(32)), true);
|
||||
});
|
||||
|
||||
it("returns false for as_ prefixed strings", () => {
|
||||
assert.equal(isApikeyToken("as_abc"), false);
|
||||
});
|
||||
|
||||
it("returns false for empty string", () => {
|
||||
assert.equal(isApikeyToken(""), false);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,181 @@
|
||||
import { describe, it } from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import {
|
||||
createuser,
|
||||
updateuser,
|
||||
clientuser,
|
||||
loginuser,
|
||||
createabode,
|
||||
updateabode,
|
||||
createresident,
|
||||
createapikey,
|
||||
} from "../../src/schema/validators.js";
|
||||
|
||||
describe("createuser validator", () => {
|
||||
it("accepts a valid CreateUser object", () => {
|
||||
const result = createuser({
|
||||
email: "user@example.com",
|
||||
name: "Alice",
|
||||
password: "#unset",
|
||||
flags: {},
|
||||
});
|
||||
assert.equal(result, true);
|
||||
});
|
||||
|
||||
it("rejects missing name", () => {
|
||||
const result = createuser({
|
||||
email: "user@example.com",
|
||||
password: "#unset",
|
||||
flags: {},
|
||||
});
|
||||
assert.equal(result, false);
|
||||
assert.ok(createuser.errors && createuser.errors.length > 0);
|
||||
});
|
||||
|
||||
it("rejects missing email", () => {
|
||||
const result = createuser({
|
||||
name: "Alice",
|
||||
password: "#unset",
|
||||
flags: {},
|
||||
});
|
||||
assert.equal(result, false);
|
||||
});
|
||||
|
||||
it("rejects missing password", () => {
|
||||
const result = createuser({
|
||||
email: "user@example.com",
|
||||
name: "Alice",
|
||||
flags: {},
|
||||
});
|
||||
assert.equal(result, false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("updateuser validator", () => {
|
||||
it("accepts update with just uid", () => {
|
||||
const result = updateuser({ uid: "11111111-1111-1111-1111-111111111111" });
|
||||
assert.equal(result, true);
|
||||
});
|
||||
|
||||
it("accepts update with uid and name", () => {
|
||||
const result = updateuser({
|
||||
uid: "11111111-1111-1111-1111-111111111111",
|
||||
name: "New Name",
|
||||
});
|
||||
assert.equal(result, true);
|
||||
});
|
||||
|
||||
it("rejects missing uid", () => {
|
||||
const result = updateuser({ name: "Alice" });
|
||||
assert.equal(result, false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("clientuser validator", () => {
|
||||
it("accepts a valid ClientUser (no password)", () => {
|
||||
const result = clientuser({
|
||||
uid: "11111111-1111-1111-1111-111111111111",
|
||||
email: "user@example.com",
|
||||
name: "Alice",
|
||||
flags: {},
|
||||
created_at: "2024-01-01T00:00:00Z",
|
||||
updated_at: "2024-01-01T00:00:00Z",
|
||||
});
|
||||
assert.equal(result, true);
|
||||
});
|
||||
|
||||
it("rejects object with password field", () => {
|
||||
const result = clientuser({
|
||||
uid: "11111111-1111-1111-1111-111111111111",
|
||||
email: "user@example.com",
|
||||
name: "Alice",
|
||||
password: "#unset",
|
||||
flags: {},
|
||||
created_at: "2024-01-01T00:00:00Z",
|
||||
updated_at: "2024-01-01T00:00:00Z",
|
||||
});
|
||||
assert.equal(result, false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("loginuser validator", () => {
|
||||
it("accepts valid LoginUser", () => {
|
||||
const result = loginuser({ email: "user@example.com", password: "secret" });
|
||||
assert.equal(result, true);
|
||||
});
|
||||
|
||||
it("rejects missing password", () => {
|
||||
const result = loginuser({ email: "user@example.com" });
|
||||
assert.equal(result, false);
|
||||
});
|
||||
|
||||
it("rejects missing email", () => {
|
||||
const result = loginuser({ password: "secret" });
|
||||
assert.equal(result, false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("createabode validator", () => {
|
||||
it("accepts valid CreateAbode", () => {
|
||||
const result = createabode({ name: "My Abode" });
|
||||
assert.equal(result, true);
|
||||
});
|
||||
|
||||
it("rejects missing name", () => {
|
||||
const result = createabode({});
|
||||
assert.equal(result, false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("updateabode validator", () => {
|
||||
it("accepts update with just aid", () => {
|
||||
const result = updateabode({ aid: "22222222-2222-2222-2222-222222222222" });
|
||||
assert.equal(result, true);
|
||||
});
|
||||
|
||||
it("accepts update with aid and name", () => {
|
||||
const result = updateabode({
|
||||
aid: "22222222-2222-2222-2222-222222222222",
|
||||
name: "New Name",
|
||||
});
|
||||
assert.equal(result, true);
|
||||
});
|
||||
});
|
||||
|
||||
describe("createresident validator", () => {
|
||||
it("accepts valid CreateResident", () => {
|
||||
const result = createresident({
|
||||
uid: "11111111-1111-1111-1111-111111111111",
|
||||
aid: "22222222-2222-2222-2222-222222222222",
|
||||
flags: {},
|
||||
});
|
||||
assert.equal(result, true);
|
||||
});
|
||||
|
||||
it("rejects missing uid", () => {
|
||||
const result = createresident({
|
||||
aid: "22222222-2222-2222-2222-222222222222",
|
||||
flags: {},
|
||||
});
|
||||
assert.equal(result, false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("createapikey validator", () => {
|
||||
it("accepts valid CreateApikey", () => {
|
||||
const result = createapikey({
|
||||
uid: "11111111-1111-1111-1111-111111111111",
|
||||
name: "My Key",
|
||||
permissions: {},
|
||||
});
|
||||
assert.equal(result, true);
|
||||
});
|
||||
|
||||
it("rejects missing name", () => {
|
||||
const result = createapikey({
|
||||
uid: "11111111-1111-1111-1111-111111111111",
|
||||
permissions: {},
|
||||
});
|
||||
assert.equal(result, false);
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user