Files
heidi/lib/pay/codes.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

172 lines
7.0 KiB
TypeScript

import { createHash, randomInt } from "node:crypto";
import { and, eq, isNull, sql } from "drizzle-orm";
import { extendEntitlement, type Entitlement } from "@bitbaum/paykit/checkout";
import { db } from "../db/index.ts";
import { entitlements, passCodes } from "../db/schema.ts";
/**
* Pass codes: a pass somebody paid for where Heidi cannot see the payment.
*
* WHY THEY EXIST. The only payment Heidi can settle by itself is a Bitcoin
* invoice on OrangeCat. An organisation that wants passes for twenty people
* pays in francs, by bank transfer, to the person who runs Heidi. So the
* owner issues one code per person, and each person redeems theirs on /pass.
*
* WHAT IS THE PACKAGE'S AND WHAT IS HERE. How long a pass runs after one more
* grant is `extendEntitlement` from `@bitbaum/paykit`, the same function a
* settled payment goes through, so a code and a payment add up the same way.
* A code moves no money and asks no provider anything, which is why the rest
* is here: making a code, keeping its hash, and granting it once.
*
* WHAT A CODE IS. Sixteen characters from an alphabet without the letters
* that are misread from a phone screen (I, L, O, U): 80 bits, written in four
* groups. It is shown once, to the owner. The table keeps its SHA-256, so a
* copy of the table is not a list of passes. A code this long cannot be
* guessed; the rate limit on redeeming is there for the database, not for the
* secret.
*/
const ALPHABET = "0123456789ABCDEFGHJKMNPQRSTVWXYZ";
const LENGTH = 16;
/** How many codes one request may issue, how long a pass may run, how long a label may be. */
export const MAX_CODES = 200;
export const MAX_DAYS = 366;
export const MAX_LABEL = 80;
/** The plan id written on a pass that came from a code. */
const CODE_PLAN = "code";
export function newCode(): string {
let code = "";
for (let i = 0; i < LENGTH; i++) code += ALPHABET[randomInt(ALPHABET.length)];
return code;
}
/** The code as a person reads and types it: four groups of four. */
export function formatCode(code: string): string {
return code.match(/.{1,4}/g)?.join("-") ?? code;
}
/**
* What somebody typed, as the code it means; null when it cannot be one.
*
* Forgiving on purpose, because it is copied by hand from an email or read
* aloud: case, spaces and dashes do not matter, and the three letters the
* alphabet leaves out are read as the digit they look like.
*/
export function normaliseCode(raw: unknown): string | null {
if (typeof raw !== "string" || raw.length > 64) return null;
const code = raw
.toUpperCase()
.replace(/[\s-]/g, "")
.replace(/O/g, "0")
.replace(/[IL]/g, "1");
if (code.length !== LENGTH) return null;
for (const c of code) if (!ALPHABET.includes(c)) return null;
return code;
}
/** What the table keeps instead of the code. */
export function codeId(code: string): string {
return createHash("sha256").update(code).digest("hex");
}
export type MintInput = { count: number; days: number; label: string; createdBy: string };
/** The request as numbers and a label, or null when it is not one the owner can have meant. */
export function readMint(raw: unknown): Omit<MintInput, "createdBy"> | null {
const v = (raw ?? {}) as Record<string, unknown>;
const count = Number(v.count);
const days = Number(v.days);
const label = typeof v.label === "string" ? v.label.trim() : "";
if (!Number.isInteger(count) || count < 1 || count > MAX_CODES) return null;
if (!Number.isInteger(days) || days < 1 || days > MAX_DAYS) return null;
if (!label || label.length > MAX_LABEL) return null;
return { count, days, label };
}
export type RedeemOutcome =
| { outcome: "granted"; entitlement: Entitlement }
/** Not a code, or not one of ours. The same answer for both. */
| { outcome: "unknown" }
| { outcome: "used" };
export type Batch = { label: string; days: number; issued: number; redeemed: number; createdAt: string };
/** The codes on a given database: the app's own, or a test's. */
export function passCodesOn(database: typeof db) {
return {
/** New codes, formatted for reading. This return value is the only place they exist. */
async mint(input: MintInput): Promise<string[]> {
const codes = Array.from({ length: input.count }, newCode);
await database.insert(passCodes).values(
codes.map((code) => ({
id: codeId(code),
hint: code.slice(-4),
days: input.days,
label: input.label,
createdBy: input.createdBy,
})),
);
return codes.map(formatCode);
},
/**
* One transaction, in the shape of `settleOnce` in `store.ts`. The UPDATE
* claims the code only where `redeemed_at` is still null, so of two
* requests arriving together one gets the row and the other is told it
* is used. The entitlement row is locked before it is read, so a code
* and a payment by the same person add up instead of overwriting.
*/
async redeem(actorId: string, raw: unknown, now: Date = new Date()): Promise<RedeemOutcome> {
const code = normaliseCode(raw);
if (!code) return { outcome: "unknown" };
const id = codeId(code);
return database.transaction(async (tx) => {
const [claimed] = await tx
.update(passCodes)
.set({ redeemedBy: actorId, redeemedAt: now })
.where(and(eq(passCodes.id, id), isNull(passCodes.redeemedAt)))
.returning({ days: passCodes.days });
if (!claimed) {
const [known] = await tx.select({ id: passCodes.id }).from(passCodes).where(eq(passCodes.id, id));
return { outcome: known ? "used" : "unknown" } as const;
}
const [current] = await tx.select().from(entitlements).where(eq(entitlements.actorId, actorId)).for("update");
const next = extendEntitlement(
current ? { planId: current.planId, expiresAt: current.expiresAt.toISOString() } : null,
{ id: CODE_PLAN, days: claimed.days },
now,
);
await tx
.insert(entitlements)
.values({ actorId, planId: next.planId, expiresAt: new Date(next.expiresAt) })
.onConflictDoUpdate({
target: entitlements.actorId,
set: { planId: next.planId, expiresAt: new Date(next.expiresAt), updatedAt: new Date() },
});
return { outcome: "granted", entitlement: next } as const;
});
},
/** What has been issued and how much of it is used, newest first. No code and no person. */
async batches(): Promise<Batch[]> {
const rows = await database
.select({
label: passCodes.label,
days: passCodes.days,
issued: sql<number>`count(*)::int`,
redeemed: sql<number>`count(${passCodes.redeemedAt})::int`,
createdAt: sql<Date | string>`min(${passCodes.createdAt})`,
})
.from(passCodes)
.groupBy(passCodes.label, passCodes.days)
.orderBy(sql`min(${passCodes.createdAt}) desc`);
return rows.map((r) => ({ ...r, createdAt: new Date(r.createdAt).toISOString() }));
},
};
}
export const codes = passCodesOn(db);