Files
heidi/lib/pay/codes.test.ts
CatoandClaude 28e9950014 Pass codes, a pass that buys a stronger model, and passes for organisations (#360)
A pass changed one number nobody reaches, was sold only for Bitcoin, and
was switched off. This makes a pass worth having and gives an organisation
a way to get one for each of its people.

- Pass codes (lib/pay/codes.ts, drizzle/0020_pass_codes.sql): the owner
  issues one code per person at /owner/pass-codes, each person redeems
  theirs on /pass. A code grants once, through paykit's extendEntitlement,
  and only its hash is stored. Needs no price and no OrangeCat.
- /pass takes a code whether or not passes are sold for Bitcoin; a pass is
  a pass without a price being set (hasPass no longer depends on one).
- The model a pass buys (lib/domain/model/pass-model.ts): one paid row in
  front of the free chain, named by HEIDI_PASS_MODELS, gated by ai-kit's
  spend rules. Off until configured; /pass promises it only then.
- Fixed: a pass tripled the allowance only in /api/chat. Saved
  conversations, where a pass holder writes, counted at the open rate.
- /organisations: a card for passes for a team, with a mail link.
- Wording in all seven interface languages; privacy page names pass_codes;
  account deletion keeps a redeemed code used and unattributed.


Claude-Session: https://claude.ai/code/session_019MDtmteJuDGFouA1itJ5tM

Co-authored-by: Claude <noreply@anthropic.com>
2026-11-26 00:31:37 +01:00

148 lines
6.7 KiB
TypeScript

import { test } from "node:test";
import assert from "node:assert/strict";
import { readdirSync, readFileSync } from "node:fs";
import { join } from "node:path";
import { PGlite } from "@electric-sql/pglite";
import { drizzle } from "drizzle-orm/pglite";
import * as schema from "../db/schema.ts";
import { codeId, formatCode, newCode, normaliseCode, passCodesOn, readMint, MAX_CODES, MAX_DAYS } from "./codes.ts";
const DAY = 86_400_000;
async function database() {
const pg = new PGlite();
const dir = join(process.cwd(), "drizzle");
for (const file of readdirSync(dir).filter((f) => f.endsWith(".sql")).sort()) {
for (const statement of readFileSync(join(dir, file), "utf8").split("--> statement-breakpoint")) {
if (statement.trim()) await pg.exec(statement);
}
}
const db = drizzle(pg, { schema });
return { pg, db, codes: passCodesOn(db as never) };
}
test("a code is sixteen characters nobody misreads, and no two are alike", () => {
const made = new Set(Array.from({ length: 500 }, newCode));
assert.equal(made.size, 500);
for (const code of made) assert.match(code, /^[0-9A-HJKMNP-TV-Z]{16}$/);
assert.equal(formatCode("ABCD1234EFGH5678"), "ABCD-1234-EFGH-5678");
});
test("what somebody types is read forgivingly, and nothing else is a code", () => {
const code = "A0B1C2D3E4F5G6H7";
assert.equal(normaliseCode("a0b1-c2d3-e4f5-g6h7"), code);
assert.equal(normaliseCode(" A0B1 C2D3 E4F5 G6H7 "), code);
// The letters the alphabet leaves out are read as the digit they look like.
assert.equal(normaliseCode("AOBI-C2D3-E4F5-G6H7"), "A0B1C2D3E4F5G6H7");
assert.equal(normaliseCode("AOBL-C2D3-E4F5-G6H7"), "A0B1C2D3E4F5G6H7");
for (const not of ["", "ABCD", "A0B1C2D3E4F5G6H7X", "A0B1C2D3E4F5G6H!", "U0B1C2D3E4F5G6H7", null, 42, "x".repeat(500)]) {
assert.equal(normaliseCode(not), null, `${String(not)} was read as a code`);
}
});
test("the owner's request is three plausible things or it is refused", () => {
assert.deepEqual(readMint({ count: 20, days: 30, label: " Pflegeheim Sonnenberg " }), { count: 20, days: 30, label: "Pflegeheim Sonnenberg" });
for (const bad of [
null,
{},
{ count: 0, days: 30, label: "x" },
{ count: MAX_CODES + 1, days: 30, label: "x" },
{ count: 1.5, days: 30, label: "x" },
{ count: 1, days: 0, label: "x" },
{ count: 1, days: MAX_DAYS + 1, label: "x" },
{ count: 1, days: 30, label: " " },
{ count: 1, days: 30, label: "x".repeat(81) },
{ count: "many", days: 30, label: "x" },
]) {
assert.equal(readMint(bad), null, `${JSON.stringify(bad)} was accepted`);
}
});
/**
* Against Heidi's own migrations on a real Postgres, like `store.test.ts`:
* the statement that is tested is the statement that ships.
*/
test("a code starts a pass once, however many times and however fast it is tried", async () => {
const { pg, db, codes } = await database();
const [code] = await codes.mint({ count: 1, days: 30, label: "Sprachschule", createdBy: "owner" });
const now = new Date("2026-11-26T09:00:00Z");
const outcomes = await Promise.all([
codes.redeem("actor-1", code, now),
codes.redeem("actor-2", code, now),
codes.redeem("actor-1", code, now),
]);
assert.deepEqual(outcomes.map((o) => o.outcome).sort(), ["granted", "used", "used"]);
const passes = await db.select().from(schema.entitlements);
assert.equal(passes.length, 1);
assert.equal(passes[0].expiresAt.getTime(), now.getTime() + 30 * DAY);
const [row] = await db.select().from(schema.passCodes);
assert.equal(row.redeemedBy, passes[0].actorId);
assert.equal(row.redeemedAt?.getTime(), now.getTime());
await pg.close();
});
test("a code adds its days to the end of a pass that is still running", async () => {
const { pg, db, codes } = await database();
const now = new Date("2026-11-26T09:00:00Z");
// A pass bought with Bitcoin ten days ago, twenty days left.
await db.insert(schema.entitlements).values({ actorId: "actor-1", planId: "month", expiresAt: new Date(now.getTime() + 20 * DAY) });
const [first, second] = await codes.mint({ count: 2, days: 90, label: "Spital", createdBy: "owner" });
const a = await codes.redeem("actor-1", first, now);
assert.equal(a.outcome, "granted");
const b = await codes.redeem("actor-1", second.toLowerCase().replaceAll("-", " "), now);
assert.equal(b.outcome, "granted");
const [pass] = await db.select().from(schema.entitlements);
assert.equal(pass.expiresAt.getTime(), now.getTime() + (20 + 90 + 90) * DAY);
await pg.close();
});
test("a code nobody issued, and a string that is not a code, get one answer and change nothing", async () => {
const { pg, db, codes } = await database();
await codes.mint({ count: 3, days: 30, label: "Kita", createdBy: "owner" });
assert.deepEqual(await codes.redeem("actor-1", formatCode(newCode())), { outcome: "unknown" });
assert.deepEqual(await codes.redeem("actor-1", "not a code"), { outcome: "unknown" });
assert.deepEqual(await codes.redeem("actor-1", undefined), { outcome: "unknown" });
assert.equal((await db.select().from(schema.entitlements)).length, 0);
await pg.close();
});
test("the table holds no code, only its hash and its last four characters", async () => {
const { pg, codes } = await database();
const issued = await codes.mint({ count: 5, days: 30, label: "Hotel", createdBy: "owner" });
assert.equal(new Set(issued).size, 5);
const dump = JSON.stringify((await pg.query("select * from pass_codes")).rows);
for (const shown of issued) {
const code = normaliseCode(shown)!;
assert.ok(!dump.includes(code) && !dump.includes(shown), "a code is stored as it was shown");
assert.ok(dump.includes(codeId(code)), "the hash of an issued code is missing");
assert.ok(dump.includes(`"hint":"${code.slice(-4)}"`));
}
await pg.close();
});
test("the owner's list counts what was issued and what is used, and names nobody", async () => {
const { pg, codes } = await database();
const school = await codes.mint({ count: 3, days: 30, label: "Sprachschule", createdBy: "owner" });
await codes.mint({ count: 2, days: 365, label: "Spital", createdBy: "owner" });
await codes.redeem("actor-7", school[0]);
await codes.redeem("actor-8", school[1]);
const batches = await codes.batches();
const byLabel = Object.fromEntries(batches.map((b) => [b.label, b]));
assert.deepEqual(
{ issued: byLabel.Sprachschule.issued, redeemed: byLabel.Sprachschule.redeemed, days: byLabel.Sprachschule.days },
{ issued: 3, redeemed: 2, days: 30 },
);
assert.deepEqual({ issued: byLabel.Spital.issued, redeemed: byLabel.Spital.redeemed }, { issued: 2, redeemed: 0 });
assert.ok(!JSON.stringify(batches).includes("actor-"), "the list names who redeemed");
assert.ok(!Number.isNaN(Date.parse(batches[0].createdAt)));
await pg.close();
});