ci: add pull request quality gates
CI / install-and-build (pull_request) Successful in 1m29s
CI / format (pull_request) Successful in 51s
CI / typecheck-source (pull_request) Successful in 41s
CI / typecheck-tests (pull_request) Successful in 39s
CI / test (pull_request) Successful in 51s
CI / lint (pull_request) Successful in 21s

Co-Authored-By: gpt-5.6-terra <noreply@openai.com>
This commit was merged in pull request #12.
This commit is contained in:
2026-07-22 21:50:29 +00:00
co-authored by Codex
parent b9fa79ff1f
commit 31d4636dde
80 changed files with 2007 additions and 398 deletions
+19 -11
View File
@@ -3,7 +3,11 @@ import assert from "node:assert/strict";
import { createServer } from "node:http";
import type { AddressInfo } from "node:net";
import { ApiInterface } from "../../../src/db/api/ApiInterface.js";
import { apiProtocols, isApiUrl, parseApiUrl } from "../../../src/db/api/url.js";
import {
apiProtocols,
isApiUrl,
parseApiUrl,
} from "../../../src/db/api/url.js";
import {
NotFoundAbodeError,
NotAuthorizedAbodeError,
@@ -86,7 +90,7 @@ describe("parseApiUrl", () => {
it("extra query params become headers", () => {
const [, { headers }] = parseApiUrl(
"http://example.com?X-Custom-Header=value"
"http://example.com?X-Custom-Header=value",
);
assert.equal(headers["X-Custom-Header"], "value");
});
@@ -94,7 +98,7 @@ describe("parseApiUrl", () => {
it("throws for non-api protocol", () => {
assert.throws(
() => parseApiUrl("sqlite:///db.sqlite"),
/Not an \{abode\+,\}http\{s,\}: protocol/
/Not an \{abode\+,\}http\{s,\}: protocol/,
);
});
});
@@ -106,18 +110,22 @@ describe("ApiInterface HTTP error mapping", () => {
before(async () => {
let nextStatus = 500;
respondWith = (s) => { nextStatus = s; };
respondWith = (s) => {
nextStatus = s;
};
const server = createServer((req, res) => {
res.writeHead(nextStatus, { "Content-Type": "application/json" });
res.end(JSON.stringify({ ok: false, error: "test" }));
});
await new Promise<void>((resolve) => server.listen(0, "127.0.0.1", resolve));
await new Promise<void>((resolve) =>
server.listen(0, "127.0.0.1", resolve),
);
const { port } = server.address() as AddressInfo;
serverUrl = `http://127.0.0.1:${port}`;
closeServer = () =>
new Promise<void>((resolve, reject) =>
server.close((err) => (err ? reject(err) : resolve()))
server.close((err) => (err ? reject(err) : resolve())),
);
});
@@ -131,7 +139,7 @@ describe("ApiInterface HTTP error mapping", () => {
(err) => {
assert.ok(err instanceof NotFoundAbodeError);
return true;
}
},
);
});
@@ -143,7 +151,7 @@ describe("ApiInterface HTTP error mapping", () => {
(err) => {
assert.ok(err instanceof NotAuthorizedAbodeError);
return true;
}
},
);
});
@@ -155,7 +163,7 @@ describe("ApiInterface HTTP error mapping", () => {
(err) => {
assert.ok(err instanceof ReadonlyAbodeError);
return true;
}
},
);
});
@@ -167,7 +175,7 @@ describe("ApiInterface HTTP error mapping", () => {
(err) => {
assert.ok(err instanceof InvalidAbodeError);
return true;
}
},
);
});
@@ -179,7 +187,7 @@ describe("ApiInterface HTTP error mapping", () => {
(err) => {
assert.ok(err instanceof ConflictAbodeError);
return true;
}
},
);
});
});
+5 -1
View File
@@ -92,7 +92,11 @@ describe("api backend: auth over HTTP", async () => {
const self = await fetch(`${server.url}/auth/self`, {
headers: { Cookie: `abode_session=${cookie}` },
});
assert.equal(self.status, 401, "session was invalidated server-side, not just the cookie cleared");
assert.equal(
self.status,
401,
"session was invalidated server-side, not just the cookie cleared",
);
});
it("POST /auth/clear-sessions invalidates outstanding session cookies", async () => {
+2 -2
View File
@@ -10,10 +10,10 @@ import { runAuthTests } from "../../shared/auth.js";
async function createExpiredApikey(
db: BackendDbInterface,
uid: string
uid: string,
): Promise<`at_${string}`> {
const si = db as SqliteInterface;
const token = (`at_${"e".repeat(32)}`) as `at_${string}`;
const token = `at_${"e".repeat(32)}` as `at_${string}`;
const kid = crypto.randomUUID();
const { sql } = si._;
si._.db.run(sql`
+2 -2
View File
@@ -46,7 +46,7 @@ describe("SqliteMigrator", () => {
assert.equal(applied.length, 3);
assert.deepEqual(
applied.map((m) => m.id),
[1, 2, 3]
[1, 2, 3],
);
db.destroy();
});
@@ -66,7 +66,7 @@ describe("SqliteMigrator", () => {
const migrator = new SqliteMigrator(db);
await assert.rejects(
() => migrator.migrateTo(9999),
/No known migration with id 9999/
/No known migration with id 9999/,
);
db.destroy();
});
+7 -1
View File
@@ -1,6 +1,12 @@
import { describe, it } from "node:test";
import assert from "node:assert/strict";
import { sql, catSql, joinSql, calcUpdates, unsafeSql } from "../../../src/db/sqlite/sql.js";
import {
sql,
catSql,
joinSql,
calcUpdates,
unsafeSql,
} from "../../../src/db/sqlite/sql.js";
describe("sql template tag", () => {
it("produces correct sql and empty vars for plain text", () => {
+22 -10
View File
@@ -10,13 +10,19 @@ function runWrappedDbSuite(name: string, makeDb: () => WrappedDb) {
before(() => {
db = makeDb();
db.run(unsafeSql("CREATE TABLE IF NOT EXISTS test (id INTEGER PRIMARY KEY, val TEXT NOT NULL)"));
db.run(
unsafeSql(
"CREATE TABLE IF NOT EXISTS test (id INTEGER PRIMARY KEY, val TEXT NOT NULL)",
),
);
});
after(() => db.destroy());
it("run INSERT returns changes count", () => {
const { changes } = db.run(sql`INSERT INTO test(val) VALUES(${{ text: "hello" }})`);
const { changes } = db.run(
sql`INSERT INTO test(val) VALUES(${{ text: "hello" }})`,
);
assert.equal(changes, 1);
});
@@ -24,7 +30,9 @@ function runWrappedDbSuite(name: string, makeDb: () => WrappedDb) {
db.run(unsafeSql("DELETE FROM test"));
db.run(sql`INSERT INTO test(val) VALUES(${{ text: "a" }})`);
db.run(sql`INSERT INTO test(val) VALUES(${{ text: "b" }})`);
const rows = db.all<{ val: string }>(unsafeSql("SELECT val FROM test ORDER BY val"));
const rows = db.all<{ val: string }>(
unsafeSql("SELECT val FROM test ORDER BY val"),
);
assert.equal(rows.length, 2);
assert.equal(rows[0].val, "a");
assert.equal(rows[1].val, "b");
@@ -38,7 +46,7 @@ function runWrappedDbSuite(name: string, makeDb: () => WrappedDb) {
assert.equal(row.val, "one");
const none = db.get<{ val: string }>(
sql`SELECT val FROM test WHERE val = ${{ text: "none" }}`
sql`SELECT val FROM test WHERE val = ${{ text: "none" }}`,
);
assert.equal(none, null);
});
@@ -49,7 +57,7 @@ function runWrappedDbSuite(name: string, makeDb: () => WrappedDb) {
db.run(sql`INSERT INTO test(val) VALUES(${{ text: "dup2" }})`);
assert.throws(
() => db.get<{ val: string }>(unsafeSql("SELECT val FROM test")),
/Multiple results/
/Multiple results/,
);
});
@@ -69,7 +77,7 @@ function runWrappedDbSuite(name: string, makeDb: () => WrappedDb) {
db.multi(() => {
db.run(sql`INSERT INTO test(val) VALUES(${{ text: "rollback" }})`);
throw new Error("abort!");
})
}),
);
const rows = db.all<{ val: string }>(unsafeSql("SELECT val FROM test"));
assert.equal(rows.length, 0);
@@ -82,7 +90,13 @@ function runWrappedDbSuite(name: string, makeDb: () => WrappedDb) {
it("rethrow propagates non-SQLite errors unchanged", () => {
const err = new Error("custom error");
assert.throws(() => db.rethrow(() => { throw err; }), (e) => e === err);
assert.throws(
() =>
db.rethrow(() => {
throw err;
}),
(e) => e === err,
);
});
});
}
@@ -93,9 +107,7 @@ describe("better-sqlite3 WrappedDb", async () => {
let bs3Ctor: (new (path: string) => WrappedDb) | null = null;
try {
const mod = await import(
"../../../src/db/sqlite/impl/better-sqlite3.js"
);
const mod = await import("../../../src/db/sqlite/impl/better-sqlite3.js");
bs3Ctor = mod.WrappedBetterSqlite3Db;
} catch {
// better-sqlite3 not available, skip
+2 -2
View File
@@ -10,7 +10,7 @@ export interface TestServer {
}
export async function createTestServer(
db: BackendDbInterface
db: BackendDbInterface,
): Promise<TestServer> {
const app = new Koa();
const router = apirouter(db);
@@ -23,7 +23,7 @@ export async function createTestServer(
url: `http://127.0.0.1:${port}`,
close: () =>
new Promise<void>((resolve, reject) =>
server.close((err) => (err ? reject(err) : resolve()))
server.close((err) => (err ? reject(err) : resolve())),
),
};
}
+27 -12
View File
@@ -1,12 +1,15 @@
import { describe, it, before, after } from "node:test";
import assert from "node:assert/strict";
import type { DbInterface } from "../../src/db/types/DbInterface.js";
import { NotFoundAbodeError, InvalidAbodeError } from "../../src/db/types/errors.js";
import {
NotFoundAbodeError,
InvalidAbodeError,
} from "../../src/db/types/errors.js";
import { hashPassword } from "../../src/util/hash.js";
export function runAbodeTests(
name: string,
getDb: () => Promise<{ db: DbInterface; close(): void }>
getDb: () => Promise<{ db: DbInterface; close(): void }>,
): void {
describe(`${name}: abodes`, async () => {
let db: DbInterface;
@@ -28,7 +31,10 @@ export function runAbodeTests(
after(() => close());
it("createAbode returns an Abode with expected fields", async () => {
const abode = await db.createAbode({ name: "Test Abode" }, { uid: ctxUid });
const abode = await db.createAbode(
{ name: "Test Abode" },
{ uid: ctxUid },
);
assert.ok(abode.aid, "has aid");
assert.equal(abode.name, "Test Abode");
assert.ok(abode.created_at);
@@ -36,7 +42,10 @@ export function runAbodeTests(
});
it("getAbodeById returns the created abode", async () => {
const created = await db.createAbode({ name: "ById Abode" }, { uid: ctxUid });
const created = await db.createAbode(
{ name: "ById Abode" },
{ uid: ctxUid },
);
const found = await db.getAbodeById(created.aid);
assert.equal(found.aid, created.aid);
assert.equal(found.name, "ById Abode");
@@ -48,14 +57,14 @@ export function runAbodeTests(
(err) => {
assert.ok(err instanceof NotFoundAbodeError);
return true;
}
},
);
});
it("listAbodes includes the created abode", async () => {
const created = await db.createAbode(
{ name: `Listed Abode ${Date.now()}` },
{ uid: ctxUid }
{ uid: ctxUid },
);
const abodes = await db.listAbodes();
assert.ok(Array.isArray(abodes));
@@ -67,32 +76,38 @@ export function runAbodeTests(
const created = await db.createAbode({ name: "Before" }, { uid: ctxUid });
const updated = await db.updateAbode(
{ aid: created.aid, name: "After" },
{ uid: ctxUid }
{ uid: ctxUid },
);
assert.equal(updated.aid, created.aid);
assert.equal(updated.name, "After");
});
it("updateAbode with no fields throws InvalidAbodeError", async () => {
const created = await db.createAbode({ name: "No Update" }, { uid: ctxUid });
const created = await db.createAbode(
{ name: "No Update" },
{ uid: ctxUid },
);
await assert.rejects(
() => db.updateAbode({ aid: created.aid }, { uid: ctxUid }),
(err) => {
assert.ok(err instanceof InvalidAbodeError);
return true;
}
},
);
});
it("deleteAbodeById removes the abode", async () => {
const created = await db.createAbode({ name: "To Delete" }, { uid: ctxUid });
const created = await db.createAbode(
{ name: "To Delete" },
{ uid: ctxUid },
);
await db.deleteAbodeById(created.aid);
await assert.rejects(
() => db.getAbodeById(created.aid),
(err) => {
assert.ok(err instanceof NotFoundAbodeError);
return true;
}
},
);
});
@@ -102,7 +117,7 @@ export function runAbodeTests(
(err) => {
assert.ok(err instanceof NotFoundAbodeError);
return true;
}
},
);
});
});
+4 -4
View File
@@ -6,7 +6,7 @@ import { hashPassword } from "../../src/util/hash.js";
export function runApikeyTests(
name: string,
getDb: () => Promise<{ db: DbInterface; close(): void }>
getDb: () => Promise<{ db: DbInterface; close(): void }>,
): void {
describe(`${name}: apikeys`, async () => {
let db: DbInterface;
@@ -69,7 +69,7 @@ export function runApikeyTests(
(err) => {
assert.ok(err instanceof NotFoundAbodeError);
return true;
}
},
);
});
@@ -85,7 +85,7 @@ export function runApikeyTests(
(err) => {
assert.ok(err instanceof NotFoundAbodeError);
return true;
}
},
);
});
@@ -95,7 +95,7 @@ export function runApikeyTests(
(err) => {
assert.ok(err instanceof NotFoundAbodeError);
return true;
}
},
);
});
});
+15 -7
View File
@@ -11,7 +11,10 @@ import { hashPassword } from "../../src/util/hash.js";
export function runAuthTests(
name: string,
getDb: () => Promise<{ db: BackendDbInterface; close(): void }>,
createExpiredApikey?: (db: BackendDbInterface, uid: string) => Promise<`at_${string}`>
createExpiredApikey?: (
db: BackendDbInterface,
uid: string,
) => Promise<`at_${string}`>,
): void {
describe(`${name}: auth`, async () => {
let db: BackendDbInterface;
@@ -23,7 +26,12 @@ export function runAuthTests(
({ db, close } = await getDb());
email = `auth-user-${Date.now()}@test.example`;
const pw = await hashPassword(password);
await db.createUser({ email, name: "Auth User", password: pw, flags: {} });
await db.createUser({
email,
name: "Auth User",
password: pw,
flags: {},
});
});
after(() => close());
@@ -40,7 +48,7 @@ export function runAuthTests(
(err) => {
assert.ok(err instanceof NotAuthorizedAbodeError);
return true;
}
},
);
});
@@ -54,7 +62,7 @@ export function runAuthTests(
(err) => {
assert.ok(err instanceof NotFoundAbodeError);
return true;
}
},
);
});
@@ -71,7 +79,7 @@ export function runAuthTests(
(err) => {
assert.ok(err instanceof ConflictAbodeError);
return true;
}
},
);
});
});
@@ -118,7 +126,7 @@ export function runAuthTests(
(err) => {
assert.ok(err instanceof NotAuthorizedAbodeError);
return true;
}
},
);
});
@@ -129,7 +137,7 @@ export function runAuthTests(
(err) => {
assert.ok(err instanceof NotFoundAbodeError);
return true;
}
},
);
});
});
+21 -12
View File
@@ -1,12 +1,15 @@
import { describe, it, before, after } from "node:test";
import assert from "node:assert/strict";
import type { DbInterface } from "../../src/db/types/DbInterface.js";
import { NotFoundAbodeError, InvalidAbodeError } from "../../src/db/types/errors.js";
import {
NotFoundAbodeError,
InvalidAbodeError,
} from "../../src/db/types/errors.js";
import { hashPassword } from "../../src/util/hash.js";
export function runResidentTests(
name: string,
getDb: () => Promise<{ db: DbInterface; close(): void }>
getDb: () => Promise<{ db: DbInterface; close(): void }>,
): void {
describe(`${name}: residents`, async () => {
let db: DbInterface;
@@ -36,7 +39,7 @@ export function runResidentTests(
uid = resUser.uid;
const abode = await db.createAbode(
{ name: `Resident Abode ${Date.now()}` },
{ uid: ctxUid }
{ uid: ctxUid },
);
aid = abode.aid;
await db.createResident({ uid, aid, flags: {} }, { uid: ctxUid });
@@ -56,12 +59,12 @@ export function runResidentTests(
() =>
db.getResidentById(
"00000000-0000-0000-0000-000000000000",
"00000000-0000-0000-0000-000000000001"
"00000000-0000-0000-0000-000000000001",
),
(err) => {
assert.ok(err instanceof NotFoundAbodeError);
return true;
}
},
);
});
@@ -101,7 +104,7 @@ export function runResidentTests(
it("updateResident updates flags", async () => {
const updated = await db.updateResident(
{ uid, aid, flags: { admin: true } },
{ uid: ctxUid }
{ uid: ctxUid },
);
assert.equal(updated.uid, uid);
assert.deepEqual(updated.flags, { admin: true });
@@ -113,7 +116,7 @@ export function runResidentTests(
(err) => {
assert.ok(err instanceof InvalidAbodeError);
return true;
}
},
);
});
@@ -125,15 +128,21 @@ export function runResidentTests(
password: pw,
flags: {},
});
const abode2 = await db.createAbode({ name: "Del Abode" }, { uid: ctxUid });
await db.createResident({ uid: user2.uid, aid: abode2.aid, flags: {} }, { uid: ctxUid });
const abode2 = await db.createAbode(
{ name: "Del Abode" },
{ uid: ctxUid },
);
await db.createResident(
{ uid: user2.uid, aid: abode2.aid, flags: {} },
{ uid: ctxUid },
);
await db.deleteResidentById(user2.uid, abode2.aid);
await assert.rejects(
() => db.getResidentById(user2.uid, abode2.aid),
(err) => {
assert.ok(err instanceof NotFoundAbodeError);
return true;
}
},
);
});
@@ -142,12 +151,12 @@ export function runResidentTests(
() =>
db.deleteResidentById(
"00000000-0000-0000-0000-000000000002",
"00000000-0000-0000-0000-000000000003"
"00000000-0000-0000-0000-000000000003",
),
(err) => {
assert.ok(err instanceof NotFoundAbodeError);
return true;
}
},
);
});
});
+3 -3
View File
@@ -6,7 +6,7 @@ import { hashPassword } from "../../src/util/hash.js";
export function runSessionTests(
name: string,
getDb: () => Promise<{ db: BackendDbInterface; close(): void }>
getDb: () => Promise<{ db: BackendDbInterface; close(): void }>,
): void {
describe(`${name}: sessions`, async () => {
let db: BackendDbInterface;
@@ -46,7 +46,7 @@ export function runSessionTests(
(err) => {
assert.ok(err instanceof NotFoundAbodeError);
return true;
}
},
);
});
@@ -58,7 +58,7 @@ export function runSessionTests(
(err) => {
assert.ok(err instanceof NotFoundAbodeError);
return true;
}
},
);
});
});
+17 -9
View File
@@ -11,7 +11,7 @@ import { hashPassword } from "../../src/util/hash.js";
export function runUserTests(
name: string,
getDb: () => Promise<{ db: DbInterface; close(): void }>,
getReadonlyDb?: () => Promise<{ db: DbInterface; close(): void }>
getReadonlyDb?: () => Promise<{ db: DbInterface; close(): void }>,
): void {
describe(`${name}: users`, async () => {
let db: DbInterface;
@@ -57,13 +57,18 @@ export function runUserTests(
(err) => {
assert.ok(err instanceof NotFoundAbodeError);
return true;
}
},
);
});
it("getUserByEmail returns the created user", async () => {
const email = `user-byemail-${Date.now()}@test.example`;
await db.createUser({ email, name: "ByEmail User", password: hashedPw, flags: {} });
await db.createUser({
email,
name: "ByEmail User",
password: hashedPw,
flags: {},
});
const found = await db.getUserByEmail(email);
assert.ok("email" in found, "result includes email");
assert.equal(found.email, email);
@@ -75,7 +80,7 @@ export function runUserTests(
(err) => {
assert.ok(err instanceof NotFoundAbodeError);
return true;
}
},
);
});
@@ -100,7 +105,10 @@ export function runUserTests(
password: hashedPw,
flags: {},
});
const updated = await db.updateUser({ uid: created.uid, name: "After Update" });
const updated = await db.updateUser({
uid: created.uid,
name: "After Update",
});
assert.equal(updated.uid, created.uid);
assert.equal(updated.name, "After Update");
});
@@ -117,7 +125,7 @@ export function runUserTests(
(err) => {
assert.ok(err instanceof InvalidAbodeError);
return true;
}
},
);
});
@@ -134,7 +142,7 @@ export function runUserTests(
(err) => {
assert.ok(err instanceof NotFoundAbodeError);
return true;
}
},
);
});
@@ -144,7 +152,7 @@ export function runUserTests(
(err) => {
assert.ok(err instanceof NotFoundAbodeError);
return true;
}
},
);
});
});
@@ -178,7 +186,7 @@ export function runUserTests(
(err) => {
assert.ok(err instanceof ReadonlyAbodeError);
return true;
}
},
);
});
});
+110 -29
View File
@@ -29,7 +29,7 @@ const MOCK_APIKEY: ClientApikey = {
};
function makeMockDb(
overrides: Partial<BackendDbInterface> = {}
overrides: Partial<BackendDbInterface> = {},
): BackendDbInterface {
return {
readonly: false,
@@ -37,42 +37,97 @@ function makeMockDb(
name: "mock",
close: async () => {},
listUsers: async () => [],
getUserById: async () => { throw new NotFoundAbodeError(); },
getUserById: async () => {
throw new NotFoundAbodeError();
},
deleteUserById: async () => {},
createUser: async () => MOCK_USER,
updateUser: async () => MOCK_USER,
getUserByEmail: async () => { throw new NotFoundAbodeError(); },
getUserByEmail: async () => {
throw new NotFoundAbodeError();
},
listAbodes: async () => [],
getAbodeById: async () => { throw new NotFoundAbodeError(); },
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 }),
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(); },
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 }),
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(); },
getNoteById: async () => {
throw new NotFoundAbodeError();
},
deleteNoteById: async () => {},
createNote: async () => { throw new Error("unimplemented"); },
updateNote: async () => { throw new Error("unimplemented"); },
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}`],
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(); },
getUserByLogin: async () => {
throw new NotFoundAbodeError();
},
getUserBySession: async () => {
throw new NotFoundAbodeError();
},
createSession: async () => `as_${"0".repeat(32)}`,
deleteSession: async () => {},
getUserByApikey: async () => { throw new NotFoundAbodeError(); },
getUserByApikey: async () => {
throw new NotFoundAbodeError();
},
...overrides,
};
}
@@ -92,7 +147,10 @@ type MockCtx = {
};
};
function makeMockCtx(headerOverrides: Record<string, string> = {}, cookieOverrides: Record<string, string> = {}): MockCtx {
function makeMockCtx(
headerOverrides: Record<string, string> = {},
cookieOverrides: Record<string, string> = {},
): MockCtx {
const clearedCookies = new Set<string>();
const ctx: MockCtx = {
headers: headerOverrides,
@@ -110,7 +168,10 @@ function makeMockCtx(headerOverrides: Record<string, string> = {}, cookieOverrid
return cookieOverrides[name];
},
set(name: string, value: string, opts?: unknown) {
if (value === "" || (opts && (opts as { expires?: Date }).expires?.getFullYear()! < 2000)) {
if (
value === "" ||
(opts && (opts as { expires?: Date }).expires?.getFullYear()! < 2000)
) {
clearedCookies.add(name);
}
},
@@ -121,11 +182,13 @@ function makeMockCtx(headerOverrides: Record<string, string> = {}, cookieOverrid
async function runMiddleware(
db: BackendDbInterface,
ctx: MockCtx
ctx: MockCtx,
): Promise<boolean> {
let nextCalled = false;
const mw = authenticate(db);
await mw(ctx as any, async () => { nextCalled = true; });
await mw(ctx as any, async () => {
nextCalled = true;
});
return nextCalled;
}
@@ -157,7 +220,9 @@ describe("authenticate middleware", () => {
it("wrong password (NotAuthorizedAbodeError) → 401 invalid_password", async () => {
const db = makeMockDb({
getUserByLogin: async () => { throw new NotAuthorizedAbodeError(); },
getUserByLogin: async () => {
throw new NotAuthorizedAbodeError();
},
});
const ctx = makeMockCtx({ Authorization: "Basic " + btoa("user:wrong") });
await runMiddleware(db, ctx);
@@ -167,9 +232,13 @@ describe("authenticate middleware", () => {
it("unknown user (NotFoundAbodeError) → 401 unknown_user", async () => {
const db = makeMockDb({
getUserByLogin: async () => { throw new NotFoundAbodeError(); },
getUserByLogin: async () => {
throw new NotFoundAbodeError();
},
});
const ctx = makeMockCtx({
Authorization: "Basic " + btoa("nobody:pass"),
});
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");
@@ -177,7 +246,9 @@ describe("authenticate middleware", () => {
it("ConflictAbodeError (#unset password) → 401 user_not_loggable", async () => {
const db = makeMockDb({
getUserByLogin: async () => { throw new ConflictAbodeError(); },
getUserByLogin: async () => {
throw new ConflictAbodeError();
},
});
const ctx = makeMockCtx({ Authorization: "Basic " + btoa("user:pass") });
await runMiddleware(db, ctx);
@@ -211,7 +282,9 @@ describe("authenticate middleware", () => {
it("invalid/expired at_ token → 401 invalid_apikey", async () => {
const db = makeMockDb({
getUserByApikey: async () => { throw new NotFoundAbodeError(); },
getUserByApikey: async () => {
throw new NotFoundAbodeError();
},
});
const ctx = makeMockCtx({ Authorization: `Bearer ${validToken}` });
await runMiddleware(db, ctx);
@@ -246,17 +319,25 @@ describe("authenticate middleware", () => {
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.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(); },
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.ok(
ctx.clearedCookies.has("abode_session"),
"cookie should be cleared",
);
assert.equal(ctx.status, 401);
});
});
+3 -1
View File
@@ -25,7 +25,9 @@ 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; });
await convertError(ctx as any, async () => {
nextCalled = true;
});
assert.equal(nextCalled, true);
assert.equal(ctx.status, 200);
});
+20 -14
View File
@@ -8,7 +8,7 @@ import { jsonBody } from "../../src/webapi/middleware/jsonBody.js";
async function request(
url: string,
opts: { method?: string; body?: unknown; contentType?: string } = {}
opts: { method?: string; body?: unknown; contentType?: string } = {},
): Promise<{ status: number; body: unknown }> {
const method = opts.method ?? "POST";
const bodyStr =
@@ -21,18 +21,19 @@ async function request(
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; }
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 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();
@@ -48,7 +49,7 @@ async function makeTestServer() {
async (ctx) => {
ctx.status = 200;
ctx.body = { ok: true };
}
},
);
router.post(
@@ -57,7 +58,7 @@ async function makeTestServer() {
async (ctx) => {
ctx.status = 200;
ctx.body = { ok: true, body: ctx.request.body };
}
},
);
app.use(router.routes());
@@ -69,7 +70,7 @@ async function makeTestServer() {
const url = `http://127.0.0.1:${port}`;
const close = () =>
new Promise<void>((resolve, reject) =>
server.close((err) => (err ? reject(err) : resolve()))
server.close((err) => (err ? reject(err) : resolve())),
);
return { url, close };
}
@@ -107,11 +108,16 @@ describe("jsonBody middleware", () => {
});
it("failing validator → 400 jsonchema_validation_failed with schema and errors", async () => {
const res = await request(url + "/fail-validate", { body: { any: "thing" } });
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");
assert.ok(
Array.isArray((res.body as any).errors),
"response includes errors",
);
});
it("includeParams: param absent from body → merged in", async () => {