/** * Phone number and OTP, nothing else (owner, 24 Oct 2026: never Google or * Apple sign-in on these apps). Live, OTP_MODE is `twilio`: the code goes out * and is checked through Twilio Verify. `fixed` answers every code with the * Worker secret OTP_FIXED_CODE, which the object never says, and runs on the * dev Worker alone (13 Nov 2026). A number OTP_TEST_CODES names proves its own * code in either mode and never reaches Twilio. A credential is * a random token the phone keeps; the object keeps only its hash. An object * that has a database id (every personal one) grants it as * `ctd__`, the shape of a Cotton MCP token, so the open * host finds the object from the credential alone (src/index.ts); a business, * reached by its own host, grants the bare secret. */ import { directory } from "./directory.ts"; import { devWorker, type Env } from "./env.ts"; import { randomToken, refuse, sha256Hex } from "./http.ts"; import { normalizePhone } from "./protocol.ts"; import type { Person, Store } from "./store.ts"; export const CODE_TTL_SECONDS = 300; export const CODES_PER_HOUR = 5; /** * How many codes one number may ask for in an hour. Production keeps the * constant; the development Worker names a larger whole number in its * CODES_PER_HOUR var, because a walk erases and signs in the same number * several times an hour (src/directory.ts `limitsFor` does the same per IP). */ export function codesPerHour(env: Pick): number { const value = env.CODES_PER_HOUR; return value !== undefined && /^\d+$/.test(value) ? Number(value) : CODES_PER_HOUR; } export const CODE_TRIES = 5; /** * AUDIT A H2 (28 Nov 2026): the countries an SMS code may go to, by calling code. THE ONE LINE TO CHANGE (or set the * Worker var SMS_COUNTRIES, the same list). India, the US and Canada, the UK and the UAE: where the owner and the * people around him are. A number elsewhere is told codes do not go there; the money is never spent. */ export const SMS_COUNTRIES = "91,1,44,971"; /** Whether an SMS code may go to `phone` (E.164) under the allow list. */ export function smsCountryAllowed(env: Pick, phone: string): boolean { const list = (env.SMS_COUNTRIES?.trim() || SMS_COUNTRIES).split(",").map((c) => c.trim().replace(/^\+/, "")).filter((c) => /^\d{1,4}$/.test(c)); return list.some((code) => phone.startsWith(`+${code}`)); } export const CREDENTIAL_TTL_SECONDS = 90 * 24 * 3600; export interface Who { person: Person; tokenHash: string; /** The device the credential was granted to: the `device_id` its sign-in named. */ deviceId: string; } function seconds(now: Date): number { return Math.floor(now.getTime() / 1000); } /** * The Worker secret OTP_TEST_CODES (owner, 13 Nov 2026): a JSON object of * E.164 number → code (six digits, what the phone's sign-in takes), one or two numbers the owner signs in * with on several devices. Such a number never reaches Twilio and proves its * own code, in every OTP_MODE. Read strictly: a value that is not exactly that * is `malformed`, and every number it names refuses (the reason is logged, * never the value), so a typo never falls open and never sends a test number * to Twilio. Unset or empty names none. */ export type TestCodes = { ok: true; codes: ReadonlyMap } | { ok: false; named: ReadonlySet }; /** The North American numbers set aside for fiction (555-0100 to 555-0199 in any area code): no person holds one. */ export const FICTIONAL = /^\+1[2-9]\d{2}55501\d{2}$/; export function testCodes(env: Pick): TestCodes { const raw = env.OTP_TEST_CODES; if (raw === undefined || raw.trim() === "") return { ok: true, codes: new Map() }; const malformed = (why: string): TestCodes => { console.error(`cottondb: OTP_TEST_CODES is malformed (${why}); its numbers cannot sign in`); return { ok: false, named: new Set(raw.match(/\+\d{7,15}/g) ?? []) }; }; let parsed: unknown; try { parsed = JSON.parse(raw); } catch { return malformed("not JSON"); } if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) return malformed("not a JSON object"); const codes = new Map(); let fenced = 0; for (const [phone, code] of Object.entries(parsed)) { if (normalizePhone(phone) !== phone) return malformed("a key is not a number in E.164"); if (typeof code !== "string" || !/^\d{6}$/.test(code)) return malformed("a code is not six digits"); // AUDIT FIX B1 (B-12): a fixed code is for a number no person can hold, never a real one. Any other number named is // left out (it signs in by SMS as every number does), and the log says how many, never which. if (!FICTIONAL.test(phone)) { fenced++; continue; } codes.set(phone, code); } if (fenced) console.error(`cottondb: OTP_TEST_CODES names ${fenced} number(s) a person could hold; they get no fixed code`); return { ok: true, codes }; } /** A test number's own code; null for any other number. A number a malformed OTP_TEST_CODES names refuses. */ function testCodeFor(tests: TestCodes, phone: string): string | null { if (!tests.ok) { if (tests.named.has(phone)) refuse(503, "otp_unconfigured", "codes can't be sent to this number right now"); return null; } return tests.codes.get(phone) ?? null; } /** * The OTP mode, `twilio` or `fixed`. `fixed` runs only on the dev Worker * (ENV_LABEL `dev`) and the test pool (`test`): on any other Worker, live * among them, it refuses, as does a mode that is neither. */ function otpMode(env: Pick): "twilio" | "fixed" { if (env.OTP_MODE === "twilio") return "twilio"; if (env.OTP_MODE === "fixed") { if (devWorker(env)) return "fixed"; console.error(`cottondb: OTP_MODE fixed refused on a Worker whose ENV_LABEL is ${JSON.stringify(env.ENV_LABEL ?? null)}`); } else { console.error(`cottondb: OTP_MODE ${JSON.stringify(env.OTP_MODE ?? null)} is neither twilio nor fixed`); } refuse(503, "otp_unconfigured", "codes can't be sent right now"); } /** Issue a challenge for `phone`: a test number keeps its own code's hash, a fixed one the fixed code's; Twilio sends any other. */ export async function issueCode(env: Env, store: Store, now: Date, phone: string, deviceId: string): Promise<{ challenge_id: string; expires_in: number }> { const t = seconds(now); if (store.codesIssuedRecently(phone, t - 3600) >= codesPerHour(env)) refuse(429, "too_many_codes", "too many codes for this number; try again later"); const id = crypto.randomUUID(); let code = testCodeFor(testCodes(env), phone); if (code === null) { if (otpMode(env) === "twilio") { // Only here is money spent: the country allow list, then the number's day and every number's day (AUDIT A H2). if (!smsCountryAllowed(env, phone)) refuse(400, "country_not_served", "Codes are not sent to numbers in this country yet."); const held = await directory(env).smsAllowed(phone); if (held) refuse(held.status, held.code, held.message); await twilioStart(env, phone); code = ""; // Twilio checks it; nothing to hash here. } else { if (!env.OTP_FIXED_CODE) refuse(503, "otp_unconfigured", "OTP_MODE is fixed but the OTP_FIXED_CODE secret is not set"); code = env.OTP_FIXED_CODE; } } store.addCode(id, phone, code ? await sha256Hex(`${id}:${code}`) : "", deviceId, t + CODE_TTL_SECONDS); return { challenge_id: id, expires_in: CODE_TTL_SECONDS }; } /** Check a code against its challenge; answers the phone number it proves. */ export async function proveCode(env: Env, store: Store, now: Date, challengeId: string, code: string, deviceId: string): Promise { const row = store.code(challengeId); const t = seconds(now); if (!row || row.used === 1 || row.expires_at < t) refuse(401, "invalid_code", "invalid or expired code"); if (row.device_id !== deviceId) refuse(401, "invalid_code", "the code was asked for from another device"); if (row.tries >= CODE_TRIES) refuse(401, "invalid_code", "too many tries; ask for a new code"); let verdict: Verdict; // A kept hash is checked only while its number is a test number, or while this Worker may run `fixed`. if (testCodeFor(testCodes(env), row.phone) !== null || (row.code_hash !== "" && otpMode(env) === "fixed")) { verdict = row.code_hash !== "" && (await sha256Hex(`${challengeId}:${code.trim()}`)) === row.code_hash ? "approved" : "wrong"; } else if (row.code_hash === "" && otpMode(env) === "twilio") { verdict = await twilioCheck(env, row.phone, code); } else { verdict = "wrong"; } if (verdict !== "approved") { store.codeTried(challengeId); // Why a code was refused is kept (never the code or the number): "wrong" alone hid a spent verification behind a right code. console.warn("cottondb: code refused", verdict, row.tries + 1); if (verdict === "gone") refuse(401, "invalid_code", "that code is no longer good; ask for a new code"); if (verdict === "spent") refuse(401, "invalid_code", "too many tries on that code; wait ten minutes, then ask for a new code"); refuse(401, "invalid_code", "invalid or expired code"); } store.codeUsed(challengeId, await sha256Hex(`${challengeId}:${code.trim()}`)); return row.phone; } /** * The number a challenge already proved, when the very same proof comes * again: same challenge, same device, same code, before the challenge * expires. Null for anything else. A browser can send one form twice (an * autofilled code that submits, then a tap on the button); the second copy * found its challenge used and was told "invalid or expired code" over a * code Twilio had just approved. Only the connect page asks this. */ export async function provenAlready(store: Store, now: Date, challengeId: string, code: string, deviceId: string): Promise { const row = store.code(challengeId); if (!row || row.used !== 1 || row.expires_at < seconds(now) || row.device_id !== deviceId || row.code_hash === "") return null; return (await sha256Hex(`${challengeId}:${code.trim()}`)) === row.code_hash ? row.phone : null; } export async function grant(store: Store, now: Date, person: Person, deviceId: string): Promise { const databaseId = store.meta("database_id"); const token = databaseId ? `ctd_${databaseId}_${randomToken(32)}` : randomToken(32); const t = seconds(now); store.addSession(await sha256Hex(token), person.id, deviceId, t, t + CREDENTIAL_TTL_SECONDS); return token; } /** Who a credential names, or null for none; a revoked or expired one refuses. */ export async function whoIs(store: Store, now: Date, token: string | null): Promise { if (!token) return null; const hash = await sha256Hex(token); const s = store.session(hash); if (!s) refuse(401, "invalid_credential", "sign in again"); if (s.revoked === 1) refuse(401, "credential_revoked", "this sign-in was ended; sign in again"); if (s.expires_at < seconds(now)) refuse(401, "credential_expired", "sign in again"); const person = store.person(s.person_id); if (!person) refuse(401, "invalid_credential", "sign in again"); return { person, tokenHash: hash, deviceId: s.device_id }; } // ── Twilio Verify ────────────────────────────────────────────────────────── function twilioAuth(env: Env): { sid: string; token: string; verify: string } { const sid = env.TWILIO_ACCOUNT_SID; const token = env.TWILIO_AUTH_TOKEN; const verify = env.TWILIO_VERIFY_SID; if (!sid || !token || !verify) refuse(503, "sms_unavailable", "codes cannot be sent right now"); return { sid, token, verify }; } /** Twilio's error code from a refusal's body, or null; the body itself goes nowhere. */ async function twilioCode(res: Response): Promise { try { const body = (await res.json()) as { code?: unknown }; return typeof body.code === "number" ? body.code : null; } catch { return null; } } /** * Twilio refusals that are about the number, not Twilio: 60200 (an invalid To), * 21211 (not a valid number), 21614 / 60205 (no SMS to it, a landline), * 21408 / 60220 / 60605 (a country or prefix the service may not send to). */ const NUMBER_REFUSED = new Set([60200, 21211, 21614, 60205, 21408, 60220, 60605]); /** Twilio's own send limits: 60203 (max send attempts), 60212 (too many concurrent requests). */ const TOO_MANY = new Set([60203, 60212]); async function twilioStart(env: Env, phone: string): Promise { const { sid, token, verify } = twilioAuth(env); const res = await fetch(`https://verify.twilio.com/v2/Services/${verify}/Verifications`, { method: "POST", headers: { authorization: `Basic ${btoa(`${sid}:${token}`)}`, "content-type": "application/x-www-form-urlencoded" }, body: new URLSearchParams({ To: phone, Channel: "sms" }), }); if (res.ok) return; const code = await twilioCode(res); console.error("cottondb: twilio start refused", res.status, code); if (code !== null && NUMBER_REFUSED.has(code)) refuse(400, "bad_phone", "a code cannot be sent to this number"); if (res.status === 429 || (code !== null && TOO_MANY.has(code))) refuse(429, "too_many_codes", "too many codes for this number; try again later"); refuse(503, "sms_unavailable", "the code could not be sent"); } /** What a check says of a code: approved, wrong, `gone` (the verification is no longer held), or `spent` (its tries ran out). */ type Verdict = "approved" | "wrong" | "gone" | "spent"; /** * Twilio's verdict on a code. 404 (Twilio no longer holds the verification: * expired, or already approved) is `gone`; 60202 (max check attempts, which * refuses even the right code until the verification expires) is `spent`; * 60200 (a code Twilio will not read) is wrong; anything else Twilio refuses * is Twilio failing, not the person. */ async function twilioCheck(env: Env, phone: string, code: string): Promise { const { sid, token, verify } = twilioAuth(env); const res = await fetch(`https://verify.twilio.com/v2/Services/${verify}/VerificationCheck`, { method: "POST", headers: { authorization: `Basic ${btoa(`${sid}:${token}`)}`, "content-type": "application/x-www-form-urlencoded" }, body: new URLSearchParams({ To: phone, Code: code.trim() }), }); if (res.status === 404) return "gone"; if (!res.ok) { const twilio = await twilioCode(res); if (twilio === 20404) return "gone"; if (twilio === 60202) return "spent"; if (twilio === 60200) return "wrong"; console.error("cottondb: twilio check refused", res.status, twilio); refuse(503, "sms_unavailable", "the code could not be checked; try again"); } let body: { status?: unknown }; try { body = (await res.json()) as { status?: unknown }; } catch { console.error("cottondb: twilio check answered no JSON", res.status); refuse(503, "sms_unavailable", "the code could not be checked; try again"); } return body.status === "approved" ? "approved" : "wrong"; }