mirror of
https://github.com/bitbaum/heidi.git
synced 2026-12-04 08:08:46 +01:00
One template for all six sectors: the moment, the cost, what exists today, the situations from the pack that fit, a pilot for that sector and a form that is kept and mailed to the owner. The home page names more of what the product covers and opens a door for organisations. Claude-Session: https://claude.ai/code/session_019MDtmtfseicWGK2CMC2U5r Co-authored-by: Claude <noreply@anthropic.com>
397 lines
17 KiB
TypeScript
397 lines
17 KiB
TypeScript
import { clientIp, slidingWindow, toHeaders, type Limiter, type LimitResult, type LimitRule } from "@bitbaum/limitkit";
|
|
import { ACTIVE_COURSE } from "../course/registry.ts";
|
|
import { dbConfigured } from "../db/index.ts";
|
|
import { run } from "../db/run.ts";
|
|
import { hit, sweep, sweepDue } from "./limit-counter.ts";
|
|
import { PASS_CHAT_MULTIPLIER } from "../config/payments.ts";
|
|
|
|
/**
|
|
* How much of Heidi one stranger may use.
|
|
*
|
|
* `limitkit` deliberately ships no limit values — how many a route allows is
|
|
* app semantics. So the numbers live here, with the reason each one is what it
|
|
* is, because a limit with no stated reason gets "temporarily" raised.
|
|
*
|
|
* Every public endpoint had NO limit until this file existed, which was a real
|
|
* hole rather than an oversight of style: two of them spend money on every
|
|
* call, and both are reachable by anyone with curl.
|
|
*/
|
|
|
|
/**
|
|
* A limit: its rule, and the in-memory window that counts callers nobody
|
|
* knows. Which store counts a given request is `allow`'s decision, below.
|
|
*/
|
|
export type Limit = { rule: LimitRule; memory: Limiter };
|
|
|
|
function limit(rule: LimitRule): Limit {
|
|
return { rule, memory: slidingWindow(rule) };
|
|
}
|
|
|
|
/**
|
|
* The assistant. Each call spends from a shared free-tier budget that is the
|
|
* same pool every other visitor draws on — so the ceiling protects other
|
|
* learners, not the server.
|
|
*
|
|
* Generous on purpose: a real conversation is a dozen turns, and someone
|
|
* working through a long WhatsApp thread should never meet this.
|
|
*/
|
|
export const chat = limit({ limit: 30, windowMs: 5 * 60_000 });
|
|
|
|
/**
|
|
* THE DAILY ALLOWANCE: how many questions a day one person may ask on Heidi's
|
|
* free models. The five-minute window above stops a flood; this is the
|
|
* budget. Every visitor draws on the same free tier, and a pass is worth
|
|
* buying only if there is a line it lifts.
|
|
*
|
|
* 100 turns is a long evening of practice and then some, so a learner who is
|
|
* learning should not meet it; somebody who does is told so in their own
|
|
* language, with the way on (`kind: "limit"` in the chat, which links /pass).
|
|
* A pass lifts it by `PASS_CHAT_MULTIPLIER`. A brought key does not draw on
|
|
* it at all: those calls are paid on the learner's own account.
|
|
*
|
|
* HEIDI_FREE_TURNS_PER_DAY default 100; 0 switches the daily allowance off
|
|
*/
|
|
export const FREE_TURNS_PER_DAY_DEFAULT = 100;
|
|
const DAY_MS = 24 * 60 * 60_000;
|
|
|
|
export function freeTurnsPerDay(env: Record<string, string | undefined> = process.env): number {
|
|
const raw = env.HEIDI_FREE_TURNS_PER_DAY?.trim();
|
|
if (!raw) return FREE_TURNS_PER_DAY_DEFAULT;
|
|
return /^\d{1,6}$/.test(raw) ? Number(raw) : FREE_TURNS_PER_DAY_DEFAULT;
|
|
}
|
|
|
|
const perDay = freeTurnsPerDay();
|
|
/** Null when the deployment switched the daily allowance off. */
|
|
export const chatDaily: Limit | null = perDay > 0 ? limit({ limit: perDay, windowMs: DAY_MS }) : null;
|
|
export const chatDailyWithPass: Limit | null = perDay > 0 ? limit({ limit: perDay * PASS_CHAT_MULTIPLIER, windowMs: DAY_MS }) : null;
|
|
|
|
/**
|
|
* Is this turn within the day's allowance. Counted per person across both
|
|
* chat routes (one purpose), and not at all for a turn on the learner's own
|
|
* key, which spends nothing of ours.
|
|
*/
|
|
export async function allowToday(
|
|
request: Request,
|
|
opts: { pass: boolean; ownKey: boolean; actorId?: string | null },
|
|
): Promise<LimitResult | null> {
|
|
const of = opts.pass ? chatDailyWithPass : chatDaily;
|
|
if (!of || opts.ownKey) return null;
|
|
const result = await allow(of, request, "chat-day", opts.actorId);
|
|
return result.allowed ? null : result;
|
|
}
|
|
|
|
/**
|
|
* The refusal when the day's allowance is spent. Its own header, so a client
|
|
* can tell "come back tomorrow, or get a pass" from "give it a moment".
|
|
*/
|
|
export function dailyLimitReached(result: LimitResult): Response {
|
|
const headers = new Headers(toHeaders(result));
|
|
headers.set(DAILY_LIMIT_HEADER, "daily");
|
|
return Response.json({ error: "Today's free questions are used up.", limit: "daily", operator: false }, { status: 429, headers });
|
|
}
|
|
|
|
export const DAILY_LIMIT_HEADER = "x-heidi-limit";
|
|
|
|
/**
|
|
* The connection probe. Tighter, because it makes a real outbound call per
|
|
* request and takes an arbitrary key — which makes it the one endpoint here
|
|
* that could be pointed at a vendor to test stolen credentials in bulk.
|
|
* Nobody legitimately needs more than a few attempts to paste a key correctly.
|
|
*/
|
|
export const modelCheck = limit({ limit: 6, windowMs: 5 * 60_000 });
|
|
|
|
/**
|
|
* Dictation that falls back to the server.
|
|
*
|
|
* The browser's own recogniser is free and local; this path is neither. It
|
|
* uploads audio and pays a vendor per second of it, so it needs a tighter
|
|
* ceiling than the chat — and unlike the chat, one abusive caller here costs
|
|
* bandwidth as well as budget. Enough for a long conversation dictated a
|
|
* sentence at a time; nowhere near enough to transcribe a podcast.
|
|
*/
|
|
export const dictation = limit({ limit: 20, windowMs: 5 * 60_000 });
|
|
|
|
/**
|
|
* Lines read aloud by the server voice (`/api/speak`), for a device with no
|
|
* German voice of its own. Each is a paid call at Google once the free tier
|
|
* is spent; a learner pressing "read aloud" on every answer of a long chat is
|
|
* well inside this, a script is not. Repeats are served from a cache and
|
|
* still count here, so the limit is about the caller, not the bill.
|
|
*/
|
|
/** Each one mints a real invoice through the payee's wallet. */
|
|
export const payCheckout = limit({ limit: 6, windowMs: 10 * 60_000 });
|
|
|
|
/**
|
|
* Redeeming a pass code. A code is 80 random bits and cannot be guessed, so
|
|
* this is not what protects it: it is what keeps a script from making the
|
|
* database look up hashes without end. A person types one code, perhaps
|
|
* twice.
|
|
*/
|
|
export const passRedeem = limit({ limit: 10, windowMs: 10 * 60_000 });
|
|
|
|
/**
|
|
* The chat allowance of somebody holding a pass (`PASS_CHAT_MULTIPLIER` times
|
|
* the open one). The one thing a pass changes.
|
|
*/
|
|
export const chatWithPass = limit({ limit: 30 * PASS_CHAT_MULTIPLIER, windowMs: 5 * 60_000 });
|
|
|
|
export const speak = limit({ limit: 40, windowMs: 5 * 60_000 });
|
|
|
|
/**
|
|
* Sentences generated for a word somebody just kept.
|
|
*
|
|
* Higher than the chat limit because it is a much smaller call — about 174
|
|
* tokens against 2,234 — and because it fires as a side effect of pressing
|
|
* save, which a learner working through a long message does several times in a
|
|
* row. Rationing it at chat rates would punish exactly the behaviour the
|
|
* feature exists to encourage.
|
|
*/
|
|
export const example = limit({ limit: 60, windowMs: 5 * 60_000 });
|
|
|
|
/**
|
|
* Making and joining study groups.
|
|
*
|
|
* Tight, because both write rows nobody asked for: a script could otherwise
|
|
* fill the table with groups, or walk invite tokens looking for one that
|
|
* resolves. Guessing a 192-bit token is not a strategy anyway, but a ceiling
|
|
* turns "not a strategy" into "not worth attempting".
|
|
*
|
|
* Nowhere near what a person does — you make a study group about once.
|
|
*/
|
|
export const groupWrite = limit({ limit: 20, windowMs: 10 * 60_000 });
|
|
|
|
/**
|
|
* Posting into a group.
|
|
*
|
|
* Looser than making one and tighter than the solo chat: every message may
|
|
* wake Heidi, which spends from the same shared budget, and a group has
|
|
* several people drawing on it at once.
|
|
*/
|
|
export const groupMessage = limit({ limit: 40, windowMs: 5 * 60_000 });
|
|
|
|
/**
|
|
* Private conversations: creating, renaming, deleting.
|
|
*
|
|
* Keyed by ACTOR rather than by IP where the caller is signed in — an office
|
|
* or a university shares one address, and rate-limiting a signed-in person by
|
|
* their neighbours' traffic is a limit on the wrong thing.
|
|
*/
|
|
export const conversationWrite = limit({ limit: 40, windowMs: 10 * 60_000 });
|
|
|
|
/**
|
|
* Posting into a private conversation.
|
|
*
|
|
* The same ceiling as the solo chat, because it is the same act — the only
|
|
* difference is that the server now remembers it.
|
|
*/
|
|
export const conversationMessage = limit({ limit: 30, windowMs: 5 * 60_000 });
|
|
|
|
/**
|
|
* The same, for somebody holding a pass. A pass holder is signed in, so this
|
|
* is the route most of their turns take; it used to count them at the open
|
|
* rate, and only `/api/chat` gave them what the pass page promises.
|
|
*/
|
|
export const conversationMessageWithPass = limit({ limit: 30 * PASS_CHAT_MULTIPLIER, windowMs: 5 * 60_000 });
|
|
|
|
/**
|
|
* Proposing topics, opening rounds, saying you will come.
|
|
*
|
|
* The same shape of hole as `groupWrite` and the same ceiling: every one of
|
|
* these writes a row nobody asked for, and a proposals board is a thing people
|
|
* see, so a script filling it with rounds is defacement rather than cost. You
|
|
* propose a topic roughly never; twenty in ten minutes is already generous.
|
|
*/
|
|
export const speakingWrite = limit({ limit: 20, windowMs: 10 * 60_000 });
|
|
|
|
/**
|
|
* One comment on one spoken take.
|
|
*
|
|
* Chat rates, because it is a chat call: the same shared free-tier budget,
|
|
* spent by the same person, on a text they typed themselves. The recording
|
|
* never reaches this — only the sentence the learner confirmed — so it costs
|
|
* no more than any other turn.
|
|
*/
|
|
export const speakingTake = limit({ limit: 30, windowMs: 5 * 60_000 });
|
|
|
|
/**
|
|
* The dialect checker. Pure, local, costs nothing but CPU — so this is only
|
|
* about not letting one client monopolise the box.
|
|
*/
|
|
export const dialectCheck = limit({ limit: 120, windowMs: 60_000 });
|
|
|
|
/** The key of a signed-in caller: the limit's purpose, the course, the account. */
|
|
export function actorKey(actorId: string, prefix: string): string {
|
|
return `${prefix}:${ACTIVE_COURSE.id}:${actorId}`;
|
|
}
|
|
|
|
/**
|
|
* Identify the caller.
|
|
*
|
|
* Behind Caddy the socket address is the proxy's, so `clientIp()` reads the
|
|
* forwarded headers — which is also why this is a rate limit and not a
|
|
* security boundary: a header can be forged. It exists to stop accidental and
|
|
* casual abuse from spending a budget shared with everybody else.
|
|
*
|
|
* The key of everybody who is not signed in: the purpose and the address.
|
|
*/
|
|
export function callerKey(request: Request, prefix: string): string {
|
|
return `${prefix}:${clientIp(request.headers) ?? "unknown"}`;
|
|
}
|
|
|
|
/**
|
|
* WHO COUNTS WHERE, and why it is two stores.
|
|
*
|
|
* A SIGNED-IN caller is counted in Postgres, by account and course
|
|
* (`limit-counter.ts`). The allowance is theirs: it does not reset when the
|
|
* app is deployed, it is the same on their phone and their laptop, and it is
|
|
* not shared with the forty other people behind one care home's address.
|
|
*
|
|
* AN ANONYMOUS caller is counted in memory, by address, as before. That is a
|
|
* decision and not a leftover. The keys of anonymous traffic are addresses,
|
|
* which strangers can mint without end, and a database write per request
|
|
* from an address nobody knows is a way to make a small shared Postgres do
|
|
* work on a stranger's behalf. Counted in memory, the worst a flood does is
|
|
* evict an old bucket (limitkit's store is bounded). The cost is the known
|
|
* one: an anonymous allowance starts again after a deploy. It exists to blunt
|
|
* scripts, and a script gains one window by it.
|
|
*
|
|
* THE COST: one statement per limited request for a signed-in caller, none
|
|
* for anybody else. Knowing that a caller is signed in is the session read
|
|
* the route makes anyway (`auth()` reads it once per request); it is skipped
|
|
* entirely when the request carries no session cookie, and it is itself
|
|
* rationed per address, so a made-up cookie cannot be used to make the
|
|
* database look up sessions without limit.
|
|
*
|
|
* IF THE DATABASE CANNOT ANSWER the caller is counted in memory under the
|
|
* same key. A limit that fails open would make an outage the moment every
|
|
* ceiling disappears; one that fails shut would turn it into a lock-out.
|
|
*/
|
|
export async function allow(of: Limit, request: Request, purpose: string, actorId?: string | null): Promise<LimitResult>;
|
|
/** For code that already knows the account and holds no request. */
|
|
export async function allow(of: Limit, request: null, purpose: string, actorId: string): Promise<LimitResult>;
|
|
export async function allow(of: Limit, request: Request | null, purpose: string, actorId?: string | null): Promise<LimitResult> {
|
|
const account = actorId ?? (request ? await signedIn(request) : null);
|
|
if (!account) return of.memory.check(request ? callerKey(request, purpose) : `${purpose}:unknown`);
|
|
const key = actorKey(account, purpose);
|
|
if (!dbConfigured()) return of.memory.check(key);
|
|
try {
|
|
const result = await hit(run, of.rule, key);
|
|
if (sweepDue(swept, Date.now())) void sweep(run).catch(() => undefined);
|
|
return result;
|
|
} catch (error) {
|
|
console.error("[limits] the counter could not be reached; counting in memory", { purpose, error: (error as Error).name });
|
|
return of.memory.check(key);
|
|
}
|
|
}
|
|
|
|
/** When this process last swept old counters (`sweepDue`). */
|
|
const swept = { last: 0 };
|
|
|
|
/** Session lookups one address may cause: far above any honest use, far below a flood. */
|
|
const sessionLookups = limit({ limit: 300, windowMs: 5 * 60_000 });
|
|
|
|
const SESSION_COOKIE = /session_token=/;
|
|
|
|
/** The account behind a request, or null: no cookie, no accounts, or no session. */
|
|
async function signedIn(request: Request): Promise<string | null> {
|
|
if (!dbConfigured() || !SESSION_COOKIE.test(request.headers.get("cookie") ?? "")) return null;
|
|
if (!sessionLookups.memory.check(callerKey(request, "session")).allowed) return null;
|
|
try {
|
|
const { auth, authEnabled } = await import("../auth/index.ts");
|
|
return authEnabled ? ((await auth())?.actorId ?? null) : null;
|
|
} catch {
|
|
return null;
|
|
}
|
|
}
|
|
|
|
export function tooMany(result: LimitResult): Response {
|
|
return Response.json(
|
|
{ error: "Too many requests. Give it a moment.", operator: false },
|
|
{ status: 429, headers: toHeaders(result) },
|
|
);
|
|
}
|
|
|
|
/**
|
|
* Progress sync. A device pushes a few seconds after practice and pulls every
|
|
* few minutes; this is room for several devices at once and nothing more.
|
|
*/
|
|
export const progressSync = limit({ limit: 60, windowMs: 5 * 60_000 });
|
|
|
|
/**
|
|
* Saving the site language. One write per click in a language menu — nobody
|
|
* changes language thirty times in ten minutes on purpose.
|
|
*/
|
|
export const preferenceWrite = limit({ limit: 30, windowMs: 10 * 60_000 });
|
|
|
|
/**
|
|
* Following a channel. One follow resolves a handle against YouTube and reads
|
|
* a feed — two outside requests on our behalf — so it is rationed per person
|
|
* like every signed-in write. Twenty in ten minutes is a whole afternoon of
|
|
* curating; a script hits it in a second.
|
|
*/
|
|
export const channelWrite = limit({ limit: 20, windowMs: 10 * 60_000 });
|
|
|
|
/**
|
|
* Fetching or pasting a video's transcript. A fetch is two requests to
|
|
* YouTube; a paste is a few kilobytes written once per video. Shared by the
|
|
* people following the channel, so one person doing it is enough for all.
|
|
*/
|
|
export const videoTranscript = limit({ limit: 20, windowMs: 10 * 60_000 });
|
|
|
|
/**
|
|
* Writing the questions for a video SPENDS A MODEL CALL from the shared free
|
|
* pool — the same pool the chat draws on. It happens once per video for
|
|
* everybody who follows the channel, on the first learner's request, so the
|
|
* ceiling is low on purpose: ten new videos in ten minutes is not a person
|
|
* learning, it is a loop.
|
|
*/
|
|
export const videoQuestions = limit({ limit: 10, windowMs: 10 * 60_000 });
|
|
|
|
/** Turning notifications on or off in a browser. A handful per device. */
|
|
export const pushWrite = limit({ limit: 20, windowMs: 10 * 60_000 });
|
|
|
|
/**
|
|
* A thumb under an answer.
|
|
*
|
|
* Chat rates, keyed by caller: it writes one small row per press and needs no
|
|
* account, like the chat it sits under. Thirty in five minutes is somebody
|
|
* rating every answer of a long conversation; a script hits it in a second.
|
|
*/
|
|
export const chatFeedback = limit({ limit: 30, windowMs: 5 * 60_000 });
|
|
|
|
/**
|
|
* Anonymous totals (`/api/usage`): one count per question answered, per run
|
|
* started or finished. A fast learner answers a question every few seconds;
|
|
* 240 in five minutes is far above that and far below a script.
|
|
*/
|
|
export const usage = limit({ limit: 240, windowMs: 5 * 60_000 });
|
|
|
|
/**
|
|
* A native speaker's verdicts (`/api/review`): one small row per line read,
|
|
* no account. A scene has about twenty lines and a careful reader takes a
|
|
* few seconds on each; 200 in five minutes is several scenes at a run.
|
|
*/
|
|
export const lineReview = limit({ limit: 200, windowMs: 5 * 60_000 });
|
|
|
|
/**
|
|
* A pilot asked for on a sector page: a person filling in a form. Five in an
|
|
* hour is a team asking for several sectors; more is not a person.
|
|
*/
|
|
export const orgRequest = limit({ limit: 5, windowMs: 60 * 60_000 });
|
|
|
|
/**
|
|
* Heidi listening to a podcast's opening minutes herself. Audio seconds on
|
|
* the shared speech tier, once per episode for everybody who follows the
|
|
* show — six in ten minutes is a person opening episodes, not a loop.
|
|
*/
|
|
export const episodeTranscribe = limit({ limit: 6, windowMs: 10 * 60_000 });
|
|
|
|
/**
|
|
* "Tell me when this language is ready" (`/api/languages/interest`).
|
|
*
|
|
* Open to anyone and it writes a row with an address somebody typed, so it is
|
|
* tight: a person asks for one to five languages once; a script filling the
|
|
* list with other people's addresses is the thing to stop.
|
|
*/
|
|
export const languageInterest = limit({ limit: 6, windowMs: 10 * 60_000 });
|