@mccaskie-labs/workbench-plans 0.0.0-stage → 0.1.1

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/dist/plans.js ADDED
@@ -0,0 +1,200 @@
1
+ // createPlans: each account's plan, switches and monthly allowances in the
2
+ // app's own database (plansMigration), checked against the repo's
3
+ // workbench/plans.json. Use it with the service client, server side: the
4
+ // functions are the service role's only (see migration.ts).
5
+ import { checkPlans, planFeatures, plansWith, upgradeFrom } from "./config.js";
6
+ import { PlansError } from "./errors.js";
7
+ import { periodOf, resetsAt } from "./period.js";
8
+ const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
9
+ function failed(what, error) {
10
+ const m = error?.message ?? "";
11
+ if (m.includes("plans_unknown_account"))
12
+ throw new PlansError("unknown_account", `${what}: no such account; sign it up first (createSignup().check)`);
13
+ if (m.includes("plans_account_exists"))
14
+ throw new PlansError("account_exists", `${what}: the account is already signed up`);
15
+ if (m.includes("plans_not_on_plan"))
16
+ throw new PlansError("not_on_plan", `${what}: the account's plan (${error?.details ?? "?"}) doesn't include it; use setPlan or grant`);
17
+ throw new PlansError("store_failed", `${what}: ${m || "no answer"}${error?.code ? ` (${error.code})` : ""}`);
18
+ }
19
+ export async function call(db, what, fn, args) {
20
+ const { data, error } = await db.rpc(fn, args);
21
+ if (error)
22
+ failed(what, error);
23
+ return data;
24
+ }
25
+ function text(v, what, max) {
26
+ if (typeof v !== "string" || !v.trim() || v.length > max)
27
+ throw new PlansError("bad_input", `${what} must be text, 1 to ${max} characters`);
28
+ return v;
29
+ }
30
+ export function createPlans(opts) {
31
+ const config = checkPlans(opts.plans);
32
+ const db = opts.db;
33
+ const now = opts.now ?? (() => new Date());
34
+ const tz = config.time_zone;
35
+ // With sign-up checks on, an account must come through them; without, the first use opens it on the default plan.
36
+ const create = !(config.signup?.checks.length);
37
+ const account = (a) => text(a, "account", 100);
38
+ const meterOf = (m) => {
39
+ if (typeof m !== "string" || !Object.hasOwn(config.meters, m))
40
+ throw new PlansError("bad_input", `unknown meter ${JSON.stringify(m)}`);
41
+ return m;
42
+ };
43
+ const featureOf = (f) => {
44
+ if (typeof f !== "string" || !config.features.includes(f))
45
+ throw new PlansError("bad_input", `unknown feature ${JSON.stringify(f)}`);
46
+ return f;
47
+ };
48
+ const allowance = (plan, meter) => config.plans[plan]?.meters[meter] ?? 0;
49
+ function refusal(reason, plan, opts) {
50
+ const out = { ok: false, reason };
51
+ if (reason === "allowance_used") {
52
+ out.resets_at = resetsAt(periodOf(now(), tz), tz);
53
+ if (opts.limit !== undefined)
54
+ out.limit = opts.limit;
55
+ }
56
+ if (reason === "not_on_plan" || reason === "allowance_used") {
57
+ const up = upgradeFrom(config, plan, (k) => {
58
+ if (opts.feature && !planFeatures(config, k).includes(opts.feature))
59
+ return false;
60
+ if (opts.meter && allowance(k, opts.meter) <= allowance(plan, opts.meter))
61
+ return false;
62
+ return true;
63
+ });
64
+ if (up)
65
+ out.upgrade_to = up;
66
+ }
67
+ return out;
68
+ }
69
+ async function status(a) {
70
+ const id = account(a);
71
+ const at = now();
72
+ const period = periodOf(at, tz);
73
+ const meters = Object.keys(config.meters);
74
+ const s = await call(db, "status", "plans_status", {
75
+ p_account: id,
76
+ p_meters: meters,
77
+ p_period: period,
78
+ p_now: at.toISOString(),
79
+ });
80
+ if (!s && !create)
81
+ throw new PlansError("unknown_account", `status: no such account ${JSON.stringify(id)}; sign it up first`);
82
+ const row = s?.account ?? { plan: config.default_plan, status: "active", switches: {}, hold_matches: [] };
83
+ const plan = String(row.plan);
84
+ const switches = (row.switches ?? {});
85
+ const has = planFeatures(config, plan);
86
+ const features = {};
87
+ for (const f of config.features)
88
+ features[f] = !has.includes(f) ? "not_on_plan" : switches[f] === false ? "switched_off" : "on";
89
+ const meterStatus = meters.map((m) => {
90
+ const c = s?.meters[m] ?? { used: 0, granted: 0 };
91
+ const limit = allowance(plan, m) + c.granted;
92
+ return { meter: m, label: config.meters[m].label, unit: config.meters[m].unit, used: c.used, limit, granted: c.granted, left: Math.max(limit - c.used, 0) };
93
+ });
94
+ return {
95
+ account: id,
96
+ plan,
97
+ plan_label: config.plans[plan]?.label ?? plan,
98
+ status: row.status === "held" ? "held" : "active",
99
+ features,
100
+ meters: meterStatus,
101
+ period,
102
+ resets_at: resetsAt(period, tz),
103
+ hold_matches: (row.hold_matches ?? []),
104
+ };
105
+ }
106
+ return {
107
+ async can(a, feature) {
108
+ const f = featureOf(feature);
109
+ const s = await status(a);
110
+ const state = s.features[f];
111
+ if (state === "on")
112
+ return { ok: true };
113
+ return refusal(state === "switched_off" ? "switched_off" : "not_on_plan", s.plan, { feature: f });
114
+ },
115
+ async use(a, meter, req = {}) {
116
+ const id = account(a);
117
+ const m = meterOf(meter);
118
+ const amount = req.amount ?? 1;
119
+ if (!Number.isInteger(amount) || amount < 1 || amount > 1_000_000)
120
+ throw new PlansError("bad_input", "amount must be a whole number, 1 or more");
121
+ const subject = req.subject === undefined ? null : text(req.subject, "subject", 200);
122
+ const key = req.idempotencyKey === undefined ? null : text(req.idempotencyKey, "idempotencyKey", 200);
123
+ const limits = {};
124
+ for (const p of Object.keys(config.plans))
125
+ limits[p] = allowance(p, m);
126
+ const at = now();
127
+ const r = await call(db, "use", "plans_use", {
128
+ p_account: id,
129
+ p_meter: m,
130
+ p_period: periodOf(at, tz),
131
+ p_limits: limits,
132
+ p_switchable: config.features.includes(m),
133
+ p_default_plan: config.default_plan,
134
+ p_create: create,
135
+ p_amount: amount,
136
+ p_subject: subject,
137
+ p_key: key,
138
+ p_now: at.toISOString(),
139
+ });
140
+ if (r.ok)
141
+ return { ok: true, useId: r.use_id, left: r.left };
142
+ return refusal(r.reason, r.plan, { meter: m, ...(r.limit !== undefined ? { limit: r.limit } : {}) });
143
+ },
144
+ async release(useId) {
145
+ if (typeof useId !== "string" || !UUID.test(useId))
146
+ throw new PlansError("bad_input", "release needs the useId use() returned");
147
+ await call(db, "release", "plans_release", { p_use: useId, p_now: now().toISOString() });
148
+ },
149
+ status,
150
+ async setPlan(a, plan, by, reason) {
151
+ if (typeof plan !== "string" || !Object.hasOwn(config.plans, plan))
152
+ throw new PlansError("bad_input", `unknown plan ${JSON.stringify(plan)}`);
153
+ await call(db, "setPlan", "plans_set_plan", { p_account: account(a), p_plan: plan, p_by: text(by, "by", 200), p_reason: text(reason, "reason", 500) });
154
+ },
155
+ async setSwitch(a, feature, on, by, reason) {
156
+ const f = featureOf(feature);
157
+ if (typeof on !== "boolean")
158
+ throw new PlansError("bad_input", "on must be true or false");
159
+ await call(db, "setSwitch", "plans_set_switch", {
160
+ p_account: account(a),
161
+ p_feature: f,
162
+ p_on: on,
163
+ p_feature_plans: plansWith(config, f),
164
+ p_default_plan: config.default_plan,
165
+ p_create: create,
166
+ p_by: text(by, "by", 200),
167
+ p_reason: text(reason, "reason", 500),
168
+ });
169
+ },
170
+ async grant(a, meter, extra, until, by, reason) {
171
+ const m = meterOf(meter);
172
+ if (!Number.isInteger(extra) || extra < 1 || extra > 1_000_000)
173
+ throw new PlansError("bad_input", "extra must be a whole number, 1 or more");
174
+ const end = Date.parse(until);
175
+ if (typeof until !== "string" || Number.isNaN(end))
176
+ throw new PlansError("bad_input", "until must be a date and time (ISO 8601)");
177
+ if (end <= now().getTime())
178
+ throw new PlansError("bad_input", "until must be in the future");
179
+ await call(db, "grant", "plans_grant", {
180
+ p_account: account(a),
181
+ p_meter: m,
182
+ p_extra: extra,
183
+ p_until: new Date(end).toISOString(),
184
+ p_default_plan: config.default_plan,
185
+ p_create: create,
186
+ p_by: text(by, "by", 200),
187
+ p_reason: text(reason, "reason", 500),
188
+ });
189
+ },
190
+ async clearHold(a, by, reason) {
191
+ return (await call(db, "clearHold", "plans_clear_hold", { p_account: account(a), p_by: text(by, "by", 200), p_reason: text(reason, "reason", 500) })) === true;
192
+ },
193
+ async held() {
194
+ return (await call(db, "held", "plans_held", {})) ?? [];
195
+ },
196
+ async cleanup() {
197
+ return await call(db, "cleanup", "plans_cleanup", { p_now: now().toISOString() });
198
+ },
199
+ };
200
+ }
@@ -0,0 +1,80 @@
1
+ import { type PlansClient } from "./plans.ts";
2
+ import type { HoldMatch, PlansConfig } from "./types.ts";
3
+ export { PlansError } from "./errors.ts";
4
+ /** HMAC-SHA-256 of `kind:value` with the project's secret, as hex. */
5
+ export declare function signalHash(secret: string, kind: string, value: string): Promise<string>;
6
+ /**
7
+ * An email address folded for comparing: lower case, a `+tag` dropped, and
8
+ * for Gmail the dots dropped and googlemail.com read as gmail.com. Null when
9
+ * it isn't an address.
10
+ */
11
+ export declare function foldEmail(email: string): string | null;
12
+ /**
13
+ * A Facebook Page address folded to `facebook.com/<name or id>`, whatever
14
+ * form it was typed in (fb.com/villasol, https://www.facebook.com/villasol/,
15
+ * m.facebook.com/villasol?ref=…, @villasol, profile.php?id=…). Null when it
16
+ * isn't a Page address. Never fetched: this is matching only.
17
+ */
18
+ export declare function foldPage(input: string): string | null;
19
+ /** A business name with its city, folded: no accents, punctuation, case or filler words. Null when either is empty. */
20
+ export declare function foldBusiness(name: string, city: string): string | null;
21
+ /**
22
+ * A phone number as +<country><number>. Philippine forms (0917 123 4567,
23
+ * +63 917 123 4567, 63-917-123-4567, 917 123 4567) all fold to
24
+ * +639171234567; another country's needs its + and code. Null when it isn't
25
+ * a number.
26
+ */
27
+ export declare function foldPhone(input: string, country?: string): string | null;
28
+ /** The network a request came from: IPv4 to its /24, IPv6 to its /48. Used only inside a daily hash, never stored. */
29
+ export declare function networkOf(ip: string): string | null;
30
+ export declare const DEVICE_COOKIE = "wb_device";
31
+ /**
32
+ * The device id from the request's `wb_device` cookie, or a new one with the
33
+ * Set-Cookie header to send back. A first-party random id: the app's privacy
34
+ * notice must say it keeps one to stop repeat free sign-ups.
35
+ */
36
+ export declare function deviceCookie(request: Request): {
37
+ id: string;
38
+ setCookie?: string;
39
+ };
40
+ /** What the sign-up form and the app's own checks give. */
41
+ export interface SignupInput {
42
+ /** The new account's id (the app's own, such as the venue's id). */
43
+ account: string;
44
+ /** The signed-in address. Needed by email_code. */
45
+ email?: string;
46
+ /** True once the person signed in with the code sent to `email`. */
47
+ emailVerified?: boolean;
48
+ /** True once the app verified the form's Turnstile token. */
49
+ turnstile?: boolean;
50
+ /** The Facebook Page address the business typed. */
51
+ page?: string;
52
+ businessName?: string;
53
+ city?: string;
54
+ phone?: string;
55
+ /** From deviceCookie(request). Needed by device_signal. */
56
+ deviceId?: string;
57
+ /** request.headers.get('cf-connecting-ip'): hashed with the day and the browser, never stored. */
58
+ ip?: string;
59
+ userAgent?: string;
60
+ }
61
+ export interface SignupResult {
62
+ /** active: signed up; held: signed up but use() answers account_held until the admin clears it; refused: not signed up (repeats "refuse"). */
63
+ status: "active" | "held" | "refused";
64
+ matches: HoldMatch[];
65
+ }
66
+ export interface SignupOptions {
67
+ /** Use the service client. */
68
+ db: PlansClient;
69
+ plans: PlansConfig;
70
+ /** PLANS_SIGNAL_SECRET: at least 32 random characters, a Worker secret. Changing it stops old signals matching. */
71
+ secret: string;
72
+ /** The country phone numbers are read in, default PH. */
73
+ country?: string;
74
+ now?: () => Date;
75
+ }
76
+ export interface Signup {
77
+ /** Runs the project's checks and opens the account on the default plan: active, held, or refused. */
78
+ check(input: SignupInput): Promise<SignupResult>;
79
+ }
80
+ export declare function createSignup(opts: SignupOptions): Signup;
package/dist/signup.js ADDED
@@ -0,0 +1,238 @@
1
+ // '@mccaskie-labs/workbench-plans/signup': the checks against repeat free
2
+ // sign-ups (docs/capabilities/06-plans-limits.md, "Abuse controls"). Each one
3
+ // raises the cost of a fake account; none is proof, so a sign-up that looks
4
+ // like a repeat is held for the app's admin to check, not refused (unless
5
+ // plans.json says `"repeats": "refuse"`).
6
+ //
7
+ // - email_code: the app signs the person in by emailed code first (the
8
+ // template's sign-in) and passes emailVerified. The address is folded
9
+ // (a+1@ and Gmail's dots) before it is compared.
10
+ // - turnstile: the app verifies the Turnstile token on its sign-up form
11
+ // (the template's lib/turnstile.ts) and passes turnstile: true.
12
+ // - business_identity: the Facebook Page address (typed, never looked up),
13
+ // the business name with its city, and the phone number, each folded; one
14
+ // free account per identity.
15
+ // - device_signal: a long-lived first-party random id in a cookie
16
+ // (deviceCookie); more than 2 sign-ups from one device in 30 days are
17
+ // repeats. A daily-keyed hash of the network (IP /24) and browser is kept
18
+ // too, never matched: the IP itself is never stored.
19
+ //
20
+ // Every value is stored only as an HMAC with the project's secret
21
+ // (PLANS_SIGNAL_SECRET, a Worker secret), so the table can match but not read.
22
+ import { checkPlans } from "./config.js";
23
+ import { PlansError } from "./errors.js";
24
+ import { call } from "./plans.js";
25
+ export { PlansError } from "./errors.js";
26
+ const enc = new TextEncoder();
27
+ /** HMAC-SHA-256 of `kind:value` with the project's secret, as hex. */
28
+ export async function signalHash(secret, kind, value) {
29
+ if (typeof secret !== "string" || secret.length < 32)
30
+ throw new PlansError("bad_input", "the signal secret must be at least 32 characters (PLANS_SIGNAL_SECRET)");
31
+ const key = await crypto.subtle.importKey("raw", enc.encode(secret), { name: "HMAC", hash: "SHA-256" }, false, ["sign"]);
32
+ const sig = await crypto.subtle.sign("HMAC", key, enc.encode(`${kind}:${value}`));
33
+ return [...new Uint8Array(sig)].map((b) => b.toString(16).padStart(2, "0")).join("");
34
+ }
35
+ /**
36
+ * An email address folded for comparing: lower case, a `+tag` dropped, and
37
+ * for Gmail the dots dropped and googlemail.com read as gmail.com. Null when
38
+ * it isn't an address.
39
+ */
40
+ export function foldEmail(email) {
41
+ const m = /^\s*([^@\s]+)@([^@\s]+\.[^@\s]+)\s*$/.exec(String(email ?? ""));
42
+ if (!m)
43
+ return null;
44
+ let local = m[1].toLowerCase();
45
+ let domain = m[2].toLowerCase().replace(/\.$/, "");
46
+ local = local.split("+")[0];
47
+ if (domain === "googlemail.com")
48
+ domain = "gmail.com";
49
+ if (domain === "gmail.com")
50
+ local = local.replace(/\./g, "");
51
+ if (!local)
52
+ return null;
53
+ return `${local}@${domain}`;
54
+ }
55
+ const FACEBOOK_HOSTS = /^(?:(?:www|m|web|mobile|business|touch|mbasic|l)\.)?(?:facebook\.com|fb\.com|fb\.me)$/;
56
+ /** Paths on facebook.com that aren't a Page's own name. */
57
+ const NOT_A_PAGE = new Set(["pages", "pg", "p", "people", "profile.php", "groups", "watch", "share", "sharer", "events", "marketplace", "permalink.php", "story.php", "photo.php", "home.php", "login", "help"]);
58
+ /**
59
+ * A Facebook Page address folded to `facebook.com/<name or id>`, whatever
60
+ * form it was typed in (fb.com/villasol, https://www.facebook.com/villasol/,
61
+ * m.facebook.com/villasol?ref=…, @villasol, profile.php?id=…). Null when it
62
+ * isn't a Page address. Never fetched: this is matching only.
63
+ */
64
+ export function foldPage(input) {
65
+ let s = String(input ?? "").trim();
66
+ if (!s)
67
+ return null;
68
+ if (/^@?[A-Za-z0-9.]{5,80}$/.test(s) && !s.includes("..") && !/\.(com|me|ph|net|org)$/i.test(s))
69
+ return `facebook.com/${s.replace(/^@/, "").replace(/\./g, "").toLowerCase()}`;
70
+ if (!/^[a-z]+:\/\//i.test(s))
71
+ s = `https://${s}`;
72
+ let url;
73
+ try {
74
+ url = new URL(s);
75
+ }
76
+ catch {
77
+ return null;
78
+ }
79
+ if (!FACEBOOK_HOSTS.test(url.hostname.toLowerCase()))
80
+ return null;
81
+ const parts = url.pathname.split("/").filter(Boolean).map((p) => decodeURIComponent(p));
82
+ const id = url.searchParams.get("id");
83
+ if ((parts[0] === "profile.php" || parts[0] === "people" || parts[0] === "p" || parts[0] === "pages" || parts[0] === "pg") && (id || parts.length > 1)) {
84
+ if (parts[0] === "profile.php")
85
+ return id && /^\d+$/.test(id) ? `facebook.com/${id}` : null;
86
+ if (parts[0] === "pg")
87
+ return parts[1] ? `facebook.com/${parts[1].replace(/\./g, "").toLowerCase()}` : null;
88
+ // pages/<Name>/<id>, people/<Name>/<id>, p/<Name>-<id>
89
+ const last = parts[parts.length - 1];
90
+ const num = /(\d{6,})$/.exec(last);
91
+ return num ? `facebook.com/${num[1]}` : null;
92
+ }
93
+ const name = parts[0];
94
+ if (!name || NOT_A_PAGE.has(name.toLowerCase()))
95
+ return null;
96
+ if (!/^[A-Za-z0-9.\-]{1,80}$/.test(name))
97
+ return null;
98
+ // Facebook ignores case and dots in a username.
99
+ return `facebook.com/${name.replace(/\./g, "").toLowerCase()}`;
100
+ }
101
+ /** Words that don't tell two businesses apart. */
102
+ const FILLER = new Set(["the", "and", "of", "inc", "corp", "co", "ltd", "llc", "opc", "ang", "ng", "sa", "at"]);
103
+ /** A business name with its city, folded: no accents, punctuation, case or filler words. Null when either is empty. */
104
+ export function foldBusiness(name, city) {
105
+ const fold = (s) => String(s ?? "")
106
+ .normalize("NFKD")
107
+ .replace(/[̀-ͯ]/g, "")
108
+ .toLowerCase()
109
+ .replace(/&/g, " and ")
110
+ .replace(/[^a-z0-9]+/g, " ")
111
+ .split(" ")
112
+ .filter((w) => w && !FILLER.has(w))
113
+ .join(" ");
114
+ const n = fold(name);
115
+ const c = fold(city).replace(/\bcity\b/g, "").trim();
116
+ return n && c ? `${n}|${c}` : null;
117
+ }
118
+ /**
119
+ * A phone number as +<country><number>. Philippine forms (0917 123 4567,
120
+ * +63 917 123 4567, 63-917-123-4567, 917 123 4567) all fold to
121
+ * +639171234567; another country's needs its + and code. Null when it isn't
122
+ * a number.
123
+ */
124
+ export function foldPhone(input, country = "PH") {
125
+ const raw = String(input ?? "").trim();
126
+ const digits = raw.replace(/[^\d]/g, "");
127
+ if (!digits)
128
+ return null;
129
+ if (country === "PH") {
130
+ let n = digits;
131
+ if (n.startsWith("63"))
132
+ n = n.slice(2);
133
+ else if (n.startsWith("0"))
134
+ n = n.slice(1);
135
+ if (/^9\d{9}$/.test(n) || /^[2-8]\d{7,9}$/.test(n))
136
+ return `+63${n}`;
137
+ if (!raw.startsWith("+"))
138
+ return null;
139
+ }
140
+ if (raw.startsWith("+") && /^\d{8,15}$/.test(digits))
141
+ return `+${digits}`;
142
+ return null;
143
+ }
144
+ /** The network a request came from: IPv4 to its /24, IPv6 to its /48. Used only inside a daily hash, never stored. */
145
+ export function networkOf(ip) {
146
+ const s = String(ip ?? "").trim();
147
+ const v4 = /^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/.exec(s);
148
+ if (v4)
149
+ return `${v4[1]}.${v4[2]}.${v4[3]}.0/24`;
150
+ if (s.includes(":")) {
151
+ const [head] = s.split("::");
152
+ const groups = (head ?? "").split(":").filter(Boolean);
153
+ while (groups.length < 3)
154
+ groups.push("0");
155
+ return `${groups.slice(0, 3).map((g) => g.toLowerCase()).join(":")}::/48`;
156
+ }
157
+ return null;
158
+ }
159
+ export const DEVICE_COOKIE = "wb_device";
160
+ /** 400 days, the most browsers keep a cookie. */
161
+ const DEVICE_MAX_AGE = 400 * 24 * 60 * 60;
162
+ const DEVICE_ID = /^[A-Za-z0-9_-]{22,64}$/;
163
+ /**
164
+ * The device id from the request's `wb_device` cookie, or a new one with the
165
+ * Set-Cookie header to send back. A first-party random id: the app's privacy
166
+ * notice must say it keeps one to stop repeat free sign-ups.
167
+ */
168
+ export function deviceCookie(request) {
169
+ const header = request.headers.get("cookie") ?? "";
170
+ for (const part of header.split(";")) {
171
+ const [k, ...v] = part.trim().split("=");
172
+ const value = v.join("=");
173
+ if (k === DEVICE_COOKIE && DEVICE_ID.test(value))
174
+ return { id: value };
175
+ }
176
+ const bytes = crypto.getRandomValues(new Uint8Array(18));
177
+ const id = btoa(String.fromCharCode(...bytes)).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
178
+ return { id, setCookie: `${DEVICE_COOKIE}=${id}; Max-Age=${DEVICE_MAX_AGE}; Path=/; HttpOnly; Secure; SameSite=Lax` };
179
+ }
180
+ export function createSignup(opts) {
181
+ const config = checkPlans(opts.plans);
182
+ const checks = config.signup?.checks ?? [];
183
+ const now = opts.now ?? (() => new Date());
184
+ const country = opts.country ?? "PH";
185
+ return {
186
+ async check(input) {
187
+ if (typeof input?.account !== "string" || !input.account.trim() || input.account.length > 100)
188
+ throw new PlansError("bad_input", "account must be text, 1 to 100 characters");
189
+ const signals = [];
190
+ const at = now();
191
+ if (checks.includes("email_code")) {
192
+ const email = foldEmail(input.email ?? "");
193
+ if (!email || input.emailVerified !== true)
194
+ throw new PlansError("check_missing", "email_code: sign the person in by emailed code first, then pass email and emailVerified: true");
195
+ signals.push({ kind: "email", value: email });
196
+ }
197
+ if (checks.includes("turnstile") && input.turnstile !== true)
198
+ throw new PlansError("check_missing", "turnstile: verify the form's Turnstile token first, then pass turnstile: true");
199
+ if (checks.includes("business_identity")) {
200
+ const page = input.page ? foldPage(input.page) : null;
201
+ if (input.page && !page)
202
+ throw new PlansError("bad_input", "page: that isn't a Facebook Page address");
203
+ const name = input.businessName || input.city ? foldBusiness(input.businessName ?? "", input.city ?? "") : null;
204
+ const phone = input.phone ? foldPhone(input.phone, country) : null;
205
+ if (input.phone && !phone)
206
+ throw new PlansError("bad_input", "phone: that isn't a phone number");
207
+ if (!page && !name && !phone)
208
+ throw new PlansError("check_missing", "business_identity: give at least one of page, businessName with city, or phone");
209
+ if (page)
210
+ signals.push({ kind: "page", value: page });
211
+ if (name)
212
+ signals.push({ kind: "name", value: name });
213
+ if (phone)
214
+ signals.push({ kind: "phone", value: phone });
215
+ }
216
+ if (checks.includes("device_signal")) {
217
+ if (!input.deviceId || !DEVICE_ID.test(input.deviceId))
218
+ throw new PlansError("check_missing", "device_signal: pass deviceId from deviceCookie(request)");
219
+ signals.push({ kind: "device", value: input.deviceId });
220
+ const net = input.ip ? networkOf(input.ip) : null;
221
+ if (net)
222
+ signals.push({ kind: "network", value: `${at.toISOString().slice(0, 10)}|${net}|${input.userAgent ?? ""}` });
223
+ }
224
+ const hashed = await Promise.all(signals.map(async (s) => ({ kind: s.kind, hash: await signalHash(opts.secret, s.kind, s.value) })));
225
+ const r = await call(opts.db, "signup", "plans_signup", {
226
+ p_account: input.account,
227
+ p_plan: config.default_plan,
228
+ p_signals: hashed,
229
+ p_per_identity: config.signup?.free_accounts_per_identity ?? 1,
230
+ p_device_max: config.signup?.device?.max ?? 2,
231
+ p_window_days: config.signup?.device?.window_days ?? 30,
232
+ p_refuse: config.signup?.repeats === "refuse",
233
+ p_now: at.toISOString(),
234
+ });
235
+ return { status: r.status, matches: r.matches ?? [] };
236
+ },
237
+ };
238
+ }
@@ -0,0 +1,33 @@
1
+ /** One CSS custom property the rules read, with its default. */
2
+ export interface StyleVariable {
3
+ /** `--wb-<tool>-<what>`. */
4
+ name: string;
5
+ value: string;
6
+ about: string;
7
+ }
8
+ /** A rule for a class in another state, or for an element inside it. */
9
+ export interface StyleState {
10
+ selector: string;
11
+ about: string;
12
+ css: string;
13
+ }
14
+ /** One class the tool puts on an element, with its default rule. */
15
+ export interface StyleClass {
16
+ name: string;
17
+ element: string;
18
+ about: string;
19
+ css: string;
20
+ states?: readonly StyleState[];
21
+ }
22
+ /** Every class and variable the tool draws with. */
23
+ export interface ToolStyles {
24
+ format: 1;
25
+ tool: string;
26
+ package: string;
27
+ title: string;
28
+ prefix: string;
29
+ variables: readonly StyleVariable[];
30
+ classes: readonly StyleClass[];
31
+ }
32
+ /** The style hooks of the usage card (renderUsage) and the limit and hold notices (renderLimit). */
33
+ export declare const PLAN_STYLES: ToolStyles;
package/dist/styles.js ADDED
@@ -0,0 +1,69 @@
1
+ // The look the usage card and notices start with (docs/capabilities-manifest.md §10).
2
+ // Every element renderUsage and renderLimit draw carries one of these
3
+ // classes, and every class has a default rule here, so the card looks
4
+ // finished out of the box and a project restyles it from its own CSS by the
5
+ // same names. `npx workbench-ui styles` writes these into the project's
6
+ // public/styles/workbench.css inside `@layer workbench`. The names are
7
+ // public: renaming one is a breaking change.
8
+ const v = (name) => `var(--wb-plan-${name})`;
9
+ /** The style hooks of the usage card (renderUsage) and the limit and hold notices (renderLimit). */
10
+ export const PLAN_STYLES = {
11
+ format: 1,
12
+ tool: "plans",
13
+ package: "@mccaskie-labs/workbench-plans",
14
+ title: "Plans and usage",
15
+ prefix: "wb-plan-",
16
+ variables: [
17
+ { name: "--wb-plan-text", value: "#e8e8ec", about: "Text: the plan's name, meter labels, notices" },
18
+ { name: "--wb-plan-muted", value: "#9a9aa6", about: "Quieter text: what's left, when it resets" },
19
+ { name: "--wb-plan-surface", value: "#1b1b1f", about: "Background of the card and the notices" },
20
+ { name: "--wb-plan-line", value: "#33333b", about: "Borders of the card and the notices" },
21
+ { name: "--wb-plan-track", value: "#2a2a31", about: "The empty part of a meter's bar" },
22
+ { name: "--wb-plan-fill", value: "#4c8dff", about: "The used part of a meter's bar" },
23
+ { name: "--wb-plan-full", value: "#d9822b", about: "A used-up meter's bar, and the limit notice's edge" },
24
+ { name: "--wb-plan-held", value: "#c9a227", about: "The edge of the \"we're checking your sign-up\" note" },
25
+ { name: "--wb-plan-accent", value: "#4c8dff", about: "The \"Switch to …\" link" },
26
+ { name: "--wb-plan-focus", value: "rgba(76,141,255,.4)", about: "The ring round the link when it has focus" },
27
+ { name: "--wb-plan-radius", value: "8px", about: "Corner rounding of the card, notices and bars" },
28
+ ],
29
+ classes: [
30
+ { name: "wb-plan-usage", element: "section", about: "The account's usage card", css: `max-width:28rem;padding:1rem;color:${v("text")};background:${v("surface")};border:1px solid ${v("line")};border-radius:${v("radius")}` },
31
+ { name: "wb-plan-title", element: "h2", about: "The plan's name", css: "margin:0 0 .75rem;font-size:1.125rem;font-weight:600" },
32
+ { name: "wb-plan-meter", element: "div", about: "One meter: its label, bar and what's left", css: "display:grid;grid-template-columns:1fr auto;gap:.25rem .75rem;align-items:center;margin:0 0 .75rem" },
33
+ { name: "wb-plan-meter-full", element: "div", about: "A meter with nothing left (added to wb-plan-meter)", css: `--wb-plan-fill:${v("full")}` },
34
+ { name: "wb-plan-meter-label", element: "span", about: "The meter's name, such as Messages read", css: "font-size:.95rem" },
35
+ {
36
+ name: "wb-plan-meter-bar",
37
+ element: "progress",
38
+ about: "How much of the allowance is used",
39
+ css: `grid-column:1 / -1;order:3;width:100%;height:.5rem;appearance:none;-webkit-appearance:none;border:0;border-radius:${v("radius")};background:${v("track")};overflow:hidden;accent-color:${v("fill")}`,
40
+ states: [
41
+ { selector: "::-webkit-progress-bar", about: "The track (WebKit)", css: `background:${v("track")};border-radius:${v("radius")}` },
42
+ { selector: "::-webkit-progress-value", about: "The used part (WebKit)", css: `background:${v("fill")};border-radius:${v("radius")}` },
43
+ { selector: "::-moz-progress-bar", about: "The used part (Firefox)", css: `background:${v("fill")};border-radius:${v("radius")}` },
44
+ ],
45
+ },
46
+ { name: "wb-plan-meter-left", element: "span", about: "\"18 of 30 left\" or \"All 30 used\"", css: `font-size:.85rem;color:${v("muted")};text-align:right` },
47
+ { name: "wb-plan-resets", element: "p", about: "When the allowance comes back", css: `margin:.25rem 0 0;font-size:.85rem;color:${v("muted")}` },
48
+ {
49
+ name: "wb-plan-limit",
50
+ element: "div",
51
+ about: "The notice when use() or can() says no",
52
+ css: `display:flex;flex-wrap:wrap;align-items:center;gap:.5rem 1rem;margin:.75rem 0;padding:.75rem 1rem;color:${v("text")};background:${v("surface")};border:1px solid ${v("line")};border-left:4px solid ${v("full")};border-radius:${v("radius")}`,
53
+ },
54
+ { name: "wb-plan-limit-text", element: "p", about: "What ran out and when it comes back", css: "margin:0;flex:1 1 16rem" },
55
+ {
56
+ name: "wb-plan-upgrade",
57
+ element: "a",
58
+ about: "Switch to the next plan",
59
+ css: `display:inline-flex;align-items:center;min-height:2.75rem;padding:0 1rem;font-weight:600;color:${v("accent")};text-decoration:none;border:1px solid ${v("accent")};border-radius:${v("radius")}`,
60
+ states: [{ selector: ":focus-visible", about: "Has focus", css: `outline:none;box-shadow:0 0 0 3px ${v("focus")}` }],
61
+ },
62
+ {
63
+ name: "wb-plan-held",
64
+ element: "p",
65
+ about: "\"We're checking your sign-up\": the account is held for review",
66
+ css: `margin:0 0 .75rem;padding:.6rem .8rem;color:${v("text")};background:${v("surface")};border:1px solid ${v("line")};border-left:4px solid ${v("held")};border-radius:${v("radius")};font-size:.95rem`,
67
+ },
68
+ ],
69
+ };