@usebecky/extension 0.0.0-stage → 0.2.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 +223 -2
- package/dist/accounts.d.ts +85 -0
- package/dist/accounts.js +149 -0
- package/dist/cli/index.d.ts +2 -0
- package/dist/cli/index.js +9 -0
- package/dist/cli/run.d.ts +25 -0
- package/dist/cli/run.js +330 -0
- package/dist/cli/skill.d.ts +16 -0
- package/dist/cli/skill.js +106 -0
- package/dist/crypto.d.ts +12 -0
- package/dist/crypto.js +56 -0
- package/dist/dev/pages.d.ts +155 -0
- package/dist/dev/pages.js +243 -0
- package/dist/dev/plans.d.ts +45 -0
- package/dist/dev/plans.js +135 -0
- package/dist/dev/samples.d.ts +61 -0
- package/dist/dev/samples.js +191 -0
- package/dist/dev/server.d.ts +120 -0
- package/dist/dev/server.js +1657 -0
- package/dist/dev/tagging.d.ts +16 -0
- package/dist/dev/tagging.js +81 -0
- package/dist/dev/ui-render.d.ts +25 -0
- package/dist/dev/ui-render.js +256 -0
- package/dist/dev/wordmark.d.ts +1 -0
- package/dist/dev/wordmark.js +2 -0
- package/dist/errors.d.ts +98 -0
- package/dist/errors.js +110 -0
- package/dist/events.d.ts +92 -0
- package/dist/events.js +54 -0
- package/dist/extension.d.ts +214 -0
- package/dist/extension.js +497 -0
- package/dist/handlers.d.ts +39 -0
- package/dist/handlers.js +113 -0
- package/dist/identity.d.ts +99 -0
- package/dist/identity.js +134 -0
- package/dist/index.d.ts +14 -0
- package/dist/index.js +17 -0
- package/dist/jwt.d.ts +62 -0
- package/dist/jwt.js +152 -0
- package/dist/manifest.d.ts +42 -0
- package/dist/manifest.js +785 -0
- package/dist/node.d.ts +10 -0
- package/dist/node.js +56 -0
- package/dist/pkce.d.ts +9 -0
- package/dist/pkce.js +16 -0
- package/dist/stores.d.ts +100 -0
- package/dist/stores.js +159 -0
- package/dist/types.d.ts +346 -0
- package/dist/types.js +70 -0
- package/dist/ui/handler.d.ts +66 -0
- package/dist/ui/handler.js +105 -0
- package/dist/ui/schema.d.ts +423 -0
- package/dist/ui/schema.js +666 -0
- package/dist/webhooks.d.ts +26 -0
- package/dist/webhooks.js +99 -0
- package/package.json +57 -4
- package/skill/usebecky-extension/SKILL.md +181 -0
- package/skill/usebecky-extension/references/accounts.md +125 -0
- package/skill/usebecky-extension/references/dev-server.md +102 -0
- package/skill/usebecky-extension/references/manifest.md +104 -0
- package/skill/usebecky-extension/references/oauth-and-tokens.md +179 -0
- package/skill/usebecky-extension/references/partner-api.md +87 -0
- package/skill/usebecky-extension/references/submit-and-pricing.md +31 -0
- package/skill/usebecky-extension/references/ui.md +172 -0
- package/skill/usebecky-extension/references/webhooks.md +97 -0
package/dist/types.d.ts
ADDED
|
@@ -0,0 +1,346 @@
|
|
|
1
|
+
import type { Plan } from './ui/schema.ts';
|
|
2
|
+
/** What an extension may read. Ask only for what it needs: customers see every scope on the consent screen. */
|
|
3
|
+
export type ExtensionScope = 'project:read' | 'analytics:read' | 'events:read';
|
|
4
|
+
export declare const EXTENSION_SCOPES: readonly ExtensionScope[];
|
|
5
|
+
/** What each scope means, in the words of usebecky's consent screen. */
|
|
6
|
+
export declare const EXTENSION_SCOPE_INFO: Readonly<Record<ExtensionScope, {
|
|
7
|
+
label: string;
|
|
8
|
+
description: string;
|
|
9
|
+
}>>;
|
|
10
|
+
export type ExtensionCategory = 'consent' | 'tags' | 'marketing' | 'support' | 'other';
|
|
11
|
+
export declare const EXTENSION_CATEGORIES: readonly ExtensionCategory[];
|
|
12
|
+
/**
|
|
13
|
+
* Product effects inside usebecky, set by usebecky only (never by the listing's developer), after review:
|
|
14
|
+
* `consent_banner` (usebecky's analytics follow the visitor's choice in the site's cookie banner) and
|
|
15
|
+
* `sgtm_forwarding` (usebecky's servers send sales, sign-ups and form leads to the customer's Google Tag Manager
|
|
16
|
+
* tagging server; an OAuth extension sets where with `ext.api(project).updateSettings()`).
|
|
17
|
+
*/
|
|
18
|
+
export type ExtensionCapability = 'consent_banner' | 'sgtm_forwarding';
|
|
19
|
+
export declare const EXTENSION_CAPABILITIES: readonly ExtensionCapability[];
|
|
20
|
+
export type ExtensionFieldType = 'text' | 'url' | 'secret' | 'boolean';
|
|
21
|
+
export declare const EXTENSION_FIELD_TYPES: readonly ExtensionFieldType[];
|
|
22
|
+
/**
|
|
23
|
+
* One setting the customer fills in when they install (`connect.mode: 'fields'`).
|
|
24
|
+
*
|
|
25
|
+
* - `text`, `url` (https only; usebecky never opens it) and `secret` (stored encrypted, never sent to you) are text.
|
|
26
|
+
* - `boolean` is a yes/no checkbox. Its value in `settings` is a JSON `true` or `false`, never a string; treat a
|
|
27
|
+
* missing key as `false`. `required: true` means it must be turned on (for example "I accept the terms").
|
|
28
|
+
* A boolean field has no `pattern` and no `placeholder`.
|
|
29
|
+
*/
|
|
30
|
+
export interface ExtensionField {
|
|
31
|
+
/** a-z, 0-9 and _, starting with a letter, at most 40 characters, unique in the listing. */
|
|
32
|
+
key: string;
|
|
33
|
+
label: string;
|
|
34
|
+
help?: string;
|
|
35
|
+
type: ExtensionFieldType;
|
|
36
|
+
required: boolean;
|
|
37
|
+
/** A regular expression (`u` flag) the value must match, at most 200 characters. Not for boolean fields. */
|
|
38
|
+
pattern?: string;
|
|
39
|
+
/** Not for boolean fields. */
|
|
40
|
+
placeholder?: string;
|
|
41
|
+
}
|
|
42
|
+
/** A setting's value: text for text, url and secret fields, true or false for boolean fields. */
|
|
43
|
+
export type ExtensionSettingValue = string | boolean;
|
|
44
|
+
/** The non-secret settings of an install (`GET /installation`, `extension.installed`), by field key. */
|
|
45
|
+
export type ExtensionSettings = Record<string, ExtensionSettingValue>;
|
|
46
|
+
/** One plan of a listing with pricing "plans". */
|
|
47
|
+
export interface ExtensionPricingPlan {
|
|
48
|
+
/** 1 to 30 characters a-z, 0-9 and dashes, unique: how your extension recognises the plan. Keep it when the price changes. */
|
|
49
|
+
id: string;
|
|
50
|
+
/** At most 30 characters, e.g. "Pro". */
|
|
51
|
+
name: string;
|
|
52
|
+
/** USD cents per project and month (before tax), 300 to 99900. */
|
|
53
|
+
amount: number;
|
|
54
|
+
/** One line for the store and the plan dialog, at most 80 characters, e.g. "250,000 requests a month". */
|
|
55
|
+
summary?: string;
|
|
56
|
+
}
|
|
57
|
+
/**
|
|
58
|
+
* - `free`: nothing to pay.
|
|
59
|
+
* - `monthly`: one price; your extension sees it as the plan "monthly".
|
|
60
|
+
* - `plans`: 2 to 6 plans; the customer picks one before checkout and can change it later on the extension's page
|
|
61
|
+
* (an upgrade takes effect right away, the difference charged at once; a downgrade at the end of the paid period).
|
|
62
|
+
* The free trial (0 to 30 days) is once per extension and project, not again after a plan change.
|
|
63
|
+
*/
|
|
64
|
+
export type ExtensionPricing = {
|
|
65
|
+
model: 'free';
|
|
66
|
+
} | {
|
|
67
|
+
model: 'monthly'; /** USD cents per project and month (before tax), 300 to 99900. */
|
|
68
|
+
amount: number; /** 0 to 30. */
|
|
69
|
+
trial_days: number;
|
|
70
|
+
} | {
|
|
71
|
+
model: 'plans'; /** 0 to 30. */
|
|
72
|
+
trial_days: number;
|
|
73
|
+
plans: ExtensionPricingPlan[];
|
|
74
|
+
};
|
|
75
|
+
export type ExtensionConnect = {
|
|
76
|
+
mode: 'oauth';
|
|
77
|
+
install_url: string;
|
|
78
|
+
redirect_uris: string[];
|
|
79
|
+
} | {
|
|
80
|
+
mode: 'fields';
|
|
81
|
+
fields: ExtensionField[];
|
|
82
|
+
};
|
|
83
|
+
/**
|
|
84
|
+
* An account at your service. Customers never sign up there by hand: if your service needs an account, usebecky creates
|
|
85
|
+
* it with you (provisioning) and opens it without a password (single sign-on). Leave it out (or `{ required: false }`)
|
|
86
|
+
* when no account is needed.
|
|
87
|
+
*
|
|
88
|
+
* - `provision: 'oauth'` (connect mode oauth): the token response carries an OpenID id_token with the customer's name and
|
|
89
|
+
* email; handleCallback() returns it as `identity`.
|
|
90
|
+
* - `provision: 'url'` (connect mode fields): usebecky POSTs a signed request to `provision_url` when the customer
|
|
91
|
+
* installs; answer with provisionHandler().
|
|
92
|
+
* - `sso_url`: "Open in <your service>" sends the customer to `sso_url?launch=<token>`; verify it with ssoHandler().
|
|
93
|
+
*/
|
|
94
|
+
export type ExtensionAccount = {
|
|
95
|
+
required: false;
|
|
96
|
+
} | {
|
|
97
|
+
required: true;
|
|
98
|
+
provision: 'oauth' | 'url';
|
|
99
|
+
/** provision 'url' only: https and a public host name (like webhook_url). */
|
|
100
|
+
provision_url?: string;
|
|
101
|
+
/** https (http://localhost while you test). */
|
|
102
|
+
sso_url: string;
|
|
103
|
+
/** Every team member may open it, not only owners and admins (default false). */
|
|
104
|
+
members_can_open?: boolean;
|
|
105
|
+
};
|
|
106
|
+
/** A store listing as usebecky keeps it. */
|
|
107
|
+
export interface ExtensionListing {
|
|
108
|
+
/** 3-40 characters a-z, 0-9 and single dashes; chosen when the extension is created, never changes. */
|
|
109
|
+
slug: string;
|
|
110
|
+
name: string;
|
|
111
|
+
publisher: {
|
|
112
|
+
name: string;
|
|
113
|
+
website: string;
|
|
114
|
+
email: string;
|
|
115
|
+
};
|
|
116
|
+
/** Uploaded in the Developer area (PNG, SVG or JPEG, at most 200 KB), served by usebecky as a PNG. */
|
|
117
|
+
logo_url: string;
|
|
118
|
+
/** One line, at most 90 characters. */
|
|
119
|
+
summary: string;
|
|
120
|
+
/** Markdown, at most 5000 characters. */
|
|
121
|
+
description: string;
|
|
122
|
+
category: ExtensionCategory;
|
|
123
|
+
pricing: ExtensionPricing;
|
|
124
|
+
links: {
|
|
125
|
+
privacy: string;
|
|
126
|
+
dpa?: string;
|
|
127
|
+
terms?: string;
|
|
128
|
+
support: string;
|
|
129
|
+
docs?: string;
|
|
130
|
+
};
|
|
131
|
+
connect: ExtensionConnect;
|
|
132
|
+
scopes: ExtensionScope[];
|
|
133
|
+
/** usebecky event types delivered to `webhook_url` (needs 'events:read'). */
|
|
134
|
+
events?: string[];
|
|
135
|
+
/** https, a public host name. Gets `events` plus extension.installed / extension.uninstalled. */
|
|
136
|
+
webhook_url?: string;
|
|
137
|
+
/** Set by usebecky only. */
|
|
138
|
+
capabilities?: ExtensionCapability[];
|
|
139
|
+
/** Plain-language list for the consent screen, e.g. "Purchases: amount, currency and product". */
|
|
140
|
+
data_shared: string[];
|
|
141
|
+
/** An account at your service: created automatically, opened with single sign-on. Absent: none needed. */
|
|
142
|
+
account?: ExtensionAccount;
|
|
143
|
+
/** Your own pages inside usebecky: sidebar rows and a settings view, drawn by usebecky from your blocks. */
|
|
144
|
+
ui?: ExtensionUi;
|
|
145
|
+
}
|
|
146
|
+
/**
|
|
147
|
+
* Pages inside usebecky (like a WordPress plugin's menu pages). usebecky POSTs a signed request to `url` whenever
|
|
148
|
+
* someone opens one and draws the blocks you answer with in its own design: see `uiHandler()`.
|
|
149
|
+
* - `pages`: at most 3 rows in the project's sidebar, in the group `section` (default "project").
|
|
150
|
+
* - `settings`: your view "settings" shows on your extension's page under Extensions.
|
|
151
|
+
*/
|
|
152
|
+
export interface ExtensionUi {
|
|
153
|
+
url: string;
|
|
154
|
+
pages?: ExtensionUiPage[];
|
|
155
|
+
settings?: boolean;
|
|
156
|
+
}
|
|
157
|
+
export interface ExtensionUiPage {
|
|
158
|
+
/** [a-z][a-z0-9-], at most 32; part of the page's address. "settings" is reserved. */
|
|
159
|
+
id: string;
|
|
160
|
+
/** The sidebar row's words, at most 24 characters. */
|
|
161
|
+
label: string;
|
|
162
|
+
section: 'backend' | 'website' | 'messages' | 'project';
|
|
163
|
+
}
|
|
164
|
+
/**
|
|
165
|
+
* The file `usebecky-extension.json`: the listing as the Developer area imports it ("Import usebecky-extension.json").
|
|
166
|
+
* `slug` must be the extension's id; `logo_url` names the logo file next to it (upload it under Store listing: the
|
|
167
|
+
* import never reads it); `$schema` and `capabilities` are ignored.
|
|
168
|
+
*/
|
|
169
|
+
export type { Plan, PlanStatus, NextPlan, PlanDiscount } from './ui/schema.ts';
|
|
170
|
+
export type ExtensionManifest = Omit<ExtensionListing, 'capabilities' | 'logo_url'> & {
|
|
171
|
+
$schema?: string;
|
|
172
|
+
logo_url?: string;
|
|
173
|
+
capabilities?: unknown;
|
|
174
|
+
};
|
|
175
|
+
/** usebecky's limits for a listing (packages/server/src/modules/extensions/listing.ts). */
|
|
176
|
+
export declare const LISTING_LIMITS: {
|
|
177
|
+
readonly nameMin: 2;
|
|
178
|
+
readonly name: 60;
|
|
179
|
+
readonly summary: 90;
|
|
180
|
+
readonly description: 5000;
|
|
181
|
+
readonly url: 2000;
|
|
182
|
+
readonly redirectUris: 10;
|
|
183
|
+
readonly fields: 20;
|
|
184
|
+
readonly fieldLabel: 80;
|
|
185
|
+
readonly fieldHelp: 300;
|
|
186
|
+
readonly fieldPlaceholder: 120;
|
|
187
|
+
readonly pattern: 200;
|
|
188
|
+
readonly dataShared: 20;
|
|
189
|
+
readonly dataSharedItem: 200;
|
|
190
|
+
/** US cents: 3 USD (the server's minimum). */
|
|
191
|
+
readonly priceMin: 300;
|
|
192
|
+
/** US cents: 999 USD. */
|
|
193
|
+
readonly priceMax: 99900;
|
|
194
|
+
readonly trialDaysMax: 30;
|
|
195
|
+
/** Pricing "plans": 2 to 6 plans, names of at most 30 characters, summaries of at most 80. */
|
|
196
|
+
readonly plansMin: 2;
|
|
197
|
+
readonly plansMax: 6;
|
|
198
|
+
readonly planName: 30;
|
|
199
|
+
readonly planSummary: 80;
|
|
200
|
+
/** A setting's value, in characters. */
|
|
201
|
+
readonly fieldValue: 2000;
|
|
202
|
+
/** Sidebar pages (ui.pages). */
|
|
203
|
+
readonly uiPages: 3;
|
|
204
|
+
/** A sidebar page's label. */
|
|
205
|
+
readonly uiLabel: 24;
|
|
206
|
+
};
|
|
207
|
+
/** Ids an extension can't have. */
|
|
208
|
+
export declare const RESERVED_SLUGS: readonly string[];
|
|
209
|
+
/** How usebecky's credentials, codes and tokens start. */
|
|
210
|
+
export declare const TOKEN_PREFIXES: {
|
|
211
|
+
readonly clientId: "ub_ci_";
|
|
212
|
+
readonly clientSecret: "ub_cs_";
|
|
213
|
+
readonly webhookSecret: "whsec_";
|
|
214
|
+
readonly authorizationCode: "ub_ac_";
|
|
215
|
+
readonly accessToken: "ub_it_";
|
|
216
|
+
readonly refreshToken: "ub_ir_";
|
|
217
|
+
};
|
|
218
|
+
/** Access tokens last an hour. */
|
|
219
|
+
export declare const ACCESS_TOKEN_TTL_SECONDS = 3600;
|
|
220
|
+
/** Refresh tokens last 90 days and are replaced on every refresh. */
|
|
221
|
+
export declare const REFRESH_TOKEN_TTL_DAYS = 90;
|
|
222
|
+
/** Authorization codes work once, within 10 minutes. */
|
|
223
|
+
export declare const AUTHORIZATION_CODE_TTL_SECONDS = 600;
|
|
224
|
+
/** Partner API requests per minute per installation (then 429 rate_limited with retry-after). */
|
|
225
|
+
export declare const PARTNER_RATE_LIMIT_PER_MINUTE = 300;
|
|
226
|
+
/** GET /extensions/v1/installation: the install the access token belongs to. Every token may call it. */
|
|
227
|
+
export interface Installation {
|
|
228
|
+
/** Install id (uuid). */
|
|
229
|
+
id: string;
|
|
230
|
+
/** The extension's slug. */
|
|
231
|
+
extension: string;
|
|
232
|
+
/** The customer's project. One install per project. `api_url` is its custom domain when it has one. */
|
|
233
|
+
project: {
|
|
234
|
+
ref: string;
|
|
235
|
+
name: string;
|
|
236
|
+
api_url: string;
|
|
237
|
+
};
|
|
238
|
+
/** What the customer allowed that your live listing still has. */
|
|
239
|
+
scopes: ExtensionScope[];
|
|
240
|
+
/**
|
|
241
|
+
* The usebecky event types this install receives (`[]` without 'events:read'): the ones the customer allowed. When
|
|
242
|
+
* your listing adds events, the customer allows them first; until then they are missing here and not delivered.
|
|
243
|
+
*/
|
|
244
|
+
events: string[];
|
|
245
|
+
/**
|
|
246
|
+
* The non-secret settings (fields mode). For oauth extensions `{}`, or the server-side tagging settings your server
|
|
247
|
+
* set with PUT /installation/settings (capability `sgtm_forwarding`).
|
|
248
|
+
*/
|
|
249
|
+
settings: ExtensionSettings;
|
|
250
|
+
/** ISO 8601. */
|
|
251
|
+
installed_at: string;
|
|
252
|
+
/**
|
|
253
|
+
* True when the install is in a test project (a developer's free project for trying extensions): its payments are
|
|
254
|
+
* simulated, so don't bill or count anything for it. Its webhook events carry `"test": true` too.
|
|
255
|
+
*/
|
|
256
|
+
test: boolean;
|
|
257
|
+
/**
|
|
258
|
+
* The install's price plan: what the customer pays for and whether it runs (trial, active, past due). Null for a free
|
|
259
|
+
* extension. A monthly listing's install has the plan "monthly". Changes arrive as extension.plan_changed.
|
|
260
|
+
*/
|
|
261
|
+
plan: Plan | null;
|
|
262
|
+
}
|
|
263
|
+
/**
|
|
264
|
+
* PUT /extensions/v1/installation/settings, for extensions usebecky gave the capability `sgtm_forwarding`: where
|
|
265
|
+
* usebecky's servers send the project's sales, sign-ups and form leads (GA4 hits on `<tagging_server_url>/g/collect`).
|
|
266
|
+
* Checked like the customer's settings form: `400 invalid_settings` in plain words.
|
|
267
|
+
*/
|
|
268
|
+
export interface TaggingSettings {
|
|
269
|
+
/** `https://` and a public host name (no IP address, port, query or credentials); a pasted `…/g/collect` and a trailing slash are trimmed. usebecky looks the name up and refuses one that points into a private network. */
|
|
270
|
+
tagging_server_url: string;
|
|
271
|
+
/** The GA4 measurement ID, `G-…` (any case: stored upper case). */
|
|
272
|
+
measurement_id: string;
|
|
273
|
+
/** Send the visitor's Google Analytics client ID with the hits of visitors who agreed, so they join the browser session. Default `false`. */
|
|
274
|
+
send_client_id?: boolean;
|
|
275
|
+
}
|
|
276
|
+
/** The answer of PUT and DELETE /extensions/v1/installation/settings: the install's settings now, as GET /installation shows them. */
|
|
277
|
+
export interface InstallationSettings {
|
|
278
|
+
settings: ExtensionSettings;
|
|
279
|
+
}
|
|
280
|
+
/** GET /extensions/v1/project (needs 'project:read'). Never the secret key, never database data. */
|
|
281
|
+
export interface Project {
|
|
282
|
+
ref: string;
|
|
283
|
+
name: string;
|
|
284
|
+
/** The project's API address (its custom domain when it has one). */
|
|
285
|
+
api_url: string;
|
|
286
|
+
/** `ub_pk_...`: safe in browsers, e.g. for a script on the customer's website. */
|
|
287
|
+
publishable_key: string;
|
|
288
|
+
/** Host names of the customer's websites (analytics settings), e.g. ["shop.example.com"]. May be empty. */
|
|
289
|
+
allowed_hosts: string[];
|
|
290
|
+
}
|
|
291
|
+
/**
|
|
292
|
+
* GET /extensions/v1/analytics/summary (needs 'analytics:read'). Totals only: no visitor ids, no rows.
|
|
293
|
+
* Channels are `direct`, `organic_search`, `social`, `email`, `paid` and `referral`.
|
|
294
|
+
*/
|
|
295
|
+
export interface AnalyticsSummary {
|
|
296
|
+
/** First day, YYYY-MM-DD (UTC, included). */
|
|
297
|
+
from: string;
|
|
298
|
+
/** Last day, YYYY-MM-DD (UTC, included). */
|
|
299
|
+
to: string;
|
|
300
|
+
visitors: number;
|
|
301
|
+
visits: number;
|
|
302
|
+
page_views: number;
|
|
303
|
+
conversions: number;
|
|
304
|
+
/** The 10 most viewed pages. */
|
|
305
|
+
top_pages: Array<{
|
|
306
|
+
path: string;
|
|
307
|
+
page_views: number;
|
|
308
|
+
visitors: number;
|
|
309
|
+
}>;
|
|
310
|
+
/** The 10 biggest channels. */
|
|
311
|
+
channels: Array<{
|
|
312
|
+
channel: string;
|
|
313
|
+
visitors: number;
|
|
314
|
+
visits: number;
|
|
315
|
+
}>;
|
|
316
|
+
/** Live-mode sales, in the smallest unit of `currency` (cents). */
|
|
317
|
+
revenue: {
|
|
318
|
+
currency: string;
|
|
319
|
+
total: number;
|
|
320
|
+
purchases: number;
|
|
321
|
+
by_channel: Array<{
|
|
322
|
+
channel: string;
|
|
323
|
+
revenue: number;
|
|
324
|
+
purchases: number;
|
|
325
|
+
}>;
|
|
326
|
+
};
|
|
327
|
+
}
|
|
328
|
+
/** POST /extensions/v1/oauth/token (RFC 6749), always with `cache-control: no-store`. */
|
|
329
|
+
export interface TokenResponse {
|
|
330
|
+
/** `ub_it_...`, one hour. */
|
|
331
|
+
access_token: string;
|
|
332
|
+
token_type: 'Bearer';
|
|
333
|
+
/** Seconds: 3600. */
|
|
334
|
+
expires_in: number;
|
|
335
|
+
/** `ub_ir_...`, 90 days. Every refresh returns a new one: store it, forget the old one. */
|
|
336
|
+
refresh_token: string;
|
|
337
|
+
/** The granted scopes, space-separated ("" for none). */
|
|
338
|
+
scope: string;
|
|
339
|
+
project_ref: string;
|
|
340
|
+
installation_id: string;
|
|
341
|
+
/**
|
|
342
|
+
* OpenID Connect id_token (listings with account.provision "oauth", authorization_code grant only): who allowed
|
|
343
|
+
* access. handleCallback() verifies it and returns the claims as `identity`.
|
|
344
|
+
*/
|
|
345
|
+
id_token?: string;
|
|
346
|
+
}
|
package/dist/types.js
ADDED
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
export const EXTENSION_SCOPES = ['project:read', 'analytics:read', 'events:read'];
|
|
2
|
+
/** What each scope means, in the words of usebecky's consent screen. */
|
|
3
|
+
export const EXTENSION_SCOPE_INFO = {
|
|
4
|
+
'project:read': {
|
|
5
|
+
label: 'See basic project details',
|
|
6
|
+
description: "The project's name, API address, publishable key and the websites it allows. Never your secret key and never the data in your database.",
|
|
7
|
+
},
|
|
8
|
+
'analytics:read': {
|
|
9
|
+
label: 'See visitor analytics totals',
|
|
10
|
+
description: 'Visitors, visits, page views, top pages, channels, conversions and revenue per channel. Totals only, never single visitors.',
|
|
11
|
+
},
|
|
12
|
+
'events:read': {
|
|
13
|
+
label: 'Get notified when things happen',
|
|
14
|
+
description: 'usebecky sends it the events listed on this page (for example a new sign-up or a purchase) as they happen.',
|
|
15
|
+
},
|
|
16
|
+
};
|
|
17
|
+
export const EXTENSION_CATEGORIES = ['consent', 'tags', 'marketing', 'support', 'other'];
|
|
18
|
+
export const EXTENSION_CAPABILITIES = ['consent_banner', 'sgtm_forwarding'];
|
|
19
|
+
export const EXTENSION_FIELD_TYPES = ['text', 'url', 'secret', 'boolean'];
|
|
20
|
+
/** usebecky's limits for a listing (packages/server/src/modules/extensions/listing.ts). */
|
|
21
|
+
export const LISTING_LIMITS = {
|
|
22
|
+
nameMin: 2,
|
|
23
|
+
name: 60,
|
|
24
|
+
summary: 90,
|
|
25
|
+
description: 5000,
|
|
26
|
+
url: 2000,
|
|
27
|
+
redirectUris: 10,
|
|
28
|
+
fields: 20,
|
|
29
|
+
fieldLabel: 80,
|
|
30
|
+
fieldHelp: 300,
|
|
31
|
+
fieldPlaceholder: 120,
|
|
32
|
+
pattern: 200,
|
|
33
|
+
dataShared: 20,
|
|
34
|
+
dataSharedItem: 200,
|
|
35
|
+
/** US cents: 3 USD (the server's minimum). */
|
|
36
|
+
priceMin: 300,
|
|
37
|
+
/** US cents: 999 USD. */
|
|
38
|
+
priceMax: 99_900,
|
|
39
|
+
trialDaysMax: 30,
|
|
40
|
+
/** Pricing "plans": 2 to 6 plans, names of at most 30 characters, summaries of at most 80. */
|
|
41
|
+
plansMin: 2,
|
|
42
|
+
plansMax: 6,
|
|
43
|
+
planName: 30,
|
|
44
|
+
planSummary: 80,
|
|
45
|
+
/** A setting's value, in characters. */
|
|
46
|
+
fieldValue: 2000,
|
|
47
|
+
/** Sidebar pages (ui.pages). */
|
|
48
|
+
uiPages: 3,
|
|
49
|
+
/** A sidebar page's label. */
|
|
50
|
+
uiLabel: 24,
|
|
51
|
+
};
|
|
52
|
+
/** Ids an extension can't have. */
|
|
53
|
+
export const RESERVED_SLUGS = ['new', 'admin', 'api', 'app', 'apps', 'developer', 'developers', 'docs', 'extension', 'extensions', 'help', 'logos', 'oauth', 'settings', 'stats', 'store', 'support', 'test', 'usebecky', 'becky'];
|
|
54
|
+
/** How usebecky's credentials, codes and tokens start. */
|
|
55
|
+
export const TOKEN_PREFIXES = {
|
|
56
|
+
clientId: 'ub_ci_',
|
|
57
|
+
clientSecret: 'ub_cs_',
|
|
58
|
+
webhookSecret: 'whsec_',
|
|
59
|
+
authorizationCode: 'ub_ac_',
|
|
60
|
+
accessToken: 'ub_it_',
|
|
61
|
+
refreshToken: 'ub_ir_',
|
|
62
|
+
};
|
|
63
|
+
/** Access tokens last an hour. */
|
|
64
|
+
export const ACCESS_TOKEN_TTL_SECONDS = 3600;
|
|
65
|
+
/** Refresh tokens last 90 days and are replaced on every refresh. */
|
|
66
|
+
export const REFRESH_TOKEN_TTL_DAYS = 90;
|
|
67
|
+
/** Authorization codes work once, within 10 minutes. */
|
|
68
|
+
export const AUTHORIZATION_CODE_TTL_SECONDS = 600;
|
|
69
|
+
/** Partner API requests per minute per installation (then 429 rate_limited with retry-after). */
|
|
70
|
+
export const PARTNER_RATE_LIMIT_PER_MINUTE = 300;
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
import { type FetchHandler } from '../handlers.ts';
|
|
2
|
+
import type { Awaitable } from '../stores.ts';
|
|
3
|
+
import { type HeaderSource, type VerifyOptions } from '../webhooks.ts';
|
|
4
|
+
import { UI_EVENT_TYPE, type ActionResult, type FieldValue, type Plan, type UiActionRequest, type UiParams, type UiRenderRequest, type UiRequest, type View } from './schema.ts';
|
|
5
|
+
/** Requests from usebecky are far smaller (30 form values of at most 10,000 characters each, and the envelope). */
|
|
6
|
+
export declare const MAX_UI_REQUEST_BYTES: number;
|
|
7
|
+
export interface UiContext {
|
|
8
|
+
/** The verified request, as usebecky sent it. */
|
|
9
|
+
request: UiRequest;
|
|
10
|
+
project: {
|
|
11
|
+
ref: string;
|
|
12
|
+
name: string;
|
|
13
|
+
};
|
|
14
|
+
/** The install's id (the same as in webhooks and tokens). */
|
|
15
|
+
install: string;
|
|
16
|
+
/** Who is looking: the pairwise `sub` (as in the id_token and launch tokens), their role in the project, their language. */
|
|
17
|
+
user: UiRequest['user'];
|
|
18
|
+
/** The page id: one of your listing's ui.pages, or "settings". */
|
|
19
|
+
page: string;
|
|
20
|
+
/** The page's state from the dashboard's address: cursor, q, sort, a tab, your own filters. Text only. */
|
|
21
|
+
params: UiParams;
|
|
22
|
+
/** The install's price plan (which plan, trial, paid, past due); null for a free extension. */
|
|
23
|
+
plan: Plan | null;
|
|
24
|
+
/** A developer's test project. */
|
|
25
|
+
test: boolean;
|
|
26
|
+
}
|
|
27
|
+
export interface UiActionContext extends UiContext {
|
|
28
|
+
request: UiActionRequest;
|
|
29
|
+
/** The button or form: its action id, the row it was on (or the checked rows of a bulk action), the form's values. */
|
|
30
|
+
action: {
|
|
31
|
+
id: string;
|
|
32
|
+
row?: string;
|
|
33
|
+
rows?: string[];
|
|
34
|
+
values: Record<string, FieldValue>;
|
|
35
|
+
};
|
|
36
|
+
}
|
|
37
|
+
/** Builds a page. Throw to answer with an error (usebecky then says "<Name> couldn't show this page."). */
|
|
38
|
+
export type PageHandler<C extends UiContext = UiContext> = (ctx: C) => Awaitable<View>;
|
|
39
|
+
/** Runs a button or form. Return nothing to show the page again, or a toast, a form's errors, a view or another page. */
|
|
40
|
+
export type ActionHandler<C extends UiActionContext = UiActionContext> = (ctx: C) => Awaitable<ActionResult | void | undefined>;
|
|
41
|
+
export interface UiHandlerOptions<C extends UiContext = UiContext, A extends UiActionContext = UiActionContext> {
|
|
42
|
+
/** `whsec_...` (pass [new, old] while you rotate it). */
|
|
43
|
+
webhookSecret: string | readonly string[] | undefined;
|
|
44
|
+
/** One handler per page id of your listing's ui.pages, plus "settings" when ui.settings is true. */
|
|
45
|
+
pages: Record<string, PageHandler<C>>;
|
|
46
|
+
/** One handler per action id your buttons and forms use. */
|
|
47
|
+
actions?: Record<string, ActionHandler<A>>;
|
|
48
|
+
/** Adds your own things to every context (ext.uiHandler adds `api`). */
|
|
49
|
+
extend?: (ctx: UiContext) => C;
|
|
50
|
+
/** Signature tolerance (default 300 seconds). */
|
|
51
|
+
verify?: VerifyOptions;
|
|
52
|
+
/** Unix seconds "now", asked on every request (tests). */
|
|
53
|
+
clock?: () => number;
|
|
54
|
+
/** Where problems go: a page that isn't valid, a handler that threw (default: console.error). */
|
|
55
|
+
log?: (message: string) => void;
|
|
56
|
+
}
|
|
57
|
+
/** Verify a request from usebecky to your ui.url (signature, age, type) and return it. */
|
|
58
|
+
export declare function verifyUiRequest(rawBody: string | Uint8Array | ArrayBuffer, headers: HeaderSource, secret: string | readonly string[] | undefined, options?: VerifyOptions): Promise<UiRequest>;
|
|
59
|
+
/**
|
|
60
|
+
* A fetch-style POST handler for your ui.url: verifies the signature, calls the page or action handler and answers with
|
|
61
|
+
* what it returns. Problems with a page (a block usebecky can't draw) are logged with where they are, like
|
|
62
|
+
* "blocks.2.items.0.value must be text"; usebecky refuses the same page with the same words in your test project.
|
|
63
|
+
*/
|
|
64
|
+
export declare function uiHandler<C extends UiContext = UiContext, A extends UiActionContext = UiActionContext>(options: UiHandlerOptions<C, A>): FetchHandler;
|
|
65
|
+
export type { UiRenderRequest, UiActionRequest };
|
|
66
|
+
export { UI_EVENT_TYPE };
|
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
// Your pages inside usebecky (listing `ui`): usebecky POSTs a signed request to ui.url whenever someone opens one of
|
|
2
|
+
// them or uses a button or form there; you answer with blocks (schema.ts) and usebecky draws them in its own design.
|
|
3
|
+
//
|
|
4
|
+
// const ui = ext.uiHandler({
|
|
5
|
+
// pages: { reviews: async (ctx) => ({ blocks: [{ type: 'stats', items: [...] }] }) },
|
|
6
|
+
// actions: { hide: async (ctx) => { await hide(ctx.action.row); return { toast: 'Hidden.' } } },
|
|
7
|
+
// })
|
|
8
|
+
// app.post('/usebecky/ui', (c) => ui(c.req.raw))
|
|
9
|
+
import { ExtensionError } from "../errors.js";
|
|
10
|
+
import { jsonResponse } from "../handlers.js";
|
|
11
|
+
import { verifyWebhook } from "../webhooks.js";
|
|
12
|
+
import { checkActionAnswer, checkView, SETTINGS_PAGE, UI_EVENT_TYPE } from "./schema.js";
|
|
13
|
+
/** Requests from usebecky are far smaller (30 form values of at most 10,000 characters each, and the envelope). */
|
|
14
|
+
export const MAX_UI_REQUEST_BYTES = 512 * 1024;
|
|
15
|
+
const bad = (code, message, hint) => new ExtensionError({ code, message, hint, status: 400 });
|
|
16
|
+
/** Verify a request from usebecky to your ui.url (signature, age, type) and return it. */
|
|
17
|
+
export async function verifyUiRequest(rawBody, headers, secret, options = {}) {
|
|
18
|
+
let event;
|
|
19
|
+
try {
|
|
20
|
+
event = (await verifyWebhook(rawBody, headers, secret, options));
|
|
21
|
+
}
|
|
22
|
+
catch (err) {
|
|
23
|
+
if (err instanceof ExtensionError && err.status === 400)
|
|
24
|
+
throw new ExtensionError({ code: err.code, message: err.message.replace(/webhook/g, 'UI request'), hint: err.hint, status: 400 });
|
|
25
|
+
throw err;
|
|
26
|
+
}
|
|
27
|
+
if (event.type !== 'ui.render' && event.type !== 'ui.action') {
|
|
28
|
+
throw bad('invalid_payload', `This is a "${String(event.type).slice(0, 40)}" event, not a UI request.`, 'Point ui.url at its own route (not your webhook_url).');
|
|
29
|
+
}
|
|
30
|
+
const project = event.project;
|
|
31
|
+
const user = event.user;
|
|
32
|
+
if (typeof event.install !== 'string' || typeof event.page !== 'string' || !project || typeof project.ref !== 'string' || !user || typeof user.sub !== 'string') {
|
|
33
|
+
throw bad('invalid_payload', 'The UI request has no install, page, project or user.');
|
|
34
|
+
}
|
|
35
|
+
if (!event.params || typeof event.params !== 'object' || Array.isArray(event.params))
|
|
36
|
+
throw bad('invalid_payload', 'The UI request has no params.');
|
|
37
|
+
if (event.type === 'ui.action') {
|
|
38
|
+
const a = event.action;
|
|
39
|
+
if (!a || typeof a.id !== 'string')
|
|
40
|
+
throw bad('invalid_payload', 'The action request has no action id.');
|
|
41
|
+
}
|
|
42
|
+
return event;
|
|
43
|
+
}
|
|
44
|
+
/**
|
|
45
|
+
* A fetch-style POST handler for your ui.url: verifies the signature, calls the page or action handler and answers with
|
|
46
|
+
* what it returns. Problems with a page (a block usebecky can't draw) are logged with where they are, like
|
|
47
|
+
* "blocks.2.items.0.value must be text"; usebecky refuses the same page with the same words in your test project.
|
|
48
|
+
*/
|
|
49
|
+
export function uiHandler(options) {
|
|
50
|
+
const log = options.log ?? ((m) => console.error(`[usebecky-extension] ${m}`));
|
|
51
|
+
const pages = Object.keys(options.pages);
|
|
52
|
+
const answer = (status, body) => jsonResponse(status, body, { 'cache-control': 'no-store' });
|
|
53
|
+
return async (request) => {
|
|
54
|
+
if (request.method !== 'POST')
|
|
55
|
+
return answer(405, { error: { code: 'method_not_allowed', message: 'usebecky sends UI requests with POST.' } });
|
|
56
|
+
if (Number(request.headers.get('content-length') ?? 0) > MAX_UI_REQUEST_BYTES)
|
|
57
|
+
return answer(413, { error: { code: 'payload_too_large', message: 'UI requests are far smaller than this.' } });
|
|
58
|
+
let req;
|
|
59
|
+
try {
|
|
60
|
+
const raw = new Uint8Array(await request.arrayBuffer());
|
|
61
|
+
if (raw.length > MAX_UI_REQUEST_BYTES)
|
|
62
|
+
return answer(413, { error: { code: 'payload_too_large', message: 'UI requests are far smaller than this.' } });
|
|
63
|
+
req = await verifyUiRequest(raw, request.headers, options.webhookSecret, { ...options.verify, ...(options.clock ? { now: options.clock() } : {}) });
|
|
64
|
+
}
|
|
65
|
+
catch (err) {
|
|
66
|
+
if (err instanceof ExtensionError)
|
|
67
|
+
return answer(err.status >= 400 ? err.status : 400, { error: err.toJSON() });
|
|
68
|
+
throw err;
|
|
69
|
+
}
|
|
70
|
+
const base = { request: req, project: { ref: req.project.ref, name: req.project.name }, install: req.install, user: req.user, page: req.page, params: req.params, plan: req.plan ?? null, test: req.test === true };
|
|
71
|
+
const ctx = options.extend ? options.extend(base) : base;
|
|
72
|
+
try {
|
|
73
|
+
if (req.type === 'ui.render') {
|
|
74
|
+
const handler = Object.hasOwn(options.pages, req.page) ? options.pages[req.page] : undefined;
|
|
75
|
+
if (!handler) {
|
|
76
|
+
log(`usebecky asked for the page "${req.page}", but uiHandler has no handler for it. Add it to pages${req.page === SETTINGS_PAGE ? ' (your listing has "settings": true)' : ' (it is in your listing\'s ui.pages)'}.`);
|
|
77
|
+
return answer(404, { error: { code: 'page_not_found', message: `No page "${req.page}".` } });
|
|
78
|
+
}
|
|
79
|
+
const view = await handler(ctx);
|
|
80
|
+
const checked = checkView(view, { pages });
|
|
81
|
+
if (!checked.ok)
|
|
82
|
+
log(`The page "${req.page}" has a problem usebecky will refuse: ${checked.problem.message}`);
|
|
83
|
+
return answer(200, { view });
|
|
84
|
+
}
|
|
85
|
+
const a = req.action;
|
|
86
|
+
const handler = options.actions && Object.hasOwn(options.actions, a.id) ? options.actions[a.id] : undefined;
|
|
87
|
+
if (!handler) {
|
|
88
|
+
log(`A button or form on the page "${req.page}" runs the action "${a.id}", but uiHandler has no handler for it. Add it to actions.`);
|
|
89
|
+
return answer(404, { error: { code: 'action_not_found', message: `No action "${a.id}".` } });
|
|
90
|
+
}
|
|
91
|
+
const actionCtx = Object.assign(ctx, { action: { id: a.id, ...(a.row !== undefined ? { row: a.row } : {}), ...(a.rows !== undefined ? { rows: a.rows } : {}), values: a.values ?? {} } });
|
|
92
|
+
const result = (await handler(actionCtx)) ?? {};
|
|
93
|
+
const checked = checkActionAnswer(result, { pages });
|
|
94
|
+
if (!checked.ok)
|
|
95
|
+
log(`The action "${a.id}" answered something usebecky will refuse: ${checked.problem.message}`);
|
|
96
|
+
return answer(200, result);
|
|
97
|
+
}
|
|
98
|
+
catch (err) {
|
|
99
|
+
const what = req.type === 'ui.render' ? `the page "${req.page}"` : `the action "${req.action.id}"`;
|
|
100
|
+
log(`${what} failed: ${err?.stack ?? err?.message ?? String(err)}`);
|
|
101
|
+
return answer(500, { error: { code: 'ui_failed', message: 'Something went wrong.' } });
|
|
102
|
+
}
|
|
103
|
+
};
|
|
104
|
+
}
|
|
105
|
+
export { UI_EVENT_TYPE };
|