@keslers/kim 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,3 +1,84 @@
1
- # Temporary Holding Version
1
+ [![GitLab](https://img.shields.io/badge/GitLab-FC6D26?logo=gitlab&logoColor=white)](https://gitlab.com/keslers/kim)
2
+ [![npm version](https://img.shields.io/npm/v/@keslers/kim.svg)](https://www.npmjs.com/package/@keslers/kim)
3
+ [![license](https://img.shields.io/npm/l/@keslers/kim)](https://www.npmjs.com/package/@keslers/kim)
2
4
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
5
+ <img src="https://gitlab.com/keslers/kim/-/raw/main/kim.png" alt="KIM" width="200" />
6
+
7
+ # KIM: Keslers Identity Manager
8
+
9
+ Passwordless sign-in, a Free/Premium plan with Stripe, and encrypted
10
+ multi-device sync, for apps on Cloudflare Workers + D1. It runs Kalendar and
11
+ Kubby.
12
+
13
+ - **Sign-in:** a 6-digit code by email (Cloudflare Email), then an
14
+ HttpOnly `__Host-` session cookie. Limits per code, email, network and day,
15
+ and an optional Cloudflare Turnstile check.
16
+ - **Plans:** Free stays in the browser. Premium is a 30-day trial, a Stripe
17
+ subscription (Payment Link + signed webhook, no Stripe API key), or `comp`
18
+ (free, set by hand).
19
+ - **Sync:** one request pushes local changes and pulls other devices'. The
20
+ last save of a record wins. Per-account limits.
21
+ - **Encryption:** every record is sealed with AES-256-GCM under a key derived
22
+ per account from one master secret, bound to its account and id.
23
+
24
+ ## Use
25
+
26
+ ```sh
27
+ npm install @keslers/kim
28
+ ```
29
+
30
+ Create the tables from [`schema.sql`](schema.sql) in your first D1 migration.
31
+
32
+ ```ts
33
+ // src/accounts.ts
34
+ import { kim } from "@keslers/kim/worker";
35
+
36
+ export const kit = kim({
37
+ app: "Kubby", // in emails and messages
38
+ slug: "kubby", // cookie: __Host-kubby_session
39
+ table: "records", // the synced records table
40
+ vaultSalt: "kubby/records/v1", // part of every key: never change it
41
+ words: { data: "inventory", records: "places and items" },
42
+ limits: { records: 20_000, size: 14_000_000, rows: 50_000 },
43
+ });
44
+
45
+ // src/index.ts
46
+ import { handle } from "@keslers/kim/worker";
47
+ import { kit } from "./accounts";
48
+
49
+ export default {
50
+ fetch: (req, env) => handle({ ...kit.routes /* , your routes */ }, req, env),
51
+ } satisfies ExportedHandler<Env>;
52
+ ```
53
+
54
+ `kit.routes` serves `/api/auth/{config,code,verify,logout,me}`, `/api/sync`,
55
+ `/api/account/delete` and `/api/stripe/webhook`. For your own routes,
56
+ `kit.requireUser` / `kit.requirePremium` give the signed-in user and plan.
57
+ `kit.openRows` decrypts your own reads of the records table.
58
+
59
+ Apps with their own account columns add them with `account.columns` and turn
60
+ them into plan fields with `account.plan`. `onSync` adds statements to every
61
+ sync. Kalendar's `src/accounts.ts` uses all three.
62
+
63
+ In the browser, `@keslers/kim/client` has `api()`, `ApiError` and the
64
+ `Plan` / `User` types.
65
+
66
+ ## Environment
67
+
68
+ | Name | |
69
+ | --- | --- |
70
+ | `DB`, `EMAIL` | D1 and Email bindings |
71
+ | `APP_URL`, `EMAIL_FROM`, `DAILY_EMAIL_CAP` | vars |
72
+ | `DATA_KEY` | secret: 32 random bytes, base64. Losing it loses every account's data. |
73
+ | `TURNSTILE_SITE_KEY` + `TURNSTILE_SECRET` | optional; both set turns the check on |
74
+ | `STRIPE_PAYMENT_LINK`, `STRIPE_PAYMENT_LINK_ID`, `STRIPE_BILLING_PORTAL` | vars; only checkouts through your own link count |
75
+ | `STRIPE_WEBHOOK_SECRET` | secret |
76
+ | `ENVIRONMENT` | `development` in `.dev.vars` (plain-http cookies, localhost origins) |
77
+
78
+ ## Security
79
+
80
+ The code holds no secrets. Its safety rests on `DATA_KEY`, the webhook secret
81
+ and the design above. Report problems through the GitLab project's issues,
82
+ marked confidential.
83
+
84
+ ISC license.
@@ -0,0 +1,24 @@
1
+ declare class ApiError extends Error {
2
+ readonly status: number;
3
+ /** the rest of the error body (e.g. `plan` on a 402) */
4
+ readonly data: Record<string, unknown>;
5
+ constructor(status: number, message: string, data?: Record<string, unknown>);
6
+ }
7
+ type User = {
8
+ id: string;
9
+ email: string;
10
+ };
11
+ /** Free is local; Premium is the paid plan. Apps may add fields. */
12
+ type Plan = {
13
+ premium: boolean;
14
+ via: "comp" | "paid" | "trial" | null;
15
+ trialUntil: number | null;
16
+ paidUntil: number | null;
17
+ ending: boolean;
18
+ checkoutUrl: string | null;
19
+ billingUrl: string | null;
20
+ };
21
+ /** GET (no body) or POST JSON to the app's own /api. */
22
+ declare function api<T>(path: string, body?: unknown): Promise<T>;
23
+
24
+ export { ApiError, type Plan, type User, api };
package/dist/client.js ADDED
@@ -0,0 +1,35 @@
1
+ // src/client.ts
2
+ var ApiError = class extends Error {
3
+ status;
4
+ /** the rest of the error body (e.g. `plan` on a 402) */
5
+ data;
6
+ constructor(status, message, data = {}) {
7
+ super(message);
8
+ this.status = status;
9
+ this.data = data;
10
+ }
11
+ };
12
+ async function api(path, body) {
13
+ let res;
14
+ try {
15
+ res = await fetch(`/api${path}`, {
16
+ method: body === void 0 ? "GET" : "POST",
17
+ headers: { "Content-Type": "application/json" },
18
+ body: body === void 0 ? void 0 : JSON.stringify(body)
19
+ });
20
+ } catch {
21
+ throw new ApiError(0, "Can't reach the server");
22
+ }
23
+ const data = await res.json().catch(() => ({}));
24
+ if (!res.ok)
25
+ throw new ApiError(
26
+ res.status,
27
+ typeof data.error === "string" ? data.error : `Request failed (${res.status})`,
28
+ data
29
+ );
30
+ return data;
31
+ }
32
+ export {
33
+ ApiError,
34
+ api
35
+ };
@@ -0,0 +1,201 @@
1
+ /** The bindings and variables every app's Worker provides. */
2
+ interface AccountsEnv {
3
+ DB: D1Database;
4
+ EMAIL: SendEmail;
5
+ /** "development" under wrangler dev (from .dev.vars) */
6
+ ENVIRONMENT?: string;
7
+ /** sender of sign-in codes, e.g. donotreply@keslers.io */
8
+ EMAIL_FROM: string;
9
+ /** sign-in emails per day, across all users */
10
+ DAILY_EMAIL_CAP?: string;
11
+ /** e.g. https://kubby.keslers.io (Turnstile checks this hostname) */
12
+ APP_URL: string;
13
+ /** encryption master key: 32 random bytes, base64 (a secret) */
14
+ DATA_KEY?: string;
15
+ TURNSTILE_SITE_KEY?: string;
16
+ TURNSTILE_SECRET?: string;
17
+ /** the app's Stripe Payment Link, and its id (plink_…) */
18
+ STRIPE_PAYMENT_LINK?: string;
19
+ STRIPE_PAYMENT_LINK_ID?: string;
20
+ STRIPE_BILLING_PORTAL?: string;
21
+ STRIPE_WEBHOOK_SECRET?: string;
22
+ }
23
+ type Limits = {
24
+ /** records an account can keep */
25
+ records: number;
26
+ /** stored characters (encrypted: about 4/3 of the JSON) */
27
+ size: number;
28
+ /** records plus deletion markers */
29
+ rows: number;
30
+ };
31
+ type Config<A = Record<string, unknown>, P = Record<string, unknown>> = {
32
+ /** shown in emails and messages: "Kubby" */
33
+ app: string;
34
+ /** names the session cookie: "kubby" → __Host-kubby_session */
35
+ slug: string;
36
+ /** the table synced records live in */
37
+ table: string;
38
+ /**
39
+ * Part of every account's encryption key. Never change it once data is
40
+ * stored: what was sealed under the old one stops opening.
41
+ */
42
+ vaultSalt: string;
43
+ /** how messages name things: { data: "inventory", records: "places and items" } */
44
+ words: {
45
+ data: string;
46
+ records: string;
47
+ };
48
+ /** per-account limits (mutable, so tests can lower them) */
49
+ limits: Limits;
50
+ /** app-specific account columns and the plan fields they become */
51
+ account?: {
52
+ /** more columns from `users u`, e.g. "u.tz, u.weekly_email" */
53
+ columns?: string;
54
+ plan?: (account: A) => P;
55
+ };
56
+ /** more statements to run with every sync (e.g. remembering a timezone) */
57
+ onSync?: (sync: {
58
+ body: Record<string, unknown>;
59
+ userId: string;
60
+ account: A;
61
+ env: AccountsEnv;
62
+ }) => D1PreparedStatement[];
63
+ };
64
+
65
+ declare const TRIAL_DAYS = 30;
66
+ /** a failed renewal keeps Premium this long while Stripe retries the card */
67
+ declare const GRACE: number;
68
+ declare const PAID_STATUSES: Set<string>;
69
+ /** A user row with everything the plan depends on. */
70
+ type Account = {
71
+ id: string;
72
+ email: string;
73
+ trial_until: number | null;
74
+ comp: number;
75
+ stripe_customer: string | null;
76
+ status: string | null;
77
+ period_end: number | null;
78
+ cancel_at_end: number | null;
79
+ };
80
+ /** SQL list of PAID_STATUSES */
81
+ declare const PAID_SQL: string;
82
+ type Plan = {
83
+ premium: boolean;
84
+ /** why Premium is on */
85
+ via: "comp" | "paid" | "trial" | null;
86
+ trialUntil: number | null;
87
+ /** paid through (renews or ends then) */
88
+ paidUntil: number | null;
89
+ /** canceled: ends at paidUntil instead of renewing */
90
+ ending: boolean;
91
+ /** Stripe Payment Link for this account, when subscriptions are open */
92
+ checkoutUrl: string | null;
93
+ /** Stripe's billing page, once there's a subscription */
94
+ billingUrl: string | null;
95
+ };
96
+
97
+ type User = {
98
+ id: string;
99
+ email: string;
100
+ };
101
+ declare function withSession(res: Response, setCookie?: string): Response;
102
+
103
+ /** An unguessable random string (256 bits by default). */
104
+ declare const randomToken: (bytes?: number) => string;
105
+ /** A uniformly random 6-digit code. */
106
+ declare function randomCode(): string;
107
+ declare function sha256(s: string): Promise<string>;
108
+ /** Compares two strings without leaking where they differ through timing. */
109
+ declare function equal(a: string, b: string): boolean;
110
+
111
+ declare class HttpError extends Error {
112
+ readonly status: number;
113
+ readonly headers: HeadersInit;
114
+ /** extra fields for the JSON body */
115
+ readonly data: Record<string, unknown>;
116
+ constructor(status: number, message: string, headers?: HeadersInit,
117
+ /** extra fields for the JSON body */
118
+ data?: Record<string, unknown>);
119
+ }
120
+ declare function json(data: unknown, status?: number, headers?: HeadersInit): Response;
121
+ /**
122
+ * Reads a JSON body. Requiring application/json also keeps other sites from
123
+ * posting here: a cross-site JSON request needs a CORS preflight we never
124
+ * answer.
125
+ */
126
+ declare function readJson(req: Request): Promise<Record<string, unknown>>;
127
+ /**
128
+ * wrangler dev, from .dev.vars, which is never deployed. (The URL can't tell:
129
+ * wrangler dev shows the Worker its production route.)
130
+ */
131
+ declare const isDev: (env: AccountsEnv) => boolean;
132
+ /**
133
+ * Browsers send Origin on every POST. Refuse ones from anywhere but this
134
+ * site (or, in dev, the Vite server on localhost), on top of SameSite
135
+ * cookies and the JSON-only rule.
136
+ */
137
+ declare function checkOrigin(req: Request, env: AccountsEnv): void;
138
+
139
+ /**
140
+ * The network an address belongs to, for per-network limits. An IPv4
141
+ * address is one network, but one IPv6 connection usually gets a whole /64
142
+ * (billions of addresses), so IPv6 counts by its first four groups.
143
+ */
144
+ declare function network(ip: string): string;
145
+
146
+ type Handler<E extends AccountsEnv = AccountsEnv> = (req: Request, env: E) => Promise<Response>;
147
+ /**
148
+ * Everything accounts need, set up for one app. `A` is the app's account row
149
+ * (base columns plus `account.columns`), `P` the extra plan fields it adds.
150
+ */
151
+ declare function kim<A extends Record<string, unknown> = Record<string, unknown>, P extends Record<string, unknown> = Record<string, never>>(config: Config<A, P>): {
152
+ /** the account routes, keyed "METHOD /path" */
153
+ routes: Record<string, Handler<AccountsEnv>>;
154
+ /** The signed-in user, or a 401. Pass `setCookie` on with `withSession`. */
155
+ requireUser: (req: Request, env: AccountsEnv) => Promise<{
156
+ user: {
157
+ id: string;
158
+ email: string;
159
+ };
160
+ account: Account & A;
161
+ plan: Plan & P;
162
+ setCookie?: string;
163
+ }>;
164
+ /** The signed-in user with Premium, or a 401 / 402. */
165
+ requirePremium: (req: Request, env: AccountsEnv) => Promise<{
166
+ user: {
167
+ id: string;
168
+ email: string;
169
+ };
170
+ account: Account & A;
171
+ plan: Plan & P;
172
+ setCookie?: string;
173
+ }>;
174
+ /** Throws the 402 that explains Premium is needed. */
175
+ needPremium: (plan: Plan) => never;
176
+ planOf: (account: Account & A, env: AccountsEnv, now?: number) => Plan & P;
177
+ /** SELECT … FROM users u LEFT JOIN subscriptions s: add a WHERE on u */
178
+ accountSelect: string;
179
+ withSession: typeof withSession;
180
+ clearCookie: (env: AccountsEnv) => string;
181
+ /**
182
+ * Decrypts the app's own reads of its records table. A row that won't
183
+ * open is left out and logged.
184
+ */
185
+ openRows: <T>(env: AccountsEnv, userId: string, rows: {
186
+ id: string;
187
+ data: string;
188
+ }[]) => Promise<{
189
+ id: string;
190
+ data: T;
191
+ }[]>;
192
+ /** per-account limits, live (tests may lower them) */
193
+ limits: Limits;
194
+ };
195
+ /**
196
+ * Answers a request from `routes`: checks the Origin, turns HttpErrors into
197
+ * JSON, and hides anything unexpected behind a 500.
198
+ */
199
+ declare function handle<E extends AccountsEnv>(routes: Record<string, Handler<E>>, req: Request, env: E): Promise<Response>;
200
+
201
+ export { type Account, type AccountsEnv, type Config, GRACE, type Handler, HttpError, type Limits, PAID_SQL, PAID_STATUSES, type Plan, TRIAL_DAYS, type User, checkOrigin, equal, handle, isDev, json, kim, network, randomCode, randomToken, readJson, sha256 };
@@ -0,0 +1,842 @@
1
+ // src/worker/crypto.ts
2
+ var b64url = (bytes) => btoa(String.fromCharCode(...bytes)).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
3
+ var randomToken = (bytes = 32) => b64url(crypto.getRandomValues(new Uint8Array(bytes)));
4
+ function randomCode() {
5
+ const buf = new Uint32Array(1);
6
+ do
7
+ crypto.getRandomValues(buf);
8
+ while (buf[0] >= 4294e6);
9
+ return String(buf[0] % 1e6).padStart(6, "0");
10
+ }
11
+ async function sha256(s) {
12
+ const digest = await crypto.subtle.digest(
13
+ "SHA-256",
14
+ new TextEncoder().encode(s)
15
+ );
16
+ return b64url(new Uint8Array(digest));
17
+ }
18
+ function equal(a, b) {
19
+ const x = new TextEncoder().encode(a);
20
+ const y = new TextEncoder().encode(b);
21
+ return x.byteLength === y.byteLength && crypto.subtle.timingSafeEqual(x, y);
22
+ }
23
+
24
+ // src/worker/http.ts
25
+ var HttpError = class extends Error {
26
+ constructor(status, message, headers = {}, data = {}) {
27
+ super(message);
28
+ this.status = status;
29
+ this.headers = headers;
30
+ this.data = data;
31
+ }
32
+ status;
33
+ headers;
34
+ data;
35
+ };
36
+ function json(data, status = 200, headers = {}) {
37
+ return new Response(JSON.stringify(data), {
38
+ status,
39
+ headers: {
40
+ "Content-Type": "application/json",
41
+ "Cache-Control": "no-store",
42
+ "X-Content-Type-Options": "nosniff",
43
+ ...headers
44
+ }
45
+ });
46
+ }
47
+ var MAX_BODY = 1e6;
48
+ async function readJson(req) {
49
+ if (!req.headers.get("Content-Type")?.startsWith("application/json"))
50
+ throw new HttpError(415, "Expected JSON");
51
+ const text = await req.text();
52
+ if (text.length > MAX_BODY) throw new HttpError(413, "Too much at once");
53
+ try {
54
+ const body = JSON.parse(text);
55
+ if (body && typeof body === "object" && !Array.isArray(body)) return body;
56
+ } catch {
57
+ }
58
+ throw new HttpError(400, "Malformed request");
59
+ }
60
+ var isDev = (env) => env.ENVIRONMENT === "development";
61
+ function checkOrigin(req, env) {
62
+ const origin = req.headers.get("Origin");
63
+ if (!origin || req.method === "GET") return;
64
+ if (origin === new URL(req.url).origin) return;
65
+ if (isDev(env) && /^http:\/\/(localhost|127\.0\.0\.1)(:\d+)?$/.test(origin))
66
+ return;
67
+ throw new HttpError(403, "Forbidden");
68
+ }
69
+
70
+ // src/worker/email.ts
71
+ async function sendCode(cfg, env, to, code) {
72
+ const app = cfg.app;
73
+ try {
74
+ await env.EMAIL.send({
75
+ from: { email: env.EMAIL_FROM, name: app },
76
+ to,
77
+ subject: `${code} is your ${app} sign-in code`,
78
+ text: `Your ${app} sign-in code is ${code}
79
+
80
+ It works for 10 minutes. If you didn't ask for it, you can ignore this email.`,
81
+ html: `<div style="font-family:system-ui,sans-serif;color:#111">
82
+ <p>Your ${app} sign-in code is</p>
83
+ <p style="font-size:28px;font-weight:600;letter-spacing:6px;margin:12px 0">${code}</p>
84
+ <p style="color:#666">It works for 10 minutes. If you didn't ask for it, you can ignore this email.</p>
85
+ </div>`
86
+ });
87
+ } catch (e) {
88
+ const err = e;
89
+ console.error("email send failed", err.code, err.message);
90
+ if (err.code === "E_RECIPIENT_SUPPRESSED")
91
+ throw new HttpError(400, "That address can't receive email from us");
92
+ if (err.code === "E_DAILY_LIMIT_EXCEEDED" || err.code === "E_RATE_LIMIT_EXCEEDED")
93
+ throw new HttpError(503, "Sign-in is busy, try again later");
94
+ throw new HttpError(502, "Couldn't send the email, try again");
95
+ }
96
+ }
97
+
98
+ // src/worker/network.ts
99
+ function network(ip) {
100
+ if (!ip.includes(":") || ip.includes(".")) return ip.split(":").pop() ?? ip;
101
+ const [head, tail = ""] = ip.toLowerCase().split("::");
102
+ const left = head ? head.split(":") : [];
103
+ const right = tail ? tail.split(":") : [];
104
+ const zeros = ip.includes("::") ? Array(Math.max(8 - left.length - right.length, 0)).fill("0") : [];
105
+ const groups = [...left, ...zeros, ...right];
106
+ return `${groups.slice(0, 4).map((g) => g.replace(/^0+(?=.)/, "")).join(":")}::/64`;
107
+ }
108
+
109
+ // src/worker/plan.ts
110
+ var DAY = 864e5;
111
+ var TRIAL_DAYS = 30;
112
+ var GRACE = 3 * DAY;
113
+ var PAID_STATUSES = /* @__PURE__ */ new Set(["active", "trialing", "past_due"]);
114
+ var PAID_SQL = [...PAID_STATUSES].map((x) => `'${x}'`).join(", ");
115
+ var accountColumns = (cfg) => `u.id, u.email, u.trial_until, u.comp, u.stripe_customer,
116
+ s.status, s.period_end, s.cancel_at_end${cfg.account?.columns ? `, ${cfg.account.columns}` : ""}`;
117
+ var accountSelect = (cfg) => `SELECT ${accountColumns(cfg)}
118
+ FROM users u LEFT JOIN subscriptions s ON s.customer = u.stripe_customer`;
119
+ function planOf(cfg, a, env, now = Date.now()) {
120
+ const paidUntil = a.period_end && a.status && PAID_STATUSES.has(a.status) ? a.period_end * 1e3 : null;
121
+ const paid = paidUntil !== null && paidUntil + GRACE > now;
122
+ const trial = (a.trial_until ?? 0) > now;
123
+ const comp = a.comp === 1;
124
+ const link = env.STRIPE_PAYMENT_LINK;
125
+ const portal = env.STRIPE_BILLING_PORTAL;
126
+ const email = encodeURIComponent(a.email);
127
+ return {
128
+ premium: comp || paid || trial,
129
+ via: comp ? "comp" : paid ? "paid" : trial ? "trial" : null,
130
+ trialUntil: a.trial_until,
131
+ paidUntil,
132
+ ending: paid && a.cancel_at_end === 1,
133
+ checkoutUrl: link && !comp && !paid ? `${link}?client_reference_id=${a.id}&prefilled_email=${email}` : null,
134
+ billingUrl: portal && a.stripe_customer ? `${portal}?prefilled_email=${email}` : null,
135
+ ...cfg.account?.plan?.(a)
136
+ };
137
+ }
138
+ function needPremium(cfg, plan) {
139
+ throw new HttpError(
140
+ 402,
141
+ plan.via === null && plan.trialUntil ? `Your Premium trial has ended. Your ${cfg.words.data} is safe in this browser; syncing is paused.` : `That's part of ${cfg.app} Premium`,
142
+ {},
143
+ { plan }
144
+ );
145
+ }
146
+
147
+ // src/worker/auth.ts
148
+ var MIN = 6e4;
149
+ var HOUR = 60 * MIN;
150
+ var DAY2 = 24 * HOUR;
151
+ var CODE_TTL = 10 * MIN;
152
+ var MAX_ATTEMPTS = 3;
153
+ var RESEND_AFTER = MIN;
154
+ var PER_EMAIL_HOURLY = 5;
155
+ var PER_EMAIL_DAILY = 10;
156
+ var PER_IP_HOURLY = 10;
157
+ var PER_IP_DAILY = 20;
158
+ var SESSION_TTL = 90 * DAY2;
159
+ var RENEW_AFTER = 10 * DAY2;
160
+ var normalizeEmail = (v) => {
161
+ const email = typeof v === "string" ? v.trim().toLowerCase() : "";
162
+ if (email.length > 254 || !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email))
163
+ throw new HttpError(400, "That doesn't look like an email address");
164
+ return email;
165
+ };
166
+ var codeHash = (email, code) => sha256(`${email}:${code}`);
167
+ async function requestCode(cfg, req, env) {
168
+ const body = await readJson(req);
169
+ const email = normalizeEmail(body.email);
170
+ const addr = req.headers.get("CF-Connecting-IP") ?? "local";
171
+ await checkTurnstile(env, body.turnstile, addr);
172
+ const ip = network(addr);
173
+ const now = Date.now();
174
+ const cap = Number(env.DAILY_EMAIL_CAP) || 100;
175
+ const claimed = await env.DB.prepare(
176
+ `INSERT INTO code_requests (email, ip, at)
177
+ SELECT ?1, ?2, ?3
178
+ WHERE NOT EXISTS (SELECT 1 FROM code_requests WHERE email = ?1 AND at > ?3 - ?4)
179
+ AND (SELECT COUNT(*) FROM code_requests WHERE email = ?1 AND at > ?3 - ?5) < ?6
180
+ AND (SELECT COUNT(*) FROM code_requests WHERE email = ?1 AND at > ?3 - ?7) < ?8
181
+ AND (SELECT COUNT(*) FROM code_requests WHERE ip = ?2 AND at > ?3 - ?5) < ?9
182
+ AND (SELECT COUNT(*) FROM code_requests WHERE ip = ?2 AND at > ?3 - ?7) < ?11
183
+ AND (SELECT COUNT(*) FROM code_requests WHERE at > ?3 - ?7) < ?10`
184
+ ).bind(
185
+ email,
186
+ ip,
187
+ now,
188
+ RESEND_AFTER,
189
+ HOUR,
190
+ PER_EMAIL_HOURLY,
191
+ DAY2,
192
+ PER_EMAIL_DAILY,
193
+ PER_IP_HOURLY,
194
+ cap,
195
+ PER_IP_DAILY
196
+ ).run();
197
+ if (!claimed.meta.changes) throw await whyLimited(env, email, now, cap);
198
+ const code = randomCode();
199
+ await env.DB.batch([
200
+ env.DB.prepare("DELETE FROM code_requests WHERE at <= ?").bind(now - DAY2),
201
+ // a new code replaces the old one and its attempt count
202
+ env.DB.prepare(
203
+ `INSERT INTO login_codes (email, code_hash, expires_at, attempts)
204
+ VALUES (?1, ?2, ?3, 0)
205
+ ON CONFLICT (email) DO UPDATE SET
206
+ code_hash = excluded.code_hash,
207
+ expires_at = excluded.expires_at,
208
+ attempts = 0`
209
+ ).bind(email, await codeHash(email, code), now + CODE_TTL)
210
+ ]);
211
+ await sendCode(cfg, env, email, code);
212
+ return json({ ok: true });
213
+ }
214
+ async function authConfig(_req, env) {
215
+ return json({ turnstile: turnstileOn(env) ? env.TURNSTILE_SITE_KEY : null });
216
+ }
217
+ var turnstileOn = (env) => Boolean(env.TURNSTILE_SITE_KEY && env.TURNSTILE_SECRET);
218
+ async function checkTurnstile(env, token, ip) {
219
+ if (!turnstileOn(env)) return;
220
+ if (typeof token !== "string" || !token || token.length > 2048)
221
+ throw new HttpError(
222
+ 400,
223
+ "Please complete the check and try again",
224
+ {},
225
+ {
226
+ turnstile: env.TURNSTILE_SITE_KEY
227
+ }
228
+ );
229
+ let result = {};
230
+ try {
231
+ const res = await fetch(
232
+ "https://challenges.cloudflare.com/turnstile/v0/siteverify",
233
+ {
234
+ method: "POST",
235
+ body: new URLSearchParams({
236
+ secret: env.TURNSTILE_SECRET ?? "",
237
+ response: token,
238
+ remoteip: ip
239
+ })
240
+ }
241
+ );
242
+ result = await res.json();
243
+ } catch (e) {
244
+ console.error("turnstile verify failed", e.message);
245
+ throw new HttpError(503, "Sign-in is busy, try again in a moment");
246
+ }
247
+ const host = new URL(env.APP_URL).hostname;
248
+ if (!result.success || !isDev(env) && result.hostname !== host)
249
+ throw new HttpError(
250
+ 400,
251
+ "That check didn't go through, try again",
252
+ {},
253
+ {
254
+ turnstile: env.TURNSTILE_SITE_KEY
255
+ }
256
+ );
257
+ }
258
+ async function whyLimited(env, email, now, cap) {
259
+ const u = await env.DB.prepare(
260
+ `SELECT
261
+ COUNT(*) AS day,
262
+ MAX(CASE WHEN email = ?1 THEN at END) AS email_last
263
+ FROM code_requests WHERE at > ?2`
264
+ ).bind(email, now - DAY2).first();
265
+ if (u?.email_last && now - u.email_last < RESEND_AFTER) {
266
+ const wait = Math.ceil((RESEND_AFTER - (now - u.email_last)) / 1e3);
267
+ return new HttpError(429, `Wait ${wait}s before asking for another code`, {
268
+ "Retry-After": String(wait)
269
+ });
270
+ }
271
+ if ((u?.day ?? 0) >= cap)
272
+ return new HttpError(503, "Sign-in is busy today, try again later");
273
+ return new HttpError(429, "Too many codes requested, try again later");
274
+ }
275
+ async function verifyCode(cfg, req, env) {
276
+ const body = await readJson(req);
277
+ const email = normalizeEmail(body.email);
278
+ const code = String(body.code ?? "").replace(/\D/g, "");
279
+ const now = Date.now();
280
+ const row = await env.DB.prepare(
281
+ `UPDATE login_codes SET attempts = attempts + 1
282
+ WHERE email = ? AND expires_at > ? AND attempts < ?
283
+ RETURNING code_hash, attempts`
284
+ ).bind(email, now, MAX_ATTEMPTS).first();
285
+ if (!row) {
286
+ await env.DB.prepare("DELETE FROM login_codes WHERE email = ?").bind(email).run();
287
+ throw new HttpError(400, "That code expired, ask for a new one");
288
+ }
289
+ if (code.length !== 6 || !equal(await codeHash(email, code), row.code_hash)) {
290
+ const left = MAX_ATTEMPTS - row.attempts;
291
+ throw new HttpError(
292
+ 400,
293
+ left > 0 ? `Wrong code, ${left} ${left === 1 ? "try" : "tries"} left` : "Wrong code, ask for a new one"
294
+ );
295
+ }
296
+ const used = await env.DB.prepare(
297
+ "DELETE FROM login_codes WHERE email = ? AND code_hash = ? RETURNING email"
298
+ ).bind(email, row.code_hash).first();
299
+ if (!used) throw new HttpError(400, "That code expired, ask for a new one");
300
+ const token = randomToken();
301
+ const [, account] = await env.DB.batch([
302
+ // a new account starts its Premium trial
303
+ env.DB.prepare(
304
+ `INSERT INTO users (id, email, created_at, trial_until)
305
+ VALUES (?, ?, ?, ?) ON CONFLICT (email) DO NOTHING`
306
+ ).bind(crypto.randomUUID(), email, now, now + TRIAL_DAYS * DAY2),
307
+ env.DB.prepare(`${accountSelect(cfg)} WHERE u.email = ?`).bind(email),
308
+ env.DB.prepare(
309
+ `INSERT INTO sessions (token_hash, user_id, created_at, expires_at)
310
+ SELECT ?1, id, ?2, ?3 FROM users WHERE email = ?4`
311
+ ).bind(await sha256(token), now, now + SESSION_TTL, email),
312
+ env.DB.prepare("DELETE FROM sessions WHERE expires_at < ?").bind(now)
313
+ ]);
314
+ const a = account.results[0];
315
+ return json(
316
+ { user: { id: a.id, email: a.email }, plan: planOf(cfg, a, env, now) },
317
+ 200,
318
+ { "Set-Cookie": cookie(cfg, env, token, SESSION_TTL) }
319
+ );
320
+ }
321
+ async function logout(cfg, req, env) {
322
+ const body = await readJson(req);
323
+ const token = readCookie(cfg, req, env);
324
+ if (token) {
325
+ const hash = await sha256(token);
326
+ await env.DB.prepare(
327
+ body.everywhere === true ? "DELETE FROM sessions WHERE user_id = (SELECT user_id FROM sessions WHERE token_hash = ?)" : "DELETE FROM sessions WHERE token_hash = ?"
328
+ ).bind(hash).run();
329
+ }
330
+ return json({ ok: true }, 200, { "Set-Cookie": cookie(cfg, env, "", 0) });
331
+ }
332
+ async function requireUser(cfg, req, env) {
333
+ const token = readCookie(cfg, req, env);
334
+ if (!token) throw new HttpError(401, "Not signed in");
335
+ const hash = await sha256(token);
336
+ const now = Date.now();
337
+ const row = await env.DB.prepare(
338
+ `SELECT ${accountColumns(cfg)}, x.expires_at
339
+ FROM sessions x
340
+ JOIN users u ON u.id = x.user_id
341
+ LEFT JOIN subscriptions s ON s.customer = u.stripe_customer
342
+ WHERE x.token_hash = ? AND x.expires_at > ?`
343
+ ).bind(hash, now).first();
344
+ if (!row)
345
+ throw new HttpError(401, "Signed out, sign in again to sync", {
346
+ "Set-Cookie": cookie(cfg, env, "", 0)
347
+ });
348
+ const { expires_at, ...account } = row;
349
+ const found = {
350
+ user: { id: account.id, email: account.email },
351
+ account,
352
+ plan: planOf(cfg, account, env, now)
353
+ };
354
+ if (expires_at - now > SESSION_TTL - RENEW_AFTER) return found;
355
+ await env.DB.prepare(
356
+ "UPDATE sessions SET expires_at = ? WHERE token_hash = ?"
357
+ ).bind(now + SESSION_TTL, hash).run();
358
+ return { ...found, setCookie: cookie(cfg, env, token, SESSION_TTL) };
359
+ }
360
+ async function requirePremium(cfg, req, env) {
361
+ const found = await requireUser(cfg, req, env);
362
+ if (!found.plan.premium) needPremium(cfg, found.plan);
363
+ return found;
364
+ }
365
+ async function me(cfg, req, env) {
366
+ const { user, plan, setCookie } = await requireUser(cfg, req, env);
367
+ return withSession(json({ user, plan }), setCookie);
368
+ }
369
+ function withSession(res, setCookie) {
370
+ if (setCookie) res.headers.append("Set-Cookie", setCookie);
371
+ return res;
372
+ }
373
+ var cookieName = (cfg, env) => isDev(env) ? `${cfg.slug}_session` : `__Host-${cfg.slug}_session`;
374
+ function readCookie(cfg, req, env) {
375
+ const name = cookieName(cfg, env);
376
+ const header = req.headers.get("Cookie") ?? "";
377
+ for (const part of header.split(";")) {
378
+ const [k, ...v] = part.trim().split("=");
379
+ if (k === name) return v.join("=") || null;
380
+ }
381
+ return null;
382
+ }
383
+ function cookie(cfg, env, value, ttl) {
384
+ const secure = isDev(env) ? "" : "; Secure";
385
+ return `${cookieName(cfg, env)}=${value}; Path=/; HttpOnly; SameSite=Lax; Max-Age=${Math.floor(ttl / 1e3)}${secure}`;
386
+ }
387
+ var clearCookie = (cfg, env) => cookie(cfg, env, "", 0);
388
+
389
+ // src/worker/account.ts
390
+ async function deleteAccount(cfg, req, env) {
391
+ const { user, plan } = await requireUser(cfg, req, env);
392
+ const body = await readJson(req);
393
+ if (String(body.email ?? "").trim().toLowerCase() !== user.email)
394
+ throw new HttpError(400, "Type your email to confirm");
395
+ if (plan.via === "paid" && !plan.ending)
396
+ throw new HttpError(
397
+ 409,
398
+ "Cancel Premium in billing first, so you aren't charged again",
399
+ {},
400
+ { billingUrl: plan.billingUrl }
401
+ );
402
+ await env.DB.batch(
403
+ [
404
+ `DELETE FROM ${cfg.table} WHERE user_id = ?`,
405
+ "DELETE FROM sessions WHERE user_id = ?",
406
+ "DELETE FROM users WHERE id = ?"
407
+ ].map((sql) => env.DB.prepare(sql).bind(user.id))
408
+ );
409
+ return json({ ok: true }, 200, { "Set-Cookie": clearCookie(cfg, env) });
410
+ }
411
+
412
+ // src/worker/stripe.ts
413
+ var TOLERANCE_S = 300;
414
+ async function stripeWebhook(req, env) {
415
+ const body = await req.text();
416
+ if (body.length > 512e3) throw new HttpError(413, "Too large");
417
+ await verify(env, req.headers.get("Stripe-Signature"), body);
418
+ const event = JSON.parse(body);
419
+ const o = event.data.object;
420
+ const now = Date.now();
421
+ const created = num(event.created) ?? Math.floor(now / 1e3);
422
+ switch (event.type) {
423
+ case "checkout.session.completed": {
424
+ const customer = str(o.customer);
425
+ if (!customer) break;
426
+ if (!env.STRIPE_PAYMENT_LINK_ID || o.payment_link !== env.STRIPE_PAYMENT_LINK_ID)
427
+ break;
428
+ const ref = str(o.client_reference_id);
429
+ const email = str(
430
+ o.customer_details?.email
431
+ )?.toLowerCase();
432
+ const linked = await env.DB.prepare(
433
+ `UPDATE users SET stripe_customer = ?1
434
+ WHERE id = (
435
+ SELECT id FROM users
436
+ WHERE id = ?2 OR (?2 IS NULL AND email = ?3)
437
+ LIMIT 1
438
+ )
439
+ AND (
440
+ stripe_customer IS NULL OR stripe_customer = ?1
441
+ OR NOT EXISTS (
442
+ SELECT 1 FROM subscriptions s
443
+ WHERE s.customer = users.stripe_customer
444
+ AND s.status IN (${PAID_SQL})
445
+ AND s.period_end * 1000 + ?5 > ?4
446
+ )
447
+ )`
448
+ ).bind(customer, ref ?? null, email ?? null, now, GRACE).run();
449
+ if (!linked.meta.changes)
450
+ console.warn("checkout not linked to an account", customer);
451
+ break;
452
+ }
453
+ case "customer.subscription.created":
454
+ case "customer.subscription.updated":
455
+ case "customer.subscription.deleted": {
456
+ const customer = str(o.customer);
457
+ if (!customer) break;
458
+ const items = o.items?.data;
459
+ const periodEnd = num(o.current_period_end) ?? num(items?.[0]?.current_period_end);
460
+ const status = event.type === "customer.subscription.deleted" ? "canceled" : str(o.status) ?? "unknown";
461
+ const ending = o.cancel_at_period_end === true || num(o.cancel_at) ? 1 : 0;
462
+ await env.DB.prepare(
463
+ // Only newer news wins (on a tie, a cancellation stays), and a
464
+ // second subscription that isn't paid never hides one that is.
465
+ `INSERT INTO subscriptions (customer, subscription, status, period_end, cancel_at_end, updated_at, event_at)
466
+ VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7)
467
+ ON CONFLICT (customer) DO UPDATE SET
468
+ subscription = excluded.subscription,
469
+ status = excluded.status,
470
+ period_end = excluded.period_end,
471
+ cancel_at_end = excluded.cancel_at_end,
472
+ updated_at = excluded.updated_at,
473
+ event_at = excluded.event_at
474
+ WHERE (
475
+ excluded.event_at > subscriptions.event_at
476
+ OR (excluded.event_at = subscriptions.event_at AND subscriptions.status != 'canceled')
477
+ ) AND (
478
+ excluded.subscription IS subscriptions.subscription
479
+ OR subscriptions.status NOT IN (${PAID_SQL})
480
+ OR excluded.status IN (${PAID_SQL})
481
+ )`
482
+ ).bind(
483
+ customer,
484
+ str(o.id) ?? null,
485
+ status,
486
+ periodEnd ?? null,
487
+ ending,
488
+ now,
489
+ created
490
+ ).run();
491
+ break;
492
+ }
493
+ }
494
+ return json({ received: true });
495
+ }
496
+ async function verify(env, header, body) {
497
+ const secret = env.STRIPE_WEBHOOK_SECRET;
498
+ if (!secret) throw new HttpError(503, "Webhook not configured");
499
+ const parts = /* @__PURE__ */ new Map();
500
+ for (const kv of (header ?? "").split(",")) {
501
+ const [k, v] = kv.split("=");
502
+ if (k && v) parts.set(k, [...parts.get(k) ?? [], v]);
503
+ }
504
+ const t = Number(parts.get("t")?.[0]);
505
+ if (!t || Math.abs(Date.now() / 1e3 - t) > TOLERANCE_S)
506
+ throw new HttpError(400, "Bad signature");
507
+ const key = await crypto.subtle.importKey(
508
+ "raw",
509
+ new TextEncoder().encode(secret),
510
+ { name: "HMAC", hash: "SHA-256" },
511
+ false,
512
+ ["sign"]
513
+ );
514
+ const mac = await crypto.subtle.sign(
515
+ "HMAC",
516
+ key,
517
+ new TextEncoder().encode(`${t}.${body}`)
518
+ );
519
+ const expected = [...new Uint8Array(mac)].map((b) => b.toString(16).padStart(2, "0")).join("");
520
+ if (!(parts.get("v1") ?? []).some((v) => equal(v, expected)))
521
+ throw new HttpError(400, "Bad signature");
522
+ }
523
+ var str = (v) => typeof v === "string" && v ? v : void 0;
524
+ var num = (v) => typeof v === "number" ? v : void 0;
525
+
526
+ // src/worker/vault.ts
527
+ var VERSION = "v1";
528
+ var enc = new TextEncoder();
529
+ var dec = new TextDecoder();
530
+ var b64url2 = (bytes) => btoa(String.fromCharCode(...bytes)).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
531
+ var fromB64 = (s) => Uint8Array.from(
532
+ atob(s.replace(/-/g, "+").replace(/_/g, "/")),
533
+ (c) => c.charCodeAt(0)
534
+ );
535
+ var master = null;
536
+ var accountKeys = /* @__PURE__ */ new Map();
537
+ function masterKey(env) {
538
+ const raw = env.DATA_KEY;
539
+ if (!raw)
540
+ throw new HttpError(503, "Storage isn't available right now, try later");
541
+ if (master?.raw !== raw) {
542
+ let bytes;
543
+ try {
544
+ bytes = fromB64(raw.trim());
545
+ } catch {
546
+ throw new Error("DATA_KEY isn't base64");
547
+ }
548
+ if (bytes.length !== 32) throw new Error("DATA_KEY must be 32 bytes");
549
+ master = {
550
+ raw,
551
+ key: crypto.subtle.importKey("raw", bytes, "HKDF", false, ["deriveKey"])
552
+ };
553
+ accountKeys.clear();
554
+ }
555
+ return master.key;
556
+ }
557
+ function accountKey(cfg, env, userId) {
558
+ const base = masterKey(env);
559
+ const id = `${cfg.vaultSalt}\0${userId}`;
560
+ let key = accountKeys.get(id);
561
+ if (!key) {
562
+ key = base.then(
563
+ (m) => crypto.subtle.deriveKey(
564
+ {
565
+ name: "HKDF",
566
+ hash: "SHA-256",
567
+ salt: enc.encode(cfg.vaultSalt),
568
+ info: enc.encode(userId)
569
+ },
570
+ m,
571
+ { name: "AES-GCM", length: 256 },
572
+ false,
573
+ ["encrypt", "decrypt"]
574
+ )
575
+ );
576
+ accountKeys.set(id, key);
577
+ }
578
+ return key;
579
+ }
580
+ var bound = (userId, recordId) => enc.encode(`${userId}/${recordId}`);
581
+ var isSealed = (stored) => stored.startsWith(`${VERSION}.`);
582
+ async function seal(cfg, env, userId, recordId, json2) {
583
+ const iv = crypto.getRandomValues(new Uint8Array(12));
584
+ const ct = await crypto.subtle.encrypt(
585
+ { name: "AES-GCM", iv, additionalData: bound(userId, recordId) },
586
+ await accountKey(cfg, env, userId),
587
+ enc.encode(json2)
588
+ );
589
+ return `${VERSION}.${b64url2(iv)}.${b64url2(new Uint8Array(ct))}`;
590
+ }
591
+ async function open(cfg, env, userId, recordId, stored) {
592
+ if (!isSealed(stored)) throw new Error("not sealed");
593
+ const [, iv, ct] = stored.split(".");
594
+ const pt = await crypto.subtle.decrypt(
595
+ {
596
+ name: "AES-GCM",
597
+ iv: fromB64(iv),
598
+ additionalData: bound(userId, recordId)
599
+ },
600
+ await accountKey(cfg, env, userId),
601
+ fromB64(ct)
602
+ );
603
+ return dec.decode(pt);
604
+ }
605
+ async function openRows(cfg, env, userId, rows) {
606
+ if (rows.length) await masterKey(env);
607
+ const opened = await Promise.all(
608
+ rows.map(async (r) => {
609
+ try {
610
+ return {
611
+ id: r.id,
612
+ data: JSON.parse(await open(cfg, env, userId, r.id, r.data))
613
+ };
614
+ } catch (e) {
615
+ console.error("record didn't open", userId, r.id, e.name);
616
+ return null;
617
+ }
618
+ })
619
+ );
620
+ return opened.filter((r) => r !== null);
621
+ }
622
+
623
+ // src/worker/sync.ts
624
+ var MAX_CHANGES = 500;
625
+ var MAX_RECORD_BYTES = 32e3;
626
+ var TOMBSTONE_DAYS = 180;
627
+ var ID = /^[\w-]{1,64}$/;
628
+ async function sync(cfg, req, env) {
629
+ const { user, account, plan, setCookie } = await requirePremium(
630
+ cfg,
631
+ req,
632
+ env
633
+ );
634
+ const body = await readJson(req);
635
+ const since = Number(body.since ?? 0);
636
+ if (!Number.isSafeInteger(since) || since < 0)
637
+ throw new HttpError(400, "Bad sync position");
638
+ const changes = parseChanges(body.changes);
639
+ const now = Date.now();
640
+ const sealed = await Promise.all(
641
+ changes.map(async (c) => ({
642
+ id: c.id,
643
+ stored: c.data ? await seal(cfg, env, user.id, c.id, JSON.stringify(c.data)) : null
644
+ }))
645
+ );
646
+ await checkLimits(cfg, env, user.id, sealed, now);
647
+ const n = changes.length;
648
+ const t = cfg.table;
649
+ const stmts = [
650
+ // the app's own extras (e.g. Kalendar remembers the timezone)
651
+ ...cfg.onSync?.({
652
+ body,
653
+ userId: user.id,
654
+ account,
655
+ env
656
+ }) ?? [],
657
+ env.DB.prepare("UPDATE users SET rev = rev + ? WHERE id = ?").bind(
658
+ n,
659
+ user.id
660
+ ),
661
+ // change i gets rev (new total - n + i + 1)
662
+ ...sealed.map(
663
+ (c, i) => env.DB.prepare(
664
+ `INSERT INTO ${t} (user_id, id, rev, data, updated_at)
665
+ VALUES (?1, ?2, (SELECT rev FROM users WHERE id = ?1) - ?3, ?4, ?5)
666
+ ON CONFLICT (user_id, id) DO UPDATE SET
667
+ rev = excluded.rev, data = excluded.data, updated_at = excluded.updated_at`
668
+ ).bind(user.id, c.id, n - i - 1, c.stored, now)
669
+ ),
670
+ env.DB.prepare("SELECT rev FROM users WHERE id = ?").bind(user.id),
671
+ env.DB.prepare(
672
+ `SELECT id, data FROM ${t} WHERE user_id = ? AND rev > ? ORDER BY rev`
673
+ ).bind(user.id, since)
674
+ ];
675
+ const results = await env.DB.batch(stmts);
676
+ const rev = results[results.length - 2].results[0].rev;
677
+ let rows = results[results.length - 1].results;
678
+ const reset = since > rev - n;
679
+ if (reset) {
680
+ const all = await env.DB.prepare(
681
+ `SELECT id, data FROM ${t} WHERE user_id = ? ORDER BY rev`
682
+ ).bind(user.id).all();
683
+ rows = all.results;
684
+ }
685
+ const pushed = new Set(changes.map((c) => c.id));
686
+ const pull = rows.filter((r) => !pushed.has(r.id));
687
+ const opened = new Map(
688
+ (await openRows(
689
+ cfg,
690
+ env,
691
+ user.id,
692
+ pull.filter((r) => r.data !== null)
693
+ )).map((r) => [r.id, r.data])
694
+ );
695
+ return withSession(
696
+ json({
697
+ plan,
698
+ rev,
699
+ reset,
700
+ changes: pull.filter((r) => r.data === null || opened.has(r.id)).map((r) => ({ id: r.id, data: opened.get(r.id) ?? null }))
701
+ }),
702
+ setCookie
703
+ );
704
+ }
705
+ async function checkLimits(cfg, env, userId, changes, now) {
706
+ if (!changes.length) return;
707
+ const ids = JSON.stringify(changes.map((c) => c.id));
708
+ const sizes = changes.map((c) => c.stored?.length ?? 0);
709
+ const usage = async () => {
710
+ const u2 = await env.DB.prepare(
711
+ `SELECT
712
+ COUNT(*) AS rows, COUNT(data) AS records,
713
+ COALESCE(SUM(LENGTH(data)), 0) AS size,
714
+ (SELECT COUNT(*) FROM ${cfg.table} WHERE user_id = ?1 AND id IN (SELECT value FROM json_each(?2))) AS had_rows,
715
+ (SELECT COUNT(data) FROM ${cfg.table} WHERE user_id = ?1 AND id IN (SELECT value FROM json_each(?2))) AS had_records,
716
+ (SELECT COALESCE(SUM(LENGTH(data)), 0) FROM ${cfg.table} WHERE user_id = ?1 AND id IN (SELECT value FROM json_each(?2))) AS had_size
717
+ FROM ${cfg.table} WHERE user_id = ?1 AND id NOT IN (SELECT value FROM json_each(?2))`
718
+ ).bind(userId, ids).first();
719
+ if (!u2) throw new Error("usage query returned nothing");
720
+ const before = {
721
+ rows: u2.rows + u2.had_rows,
722
+ records: u2.records + u2.had_records,
723
+ size: u2.size + u2.had_size
724
+ };
725
+ const after = {
726
+ rows: u2.rows + changes.length,
727
+ records: u2.records + sizes.filter((n) => n > 0).length,
728
+ size: u2.size + sizes.reduce((a, b) => a + b, 0)
729
+ };
730
+ return { before, after };
731
+ };
732
+ const over = ({ before, after }) => Object.keys(cfg.limits).find(
733
+ (k) => after[k] > cfg.limits[k] && after[k] > before[k]
734
+ );
735
+ let u = await usage();
736
+ if (over(u) === "rows") {
737
+ await env.DB.prepare(
738
+ `DELETE FROM ${cfg.table} WHERE user_id = ? AND data IS NULL AND updated_at < ?`
739
+ ).bind(userId, now - TOMBSTONE_DAYS * 864e5).run();
740
+ u = await usage();
741
+ }
742
+ const limit = over(u);
743
+ if (limit)
744
+ throw new HttpError(
745
+ 413,
746
+ limit === "size" ? `Your ${cfg.words.data} has reached its size limit. Delete some ${cfg.words.records} or shorten long notes to keep syncing.` : `Your ${cfg.words.data} has reached its limit of ${cfg.limits.records.toLocaleString("en-US")} ${cfg.words.records}. Delete some to keep syncing.`
747
+ );
748
+ }
749
+ function parseChanges(v) {
750
+ if (v === void 0) return [];
751
+ if (!Array.isArray(v)) throw new HttpError(400, "Bad changes");
752
+ if (v.length > MAX_CHANGES)
753
+ throw new HttpError(413, "Too many changes at once");
754
+ const seen = /* @__PURE__ */ new Set();
755
+ return v.map((c) => {
756
+ const id = c?.id;
757
+ const data = c?.data ?? null;
758
+ if (typeof id !== "string" || !ID.test(id) || seen.has(id))
759
+ throw new HttpError(400, "Bad record id");
760
+ seen.add(id);
761
+ if (data !== null) {
762
+ if (typeof data !== "object" || Array.isArray(data) || data.id !== id)
763
+ throw new HttpError(400, "Bad record");
764
+ if (JSON.stringify(data).length > MAX_RECORD_BYTES)
765
+ throw new HttpError(413, "A record is too large");
766
+ }
767
+ return { id, data };
768
+ });
769
+ }
770
+
771
+ // src/worker/index.ts
772
+ function kim(config) {
773
+ if (!/^\w+$/.test(config.table))
774
+ throw new Error("kim: table must be a plain table name");
775
+ if (!/^[a-z0-9-]+$/.test(config.slug))
776
+ throw new Error("kim: slug must be lowercase letters, digits or -");
777
+ const cfg = config;
778
+ const routes = {
779
+ "GET /api/auth/config": authConfig,
780
+ "POST /api/auth/code": (req, env) => requestCode(cfg, req, env),
781
+ "POST /api/auth/verify": (req, env) => verifyCode(cfg, req, env),
782
+ "POST /api/auth/logout": (req, env) => logout(cfg, req, env),
783
+ "GET /api/auth/me": (req, env) => me(cfg, req, env),
784
+ "POST /api/sync": (req, env) => sync(cfg, req, env),
785
+ "POST /api/account/delete": (req, env) => deleteAccount(cfg, req, env),
786
+ "POST /api/stripe/webhook": stripeWebhook
787
+ };
788
+ return {
789
+ /** the account routes, keyed "METHOD /path" */
790
+ routes,
791
+ /** The signed-in user, or a 401. Pass `setCookie` on with `withSession`. */
792
+ requireUser: (req, env) => requireUser(cfg, req, env),
793
+ /** The signed-in user with Premium, or a 401 / 402. */
794
+ requirePremium: (req, env) => requirePremium(cfg, req, env),
795
+ /** Throws the 402 that explains Premium is needed. */
796
+ needPremium: (plan) => needPremium(cfg, plan),
797
+ planOf: (account, env, now) => planOf(cfg, account, env, now),
798
+ /** SELECT … FROM users u LEFT JOIN subscriptions s: add a WHERE on u */
799
+ accountSelect: accountSelect(cfg),
800
+ withSession,
801
+ clearCookie: (env) => clearCookie(cfg, env),
802
+ /**
803
+ * Decrypts the app's own reads of its records table. A row that won't
804
+ * open is left out and logged.
805
+ */
806
+ openRows: (env, userId, rows) => openRows(cfg, env, userId, rows),
807
+ /** per-account limits, live (tests may lower them) */
808
+ limits: cfg.limits
809
+ };
810
+ }
811
+ async function handle(routes, req, env) {
812
+ const { pathname } = new URL(req.url);
813
+ try {
814
+ const handler = routes[`${req.method} ${pathname}`];
815
+ if (!handler) return json({ error: "Not found" }, 404);
816
+ checkOrigin(req, env);
817
+ return await handler(req, env);
818
+ } catch (e) {
819
+ if (e instanceof HttpError)
820
+ return json({ error: e.message, ...e.data }, e.status, e.headers);
821
+ console.error(e);
822
+ return json({ error: "Something went wrong" }, 500);
823
+ }
824
+ }
825
+ export {
826
+ GRACE,
827
+ HttpError,
828
+ PAID_SQL,
829
+ PAID_STATUSES,
830
+ TRIAL_DAYS,
831
+ checkOrigin,
832
+ equal,
833
+ handle,
834
+ isDev,
835
+ json,
836
+ kim,
837
+ network,
838
+ randomCode,
839
+ randomToken,
840
+ readJson,
841
+ sha256
842
+ };
package/package.json CHANGED
@@ -1,6 +1,51 @@
1
1
  {
2
- "name": "@keslers/kim",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
2
+ "name": "@keslers/kim",
3
+ "version": "0.1.0",
4
+ "description": "Passwordless sign-in, Premium plans, Stripe and encrypted sync for Cloudflare Workers apps",
5
+ "keywords": [
6
+ "cloudflare-workers",
7
+ "d1",
8
+ "auth",
9
+ "stripe",
10
+ "sync"
11
+ ],
12
+ "homepage": "https://gitlab.com/keslers/kim#readme",
13
+ "bugs": {
14
+ "url": "https://gitlab.com/keslers/kim/-/issues"
15
+ },
16
+ "repository": {
17
+ "type": "git",
18
+ "url": "git+https://gitlab.com/keslers/kim.git"
19
+ },
20
+ "license": "ISC",
21
+ "author": "Christian 'CJ' Kesler, Kesler Technologies",
22
+ "type": "module",
23
+ "exports": {
24
+ "./worker": {
25
+ "types": "./dist/worker/index.d.ts",
26
+ "import": "./dist/worker/index.js"
27
+ },
28
+ "./client": {
29
+ "types": "./dist/client.d.ts",
30
+ "import": "./dist/client.js"
31
+ },
32
+ "./schema.sql": "./schema.sql"
33
+ },
34
+ "files": [
35
+ "dist",
36
+ "schema.sql"
37
+ ],
38
+ "scripts": {
39
+ "build": "tsup",
40
+ "check": "tsc --noEmit && biome check src tsup.config.ts"
41
+ },
42
+ "devDependencies": {
43
+ "@biomejs/biome": "^2.6.8",
44
+ "@cloudflare/workers-types": "^4",
45
+ "tsup": "^8",
46
+ "typescript": "~5.9.3"
47
+ },
48
+ "publishConfig": {
49
+ "access": "public"
50
+ }
51
+ }
package/schema.sql ADDED
@@ -0,0 +1,69 @@
1
+ -- The tables @keslers/kim uses. Copy this into the app's first D1
2
+ -- migration. Rename `records` to match Config.table. Apps may add their own
3
+ -- columns to `users` (see Config.account).
4
+
5
+ CREATE TABLE users (
6
+ id TEXT PRIMARY KEY,
7
+ email TEXT NOT NULL UNIQUE,
8
+ created_at INTEGER NOT NULL,
9
+ -- bumped once per synced change; clients pull "everything after rev N"
10
+ rev INTEGER NOT NULL DEFAULT 0,
11
+ -- every account gets a Premium trial from its first sign-in
12
+ trial_until INTEGER,
13
+ -- Premium on the house (the owner, friends): set by hand
14
+ comp INTEGER NOT NULL DEFAULT 0,
15
+ stripe_customer TEXT
16
+ );
17
+ CREATE INDEX users_stripe_customer ON users (stripe_customer);
18
+
19
+ -- One pending sign-in code per email (only its hash is kept).
20
+ CREATE TABLE login_codes (
21
+ email TEXT PRIMARY KEY,
22
+ code_hash TEXT NOT NULL,
23
+ expires_at INTEGER NOT NULL,
24
+ attempts INTEGER NOT NULL DEFAULT 0
25
+ );
26
+
27
+ -- Recent code requests, for rate limits and the daily email cap.
28
+ CREATE TABLE code_requests (
29
+ email TEXT NOT NULL,
30
+ ip TEXT NOT NULL,
31
+ at INTEGER NOT NULL
32
+ );
33
+ CREATE INDEX code_requests_at ON code_requests (at);
34
+
35
+ CREATE TABLE sessions (
36
+ token_hash TEXT PRIMARY KEY,
37
+ user_id TEXT NOT NULL REFERENCES users (id) ON DELETE CASCADE,
38
+ created_at INTEGER NOT NULL,
39
+ expires_at INTEGER NOT NULL
40
+ );
41
+ CREATE INDEX sessions_user ON sessions (user_id);
42
+
43
+ -- One synced record as the client stores it, encrypted (vault.ts).
44
+ -- Deleted records stay as tombstones (data NULL) so the deletion reaches
45
+ -- other devices.
46
+ CREATE TABLE records (
47
+ user_id TEXT NOT NULL REFERENCES users (id) ON DELETE CASCADE,
48
+ id TEXT NOT NULL,
49
+ rev INTEGER NOT NULL,
50
+ data TEXT,
51
+ updated_at INTEGER NOT NULL,
52
+ PRIMARY KEY (user_id, id)
53
+ );
54
+ CREATE INDEX records_rev ON records (user_id, rev);
55
+
56
+ -- Subscription state as Stripe reports it, by Stripe customer. Webhooks can
57
+ -- arrive in any order, so this doesn't depend on the user link existing yet.
58
+ CREATE TABLE subscriptions (
59
+ customer TEXT PRIMARY KEY,
60
+ subscription TEXT,
61
+ status TEXT NOT NULL,
62
+ period_end INTEGER,
63
+ -- canceled, but paid up until period_end
64
+ cancel_at_end INTEGER NOT NULL DEFAULT 0,
65
+ updated_at INTEGER NOT NULL,
66
+ -- when Stripe created the event this row came from (seconds), so a
67
+ -- late-delivered older event can't overwrite a newer one
68
+ event_at INTEGER NOT NULL DEFAULT 0
69
+ );