Cotton code
377 lines · 18.5 KB · TypeScriptRaw
/** * A shaken report (owner, 13 Nov 2026): every Cotton app's "Report a problem" * screen sends one sentence, the screenshot of the screen the person was on * and the app's recent log, and it lands in COTTON'S OWN DATABASE — one * business object for Cotton the product (slug `cotton-product`), never in * anyone's Personal. The record is the truth: one `app_report` row (the * developer kit's table, crates/cotton-core/kits/developer/tables/app_report.json), * the picture and the log as media of that object. * *   POST /v1/feedback   on the open host, with a device credential (signed in) *        or with none (anonymous): *        { id, sentence, app, build?, platform?, device?, os?, route?, *          screenshot?: { type: "image/png"|"image/jpeg", base64 }, *          log?: string[] | string } *     → 201 { id, status: "new", sender: "signed_in"|"anonymous", pushed } *     → 200 the same with `duplicate: true` when `id` was taken already (a retry) * * WHO SENT IT is the door's to say, never the body's: a bearer is a device * credential (`ctd_<database>_…`) that the sender's own object vouches for * (`Business.feedbackSender`), which answers its owner's number and name; no * bearer is anonymous, and nothing in an anonymous body can claim a number * (`sender_number` is written only from the vouched sender). A bearer that is * no good is refused, never quietly made anonymous. * * LIMITS: per IP (hashed under the object's own salt, never kept raw) and per * signed-in number, each an hour's count, plus a ceiling on anonymous reports * from everyone in an hour; the request, the picture and the log are capped. * * THE OWNER IS TOLD: each new report is an alert push to the phones of the * object's `owner_phone` (src/chat/push.ts's senders: the same APNs provider * token and FCM access token), through that number's own object * (`Business.feedbackAlert`), which holds its phones' alert tokens * (`chat_device`). No owner, no object for the number, or no phone with a * token: the row is written all the same and `pushed` says false. * * THE CHAT SEAM: a signed-in report keeps the sender's number * (`sender_number`); `chat_thread` stays empty. A later job opens a Cotton * chat thread between that number and a "Cotton" identity, shows the report * as its card and writes the thread's id there. Nothing here waits on chat. */import type { Env } from "./env.ts";import { apnsHost, canPush, forgetProviderToken, providerToken } from "./calling/apns.ts";import { accessToken, account, canPushAndroid, fcmHosts, forgetAccessToken, project } from "./calling/fcm.ts";import type { Platform, PushOutcome } from "./calling/push.ts";import type { Engine, Outcome } from "./engine.ts";import { json, Refused, refuse } from "./http.ts";import { normalizePhone } from "./protocol.ts";/** The one object for Cotton the product. */export const FEEDBACK_SLUG = "cotton-product";export const FEEDBACK_PATH = "/v1/feedback";/** The developer kit's table a report is written to. */export const TABLE = "app_report";export const CAPS = {  /** The whole request: a 4 MB picture as base64 is about 5.4 MB. */  request: 6 * 1024 * 1024,  screenshot: 4 * 1024 * 1024,  log: 256 * 1024,  sentence: 2000,  /** build, device, os */  short: 120,  route: 300,};export const LIMITS = {  perIpHour: 10,  perNumberHour: 20,  anonymousHour: 200,};const HOUR = 60 * 60 * 1000;const ID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;const APP = /^[a-z][a-z0-9-]{0,40}$/;const PLATFORMS = ["ios", "android", "macos"];/** A device credential, which names the database whose object granted it. */const DEVICE_CREDENTIAL = /^ctd_([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})_./;export const SCHEMA = `CREATE TABLE IF NOT EXISTS feedback_hit (who TEXT NOT NULL, at INTEGER NOT NULL);CREATE INDEX IF NOT EXISTS feedback_hit_who ON feedback_hit (who, at);`;/** Who sent a report, as their own object vouched: their number and name. */export interface Sender {  number: string;  name: string | null;}/** What the door hands the Cotton object. */export interface FeedbackAsk {  ip: string;  sender: Sender | null;  report: Record<string, unknown>;}/** An answer that crosses RPC whole: a refusal is a status and a body, never a thrown error. */export interface Answered {  status: number;  body: Record<string, unknown>;}/** What one alert says. */export interface FeedbackAlert {  id: string;  app: string;  sentence: string;}interface Stub {  feedbackSender(token: string): Promise<Sender | null>;  feedbackIn(ask: FeedbackAsk): Promise<Answered>;}// ── the door (src/open.ts) ───────────────────────────────────────────────/** * `POST /v1/feedback` on the open host: the sender settled from the bearer, * the body read under its cap, and the report handed to the Cotton object. */export async function door(request: Request, env: Env, ip: string, token: string | null, objectOf: (databaseId: string) => Promise<string | null>): Promise<Response> {  const declared = Number(request.headers.get("content-length") ?? "0");  if (declared > CAPS.request) refuse(413, "too_large", `a report is at most ${CAPS.request} bytes`);  let sender: Sender | null = null;  if (token) {    const named = DEVICE_CREDENTIAL.exec(token);    const slug = named ? await objectOf(named[1]!) : null;    if (!slug) refuse(401, "invalid_credential", "a report goes with this phone's sign-in, or with none");    sender = await stub(env, slug).feedbackSender(token);    if (!sender) refuse(401, "invalid_credential", "sign in again, or send the report signed out");  }  const raw = await request.arrayBuffer().catch(() => refuse(400, "bad_request", "the body could not be read"));  if (raw.byteLength > CAPS.request) refuse(413, "too_large", `a report is at most ${CAPS.request} bytes`);  let report: unknown;  try {    report = JSON.parse(new TextDecoder().decode(raw));  } catch {    refuse(400, "bad_json", "the body is not JSON");  }  if (!report || typeof report !== "object" || Array.isArray(report)) refuse(400, "bad_request", "a report is a JSON object");  const answer = await stub(env, FEEDBACK_SLUG).feedbackIn({ ip, sender, report: report as Record<string, unknown> });  return json(answer.body, answer.status);}function stub(env: Env, slug: string): DurableObjectStub & Stub {  return env.BUSINESS.get(env.BUSINESS.idFromName(slug), { locationHint: "apac" }) as unknown as DurableObjectStub & Stub;}// ── the Cotton object ────────────────────────────────────────────────────export interface FeedbackHost {  sql: SqlStorage;  env: Env;  slug: string;  kind: string | null;  ownerPhone: string | null;  defines(table: string): boolean;  held(id: string): boolean;  write<T>(fn: (engine: Engine, version: number, outcome: Outcome) => T): T;  /** The salt an IP is hashed under, made once and kept in the object's meta. */  salt(): string;  /** The owner's object, by number, told of a new report: whether a phone was pushed. */  tellOwner(number: string, alert: FeedbackAlert): Promise<boolean>;}/** A report arriving: refused with a status and words, or written and the owner told. */export async function take(host: FeedbackHost, ask: FeedbackAsk): Promise<Answered> {  try {    return await intake(host, ask);  } catch (error) {    if (error instanceof Refused) return { status: error.status, body: { code: error.code, message: error.message } };    throw error;  }}async function intake(host: FeedbackHost, ask: FeedbackAsk): Promise<Answered> {  if (host.kind !== "business" || !host.defines(TABLE)) refuse(503, "not_ready", "Cotton's own database is not made yet; the report stays on the phone and is sent later");  const r = ask.report;  const id = typeof r.id === "string" && ID.test(r.id) ? r.id : refuse(400, "bad_id", "id: the report's own uuid, made on the phone, so a retry is the same report");  const sender = ask.sender ? { number: normalizePhone(ask.sender.number) ?? refuse(400, "bad_sender", "the sender's number is not a number"), name: ask.sender.name?.trim() || null } : null;  const senderKind = sender ? "signed_in" : "anonymous";  // A retry of a report already written is answered as the first was, and counts against nothing.  if (host.held(id)) return { status: 200, body: { id, status: "new", sender: senderKind, pushed: false, duplicate: true } };  const sentence = typeof r.sentence === "string" ? r.sentence.trim() : "";  if (!sentence) refuse(400, "bad_sentence", "a report needs its sentence");  if ([...sentence].length > CAPS.sentence) refuse(400, "bad_sentence", `the sentence is over ${CAPS.sentence} characters`);  const app = typeof r.app === "string" && APP.test(r.app) ? r.app : refuse(400, "bad_app", "app: the app's slug (cotton, books, money, …)");  const platform = r.platform === undefined || r.platform === null ? null : PLATFORMS.includes(String(r.platform)) ? String(r.platform) : refuse(400, "bad_platform", `platform: one of ${PLATFORMS.join(", ")}`);  const build = short(r.build, "build", CAPS.short);  const device = short(r.device, "device", CAPS.short);  const os = short(r.os, "os", CAPS.short);  const route = short(r.route, "route", CAPS.route);  const picture = screenshotOf(r.screenshot);  const log = logOf(r.log);  // The limits, counted before anything is kept.  const now = Date.now();  sweep(host.sql, now);  const ipKey = `ip:${await hash(`${host.salt()}:${ask.ip}`)}`;  if (count(host.sql, ipKey, now) >= LIMITS.perIpHour) refuse(429, "too_many_reports", "Too many reports from here in the last hour; it is kept and sent later.");  const numberKey = sender ? `number:${await hash(`${host.salt()}:${sender.number}`)}` : null;  if (numberKey && count(host.sql, numberKey, now) >= LIMITS.perNumberHour) refuse(429, "too_many_reports", "Too many reports from this number in the last hour; it is kept and sent later.");  if (!sender && count(host.sql, "anonymous", now) >= LIMITS.anonymousHour) refuse(429, "too_many_reports", "Too many reports right now; it is kept and sent later.");  hit(host.sql, ipKey, now);  if (numberKey) hit(host.sql, numberKey, now);  else hit(host.sql, "anonymous", now);  // The media first: a row naming bytes nobody kept would be a report whose picture never comes.  const screenshot = picture ? await keep(host, picture.bytes, picture.ext, picture.type) : null;  const logKey = log ? await keep(host, new TextEncoder().encode(log), "txt", "text/plain; charset=utf-8") : null;  const madeAt = new Date(now).toISOString();  const data: Record<string, unknown> = {    sentence,    status: "new",    app,    platform,    build,    device,    os,    route,    screenshot,    log: logKey,    sender: senderKind,    sender_number: sender?.number ?? null,    sender_name: sender?.name ?? null,    made_at: madeAt,    chat_thread: null,  };  for (const key of Object.keys(data)) if (data[key] === null) delete data[key];  host.write((engine, version, outcome) => engine.create(TABLE, data, version, outcome, 0, { id }));  const pushed = host.ownerPhone ? await host.tellOwner(host.ownerPhone, { id, app, sentence }).catch(() => false) : false;  return { status: 201, body: { id, status: "new", sender: senderKind, pushed } };}function short(value: unknown, what: string, max: number): string | null {  if (value === undefined || value === null || value === "") return null;  if (typeof value !== "string") refuse(400, `bad_${what}`, `${what} is text`);  const trimmed = value.trim();  if ([...trimmed].length > max) refuse(400, `bad_${what}`, `${what} is at most ${max} characters`);  return trimmed || null;}const PICTURES: Record<string, { ext: string; magic: number[] }> = {  "image/png": { ext: "png", magic: [0x89, 0x50, 0x4e, 0x47] },  "image/jpeg": { ext: "jpg", magic: [0xff, 0xd8, 0xff] },};function screenshotOf(value: unknown): { bytes: Uint8Array; ext: string; type: string } | null {  if (value === undefined || value === null) return null;  const v = value as { type?: unknown; base64?: unknown };  const kind = typeof v.type === "string" ? PICTURES[v.type] : undefined;  if (!kind || typeof v.base64 !== "string") refuse(400, "bad_screenshot", "screenshot: { type: image/png or image/jpeg, base64 }");  if (v.base64.length > Math.ceil((CAPS.screenshot * 4) / 3) + 4) refuse(413, "screenshot_too_large", `the screenshot is over ${CAPS.screenshot} bytes`);  let bytes: Uint8Array;  try {    bytes = Uint8Array.from(atob(v.base64), (c) => c.charCodeAt(0));  } catch {    refuse(400, "bad_screenshot", "the screenshot's base64 does not read");  }  if (!bytes.length) refuse(400, "bad_screenshot", "the screenshot is empty");  if (bytes.length > CAPS.screenshot) refuse(413, "screenshot_too_large", `the screenshot is over ${CAPS.screenshot} bytes`);  if (!kind.magic.every((b, i) => bytes[i] === b)) refuse(400, "bad_screenshot", `the screenshot is not a ${v.type as string}`);  return { bytes, ext: kind.ext, type: v.type as string };}function logOf(value: unknown): string | null {  if (value === undefined || value === null) return null;  let text: string;  if (typeof value === "string") text = value;  else if (Array.isArray(value) && value.every((l) => typeof l === "string")) text = (value as string[]).join("\n");  else refuse(400, "bad_log", "log: the app's recent lines, a list of text or one text");  if (new TextEncoder().encode(text).length > CAPS.log) refuse(413, "log_too_large", `the log is over ${CAPS.log} bytes`);  return text.trim() ? text : null;}/** Bytes kept in the object's photo store under its slug, by their content address. */async function keep(host: FeedbackHost, bytes: Uint8Array, ext: string, type: string): Promise<string> {  const digest = await crypto.subtle.digest("SHA-256", bytes);  const sha = [...new Uint8Array(digest)].map((b) => b.toString(16).padStart(2, "0")).join("");  const key = `${host.slug}/feedback/${sha}.${ext}`;  if (!(await host.env.PHOTOS.head(key))) await host.env.PHOTOS.put(key, bytes, { httpMetadata: { contentType: type } });  return key;}async function hash(text: string): Promise<string> {  const digest = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(text));  return [...new Uint8Array(digest)].slice(0, 16).map((b) => b.toString(16).padStart(2, "0")).join("");}function count(sql: SqlStorage, who: string, now: number): number {  return sql.exec<{ n: number }>("SELECT count(*) AS n FROM feedback_hit WHERE who = ? AND at >= ?", who, now - HOUR).one().n;}function hit(sql: SqlStorage, who: string, now: number): void {  sql.exec("INSERT INTO feedback_hit (who, at) VALUES (?, ?)", who, now);}function sweep(sql: SqlStorage, now: number): void {  sql.exec("DELETE FROM feedback_hit WHERE at < ?", now - HOUR);}// ── the owner's object: the alert ────────────────────────────────────────/** The words of a report's push: the app and the start of the sentence. */export function alertWords(alert: FeedbackAlert): { title: string; body: string } {  const sentence = [...alert.sentence];  return { title: `Report from ${alert.app}`, body: sentence.length > 140 ? `${sentence.slice(0, 139).join("")}…` : alert.sentence };}export interface AlertTarget {  platform: Platform;  token: string;  topic: string;  sandbox: boolean;}/** One report alert to one of the owner's phones. Nothing of the token is logged. */export async function pushAlert(env: Env, device: AlertTarget, alert: FeedbackAlert): Promise<PushOutcome> {  const words = alertWords(alert);  if (device.platform === "ios") {    if (!canPush(env)) return "failed";    let res: Response;    try {      const jwt = await providerToken(env);      res = await fetch(`${apnsHost(env, device.sandbox)}/3/device/${encodeURIComponent(device.token)}`, {        method: "POST",        headers: { authorization: `bearer ${jwt}`, "apns-topic": device.topic, "apns-push-type": "alert", "apns-priority": "10", "content-type": "application/json" },        body: JSON.stringify({ aps: { alert: words, sound: "default" }, feedback: alert.id }),      });    } catch {      return "failed";    }    if (res.ok) return "sent";    if (res.status === 410) return "gone";    const reason = await res.json().then((b) => (b as { reason?: string }).reason, () => undefined);    if (reason === "ExpiredProviderToken") forgetProviderToken();    return reason === "BadDeviceToken" || reason === "Unregistered" ? "gone" : "failed";  }  if (!canPushAndroid(env)) return "failed";  const sa = account(env);  const id = sa ? project(env, sa) : null;  if (!sa || !id) return "failed";  let res: Response;  try {    const bearer = await accessToken(env);    if (!bearer) return "failed";    res = await fetch(`${fcmHosts(env).send}/v1/projects/${encodeURIComponent(id)}/messages:send`, {      method: "POST",      headers: { authorization: `Bearer ${bearer}`, "content-type": "application/json" },      // A notification message: the system draws it, so no handler of the app's has to know a report.      body: JSON.stringify({ message: { token: device.token, notification: words, data: { kind: "feedback", id: alert.id }, android: { priority: "HIGH" } } }),    });  } catch {    return "failed";  }  if (res.ok) return "sent";  if (res.status === 401) forgetAccessToken();  if (res.status === 404) return "gone";  const error = await res.json().then((b) => (b as { error?: { details?: { errorCode?: string }[] } }).error, () => undefined);  return error?.details?.some((d) => d.errorCode === "UNREGISTERED") ? "gone" : "failed";}/** Every phone of this (personal) object that keeps an alert token is told; a token gone is dropped. Whether any was pushed. */export async function alertPhones(sql: SqlStorage, env: Env, alert: FeedbackAlert): Promise<boolean> {  const phones = sql    .exec<{ device_id: string; platform: Platform | null; token: string | null; topic: string | null; sandbox: number }>("SELECT device_id, platform, token, topic, sandbox FROM chat_device WHERE token IS NOT NULL AND platform IS NOT NULL")    .toArray();  let pushed = false;  for (const phone of phones) {    const outcome = await pushAlert(env, { platform: phone.platform!, token: phone.token!, topic: phone.topic ?? "", sandbox: phone.sandbox === 1 }, alert);    if (outcome === "sent") pushed = true;    if (outcome === "gone") sql.exec("UPDATE chat_device SET token = NULL, platform = NULL, topic = NULL WHERE device_id = ?", phone.device_id);  }  return pushed;}