@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
|
@@ -0,0 +1,1657 @@
|
|
|
1
|
+
// The dev server: a pretend usebecky on your computer, so you can build an extension without a real project. It
|
|
2
|
+
// answers like usebecky (packages/server/src/modules/extensions: install.ts, oauth.ts, partner.ts, webhooks.ts) with
|
|
3
|
+
// the same parameters, prefixes, checks, error codes and messages, for two fake projects:
|
|
4
|
+
//
|
|
5
|
+
// GET / your projects: Install (the store), the install's state, Send event, Disconnect
|
|
6
|
+
// GET /oauth/authorize the consent screen (the dashboard's /oauth/authorize): client_id, exact
|
|
7
|
+
// redirect_uri, PKCE S256, scopes; a wrong link stops here, nothing redirects
|
|
8
|
+
// POST /oauth/authorize Allow → redirect_uri?code=ub_ac_…&state=… (a new install sends
|
|
9
|
+
// extension.installed); Cancel → ?error=access_denied&error_description=…&state=…
|
|
10
|
+
// POST /extensions/v1/oauth/token authorization_code (PKCE) and refresh_token (rotated; reuse revokes every
|
|
11
|
+
// token of the install), client_secret_basic or client_secret_post
|
|
12
|
+
// POST /extensions/v1/oauth/revoke RFC 7009
|
|
13
|
+
// GET /extensions/v1/installation | /project | /analytics/summary
|
|
14
|
+
// PUT | DELETE /extensions/v1/installation/settings server-side tagging settings (only with `capabilities:
|
|
15
|
+
// ['sgtm_forwarding']`, CLI --capability sgtm_forwarding); the form is
|
|
16
|
+
// checked like usebecky (tagging.ts), the name is not looked up
|
|
17
|
+
// GET /dev/install?project= fields mode: the settings form a customer fills in (checkboxes for yes/no fields)
|
|
18
|
+
// GET /project/:ref/extensions/:slug the extension's page in the project (install_url's return_url)
|
|
19
|
+
// POST /dev/send {type, project} a signed event to your webhook_url
|
|
20
|
+
// POST /dev/uninstall {project} Disconnect: tokens revoked, extension.uninstalled sent
|
|
21
|
+
// GET /.well-known/openid-configuration the dev server as an OpenID Connect provider (issuer = its own URL)
|
|
22
|
+
// GET /.well-known/jwks.json its own ES256 public key (made at start; the hosted usebecky rotates)
|
|
23
|
+
// POST /dev/provision {project} account.provision "url": the signed call to your provision_url, then the
|
|
24
|
+
// settings form, filled in with what you answered, for the customer to confirm
|
|
25
|
+
// GET /dev/launch?project= "Open in <name>": 302 to your sso_url?launch=<token> (60 s, single use)
|
|
26
|
+
// GET /project/:ref/x/:page one of your pages inside usebecky (listing ui.pages), drawn from the blocks
|
|
27
|
+
// your ui.url answers (ui-render.ts); POST: a button or form → ui.action. A
|
|
28
|
+
// view with refresh_seconds is asked for again like the dashboard does it
|
|
29
|
+
// GET /dev/start?project=&plan= Install with a plan picked first (paid extensions)
|
|
30
|
+
// POST /dev/plan {project, plan?, status?, trial_days?, next_plan?, cancel_at_period_end?, discount_*?, renew?}
|
|
31
|
+
// the dev panel: set the install's plan (extension.plan_changed when its id,
|
|
32
|
+
// status, end or next plan change)
|
|
33
|
+
// POST /dev/plan-change {project, plan} usebecky's plan dialog (the extension's page, ?plan= and plan buttons open
|
|
34
|
+
// it): an upgrade now, a downgrade at the period end, in the trial now
|
|
35
|
+
//
|
|
36
|
+
// Plans (listing pricing "plans", or a monthly price as the one plan "monthly"): every install gets the plan object
|
|
37
|
+
// usebecky gives it (plans.ts) on GET /installation, in extension.installed and on every ui request.
|
|
38
|
+
//
|
|
39
|
+
// Accounts (listing `account`): customers never sign up by hand. With account.provision "oauth" the token response
|
|
40
|
+
// carries an id_token for a pretend person (Ada Lovelace, ada@example.com); with "url" the dev server calls your
|
|
41
|
+
// provision_url when you install. sso_url and provision_url are mapped onto `appUrl` like the other addresses.
|
|
42
|
+
//
|
|
43
|
+
// `appUrl` maps the manifest's addresses (install_url, redirect_uris, webhook_url) onto your local server:
|
|
44
|
+
// https://my-extension.com/oauth/callback becomes http://localhost:3000/oauth/callback. Not imitated: payments (a paid
|
|
45
|
+
// extension installs at once, in its free trial when the listing has one), retries of failed webhooks (one try).
|
|
46
|
+
//
|
|
47
|
+
// Real or test project: by default the fake projects behave like real ones (GET /installation says `test: false`,
|
|
48
|
+
// events carry no `test`). `testProject: true` (CLI: --test-project) makes them behave like a test project:
|
|
49
|
+
// `test: true` on the installation, `"test": true` on every event and provision request.
|
|
50
|
+
//
|
|
51
|
+
// Only for this computer: it listens on 127.0.0.1 and answers only requests addressed to localhost, 127.0.0.1 or [::1]
|
|
52
|
+
// (or the `host` you bind it to). A web page can point its own domain at 127.0.0.1 and then read the answers as its
|
|
53
|
+
// own (DNS rebinding); the Host header gives that away. Requests that change something (every POST) and "Open in"
|
|
54
|
+
// (/dev/launch) are refused when a browser says they come from another website (Origin, Sec-Fetch-Site): a page can't
|
|
55
|
+
// install, disconnect, send events or sign you in behind your back. curl, your tests and your extension's server send
|
|
56
|
+
// neither header and keep working.
|
|
57
|
+
import fs from 'node:fs';
|
|
58
|
+
import http from 'node:http';
|
|
59
|
+
import { isIP } from 'node:net';
|
|
60
|
+
import path from 'node:path';
|
|
61
|
+
import { PROVISION_EVENT_TYPE } from "../accounts.js";
|
|
62
|
+
import { base64url, randomToken, sha256 } from "../crypto.js";
|
|
63
|
+
import { ID_TOKEN_TTL_SECONDS, LAUNCH_TOKEN_TTL_SECONDS, LAUNCH_TOKEN_TYPE, OIDC_SCOPES } from "../identity.js";
|
|
64
|
+
import { generateEs256Key, signEs256 } from "../jwt.js";
|
|
65
|
+
import { ALL_EVENT_TYPES, EXTENSION_EVENT_TYPES, SUBSCRIBABLE_EVENT_TYPES } from "../events.js";
|
|
66
|
+
import { escapeHtml } from "../handlers.js";
|
|
67
|
+
import { validateManifest } from "../manifest.js";
|
|
68
|
+
import { ACCESS_TOKEN_TTL_SECONDS, AUTHORIZATION_CODE_TTL_SECONDS, EXTENSION_FIELD_TYPES, EXTENSION_SCOPE_INFO, EXTENSION_SCOPES, LISTING_LIMITS, PARTNER_RATE_LIMIT_PER_MINUTE, REFRESH_TOKEN_TTL_DAYS, TOKEN_PREFIXES, } from "../types.js";
|
|
69
|
+
import { signWebhook } from "../webhooks.js";
|
|
70
|
+
import { consentPage, consentProblemPage, errorHtml, extensionPage, homePage, projectPage, provisionPage, settingsPage } from "./pages.js";
|
|
71
|
+
import { renderBlocks, renderView } from "./ui-render.js";
|
|
72
|
+
import { ACTION_ID, checkActionAnswer, checkRenderAnswer, checkRequestParams, SETTINGS_PAGE, UI_EVENT_TYPE, UI_LIMITS, UI_SECTIONS } from "../ui/schema.js";
|
|
73
|
+
import { deliveryEvent, pricingPlans, testEvent } from "./samples.js";
|
|
74
|
+
import { applyPanel, changePlan, DevPlanError, planKey, planView, renew, startPlan } from "./plans.js";
|
|
75
|
+
import { checkTaggingSettings, TAGGING_KEYS, TaggingSettingsError } from "./tagging.js";
|
|
76
|
+
/** Test credentials the dev server accepts (and `npm run dev` passes to your extension). Real prefixes, never real values. */
|
|
77
|
+
export const DEV_CREDENTIALS = {
|
|
78
|
+
clientId: 'ub_ci_DevServerTestClient00000',
|
|
79
|
+
clientSecret: 'ub_cs_DevServerTestSecretNeverUseInProduction0',
|
|
80
|
+
webhookSecret: 'whsec_DevServerWebhookSecretNotReal000',
|
|
81
|
+
};
|
|
82
|
+
export const DEV_PORT = 4400;
|
|
83
|
+
/** The pretend person who installs on the dev server (the signed-in usebecky account). */
|
|
84
|
+
export const DEV_PERSON = { name: 'Ada Lovelace', email: 'ada@example.com', email_verified: true, role: 'owner' };
|
|
85
|
+
export const DEV_PROJECTS = [
|
|
86
|
+
{ ref: 'devshop00001', name: 'Acme Shop', plan: 'pro', api_url: 'https://api.usebecky.com', publishable_key: 'ub_pk_devshop00001_DevPublishableKey0000001', allowed_hosts: ['shop.example.com', 'www.shop.example.com'] },
|
|
87
|
+
{ ref: 'devblog00002', name: 'Side Project Blog', plan: 'free', api_url: 'https://api.usebecky.com', publishable_key: 'ub_pk_devblog00002_DevPublishableKey0000002', allowed_hosts: ['blog.example.com'] },
|
|
88
|
+
];
|
|
89
|
+
/** An RFC 6749 error from the token endpoint. */
|
|
90
|
+
class OAuthError extends Error {
|
|
91
|
+
error;
|
|
92
|
+
status;
|
|
93
|
+
constructor(error, description, status = 400) {
|
|
94
|
+
super(description);
|
|
95
|
+
this.error = error;
|
|
96
|
+
this.status = status;
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
/** A link the consent screen refuses. */
|
|
100
|
+
class ConsentError extends Error {
|
|
101
|
+
code;
|
|
102
|
+
hint;
|
|
103
|
+
constructor(code, message, hint) {
|
|
104
|
+
super(message);
|
|
105
|
+
this.code = code;
|
|
106
|
+
if (hint)
|
|
107
|
+
this.hint = hint;
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
/** An invalid setting (400 invalid_settings with details.field). */
|
|
111
|
+
class SettingsError extends Error {
|
|
112
|
+
field;
|
|
113
|
+
hint;
|
|
114
|
+
constructor(field, message, hint) {
|
|
115
|
+
super(message);
|
|
116
|
+
this.field = field;
|
|
117
|
+
if (hint)
|
|
118
|
+
this.hint = hint;
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
const MAX_BODY = 64 * 1024;
|
|
122
|
+
const NO_STORE = { 'cache-control': 'no-store', pragma: 'no-cache' };
|
|
123
|
+
const CHALLENGE_RE = /^[A-Za-z0-9\-._~]{43,128}$/;
|
|
124
|
+
const VERIFIER_RE = CHALLENGE_RE;
|
|
125
|
+
const DAY_MS = 86_400_000;
|
|
126
|
+
const DATE = /^(\d{4})-(\d{2})-(\d{2})$/;
|
|
127
|
+
const MAX_CUSTOM_DAYS = 800;
|
|
128
|
+
const PLANS = { free: { name: 'Free', history: 7 }, pro: { name: 'Pro', history: 90 }, business: { name: 'Business', history: 395 } };
|
|
129
|
+
const ALNUM = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
|
|
130
|
+
function randomAlnum(n) {
|
|
131
|
+
const bytes = globalThis.crypto.getRandomValues(new Uint8Array(n));
|
|
132
|
+
let out = '';
|
|
133
|
+
for (const b of bytes)
|
|
134
|
+
out += ALNUM[b % ALNUM.length];
|
|
135
|
+
return out;
|
|
136
|
+
}
|
|
137
|
+
function readBody(req) {
|
|
138
|
+
return new Promise((resolve, reject) => {
|
|
139
|
+
let size = 0;
|
|
140
|
+
const chunks = [];
|
|
141
|
+
req.on('data', (c) => {
|
|
142
|
+
size += c.length;
|
|
143
|
+
if (size > MAX_BODY) {
|
|
144
|
+
reject(new Error('body too large'));
|
|
145
|
+
req.destroy();
|
|
146
|
+
}
|
|
147
|
+
else
|
|
148
|
+
chunks.push(c);
|
|
149
|
+
});
|
|
150
|
+
req.on('end', () => resolve(Buffer.concat(chunks).toString('utf8')));
|
|
151
|
+
req.on('error', reject);
|
|
152
|
+
});
|
|
153
|
+
}
|
|
154
|
+
/** The person's language from Accept-Language ("de-DE,de;q=0.9" → "de-DE"), like usebecky; "en" when there is none. */
|
|
155
|
+
function localeOf(header) {
|
|
156
|
+
const first = (Array.isArray(header) ? header[0] : (header ?? '')).split(',')[0]?.split(';')[0]?.trim() ?? '';
|
|
157
|
+
return /^[A-Za-z]{2,3}(-[A-Za-z0-9]{2,8}){0,2}$/.test(first) ? first : 'en';
|
|
158
|
+
}
|
|
159
|
+
function parseBody(text, contentType) {
|
|
160
|
+
if (!text)
|
|
161
|
+
return {};
|
|
162
|
+
if (contentType?.includes('application/json')) {
|
|
163
|
+
try {
|
|
164
|
+
const v = JSON.parse(text);
|
|
165
|
+
return v && typeof v === 'object' ? Object.fromEntries(Object.entries(v).map(([k, x]) => [k, typeof x === 'string' ? x : JSON.stringify(x)])) : {};
|
|
166
|
+
}
|
|
167
|
+
catch {
|
|
168
|
+
return {};
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
return Object.fromEntries(new URLSearchParams(text));
|
|
172
|
+
}
|
|
173
|
+
/** Load and check the manifest (problems are shown on the home page, not fatal). */
|
|
174
|
+
function loadManifest(opts) {
|
|
175
|
+
const check = (m) => validateManifest(m, { allowPrivateWebhookUrl: true }).errors.map((e) => `usebecky-extension.json: ${e.path ? `${e.path}: ` : ''}${e.message}`);
|
|
176
|
+
if (opts.manifest !== undefined)
|
|
177
|
+
return { manifest: opts.manifest ?? null, dir: process.cwd(), problems: opts.manifest ? check(opts.manifest) : [] };
|
|
178
|
+
const file = path.resolve(opts.manifestPath ?? 'usebecky-extension.json');
|
|
179
|
+
if (!fs.existsSync(file))
|
|
180
|
+
return { manifest: null, dir: process.cwd(), problems: opts.manifestPath ? [`${file} does not exist.`] : [] };
|
|
181
|
+
try {
|
|
182
|
+
const manifest = JSON.parse(fs.readFileSync(file, 'utf8'));
|
|
183
|
+
return { manifest, dir: path.dirname(file), problems: check(manifest) };
|
|
184
|
+
}
|
|
185
|
+
catch (err) {
|
|
186
|
+
return { manifest: null, dir: path.dirname(file), problems: [`usebecky-extension.json is not valid JSON: ${err.message}`] };
|
|
187
|
+
}
|
|
188
|
+
}
|
|
189
|
+
/** Map an address from the manifest onto the local app: same path and query, the app's origin. */
|
|
190
|
+
export function mapToApp(url, appUrl) {
|
|
191
|
+
if (!url)
|
|
192
|
+
return null;
|
|
193
|
+
try {
|
|
194
|
+
const u = new URL(url);
|
|
195
|
+
if (!appUrl)
|
|
196
|
+
return u.toString();
|
|
197
|
+
const a = new URL(appUrl);
|
|
198
|
+
u.protocol = a.protocol;
|
|
199
|
+
u.host = a.host;
|
|
200
|
+
return u.toString();
|
|
201
|
+
}
|
|
202
|
+
catch {
|
|
203
|
+
return null;
|
|
204
|
+
}
|
|
205
|
+
}
|
|
206
|
+
const isLocalhost = (url) => {
|
|
207
|
+
try {
|
|
208
|
+
const u = new URL(url);
|
|
209
|
+
return u.protocol === 'http:' && ['localhost', '127.0.0.1', '[::1]'].includes(u.hostname);
|
|
210
|
+
}
|
|
211
|
+
catch {
|
|
212
|
+
return false;
|
|
213
|
+
}
|
|
214
|
+
};
|
|
215
|
+
// ---- Only for this computer: Host, Origin and Sec-Fetch-Site --------------------------------------
|
|
216
|
+
/** Names that always mean this computer, as URL.hostname writes them. */
|
|
217
|
+
const LOOPBACK_HOSTS = ['localhost', '127.0.0.1', '[::1]'];
|
|
218
|
+
/** Bound to every address: then any of the computer's IP addresses reaches it too. */
|
|
219
|
+
const WILDCARD_HOSTS = new Set(['0.0.0.0', '::', '[::]']);
|
|
220
|
+
/** "Example.COM:4400" → "example.com", "[::1]:4400" → "[::1]", "127.1" → "127.0.0.1"; null when it is no host. */
|
|
221
|
+
function hostnameOf(host) {
|
|
222
|
+
try {
|
|
223
|
+
const u = new URL(`http://${host}`);
|
|
224
|
+
return u.username || u.password || u.pathname !== '/' || u.search || u.hash ? null : u.hostname;
|
|
225
|
+
}
|
|
226
|
+
catch {
|
|
227
|
+
return null;
|
|
228
|
+
}
|
|
229
|
+
}
|
|
230
|
+
/**
|
|
231
|
+
* Which Host headers the dev server answers. A web page can point its own domain at 127.0.0.1 and then read the dev
|
|
232
|
+
* server's answers as its own (DNS rebinding); it can't change the name the browser sends as Host. An IP address can't
|
|
233
|
+
* be rebound (no DNS), so binding to every address accepts any IP address.
|
|
234
|
+
*/
|
|
235
|
+
function hostPolicy(bind, extra = []) {
|
|
236
|
+
const anyIp = WILDCARD_HOSTS.has(bind);
|
|
237
|
+
const names = new Set(LOOPBACK_HOSTS);
|
|
238
|
+
for (const h of anyIp ? extra : [bind, ...extra]) {
|
|
239
|
+
const name = hostnameOf(h.includes(':') && !h.startsWith('[') ? `[${h}]` : h);
|
|
240
|
+
if (name)
|
|
241
|
+
names.add(name);
|
|
242
|
+
}
|
|
243
|
+
return (hostname) => names.has(hostname) || (anyIp && isIP(hostname.replace(/^\[(.*)\]$/, '$1')) !== 0);
|
|
244
|
+
}
|
|
245
|
+
/** POST, PUT, DELETE...: they change something, so a browser must say they come from the dev server's own pages. */
|
|
246
|
+
const SAFE_METHODS = new Set(['GET', 'HEAD', 'OPTIONS']);
|
|
247
|
+
/** A GET that signs someone in ("Open in" mints a launch token): only from the dev server's own pages, too. */
|
|
248
|
+
const SIGN_IN_PATHS = new Set(['/dev/launch']);
|
|
249
|
+
/**
|
|
250
|
+
* Where a browser says a request comes from, when that is another website (else null). Browsers send Origin with every
|
|
251
|
+
* POST and Sec-Fetch-Site with every request; curl, tests and servers send neither and are let through.
|
|
252
|
+
*/
|
|
253
|
+
function foreignSource(req, sameOrigin) {
|
|
254
|
+
const origin = req.headers.origin;
|
|
255
|
+
// "null": a sandboxed frame or a file, never one of the dev server's pages.
|
|
256
|
+
if (origin !== undefined && !sameOrigin(origin))
|
|
257
|
+
return origin;
|
|
258
|
+
const site = req.headers['sec-fetch-site'];
|
|
259
|
+
if (site !== undefined && site !== 'same-origin' && site !== 'none')
|
|
260
|
+
return `a ${site} page`;
|
|
261
|
+
return null;
|
|
262
|
+
}
|
|
263
|
+
const str = (v, max = 2000) => (typeof v === 'string' && v.length <= max ? v : null);
|
|
264
|
+
const ymd = (t) => new Date(t).toISOString().slice(0, 10);
|
|
265
|
+
/** Deterministic pretend numbers for a project and date range. */
|
|
266
|
+
function fakeSummary(project, from, to) {
|
|
267
|
+
let seed = [...`${project}${from}${to}`].reduce((n, ch) => (n * 31 + ch.charCodeAt(0)) >>> 0, 7);
|
|
268
|
+
const rnd = (min, max) => {
|
|
269
|
+
seed = (seed * 1103515245 + 12345) >>> 0;
|
|
270
|
+
return min + (seed % (max - min + 1));
|
|
271
|
+
};
|
|
272
|
+
const days = Math.round((Date.parse(to) - Date.parse(from)) / DAY_MS) + 1;
|
|
273
|
+
const visitors = rnd(40, 90) * days;
|
|
274
|
+
const visits = Math.round(visitors * 1.3);
|
|
275
|
+
const pageViews = Math.round(visits * 2.4);
|
|
276
|
+
const purchases = Math.round(visits * 0.021);
|
|
277
|
+
const share = (n, f) => Math.round(n * f);
|
|
278
|
+
const total = purchases * 2900;
|
|
279
|
+
return {
|
|
280
|
+
from,
|
|
281
|
+
to,
|
|
282
|
+
visitors,
|
|
283
|
+
visits,
|
|
284
|
+
page_views: pageViews,
|
|
285
|
+
conversions: Math.round(visits * 0.034),
|
|
286
|
+
top_pages: [
|
|
287
|
+
{ path: '/', page_views: share(pageViews, 0.38), visitors: share(visitors, 0.61) },
|
|
288
|
+
{ path: '/pricing', page_views: share(pageViews, 0.17), visitors: share(visitors, 0.24) },
|
|
289
|
+
{ path: '/blog/launch', page_views: share(pageViews, 0.09), visitors: share(visitors, 0.12) },
|
|
290
|
+
],
|
|
291
|
+
channels: [
|
|
292
|
+
{ channel: 'organic_search', visitors: share(visitors, 0.44), visits: share(visits, 0.42) },
|
|
293
|
+
{ channel: 'direct', visitors: share(visitors, 0.31), visits: share(visits, 0.33) },
|
|
294
|
+
{ channel: 'social', visitors: share(visitors, 0.15), visits: share(visits, 0.15) },
|
|
295
|
+
{ channel: 'referral', visitors: share(visitors, 0.1), visits: share(visits, 0.1) },
|
|
296
|
+
],
|
|
297
|
+
revenue: {
|
|
298
|
+
currency: 'usd',
|
|
299
|
+
total,
|
|
300
|
+
purchases,
|
|
301
|
+
by_channel: [
|
|
302
|
+
{ channel: 'organic_search', revenue: share(total, 0.5), purchases: share(purchases, 0.5) },
|
|
303
|
+
{ channel: 'direct', revenue: total - share(total, 0.5), purchases: purchases - share(purchases, 0.5) },
|
|
304
|
+
],
|
|
305
|
+
},
|
|
306
|
+
};
|
|
307
|
+
}
|
|
308
|
+
export async function startDevServer(options = {}) {
|
|
309
|
+
const log = options.log ?? ((line) => console.log(line));
|
|
310
|
+
const credentials = {
|
|
311
|
+
clientId: options.clientId ?? DEV_CREDENTIALS.clientId,
|
|
312
|
+
clientSecret: options.clientSecret ?? DEV_CREDENTIALS.clientSecret,
|
|
313
|
+
webhookSecret: options.webhookSecret ?? DEV_CREDENTIALS.webhookSecret,
|
|
314
|
+
};
|
|
315
|
+
const ttl = options.accessTokenTtl ?? ACCESS_TOKEN_TTL_SECONDS;
|
|
316
|
+
const perMinute = options.rateLimitPerMinute ?? PARTNER_RATE_LIMIT_PER_MINUTE;
|
|
317
|
+
const doFetch = options.fetch ?? fetch;
|
|
318
|
+
const { manifest, dir, problems } = loadManifest(options);
|
|
319
|
+
const appUrl = options.appUrl?.replace(/\/+$/, '');
|
|
320
|
+
const testProject = options.testProject === true;
|
|
321
|
+
const capabilities = [...(options.capabilities ?? [])];
|
|
322
|
+
const bindHost = options.host ?? '127.0.0.1';
|
|
323
|
+
const hostAllowed = hostPolicy(bindHost, options.allowedHosts);
|
|
324
|
+
let ownPort = 0;
|
|
325
|
+
// ---- The listing (usebecky-extension.json; without one: oauth with every scope, any localhost callback) ----
|
|
326
|
+
const slug = typeof manifest?.slug === 'string' ? manifest.slug : 'my-extension';
|
|
327
|
+
const extensionName = typeof manifest?.name === 'string' ? manifest.name : 'Your extension';
|
|
328
|
+
const publisher = typeof manifest?.publisher?.name === 'string' ? manifest.publisher.name : extensionName;
|
|
329
|
+
const mode = manifest?.connect?.mode === 'fields' ? 'fields' : 'oauth';
|
|
330
|
+
const fields = mode === 'fields' && Array.isArray(manifest?.connect?.fields)
|
|
331
|
+
? manifest.connect.fields.filter((f) => f && typeof f.key === 'string' && typeof f.label === 'string' && EXTENSION_FIELD_TYPES.includes(f.type))
|
|
332
|
+
: [];
|
|
333
|
+
const listedScopes = Array.isArray(manifest?.scopes) ? [...new Set(manifest.scopes.filter((s) => EXTENSION_SCOPES.includes(s)))] : [...EXTENSION_SCOPES];
|
|
334
|
+
const listedEvents = Array.isArray(manifest?.events) ? manifest.events.filter((t) => SUBSCRIBABLE_EVENT_TYPES.includes(t)) : manifest ? [] : [...SUBSCRIBABLE_EVENT_TYPES];
|
|
335
|
+
const listedRedirects = manifest?.connect?.mode === 'oauth' && Array.isArray(manifest.connect.redirect_uris) ? manifest.connect.redirect_uris.filter((r) => typeof r === 'string') : [];
|
|
336
|
+
const allowedRedirects = new Set(listedRedirects.flatMap((r) => [r, mapToApp(r, appUrl)].filter((x) => !!x)));
|
|
337
|
+
const installUrl = mode === 'oauth' ? (manifest ? mapToApp(manifest.connect?.install_url, appUrl) : appUrl ? `${appUrl}/install` : null) : null;
|
|
338
|
+
const webhookUrl = manifest ? mapToApp(manifest.webhook_url, appUrl) : appUrl ? `${appUrl}/webhooks/usebecky` : null;
|
|
339
|
+
const dataShared = Array.isArray(manifest?.data_shared) ? manifest.data_shared.filter((d) => typeof d === 'string') : [];
|
|
340
|
+
// Price plans: pricing "plans", or a monthly price as the one plan "monthly"; none for a free extension.
|
|
341
|
+
const pricing = manifest?.pricing?.model === 'plans' && !Array.isArray(manifest.pricing.plans) ? null : manifest?.pricing;
|
|
342
|
+
const devPlans = pricingPlans(pricing, extensionName).filter((p) => typeof p.id === 'string' && p.id && typeof p.name === 'string' && Number.isFinite(p.amount));
|
|
343
|
+
const trialDays = devPlans.length && Number.isInteger(pricing?.trial_days) ? Math.min(30, Math.max(0, pricing.trial_days)) : 0;
|
|
344
|
+
const pendingPlan = new Map(); // by project ref: the plan picked before installing
|
|
345
|
+
const logoFile = typeof manifest?.logo_url === 'string' && !/^https?:/i.test(manifest.logo_url) ? path.resolve(dir, manifest.logo_url) : null;
|
|
346
|
+
const logoUrl = logoFile ? '/logo' : typeof manifest?.logo_url === 'string' ? manifest.logo_url : null;
|
|
347
|
+
// Accounts at your service (listing `account`): created automatically, opened with single sign-on.
|
|
348
|
+
const acc = manifest?.account?.required === true ? manifest.account : null;
|
|
349
|
+
const account = acc
|
|
350
|
+
? {
|
|
351
|
+
provision: acc.provision === 'url' ? 'url' : 'oauth',
|
|
352
|
+
provisionUrl: acc.provision === 'url' ? mapToApp(acc.provision_url, appUrl) : null,
|
|
353
|
+
ssoUrl: mapToApp(acc.sso_url, appUrl),
|
|
354
|
+
}
|
|
355
|
+
: null;
|
|
356
|
+
// Your pages inside usebecky (listing `ui`): the dev server asks your ui.url for them and draws the blocks.
|
|
357
|
+
const uiSpec = manifest?.ui && typeof manifest.ui === 'object' && typeof manifest.ui.url === 'string' ? manifest.ui : null;
|
|
358
|
+
const ui = uiSpec
|
|
359
|
+
? {
|
|
360
|
+
url: mapToApp(uiSpec.url, appUrl),
|
|
361
|
+
pages: (Array.isArray(uiSpec.pages) ? uiSpec.pages : [])
|
|
362
|
+
.filter((p) => p && typeof p.id === 'string' && typeof p.label === 'string')
|
|
363
|
+
.map((p) => ({ id: p.id, label: p.label, section: UI_SECTIONS.includes(p.section) ? p.section : 'project' })),
|
|
364
|
+
settings: uiSpec.settings === true,
|
|
365
|
+
}
|
|
366
|
+
: null;
|
|
367
|
+
const uiPageIds = ui ? [...ui.pages.map((p) => p.id), ...(ui.settings ? [SETTINGS_PAGE] : [])] : [];
|
|
368
|
+
// The dev server's own signing key: id_tokens and launch tokens verify against its JWKS (issuer = its URL).
|
|
369
|
+
const signing = await generateEs256Key();
|
|
370
|
+
const provisioned = new Map(); // by project ref
|
|
371
|
+
const installs = new Map(); // by project ref
|
|
372
|
+
const codes = new Map();
|
|
373
|
+
const tokens = new Map();
|
|
374
|
+
const deliveries = [];
|
|
375
|
+
const hits = new Map();
|
|
376
|
+
const failures = new Map();
|
|
377
|
+
let tokenCalls = { count: 0, resetAt: 0 };
|
|
378
|
+
let base = '';
|
|
379
|
+
const projectOf = (ref) => DEV_PROJECTS.find((p) => p.ref === ref);
|
|
380
|
+
const installById = (id) => [...installs.values()].find((i) => i.id === id);
|
|
381
|
+
const effectiveScopes = (i) => i.scopes.filter((s) => listedScopes.includes(s));
|
|
382
|
+
const extensionPath = (ref) => `/project/${ref}/extensions/${slug}`;
|
|
383
|
+
/** A plan button opens usebecky's plan dialog: the extension's page with the plan picked (the deep link ?plan=). */
|
|
384
|
+
const planHrefFor = (ref) => (plan) => `${extensionPath(ref)}?plan=${encodeURIComponent(plan)}#plan`;
|
|
385
|
+
/** What leaves usebecky: no secret fields; yes/no fields are always true or false. oauth: {}, or the server-side
|
|
386
|
+
* tagging settings your server set (capability sgtm_forwarding). */
|
|
387
|
+
function publicSettings(i) {
|
|
388
|
+
if (mode !== 'fields') {
|
|
389
|
+
const out = {};
|
|
390
|
+
if (capabilities.includes('sgtm_forwarding'))
|
|
391
|
+
for (const k of TAGGING_KEYS)
|
|
392
|
+
if (i.settings[k] !== undefined)
|
|
393
|
+
out[k] = i.settings[k];
|
|
394
|
+
return out;
|
|
395
|
+
}
|
|
396
|
+
const out = {};
|
|
397
|
+
for (const f of fields) {
|
|
398
|
+
if (f.type === 'secret')
|
|
399
|
+
continue;
|
|
400
|
+
if (f.type === 'boolean')
|
|
401
|
+
out[f.key] = i.settings[f.key] === true;
|
|
402
|
+
else if (i.settings[f.key] !== undefined)
|
|
403
|
+
out[f.key] = i.settings[f.key];
|
|
404
|
+
}
|
|
405
|
+
return out;
|
|
406
|
+
}
|
|
407
|
+
/** oauth: a working refresh token; fields: every required setting filled in (a required yes/no field turned on). */
|
|
408
|
+
function isConnected(i) {
|
|
409
|
+
if (i.status !== 'active' && i.status !== 'error')
|
|
410
|
+
return false;
|
|
411
|
+
if (mode === 'fields')
|
|
412
|
+
return fields.every((f) => !f.required || !!i.settings[f.key]);
|
|
413
|
+
return [...tokens.values()].some((t) => t.install === i.id && t.kind === 'refresh' && !t.revoked && t.expiresAt > Date.now());
|
|
414
|
+
}
|
|
415
|
+
/** The listing's events, when the customer allowed 'events:read' (what an install gets at consent). */
|
|
416
|
+
const allowedEvents = (scopes) => (scopes.includes('events:read') ? [...listedEvents] : []);
|
|
417
|
+
/** What the install receives now: what the customer allowed that the listing still has. */
|
|
418
|
+
const effectiveEvents = (i) => (effectiveScopes(i).includes('events:read') ? i.events.filter((t) => listedEvents.includes(t)) : []);
|
|
419
|
+
function installationOf(i) {
|
|
420
|
+
return {
|
|
421
|
+
id: i.id,
|
|
422
|
+
extension: slug,
|
|
423
|
+
project: { ref: i.project.ref, name: i.project.name, api_url: i.project.api_url },
|
|
424
|
+
scopes: effectiveScopes(i),
|
|
425
|
+
events: effectiveEvents(i),
|
|
426
|
+
settings: publicSettings(i),
|
|
427
|
+
installed_at: i.installedAt,
|
|
428
|
+
test: testProject,
|
|
429
|
+
plan: planOf(i),
|
|
430
|
+
};
|
|
431
|
+
}
|
|
432
|
+
/** The install's plan object (null for a free extension). */
|
|
433
|
+
function planOf(i) {
|
|
434
|
+
return i.plan && devPlans.length ? planView(i.plan, devPlans) : null;
|
|
435
|
+
}
|
|
436
|
+
/** A new install's plan: the one picked before installing, in the listing's free trial. */
|
|
437
|
+
function newPlan(ref) {
|
|
438
|
+
const picked = pendingPlan.get(ref);
|
|
439
|
+
pendingPlan.delete(ref);
|
|
440
|
+
return devPlans.length ? startPlan(devPlans, trialDays, picked) : null;
|
|
441
|
+
}
|
|
442
|
+
/** Set the install's plan; extension.plan_changed when its id, status, end or next plan changed (like usebecky). */
|
|
443
|
+
async function updatePlan(i, next) {
|
|
444
|
+
const previous = planOf(i);
|
|
445
|
+
i.plan = next;
|
|
446
|
+
const plan = planOf(i);
|
|
447
|
+
if (planKey(previous) === planKey(plan))
|
|
448
|
+
return null;
|
|
449
|
+
log(` · plan on ${i.project.name}: ${plan ? `${plan.id} (${plan.status}${plan.cancel_at_period_end ? ', ends at period end' : ''}${plan.next_plan ? `, then ${plan.next_plan.id}` : ''})` : 'none'}`);
|
|
450
|
+
return deliver(deliveryEvent('extension.plan_changed', sampleInstall(i), { previous }));
|
|
451
|
+
}
|
|
452
|
+
const installFor = (ref) => (ref ? installs.get(ref) : [...installs.values()][0]);
|
|
453
|
+
async function setPlan(ref, patch) {
|
|
454
|
+
const i = installFor(ref);
|
|
455
|
+
if (!i)
|
|
456
|
+
throw new DevPlanError('project', 'Nothing is installed in that project yet.');
|
|
457
|
+
if (!i.plan || !devPlans.length)
|
|
458
|
+
throw new DevPlanError('plan', `${extensionName} is free: it has no plan. Add pricing to usebecky-extension.json.`);
|
|
459
|
+
const sent = await updatePlan(i, patch.renew === true || patch.renew === '1' || patch.renew === 'true' ? renew(i.plan) : applyPanel(i.plan, devPlans, patch));
|
|
460
|
+
return { plan: planOf(i), sent };
|
|
461
|
+
}
|
|
462
|
+
async function changeTo(ref, target) {
|
|
463
|
+
const i = installFor(ref);
|
|
464
|
+
if (!i)
|
|
465
|
+
throw new DevPlanError('project', 'Nothing is installed in that project yet.');
|
|
466
|
+
if (!i.plan || !devPlans.length)
|
|
467
|
+
throw new DevPlanError('plan', `${extensionName} is free: it has no plan.`);
|
|
468
|
+
const { state, effect } = changePlan(i.plan, devPlans, target);
|
|
469
|
+
if (effect === 'now' && i.plan.status !== 'trialing')
|
|
470
|
+
log(` · upgrade on ${i.project.name}: usebecky charges the prorated difference now (not on the dev server)`);
|
|
471
|
+
const sent = await updatePlan(i, state);
|
|
472
|
+
return { plan: planOf(i), effect, sent };
|
|
473
|
+
}
|
|
474
|
+
const sampleInstall = (i) => ({ id: i.id, extension: slug, project: { ref: i.project.ref, name: i.project.name }, scopes: [...i.scopes], settings: publicSettings(i), ...(i.partnerAccountId ? { account_id: i.partnerAccountId } : {}), plan: planOf(i) });
|
|
475
|
+
// ---- Accounts: the pretend person, id_tokens, launch tokens, provision calls (identity.ts, provision.ts) ----
|
|
476
|
+
/** Pairwise like usebecky: stable for this person and this extension only. */
|
|
477
|
+
const personSub = async () => base64url(await sha256(`usebecky-dev-server:${slug}:${DEV_PERSON.email}`));
|
|
478
|
+
async function idToken(i, nonce) {
|
|
479
|
+
const now = Math.floor(Date.now() / 1000);
|
|
480
|
+
return signEs256(signing.privateKey, { kid: signing.publicJwk.kid, typ: 'JWT' }, { iss: base, sub: await personSub(), aud: credentials.clientId, iat: now, exp: now + ID_TOKEN_TTL_SECONDS, ...(nonce ? { nonce } : {}), email: DEV_PERSON.email, email_verified: DEV_PERSON.email_verified, name: DEV_PERSON.name, usebecky_project: i.project.ref, usebecky_install: i.id, usebecky_role: DEV_PERSON.role });
|
|
481
|
+
}
|
|
482
|
+
/** "Open in": the sso_url with a launch token, or a reason it can't be opened. */
|
|
483
|
+
async function launchFor(ref) {
|
|
484
|
+
const i = ref ? installs.get(ref) : [...installs.values()][0];
|
|
485
|
+
if (!account?.ssoUrl)
|
|
486
|
+
throw new Error('usebecky-extension.json has no account.sso_url, so there is nothing to open.');
|
|
487
|
+
if (!i)
|
|
488
|
+
throw new Error('Nothing is installed yet. Install the extension first.');
|
|
489
|
+
if (account.provision === 'url' && !i.partnerAccountId)
|
|
490
|
+
throw new Error('The account was not created yet: install again, your provision endpoint has to answer first.');
|
|
491
|
+
if (account.provision === 'oauth' && !isConnected(i))
|
|
492
|
+
throw new Error('The extension is not connected yet: finish the install on your website first.');
|
|
493
|
+
const now = Math.floor(Date.now() / 1000);
|
|
494
|
+
const token = await signEs256(signing.privateKey, { kid: signing.publicJwk.kid, typ: LAUNCH_TOKEN_TYPE }, {
|
|
495
|
+
iss: base,
|
|
496
|
+
sub: await personSub(),
|
|
497
|
+
aud: credentials.clientId,
|
|
498
|
+
jti: randomToken(16),
|
|
499
|
+
iat: now,
|
|
500
|
+
exp: now + LAUNCH_TOKEN_TTL_SECONDS,
|
|
501
|
+
email: DEV_PERSON.email,
|
|
502
|
+
email_verified: DEV_PERSON.email_verified,
|
|
503
|
+
name: DEV_PERSON.name,
|
|
504
|
+
usebecky_project: i.project.ref,
|
|
505
|
+
usebecky_install: i.id,
|
|
506
|
+
usebecky_role: DEV_PERSON.role,
|
|
507
|
+
...(i.partnerAccountId ? { partner_account_id: i.partnerAccountId } : {}),
|
|
508
|
+
});
|
|
509
|
+
const u = new URL(account.ssoUrl);
|
|
510
|
+
u.searchParams.set('launch', token);
|
|
511
|
+
return u.toString();
|
|
512
|
+
}
|
|
513
|
+
/** account.provision "url": POST the signed provision request to your provision_url (one try, 10 seconds, no redirects). */
|
|
514
|
+
async function provisionFor(project) {
|
|
515
|
+
if (!account?.provisionUrl)
|
|
516
|
+
return { ok: false, error: 'usebecky-extension.json has no account.provision_url.' };
|
|
517
|
+
const installId = provisioned.get(project.ref)?.installId ?? crypto.randomUUID();
|
|
518
|
+
const envelope = {
|
|
519
|
+
id: `prv_${installId.replace(/-/g, '')}`,
|
|
520
|
+
type: PROVISION_EVENT_TYPE,
|
|
521
|
+
created_at: new Date().toISOString(),
|
|
522
|
+
extension: slug,
|
|
523
|
+
install: installId,
|
|
524
|
+
project: { ref: project.ref, name: project.name },
|
|
525
|
+
user: { sub: await personSub(), email: DEV_PERSON.email, email_verified: DEV_PERSON.email_verified, name: DEV_PERSON.name },
|
|
526
|
+
// Like usebecky: only a test project's provision requests say so.
|
|
527
|
+
...(testProject ? { test: true } : {}),
|
|
528
|
+
};
|
|
529
|
+
const body = JSON.stringify(envelope);
|
|
530
|
+
const started = Date.now();
|
|
531
|
+
let res;
|
|
532
|
+
try {
|
|
533
|
+
res = await doFetch(account.provisionUrl, {
|
|
534
|
+
method: 'POST',
|
|
535
|
+
headers: {
|
|
536
|
+
'content-type': 'application/json',
|
|
537
|
+
accept: 'application/json',
|
|
538
|
+
'user-agent': 'usebecky-provision/1',
|
|
539
|
+
'usebecky-event-type': PROVISION_EVENT_TYPE,
|
|
540
|
+
'usebecky-event-id': envelope.id,
|
|
541
|
+
'idempotency-key': installId,
|
|
542
|
+
'usebecky-signature': await signWebhook(body, credentials.webhookSecret),
|
|
543
|
+
},
|
|
544
|
+
body,
|
|
545
|
+
redirect: 'manual',
|
|
546
|
+
signal: AbortSignal.timeout(10_000),
|
|
547
|
+
});
|
|
548
|
+
}
|
|
549
|
+
catch (err) {
|
|
550
|
+
const error = `${err.message}. Is your extension running at ${new URL(account.provisionUrl).origin}?`;
|
|
551
|
+
log(` ✖ ${PROVISION_EVENT_TYPE} → ${account.provisionUrl}: ${error}`);
|
|
552
|
+
return { ok: false, error };
|
|
553
|
+
}
|
|
554
|
+
const text = await res.text().catch(() => '');
|
|
555
|
+
const ms = Date.now() - started;
|
|
556
|
+
const fail = (error) => {
|
|
557
|
+
log(` ✖ ${PROVISION_EVENT_TYPE} → ${account.provisionUrl} (${res.status}, ${ms} ms): ${error}`);
|
|
558
|
+
return { ok: false, error };
|
|
559
|
+
};
|
|
560
|
+
if (res.status >= 300 && res.status < 400)
|
|
561
|
+
return fail(`Your endpoint answered with a redirect (HTTP ${res.status}); usebecky never follows redirects.`);
|
|
562
|
+
if (!res.ok)
|
|
563
|
+
return fail(`Your endpoint answered HTTP ${res.status}: ${text.slice(0, 200)}`);
|
|
564
|
+
let answer;
|
|
565
|
+
try {
|
|
566
|
+
answer = JSON.parse(text);
|
|
567
|
+
}
|
|
568
|
+
catch {
|
|
569
|
+
return fail('Your endpoint did not answer with JSON: { "account_id": "...", "settings": { ... } }.');
|
|
570
|
+
}
|
|
571
|
+
const accountId = typeof answer?.account_id === 'string' ? answer.account_id.trim() : '';
|
|
572
|
+
if (!accountId || accountId.length > 200)
|
|
573
|
+
return fail('The answer has no account_id (1 to 200 characters).');
|
|
574
|
+
const settings = {};
|
|
575
|
+
if (answer.settings !== undefined && answer.settings !== null) {
|
|
576
|
+
if (typeof answer.settings !== 'object' || Array.isArray(answer.settings))
|
|
577
|
+
return fail('settings must be an object with your setup field keys.');
|
|
578
|
+
for (const [k, v] of Object.entries(answer.settings)) {
|
|
579
|
+
const f = fields.find((x) => x.key === k);
|
|
580
|
+
if (!f)
|
|
581
|
+
return fail(`settings has "${k}", which is not one of your setup fields (${fields.map((x) => x.key).join(', ')}).`);
|
|
582
|
+
if (f.type === 'boolean' ? typeof v !== 'boolean' : typeof v !== 'string')
|
|
583
|
+
return fail(`settings.${k} must be ${f.type === 'boolean' ? 'true or false' : 'text'}.`);
|
|
584
|
+
settings[k] = v;
|
|
585
|
+
}
|
|
586
|
+
}
|
|
587
|
+
log(` ✔ ${PROVISION_EVENT_TYPE} → ${account.provisionUrl} (${res.status}, ${ms} ms): account ${accountId}`);
|
|
588
|
+
const value = { installId, accountId, settings };
|
|
589
|
+
provisioned.set(project.ref, value);
|
|
590
|
+
return { ok: true, value };
|
|
591
|
+
}
|
|
592
|
+
/** install_url with ?project=<ref>&return_url=<the extension's page>, like the store's Install. */
|
|
593
|
+
function installHref(ref) {
|
|
594
|
+
if (mode === 'fields')
|
|
595
|
+
return `/dev/install?project=${encodeURIComponent(ref)}`;
|
|
596
|
+
if (!installUrl)
|
|
597
|
+
return null;
|
|
598
|
+
const u = new URL(installUrl);
|
|
599
|
+
u.searchParams.set('project', ref);
|
|
600
|
+
u.searchParams.set('return_url', `${base}${extensionPath(ref)}`);
|
|
601
|
+
return u.toString();
|
|
602
|
+
}
|
|
603
|
+
function revokeAll(installId, why) {
|
|
604
|
+
let any = false;
|
|
605
|
+
for (const t of tokens.values()) {
|
|
606
|
+
if (t.install === installId && !t.revoked) {
|
|
607
|
+
t.revoked = true;
|
|
608
|
+
any = true;
|
|
609
|
+
}
|
|
610
|
+
}
|
|
611
|
+
if (!any || !why)
|
|
612
|
+
return;
|
|
613
|
+
const i = installById(installId);
|
|
614
|
+
if (i) {
|
|
615
|
+
if (i.status === 'active')
|
|
616
|
+
i.status = 'error';
|
|
617
|
+
i.lastError = `Every token was revoked because ${why}. Connect the extension again.`;
|
|
618
|
+
}
|
|
619
|
+
log(` ✖ every token of the install on ${i?.project.name ?? '?'} was revoked: ${why} (usebecky does the same). The customer has to connect again.`);
|
|
620
|
+
}
|
|
621
|
+
function issue(i) {
|
|
622
|
+
const access = `${TOKEN_PREFIXES.accessToken}${randomAlnum(40)}`;
|
|
623
|
+
const refresh = `${TOKEN_PREFIXES.refreshToken}${randomAlnum(48)}`;
|
|
624
|
+
tokens.set(access, { kind: 'access', install: i.id, expiresAt: Date.now() + ttl * 1000, revoked: false });
|
|
625
|
+
tokens.set(refresh, { kind: 'refresh', install: i.id, expiresAt: Date.now() + REFRESH_TOKEN_TTL_DAYS * DAY_MS, revoked: false });
|
|
626
|
+
return { access_token: access, token_type: 'Bearer', expires_in: ttl, refresh_token: refresh, scope: i.scopes.join(' '), project_ref: i.project.ref, installation_id: i.id };
|
|
627
|
+
}
|
|
628
|
+
/** Your ui.url: the signed request usebecky sends (render 8 s, action 15 s, one try, no redirects); the answer checked like usebecky checks it. */
|
|
629
|
+
async function askUi(project, install, page, params, locale, action) {
|
|
630
|
+
if (!ui?.url)
|
|
631
|
+
return { ok: false, error: 'usebecky-extension.json has no ui.url.' };
|
|
632
|
+
const kind = action ? 'ui.action' : 'ui.render';
|
|
633
|
+
const id = `uireq_${randomToken(12)}`;
|
|
634
|
+
const envelope = {
|
|
635
|
+
id,
|
|
636
|
+
type: kind,
|
|
637
|
+
created_at: new Date().toISOString(),
|
|
638
|
+
extension: slug,
|
|
639
|
+
install: install.id,
|
|
640
|
+
project: { ref: project.ref, name: project.name },
|
|
641
|
+
user: { sub: await personSub(), role: 'owner', locale },
|
|
642
|
+
page,
|
|
643
|
+
params,
|
|
644
|
+
plan: planOf(install),
|
|
645
|
+
...(action ? { action } : {}),
|
|
646
|
+
...(testProject ? { test: true } : {}),
|
|
647
|
+
};
|
|
648
|
+
const body = JSON.stringify(envelope);
|
|
649
|
+
const started = Date.now();
|
|
650
|
+
const where = `${kind} "${page}"${action ? ` (${action.id})` : ''} → ${ui.url}`;
|
|
651
|
+
let res;
|
|
652
|
+
try {
|
|
653
|
+
res = await doFetch(ui.url, {
|
|
654
|
+
method: 'POST',
|
|
655
|
+
headers: {
|
|
656
|
+
'content-type': 'application/json',
|
|
657
|
+
accept: 'application/json',
|
|
658
|
+
'user-agent': 'usebecky-ui/1',
|
|
659
|
+
'usebecky-event-type': UI_EVENT_TYPE,
|
|
660
|
+
'usebecky-event-id': id,
|
|
661
|
+
...(action ? { 'idempotency-key': id } : {}),
|
|
662
|
+
'usebecky-signature': await signWebhook(body, credentials.webhookSecret),
|
|
663
|
+
},
|
|
664
|
+
body,
|
|
665
|
+
redirect: 'manual',
|
|
666
|
+
signal: AbortSignal.timeout(action ? 15_000 : 8_000),
|
|
667
|
+
});
|
|
668
|
+
}
|
|
669
|
+
catch (err) {
|
|
670
|
+
const e = err;
|
|
671
|
+
const error = e.name === 'TimeoutError' ? `Your ui.url didn't answer within ${action ? 15 : 8} seconds.` : `${e.message}. Is your extension running at ${new URL(ui.url).origin}?`;
|
|
672
|
+
log(` ✖ ${where}: ${error}`);
|
|
673
|
+
return { ok: false, error };
|
|
674
|
+
}
|
|
675
|
+
const text = await res.text().catch(() => '');
|
|
676
|
+
const fail = (error) => {
|
|
677
|
+
log(` ✖ ${where} (${res.status}, ${Date.now() - started} ms): ${error}`);
|
|
678
|
+
return { ok: false, error };
|
|
679
|
+
};
|
|
680
|
+
if (res.status >= 300 && res.status < 400)
|
|
681
|
+
return fail(`Your ui.url answered with a redirect (HTTP ${res.status}); usebecky never follows redirects.`);
|
|
682
|
+
if (!res.ok)
|
|
683
|
+
return fail(`Your ui.url answered HTTP ${res.status}: ${text.slice(0, 200)}`);
|
|
684
|
+
if (Buffer.byteLength(text) > UI_LIMITS.responseBytes)
|
|
685
|
+
return fail(`The answer is larger than ${UI_LIMITS.responseBytes / 1024} KB; usebecky reads no more.`);
|
|
686
|
+
let value;
|
|
687
|
+
try {
|
|
688
|
+
value = JSON.parse(text);
|
|
689
|
+
}
|
|
690
|
+
catch {
|
|
691
|
+
return fail(`The answer isn't JSON. Answer ${action ? '{"toast": "Saved."} (or {})' : '{"view": {"blocks": […]}}'}.`);
|
|
692
|
+
}
|
|
693
|
+
const checked = action ? checkActionAnswer(value, { pages: uiPageIds }) : checkRenderAnswer(value, { pages: uiPageIds });
|
|
694
|
+
if (!checked.ok)
|
|
695
|
+
return fail(`usebecky can't show this: ${checked.problem.message}`);
|
|
696
|
+
log(` ✔ ${where} (${res.status}, ${Date.now() - started} ms)`);
|
|
697
|
+
return { ok: true, value: checked.value };
|
|
698
|
+
}
|
|
699
|
+
const UI_GROUPS = { backend: 'Backend', website: 'Website & sales', messages: 'Messages', project: 'Project' };
|
|
700
|
+
const uiPath = (ref, page, params = {}) => {
|
|
701
|
+
const q = new URLSearchParams(Object.entries(params).filter(([, v]) => v !== '')).toString();
|
|
702
|
+
return `/project/${encodeURIComponent(ref)}/x/${encodeURIComponent(page)}${q ? `?${q}` : ''}`;
|
|
703
|
+
};
|
|
704
|
+
const uiLinks = (ref, current) => (ui?.pages ?? []).map((p) => ({ href: uiPath(ref, p.id), label: p.label, current: p.id === current, logoUrl }));
|
|
705
|
+
const uiNav = (ref, current) => [
|
|
706
|
+
...['backend', 'website', 'messages'].map((sec) => ({ label: UI_GROUPS[sec], links: uiLinks(ref, current).filter((_, i) => ui.pages[i].section === sec) })),
|
|
707
|
+
{ label: 'Project', links: [...uiLinks(ref, current).filter((_, i) => ui.pages[i].section === 'project'), { href: extensionPath(ref), label: 'Extensions', current: current === SETTINGS_PAGE }] },
|
|
708
|
+
];
|
|
709
|
+
/** GET: one of your pages. POST: a button or form on it (→ ui.action), then the page again, another page or the errors. */
|
|
710
|
+
async function uiPageRoute(req, res, method, url, ref, pageId) {
|
|
711
|
+
const project = projectOf(ref);
|
|
712
|
+
if (!project || !ui)
|
|
713
|
+
return html(res, 404, errorHtml('Not found', 'There is no such project, or usebecky-extension.json has no "ui".'));
|
|
714
|
+
if (!uiPageIds.includes(pageId))
|
|
715
|
+
return html(res, 404, errorHtml('No such page', `Your listing has no page "${pageId}". Its pages: ${uiPageIds.join(', ') || 'none'}.`));
|
|
716
|
+
const install = installs.get(project.ref);
|
|
717
|
+
if (!install || install.status !== 'active')
|
|
718
|
+
return html(res, 409, errorHtml('Not installed', `Install ${extensionName} in ${project.name} first: its pages show once it is installed.`));
|
|
719
|
+
const locale = localeOf(req.headers['accept-language']);
|
|
720
|
+
const label = pageId === SETTINGS_PAGE ? 'Settings' : ui.pages.find((p) => p.id === pageId).label;
|
|
721
|
+
const by = { name: extensionName, logoUrl };
|
|
722
|
+
const show = (status, inner, notice) => html(res, status, projectPage(`${label} · ${project.name}`, project, uiNav(project.ref, pageId), `${notice ? `<p class="note${notice.bad ? ' bad' : ''}">${escapeHtml(notice.text)}</p>` : ''}${inner}`));
|
|
723
|
+
const failed = (error, kind) => show(502, `<div class="ub-head"><div><div class="ub-by">${escapeHtml(extensionName)}</div><h1>${escapeHtml(label)}</h1></div></div>`, { text: `${extensionName} couldn't ${kind === 'render' ? 'show this page' : 'do that'}. Because: ${error}`, bad: true });
|
|
724
|
+
const draw = (view, params, extra = {}) => show(200, renderView(view, { base: `/project/${encodeURIComponent(project.ref)}/x`, page: pageId, params, errors: extra.errors, values: extra.values, fallbackTitle: label, by, planHref: planHrefFor(project.ref) }), extra.notice ? { text: extra.notice, bad: false } : null);
|
|
725
|
+
if (method === 'GET') {
|
|
726
|
+
const params = Object.fromEntries([...url.searchParams].filter(([k]) => !k.startsWith('_')));
|
|
727
|
+
const pc = checkRequestParams(params);
|
|
728
|
+
if (!pc.ok)
|
|
729
|
+
return html(res, 400, errorHtml('Not a page address usebecky would send', pc.problem.message));
|
|
730
|
+
const r = await askUi(project, install, pageId, params, locale);
|
|
731
|
+
if (!r.ok)
|
|
732
|
+
return failed(r.error, 'render');
|
|
733
|
+
return draw(r.value, params, { notice: url.searchParams.get('_toast') });
|
|
734
|
+
}
|
|
735
|
+
const form = new URLSearchParams(await readBody(req));
|
|
736
|
+
let params = {};
|
|
737
|
+
try {
|
|
738
|
+
const p = JSON.parse(form.get('_params') ?? '{}');
|
|
739
|
+
if (checkRequestParams(p).ok)
|
|
740
|
+
params = p;
|
|
741
|
+
}
|
|
742
|
+
catch { }
|
|
743
|
+
const id = form.get('_action') ?? '';
|
|
744
|
+
if (!ACTION_ID.test(id))
|
|
745
|
+
return html(res, 400, errorHtml('No action', 'This button or form has no action id.'));
|
|
746
|
+
const action = { id };
|
|
747
|
+
const row = form.get('_row');
|
|
748
|
+
if (row)
|
|
749
|
+
action.row = row;
|
|
750
|
+
if (form.get('_bulk')) {
|
|
751
|
+
const rows = [...new Set(form.getAll('_rows'))].slice(0, UI_LIMITS.selectedRows);
|
|
752
|
+
if (!rows.length)
|
|
753
|
+
return redirect(res, `${uiPath(project.ref, pageId, params)}${Object.keys(params).length ? '&' : '?'}_toast=${encodeURIComponent('Pick at least one row first.')}`);
|
|
754
|
+
action.rows = rows;
|
|
755
|
+
}
|
|
756
|
+
const types = form.get('_types');
|
|
757
|
+
if (types) {
|
|
758
|
+
const values = {};
|
|
759
|
+
try {
|
|
760
|
+
for (const [key, type] of Object.entries(JSON.parse(types))) {
|
|
761
|
+
const raw = form.get(`f.${key}`);
|
|
762
|
+
if (type === 'checkbox')
|
|
763
|
+
values[key] = raw === 'true';
|
|
764
|
+
else if (type === 'number')
|
|
765
|
+
values[key] = raw === null || raw.trim() === '' || !Number.isFinite(Number(raw)) ? null : Number(raw);
|
|
766
|
+
else
|
|
767
|
+
values[key] = raw ?? '';
|
|
768
|
+
}
|
|
769
|
+
}
|
|
770
|
+
catch { }
|
|
771
|
+
action.values = values;
|
|
772
|
+
}
|
|
773
|
+
const back = form.get('_back');
|
|
774
|
+
const backTo = back && back === extensionPath(project.ref) ? back : null;
|
|
775
|
+
const r = await askUi(project, install, pageId, params, locale, action);
|
|
776
|
+
if (!r.ok)
|
|
777
|
+
return failed(r.error, 'action');
|
|
778
|
+
const result = r.value;
|
|
779
|
+
const toast = result.toast ? `_toast=${encodeURIComponent(result.toast)}` : '';
|
|
780
|
+
const join = (path) => (toast ? `${path}${path.includes('?') ? '&' : '?'}${toast}` : path);
|
|
781
|
+
if (result.errors && Object.keys(result.errors).length) {
|
|
782
|
+
const again = await askUi(project, install, pageId, params, locale);
|
|
783
|
+
if (!again.ok)
|
|
784
|
+
return failed(again.error, 'render');
|
|
785
|
+
return draw(again.value, params, { errors: result.errors, values: action.values, notice: result.toast });
|
|
786
|
+
}
|
|
787
|
+
if (result.view)
|
|
788
|
+
return draw(result.view, params, { notice: result.toast });
|
|
789
|
+
if (result.go)
|
|
790
|
+
return redirect(res, join(uiPath(project.ref, result.go.page, result.go.params ?? {})));
|
|
791
|
+
return redirect(res, join(backTo ?? uiPath(project.ref, pageId, params)));
|
|
792
|
+
}
|
|
793
|
+
async function deliver(sample) {
|
|
794
|
+
// A test project flags every event it sends; a real project's events have no `test` (only "Send test event" does).
|
|
795
|
+
const event = testProject ? { ...sample, test: true } : sample;
|
|
796
|
+
if (!webhookUrl) {
|
|
797
|
+
const d = { type: event.type, url: '', status: null, ms: 0, error: 'No webhook_url in usebecky-extension.json.', eventId: event.id };
|
|
798
|
+
deliveries.push(d);
|
|
799
|
+
log(` ✖ ${event.type}: not sent (no webhook_url in usebecky-extension.json)`);
|
|
800
|
+
return d;
|
|
801
|
+
}
|
|
802
|
+
const body = JSON.stringify(event);
|
|
803
|
+
const started = Date.now();
|
|
804
|
+
let d;
|
|
805
|
+
try {
|
|
806
|
+
const res = await doFetch(webhookUrl, {
|
|
807
|
+
method: 'POST',
|
|
808
|
+
headers: {
|
|
809
|
+
'content-type': 'application/json',
|
|
810
|
+
'user-agent': 'usebecky-webhooks/1',
|
|
811
|
+
'usebecky-event-id': event.id,
|
|
812
|
+
'usebecky-event-type': event.type,
|
|
813
|
+
'usebecky-signature': await signWebhook(body, credentials.webhookSecret),
|
|
814
|
+
},
|
|
815
|
+
body,
|
|
816
|
+
redirect: 'manual',
|
|
817
|
+
signal: AbortSignal.timeout(10_000),
|
|
818
|
+
});
|
|
819
|
+
d = { type: event.type, url: webhookUrl, status: res.status, ms: Date.now() - started, eventId: event.id };
|
|
820
|
+
if (res.status >= 300 && res.status < 400)
|
|
821
|
+
d.error = 'Your endpoint answered with a redirect. usebecky never follows redirects: use the final address as webhook_url.';
|
|
822
|
+
else if (!res.ok)
|
|
823
|
+
d.error = `HTTP ${res.status}: ${(await res.text()).slice(0, 200)}`;
|
|
824
|
+
else
|
|
825
|
+
await res.body?.cancel().catch(() => { });
|
|
826
|
+
}
|
|
827
|
+
catch (err) {
|
|
828
|
+
d = { type: event.type, url: webhookUrl, status: null, ms: Date.now() - started, error: `${err.message}. Is your extension running at ${new URL(webhookUrl).origin}?`, eventId: event.id };
|
|
829
|
+
}
|
|
830
|
+
deliveries.push(d);
|
|
831
|
+
log(d.error ? ` ✖ ${event.type} → ${webhookUrl}: ${d.error}` : ` ✔ ${event.type} → ${webhookUrl} (${d.status}, ${d.ms} ms)`);
|
|
832
|
+
return d;
|
|
833
|
+
}
|
|
834
|
+
function sendEvent(type, project) {
|
|
835
|
+
const ref = project || [...installs.keys()][0];
|
|
836
|
+
const install = ref ? installs.get(ref) : undefined;
|
|
837
|
+
if (install)
|
|
838
|
+
return deliver(deliveryEvent(type, sampleInstall(install)));
|
|
839
|
+
const p = projectOf(ref);
|
|
840
|
+
return deliver(testEvent(type, { slug, scopes: listedScopes, name: extensionName, pricing }, p ? { ref: p.ref, name: p.name } : ref ? { ref, name: 'Your project' } : undefined));
|
|
841
|
+
}
|
|
842
|
+
/** Check the settings a customer sent (usebecky's validateSettings, plus yes/no fields). */
|
|
843
|
+
function validateSettings(input, previous) {
|
|
844
|
+
const out = {};
|
|
845
|
+
for (const f of fields) {
|
|
846
|
+
let v = input[f.key];
|
|
847
|
+
if (f.type === 'boolean') {
|
|
848
|
+
if (v === undefined || v === null)
|
|
849
|
+
v = false;
|
|
850
|
+
if (typeof v !== 'boolean')
|
|
851
|
+
throw new SettingsError(f.key, `"${f.label}" must be true or false.`, f.help);
|
|
852
|
+
if (f.required && !v)
|
|
853
|
+
throw new SettingsError(f.key, `Turn on "${f.label}".`, f.help);
|
|
854
|
+
out[f.key] = v;
|
|
855
|
+
continue;
|
|
856
|
+
}
|
|
857
|
+
if (f.type === 'secret' && previous[f.key] !== undefined && (v === undefined || v === ''))
|
|
858
|
+
v = previous[f.key];
|
|
859
|
+
if (v === undefined || v === null || v === '') {
|
|
860
|
+
if (f.required)
|
|
861
|
+
throw new SettingsError(f.key, `Fill in "${f.label}".`, f.help);
|
|
862
|
+
continue;
|
|
863
|
+
}
|
|
864
|
+
if (typeof v !== 'string')
|
|
865
|
+
throw new SettingsError(f.key, `"${f.label}" must be text.`);
|
|
866
|
+
const s = v.trim();
|
|
867
|
+
if (s.length > LISTING_LIMITS.fieldValue)
|
|
868
|
+
throw new SettingsError(f.key, `"${f.label}" is too long (at most ${LISTING_LIMITS.fieldValue} characters).`);
|
|
869
|
+
if (f.type === 'url') {
|
|
870
|
+
let u = null;
|
|
871
|
+
try {
|
|
872
|
+
u = new URL(s);
|
|
873
|
+
}
|
|
874
|
+
catch { }
|
|
875
|
+
if (!u || u.protocol !== 'https:' || u.username || u.password)
|
|
876
|
+
throw new SettingsError(f.key, `"${f.label}" must be a full address starting with https://`, f.help);
|
|
877
|
+
}
|
|
878
|
+
if (f.pattern) {
|
|
879
|
+
let ok = false;
|
|
880
|
+
try {
|
|
881
|
+
ok = new RegExp(f.pattern, 'u').test(s);
|
|
882
|
+
}
|
|
883
|
+
catch { }
|
|
884
|
+
if (!ok)
|
|
885
|
+
throw new SettingsError(f.key, `"${f.label}" doesn't look right.`, f.help ?? (f.placeholder ? `Example: ${f.placeholder}` : undefined));
|
|
886
|
+
}
|
|
887
|
+
out[f.key] = s;
|
|
888
|
+
}
|
|
889
|
+
return out;
|
|
890
|
+
}
|
|
891
|
+
// ---- HTTP helpers ----------------------------------------------------------------------------
|
|
892
|
+
const send = (res, status, body, type, extra = {}) => {
|
|
893
|
+
res.writeHead(status, { 'content-type': type, 'cache-control': 'no-store', ...extra });
|
|
894
|
+
res.end(body);
|
|
895
|
+
};
|
|
896
|
+
const html = (res, status, body) => send(res, status, body, 'text/html; charset=utf-8', { 'x-frame-options': 'DENY' });
|
|
897
|
+
const json = (res, status, body, extra = {}) => send(res, status, JSON.stringify(body), 'application/json', extra);
|
|
898
|
+
/** usebecky's error body: { error: { code, message, hint?, details? } }. */
|
|
899
|
+
const apiError = (res, status, code, message, hint, details, extra = {}) => json(res, status, { error: { code, message, ...(hint ? { hint } : {}), ...(details ? { details } : {}) } }, extra);
|
|
900
|
+
const redirect = (res, location) => send(res, 302, '', 'text/plain', { location });
|
|
901
|
+
function resolveConsent(q) {
|
|
902
|
+
const clientId = str(q.client_id, 100);
|
|
903
|
+
if (!clientId)
|
|
904
|
+
throw new ConsentError('invalid_client', "This link is missing the extension's client_id.", 'Go back to the website you came from and start again.');
|
|
905
|
+
if (clientId !== credentials.clientId) {
|
|
906
|
+
log(` ✖ consent screen: unknown client_id "${clientId.slice(0, 40)}". The dev server's is ${credentials.clientId} (USEBECKY_CLIENT_ID).`);
|
|
907
|
+
throw new ConsentError('invalid_client', "This extension isn't known to usebecky.", 'Go back to the website you came from. If it keeps happening, tell its developer.');
|
|
908
|
+
}
|
|
909
|
+
const redirectUri = str(q.redirect_uri);
|
|
910
|
+
if (!redirectUri)
|
|
911
|
+
throw new ConsentError('invalid_redirect_uri', 'This link is missing the redirect_uri.', 'Go back to the website you came from and start again.');
|
|
912
|
+
const registered = mode === 'oauth' && (allowedRedirects.has(redirectUri) || (!listedRedirects.length && isLocalhost(redirectUri)));
|
|
913
|
+
if (!registered) {
|
|
914
|
+
log(` ✖ consent screen: redirect_uri "${redirectUri}" is not in connect.redirect_uris (${mode === 'oauth' ? `with the dev server's app address: ${[...allowedRedirects].join(', ') || 'none'}` : 'connect.mode is "fields"'}).`);
|
|
915
|
+
throw new ConsentError('invalid_redirect_uri', "This link sends you back to an address the extension didn't register.", "For your safety nothing happens. Tell the extension's developer: the redirect_uri must match one in the listing exactly.");
|
|
916
|
+
}
|
|
917
|
+
if (q.response_type !== undefined && q.response_type !== 'code')
|
|
918
|
+
throw new ConsentError('unsupported_response_type', 'This link asks for something usebecky doesn\'t support (response_type must be "code").');
|
|
919
|
+
if (q.code_challenge_method !== 'S256')
|
|
920
|
+
throw new ConsentError('invalid_request', 'This link is missing the security check usebecky requires (PKCE with code_challenge_method=S256).', "Tell the extension's developer.");
|
|
921
|
+
const codeChallenge = str(q.code_challenge, 128);
|
|
922
|
+
if (!codeChallenge || !CHALLENGE_RE.test(codeChallenge))
|
|
923
|
+
throw new ConsentError('invalid_request', 'The security check (code_challenge) in this link is not valid.', "Tell the extension's developer.");
|
|
924
|
+
const asked = typeof q.scope === 'string' && q.scope.trim() ? [...new Set(q.scope.trim().split(/\s+/))] : [...listedScopes];
|
|
925
|
+
const isOidc = (s) => OIDC_SCOPES.includes(s);
|
|
926
|
+
const requested = asked.filter((s) => !isOidc(s));
|
|
927
|
+
const fromSignIn = account?.provision === 'oauth';
|
|
928
|
+
const oidcAsked = asked.filter(isOidc);
|
|
929
|
+
if (oidcAsked.length && !fromSignIn)
|
|
930
|
+
throw new ConsentError('invalid_scope', `This link asks for permissions the extension didn't list: ${oidcAsked.join(', ')}.`, "Tell the extension's developer: openid, email and profile are only for extensions that create accounts from the sign-in.");
|
|
931
|
+
const extra = requested.filter((s) => !listedScopes.includes(s));
|
|
932
|
+
if (extra.length)
|
|
933
|
+
throw new ConsentError('invalid_scope', `This link asks for permissions the extension didn't list: ${extra.join(', ').slice(0, 200)}.`, "Tell the extension's developer.");
|
|
934
|
+
const state = q.state === undefined || q.state === '' ? null : str(q.state, 1000);
|
|
935
|
+
if (q.state !== undefined && q.state !== '' && state === null)
|
|
936
|
+
throw new ConsentError('invalid_request', 'The state value in this link is too long.');
|
|
937
|
+
const project = q.project === undefined || q.project === '' ? null : str(q.project, 40);
|
|
938
|
+
const nonce = q.nonce === undefined || q.nonce === '' ? null : str(q.nonce, 255);
|
|
939
|
+
if (q.nonce !== undefined && q.nonce !== '' && nonce === null)
|
|
940
|
+
throw new ConsentError('invalid_request', 'The nonce value in this link is too long (at most 255 characters).', "Tell the extension's developer.");
|
|
941
|
+
return { redirectUri, scopes: requested, state, codeChallenge, project, oidc: fromSignIn, nonce };
|
|
942
|
+
}
|
|
943
|
+
const CONSENT_PARAMS = ['client_id', 'redirect_uri', 'response_type', 'scope', 'state', 'code_challenge', 'code_challenge_method', 'nonce'];
|
|
944
|
+
// ---- Token endpoint (oauth.ts) ------------------------------------------------------------------
|
|
945
|
+
async function readTokenBody(req) {
|
|
946
|
+
const ct = (req.headers['content-type'] ?? '').toLowerCase();
|
|
947
|
+
let raw;
|
|
948
|
+
if (ct.includes('application/json')) {
|
|
949
|
+
try {
|
|
950
|
+
raw = JSON.parse((await readBody(req)) || 'null') ?? {};
|
|
951
|
+
}
|
|
952
|
+
catch {
|
|
953
|
+
throw new OAuthError('invalid_request', 'The request body could not be read.');
|
|
954
|
+
}
|
|
955
|
+
}
|
|
956
|
+
else if (ct.includes('application/x-www-form-urlencoded')) {
|
|
957
|
+
try {
|
|
958
|
+
raw = Object.fromEntries(new URLSearchParams(await readBody(req)));
|
|
959
|
+
}
|
|
960
|
+
catch {
|
|
961
|
+
throw new OAuthError('invalid_request', 'The request body could not be read.');
|
|
962
|
+
}
|
|
963
|
+
}
|
|
964
|
+
else
|
|
965
|
+
throw new OAuthError('invalid_request', 'Send the parameters as application/x-www-form-urlencoded (or JSON).');
|
|
966
|
+
if (!raw || typeof raw !== 'object' || Array.isArray(raw))
|
|
967
|
+
throw new OAuthError('invalid_request', 'The request body must be an object.');
|
|
968
|
+
const out = {};
|
|
969
|
+
for (const [k, v] of Object.entries(raw)) {
|
|
970
|
+
if (typeof v !== 'string')
|
|
971
|
+
throw new OAuthError('invalid_request', `The parameter "${k}" must be a single string.`);
|
|
972
|
+
out[k] = v;
|
|
973
|
+
}
|
|
974
|
+
return out;
|
|
975
|
+
}
|
|
976
|
+
const formDecode = (s) => {
|
|
977
|
+
try {
|
|
978
|
+
return decodeURIComponent(s.replace(/\+/g, ' '));
|
|
979
|
+
}
|
|
980
|
+
catch {
|
|
981
|
+
throw new OAuthError('invalid_client', 'The client credentials in the Authorization header are not correctly encoded.', 401);
|
|
982
|
+
}
|
|
983
|
+
};
|
|
984
|
+
/** client_secret_basic or client_secret_post, never both. */
|
|
985
|
+
function authenticateClient(req, body) {
|
|
986
|
+
const header = req.headers.authorization ?? '';
|
|
987
|
+
const m = /^Basic\s+([A-Za-z0-9+/=]+)\s*$/i.exec(header);
|
|
988
|
+
let clientId;
|
|
989
|
+
let secret;
|
|
990
|
+
if (m) {
|
|
991
|
+
const decoded = Buffer.from(m[1], 'base64').toString('utf8');
|
|
992
|
+
const i = decoded.indexOf(':');
|
|
993
|
+
if (i < 0)
|
|
994
|
+
throw new OAuthError('invalid_client', 'The Authorization header must be Basic base64(client_id:client_secret).', 401);
|
|
995
|
+
clientId = formDecode(decoded.slice(0, i));
|
|
996
|
+
secret = formDecode(decoded.slice(i + 1));
|
|
997
|
+
if (body.client_secret !== undefined)
|
|
998
|
+
throw new OAuthError('invalid_request', 'Send the client secret one way only: the Authorization header or the body.');
|
|
999
|
+
if (body.client_id !== undefined && body.client_id !== clientId)
|
|
1000
|
+
throw new OAuthError('invalid_request', 'client_id in the body does not match the Authorization header.');
|
|
1001
|
+
}
|
|
1002
|
+
else if (header && /^\s*\S/.test(header)) {
|
|
1003
|
+
throw new OAuthError('invalid_client', 'Authenticate with HTTP Basic (client_id:client_secret) or client_id and client_secret in the body.', 401);
|
|
1004
|
+
}
|
|
1005
|
+
else {
|
|
1006
|
+
clientId = body.client_id;
|
|
1007
|
+
secret = body.client_secret;
|
|
1008
|
+
}
|
|
1009
|
+
if (!clientId || !secret)
|
|
1010
|
+
throw new OAuthError('invalid_client', 'Client authentication is required: client_id and client_secret.', 401);
|
|
1011
|
+
const key = clientId.slice(0, 100);
|
|
1012
|
+
const fails = failures.get(key);
|
|
1013
|
+
if (fails && fails.resetAt > Date.now() && fails.count >= 20)
|
|
1014
|
+
throw new OAuthError('slow_down', 'Too many failed attempts. Wait a minute and try again.', 429);
|
|
1015
|
+
if (clientId !== credentials.clientId || secret !== credentials.clientSecret) {
|
|
1016
|
+
const now = Date.now();
|
|
1017
|
+
const w = fails && fails.resetAt > now ? fails : { count: 0, resetAt: now + 60_000 };
|
|
1018
|
+
w.count++;
|
|
1019
|
+
failures.set(key, w);
|
|
1020
|
+
log(` ✖ token endpoint: wrong client id or secret. The dev server's are ${credentials.clientId} and its test secret (USEBECKY_CLIENT_ID, USEBECKY_CLIENT_SECRET).`);
|
|
1021
|
+
throw new OAuthError('invalid_client', 'Unknown client or wrong client secret.', 401);
|
|
1022
|
+
}
|
|
1023
|
+
return { basic: !!m };
|
|
1024
|
+
}
|
|
1025
|
+
async function authorizationCodeGrant(body) {
|
|
1026
|
+
const { code, redirect_uri: redirectUri, code_verifier: verifier } = body;
|
|
1027
|
+
if (!code || !redirectUri || !verifier)
|
|
1028
|
+
throw new OAuthError('invalid_request', 'code, redirect_uri and code_verifier are required.');
|
|
1029
|
+
if (!VERIFIER_RE.test(verifier))
|
|
1030
|
+
throw new OAuthError('invalid_request', 'code_verifier must be 43 to 128 characters of A-Z, a-z, 0-9, "-", ".", "_" and "~".');
|
|
1031
|
+
// Claim the code first (single use): a wrong verifier or redirect_uri burns it too.
|
|
1032
|
+
const c = codes.get(code);
|
|
1033
|
+
if (!c || c.used) {
|
|
1034
|
+
if (c?.used)
|
|
1035
|
+
revokeAll(c.install, 'an authorization code was used twice');
|
|
1036
|
+
throw new OAuthError('invalid_grant', 'The authorization code is invalid, expired or already used.');
|
|
1037
|
+
}
|
|
1038
|
+
c.used = true;
|
|
1039
|
+
if (c.expiresAt <= Date.now())
|
|
1040
|
+
throw new OAuthError('invalid_grant', 'The authorization code expired (codes last 10 minutes). Start the connection again.');
|
|
1041
|
+
if (c.redirectUri !== redirectUri)
|
|
1042
|
+
throw new OAuthError('invalid_grant', 'redirect_uri does not match the one used to get the code.');
|
|
1043
|
+
if (base64url(await sha256(verifier)) !== c.challenge)
|
|
1044
|
+
throw new OAuthError('invalid_grant', 'code_verifier does not match the code_challenge (PKCE S256).');
|
|
1045
|
+
const install = installById(c.install);
|
|
1046
|
+
if (!install || install.status !== 'active')
|
|
1047
|
+
throw new OAuthError('invalid_grant', 'The extension is no longer installed in this project.');
|
|
1048
|
+
log(` ✔ tokens issued for ${install.project.name}${c.oidc ? ' (with an id_token: create the account from it)' : ''}`);
|
|
1049
|
+
const tokens = issue(install);
|
|
1050
|
+
if (!c.oidc)
|
|
1051
|
+
return tokens;
|
|
1052
|
+
return { ...tokens, scope: [tokens.scope, ...OIDC_SCOPES].filter(Boolean).join(' '), id_token: await idToken(install, c.nonce) };
|
|
1053
|
+
}
|
|
1054
|
+
function refreshTokenGrant(body) {
|
|
1055
|
+
const token = body.refresh_token;
|
|
1056
|
+
if (!token)
|
|
1057
|
+
throw new OAuthError('invalid_request', 'refresh_token is required.');
|
|
1058
|
+
const t = tokens.get(token);
|
|
1059
|
+
if (!t || t.kind !== 'refresh')
|
|
1060
|
+
throw new OAuthError('invalid_grant', 'The refresh token is invalid.');
|
|
1061
|
+
if (t.revoked) {
|
|
1062
|
+
revokeAll(t.install, 'a refresh token was used after it had been replaced');
|
|
1063
|
+
throw new OAuthError('invalid_grant', 'The refresh token was already used. Every token of this installation is revoked; the customer has to connect again.');
|
|
1064
|
+
}
|
|
1065
|
+
if (t.expiresAt <= Date.now())
|
|
1066
|
+
throw new OAuthError('invalid_grant', 'The refresh token expired. The customer has to connect again.');
|
|
1067
|
+
const install = installById(t.install);
|
|
1068
|
+
if (body.scope !== undefined) {
|
|
1069
|
+
const asked = body.scope.split(' ').filter(Boolean);
|
|
1070
|
+
if (!install || asked.some((s) => !install.scopes.includes(s)))
|
|
1071
|
+
throw new OAuthError('invalid_scope', 'A refresh can only keep the permissions already granted.');
|
|
1072
|
+
}
|
|
1073
|
+
t.revoked = true; // rotated
|
|
1074
|
+
if (!install || install.status !== 'active')
|
|
1075
|
+
throw new OAuthError('invalid_grant', 'The extension is no longer connected to this project.');
|
|
1076
|
+
log(` ✔ tokens refreshed for ${install.project.name}`);
|
|
1077
|
+
return issue(install);
|
|
1078
|
+
}
|
|
1079
|
+
async function tokenRoute(req, res, kind) {
|
|
1080
|
+
let basic = /^Basic\s/i.test(req.headers.authorization ?? '');
|
|
1081
|
+
try {
|
|
1082
|
+
const now = Date.now();
|
|
1083
|
+
if (tokenCalls.resetAt <= now)
|
|
1084
|
+
tokenCalls = { count: 0, resetAt: now + 60_000 };
|
|
1085
|
+
if (++tokenCalls.count > 600)
|
|
1086
|
+
throw new OAuthError('slow_down', 'Too many requests. Wait a minute and try again.', 429);
|
|
1087
|
+
const body = await readTokenBody(req);
|
|
1088
|
+
basic = authenticateClient(req, body).basic;
|
|
1089
|
+
if (kind === 'revoke') {
|
|
1090
|
+
if (!body.token)
|
|
1091
|
+
throw new OAuthError('invalid_request', 'token is required.');
|
|
1092
|
+
const t = tokens.get(body.token);
|
|
1093
|
+
if (t?.kind === 'refresh')
|
|
1094
|
+
revokeAll(t.install, null);
|
|
1095
|
+
else if (t)
|
|
1096
|
+
t.revoked = true;
|
|
1097
|
+
if (t)
|
|
1098
|
+
log(' · tokens revoked by the extension');
|
|
1099
|
+
res.writeHead(200, NO_STORE);
|
|
1100
|
+
return res.end();
|
|
1101
|
+
}
|
|
1102
|
+
let answer;
|
|
1103
|
+
if (body.grant_type === 'authorization_code')
|
|
1104
|
+
answer = await authorizationCodeGrant(body);
|
|
1105
|
+
else if (body.grant_type === 'refresh_token')
|
|
1106
|
+
answer = refreshTokenGrant(body);
|
|
1107
|
+
else
|
|
1108
|
+
throw new OAuthError(body.grant_type ? 'unsupported_grant_type' : 'invalid_request', body.grant_type ? `grant_type "${body.grant_type.slice(0, 40)}" is not supported. Use authorization_code or refresh_token.` : 'grant_type is required.');
|
|
1109
|
+
return json(res, 200, answer, NO_STORE);
|
|
1110
|
+
}
|
|
1111
|
+
catch (err) {
|
|
1112
|
+
if (!(err instanceof OAuthError))
|
|
1113
|
+
throw err;
|
|
1114
|
+
if (err.error !== 'invalid_client')
|
|
1115
|
+
log(` ✖ ${kind === 'token' ? 'token endpoint' : 'revoke'}: ${err.error}: ${err.message}`);
|
|
1116
|
+
return json(res, err.status, { error: err.error, error_description: err.message }, { ...NO_STORE, ...(err.status === 401 && basic ? { 'www-authenticate': 'Basic realm="usebecky extensions"' } : {}) });
|
|
1117
|
+
}
|
|
1118
|
+
}
|
|
1119
|
+
// ---- Partner API (partner.ts) -----------------------------------------------------------------
|
|
1120
|
+
function partnerAuth(req, res) {
|
|
1121
|
+
const m = /^Bearer\s+(\S+)\s*$/i.exec(req.headers.authorization ?? '');
|
|
1122
|
+
const token = m ? m[1] : null;
|
|
1123
|
+
if (!token || !token.startsWith(TOKEN_PREFIXES.accessToken)) {
|
|
1124
|
+
apiError(res, 401, 'invalid_token', 'An extension access token is required.', 'Send "Authorization: Bearer ub_it_..." from your server. Project API keys don\'t work here.', undefined, { 'www-authenticate': 'Bearer realm="usebecky extensions"' });
|
|
1125
|
+
return null;
|
|
1126
|
+
}
|
|
1127
|
+
const t = tokens.get(token);
|
|
1128
|
+
const known = !!t && t.kind === 'access' && !t.revoked;
|
|
1129
|
+
const install = t ? installById(t.install) : undefined;
|
|
1130
|
+
if (!known || !install || t.expiresAt <= Date.now()) {
|
|
1131
|
+
const expired = known && !!install && t.expiresAt <= Date.now();
|
|
1132
|
+
apiError(res, 401, 'invalid_token', expired ? 'The access token expired (they last one hour).' : 'The access token is invalid or was revoked.', 'Get a new access token with your refresh token (POST /extensions/v1/oauth/token).', undefined, {
|
|
1133
|
+
'www-authenticate': 'Bearer realm="usebecky extensions", error="invalid_token"',
|
|
1134
|
+
});
|
|
1135
|
+
return null;
|
|
1136
|
+
}
|
|
1137
|
+
if (install.status !== 'active') {
|
|
1138
|
+
apiError(res, 403, 'installation_inactive', 'This installation is not active.', 'The customer has to connect the extension again from their project.');
|
|
1139
|
+
return null;
|
|
1140
|
+
}
|
|
1141
|
+
const now = Date.now();
|
|
1142
|
+
const w = hits.get(install.id);
|
|
1143
|
+
const win = w && w.resetAt > now ? w : { count: 0, resetAt: now + 60_000 };
|
|
1144
|
+
win.count++;
|
|
1145
|
+
hits.set(install.id, win);
|
|
1146
|
+
if (win.count > perMinute) {
|
|
1147
|
+
apiError(res, 429, 'rate_limited', `Too many requests: at most ${perMinute} per minute per installation.`, 'Wait a minute, and cache what you can.', undefined, { 'retry-after': '60' });
|
|
1148
|
+
return null;
|
|
1149
|
+
}
|
|
1150
|
+
return { install, scopes: effectiveScopes(install) };
|
|
1151
|
+
}
|
|
1152
|
+
function requireScope(res, granted, scope) {
|
|
1153
|
+
if (granted.includes(scope))
|
|
1154
|
+
return true;
|
|
1155
|
+
apiError(res, 403, 'insufficient_scope', `This needs the "${scope}" permission.`, 'Add it to your listing (it goes live after review) and have the customer connect again to grant it.', { required_scope: scope });
|
|
1156
|
+
return false;
|
|
1157
|
+
}
|
|
1158
|
+
/** GET /analytics/summary: usebecky's range rules and the plan's analytics history. */
|
|
1159
|
+
function summary(res, project, q) {
|
|
1160
|
+
const qf = q.get('from') || undefined;
|
|
1161
|
+
const qt = q.get('to') || undefined;
|
|
1162
|
+
if ((qf && !qt) || (!qf && qt))
|
|
1163
|
+
return apiError(res, 400, 'invalid_range', 'Send both "from" and "to" (YYYY-MM-DD), or neither for the last 30 days.');
|
|
1164
|
+
const now = Date.now();
|
|
1165
|
+
const from = qf ?? ymd(now - 29 * DAY_MS);
|
|
1166
|
+
const to = qt ?? ymd(now);
|
|
1167
|
+
const parse = (v, name) => {
|
|
1168
|
+
const m = DATE.exec(v.trim());
|
|
1169
|
+
const t = m ? Date.UTC(Number(m[1]), Number(m[2]) - 1, Number(m[3])) : NaN;
|
|
1170
|
+
if (!m || Number.isNaN(t) || ymd(t) !== v.trim() || Number(m[1]) < 2000) {
|
|
1171
|
+
apiError(res, 400, 'invalid_range', `"${name}" must be a date like 2026-01-31.`, 'Send both from and to, e.g. ?from=2026-01-01&to=2026-01-31 (both days are included).');
|
|
1172
|
+
return null;
|
|
1173
|
+
}
|
|
1174
|
+
return t;
|
|
1175
|
+
};
|
|
1176
|
+
const f = parse(from, 'from');
|
|
1177
|
+
if (f === null)
|
|
1178
|
+
return;
|
|
1179
|
+
const t = parse(to, 'to');
|
|
1180
|
+
if (t === null)
|
|
1181
|
+
return;
|
|
1182
|
+
const days = Math.round((t - f) / DAY_MS) + 1;
|
|
1183
|
+
if (days < 1)
|
|
1184
|
+
return apiError(res, 400, 'invalid_range', '"from" must be on or before "to".');
|
|
1185
|
+
if (days > MAX_CUSTOM_DAYS)
|
|
1186
|
+
return apiError(res, 400, 'invalid_range', `A custom range can be at most ${MAX_CUSTOM_DAYS} days long.`);
|
|
1187
|
+
if (f > now)
|
|
1188
|
+
return apiError(res, 400, 'invalid_range', '"from" is in the future.', 'Pick a start date of today or earlier.');
|
|
1189
|
+
const plan = PLANS[project.plan];
|
|
1190
|
+
const need = Math.max(1, Math.ceil((now - f) / DAY_MS));
|
|
1191
|
+
if (need > plan.history + 1) {
|
|
1192
|
+
const required = ['pro', 'business'].find((p) => PLANS[p].history >= need && PLANS[p].history > plan.history) ?? null;
|
|
1193
|
+
return apiError(res, 403, 'plan_required', `The ${plan.name} plan shows the last ${plan.history} days of visitor analytics.`, required ? `To look further back, upgrade to ${PLANS[required].name} in Dashboard → Settings → Usage & plan. Or pick a shorter date range.` : 'Pick a shorter date range.', { quota: 'analytics_history_days', limit: plan.history, days: need, plan: project.plan, required_plan: required, upgrade_url: `${base}/project/${project.ref}/settings/usage?upgrade=analytics_history_days` });
|
|
1194
|
+
}
|
|
1195
|
+
return json(res, 200, fakeSummary(project.ref, from, to));
|
|
1196
|
+
}
|
|
1197
|
+
// ---- Only for this computer ---------------------------------------------------------------------
|
|
1198
|
+
/** The dev server's own pages, at any of the names it answers to (localhost or 127.0.0.1, say), on its port. */
|
|
1199
|
+
function isOwnOrigin(origin) {
|
|
1200
|
+
try {
|
|
1201
|
+
const o = new URL(origin);
|
|
1202
|
+
return o.protocol === 'http:' && o.origin === origin && hostAllowed(o.hostname) && (o.port || '80') === String(ownPort);
|
|
1203
|
+
}
|
|
1204
|
+
catch {
|
|
1205
|
+
return false;
|
|
1206
|
+
}
|
|
1207
|
+
}
|
|
1208
|
+
/** Refuse what a web page might send: another host name (DNS rebinding), or a change from another website. True: refused. */
|
|
1209
|
+
function refuseForeign(req, res, method, pathname) {
|
|
1210
|
+
const host = req.headers.host;
|
|
1211
|
+
if (host !== undefined) {
|
|
1212
|
+
const name = hostnameOf(host);
|
|
1213
|
+
if (!name || !hostAllowed(name)) {
|
|
1214
|
+
log(` ✖ refused a request addressed to "${host.slice(0, 80)}": the dev server only answers to localhost`);
|
|
1215
|
+
apiError(res, 403, 'host_not_allowed', `The dev server only answers requests addressed to this computer (localhost), not to "${host.slice(0, 80)}".`, `Open ${base}.`);
|
|
1216
|
+
return true;
|
|
1217
|
+
}
|
|
1218
|
+
}
|
|
1219
|
+
if (SAFE_METHODS.has(method) && !SIGN_IN_PATHS.has(pathname))
|
|
1220
|
+
return false;
|
|
1221
|
+
const from = foreignSource(req, isOwnOrigin);
|
|
1222
|
+
if (!from)
|
|
1223
|
+
return false;
|
|
1224
|
+
log(` ✖ refused ${method} ${(req.url ?? '').split('?')[0]} from another website (${from.slice(0, 80)})`);
|
|
1225
|
+
apiError(res, 403, 'cross_site_request', `The dev server refused a request from another website (${from.slice(0, 80)}).`, `Use the buttons on ${base}, or send it without a browser (curl, your tests).`);
|
|
1226
|
+
return true;
|
|
1227
|
+
}
|
|
1228
|
+
// ---- Routes -------------------------------------------------------------------------------------
|
|
1229
|
+
async function handle(req, res) {
|
|
1230
|
+
const method = req.method ?? 'GET';
|
|
1231
|
+
const url = new URL(req.url ?? '/', base);
|
|
1232
|
+
const pathname = url.pathname.replace(/\/+$/, '') || '/';
|
|
1233
|
+
if (refuseForeign(req, res, method, pathname))
|
|
1234
|
+
return;
|
|
1235
|
+
const route = `${method} ${pathname}`;
|
|
1236
|
+
const read = async () => parseBody(await readBody(req), req.headers['content-type']);
|
|
1237
|
+
const page = /^\/project\/([^/]+)\/extensions\/([^/]+)$/.exec(pathname);
|
|
1238
|
+
if (method === 'GET' && page) {
|
|
1239
|
+
const project = projectOf(page[1]);
|
|
1240
|
+
if (!project || page[2] !== slug)
|
|
1241
|
+
return html(res, 404, errorHtml('Not found', 'There is no such project or extension on the dev server.'));
|
|
1242
|
+
const install = installs.get(project.ref);
|
|
1243
|
+
const state = !install ? 'not_added' : install.status === 'error' ? 'reconnect' : isConnected(install) ? 'connected' : 'not_connected';
|
|
1244
|
+
let uiSettings = null;
|
|
1245
|
+
if (ui?.settings && install?.status === 'active') {
|
|
1246
|
+
const r = await askUi(project, install, SETTINGS_PAGE, {}, localeOf(req.headers['accept-language']));
|
|
1247
|
+
uiSettings = r.ok
|
|
1248
|
+
? renderBlocks(r.value, { base: `/project/${encodeURIComponent(project.ref)}/x`, page: SETTINGS_PAGE, params: {}, back: extensionPath(project.ref), planHref: planHrefFor(project.ref) })
|
|
1249
|
+
: `<p class="note bad">${escapeHtml(`${extensionName} couldn't show its settings. Because: ${r.error}`)}</p>`;
|
|
1250
|
+
}
|
|
1251
|
+
return html(res, 200, extensionPage({
|
|
1252
|
+
extensionName,
|
|
1253
|
+
logoUrl,
|
|
1254
|
+
project,
|
|
1255
|
+
mode,
|
|
1256
|
+
state,
|
|
1257
|
+
settings: install ? publicSettings(install) : {},
|
|
1258
|
+
fields,
|
|
1259
|
+
actionHref: mode === 'oauth' && state === 'connected' ? (installUrl ? new URL(installUrl).origin : null) : installHref(project.ref),
|
|
1260
|
+
notice: url.searchParams.get('saved') ? 'Saved.' : url.searchParams.get('_toast'),
|
|
1261
|
+
pages: install?.status === 'active' ? uiLinks(project.ref) : [],
|
|
1262
|
+
uiSettings,
|
|
1263
|
+
plans: devPlans,
|
|
1264
|
+
plan: install ? planOf(install) : null,
|
|
1265
|
+
pickedPlan: url.searchParams.get('plan'),
|
|
1266
|
+
}));
|
|
1267
|
+
}
|
|
1268
|
+
const uiRoute = /^\/project\/([^/]+)\/x\/([^/]+)$/.exec(pathname);
|
|
1269
|
+
if (uiRoute && (method === 'GET' || method === 'POST'))
|
|
1270
|
+
return uiPageRoute(req, res, method, url, decodeURIComponent(uiRoute[1]), decodeURIComponent(uiRoute[2]));
|
|
1271
|
+
switch (route) {
|
|
1272
|
+
case 'GET /': {
|
|
1273
|
+
const sent = url.searchParams.get('sent');
|
|
1274
|
+
const last = deliveries[deliveries.length - 1];
|
|
1275
|
+
const notice = sent && last ? (last.error ? { text: `${last.type} was not delivered: ${last.error}`, bad: true } : { text: `Sent ${last.type} to your webhook (HTTP ${last.status}, ${last.ms} ms).`, bad: false }) : url.searchParams.get('disconnected') ? { text: 'Disconnected. Your extension got extension.uninstalled.', bad: false } : url.searchParams.get('plan') ? { text: 'Plan updated.', bad: false } : null;
|
|
1276
|
+
const eventTypes = ['test.ping', ...EXTENSION_EVENT_TYPES, ...listedEvents];
|
|
1277
|
+
const projects = DEV_PROJECTS.map((p) => {
|
|
1278
|
+
const i = installs.get(p.ref);
|
|
1279
|
+
const canOpen = !!i && !!account?.ssoUrl && i.status === 'active' && (account.provision === 'url' ? !!i.partnerAccountId : isConnected(i));
|
|
1280
|
+
return { ref: p.ref, name: p.name, plan: p.plan, install: i ? { status: i.status, connected: isConnected(i), plan: planOf(i) } : null, installHref: installHref(p.ref), pageHref: extensionPath(p.ref), openHref: canOpen ? `/dev/launch?project=${encodeURIComponent(p.ref)}` : null, pages: i?.status === 'active' ? uiLinks(p.ref) : [] };
|
|
1281
|
+
});
|
|
1282
|
+
return html(res, 200, homePage({
|
|
1283
|
+
extensionName,
|
|
1284
|
+
summary: typeof manifest?.summary === 'string' ? manifest.summary : 'Add usebecky-extension.json to this folder to describe your extension.',
|
|
1285
|
+
logoUrl,
|
|
1286
|
+
mode,
|
|
1287
|
+
projects,
|
|
1288
|
+
eventTypes,
|
|
1289
|
+
webhookUrl,
|
|
1290
|
+
credentials,
|
|
1291
|
+
url: base,
|
|
1292
|
+
notice,
|
|
1293
|
+
problems,
|
|
1294
|
+
testProject,
|
|
1295
|
+
plans: devPlans,
|
|
1296
|
+
}));
|
|
1297
|
+
}
|
|
1298
|
+
case 'GET /logo': {
|
|
1299
|
+
if (!logoFile || !fs.existsSync(logoFile))
|
|
1300
|
+
return apiError(res, 404, 'not_found', 'No logo file.');
|
|
1301
|
+
const ext = path.extname(logoFile).toLowerCase();
|
|
1302
|
+
const type = ext === '.svg' ? 'image/svg+xml' : ext === '.png' ? 'image/png' : 'image/jpeg';
|
|
1303
|
+
res.writeHead(200, { 'content-type': type, 'content-security-policy': "default-src 'none'; style-src 'unsafe-inline'" });
|
|
1304
|
+
return res.end(fs.readFileSync(logoFile));
|
|
1305
|
+
}
|
|
1306
|
+
case 'GET /healthz':
|
|
1307
|
+
return json(res, 200, { ok: true });
|
|
1308
|
+
case 'GET /.well-known/openid-configuration':
|
|
1309
|
+
return json(res, 200, {
|
|
1310
|
+
issuer: base,
|
|
1311
|
+
authorization_endpoint: `${base}/oauth/authorize`,
|
|
1312
|
+
token_endpoint: `${base}/extensions/v1/oauth/token`,
|
|
1313
|
+
revocation_endpoint: `${base}/extensions/v1/oauth/revoke`,
|
|
1314
|
+
jwks_uri: `${base}/.well-known/jwks.json`,
|
|
1315
|
+
response_types_supported: ['code'],
|
|
1316
|
+
grant_types_supported: ['authorization_code', 'refresh_token'],
|
|
1317
|
+
subject_types_supported: ['pairwise'],
|
|
1318
|
+
id_token_signing_alg_values_supported: ['ES256'],
|
|
1319
|
+
token_endpoint_auth_methods_supported: ['client_secret_basic', 'client_secret_post'],
|
|
1320
|
+
code_challenge_methods_supported: ['S256'],
|
|
1321
|
+
scopes_supported: [...OIDC_SCOPES, ...EXTENSION_SCOPES],
|
|
1322
|
+
claims_supported: ['iss', 'sub', 'aud', 'exp', 'iat', 'nonce', 'email', 'email_verified', 'name', 'usebecky_project', 'usebecky_install', 'usebecky_role'],
|
|
1323
|
+
});
|
|
1324
|
+
case 'GET /.well-known/jwks.json':
|
|
1325
|
+
return json(res, 200, { keys: [signing.publicJwk] });
|
|
1326
|
+
case 'GET /dev/launch': {
|
|
1327
|
+
try {
|
|
1328
|
+
const to = await launchFor(url.searchParams.get('project') ?? undefined);
|
|
1329
|
+
log(` · Open in ${extensionName}: launch token sent to ${account?.ssoUrl}`);
|
|
1330
|
+
return redirect(res, to);
|
|
1331
|
+
}
|
|
1332
|
+
catch (err) {
|
|
1333
|
+
return html(res, 400, errorHtml(`Can't open ${extensionName}`, err.message));
|
|
1334
|
+
}
|
|
1335
|
+
}
|
|
1336
|
+
case 'POST /dev/provision': {
|
|
1337
|
+
const form = await read();
|
|
1338
|
+
const project = projectOf(form.project);
|
|
1339
|
+
if (mode !== 'fields' || account?.provision !== 'url' || !project)
|
|
1340
|
+
return html(res, 400, errorHtml('Not possible', 'This extension does not create accounts with a provision URL.'));
|
|
1341
|
+
const out = await provisionFor(project);
|
|
1342
|
+
if (!out.ok)
|
|
1343
|
+
return html(res, 502, provisionPage({ extensionName, logoUrl, project, person: DEV_PERSON, error: out.error }));
|
|
1344
|
+
return send(res, 303, '', 'text/plain', { location: `/dev/install?project=${encodeURIComponent(project.ref)}` });
|
|
1345
|
+
}
|
|
1346
|
+
case 'GET /oauth/authorize': {
|
|
1347
|
+
const q = Object.fromEntries(url.searchParams);
|
|
1348
|
+
let c;
|
|
1349
|
+
try {
|
|
1350
|
+
c = resolveConsent(q);
|
|
1351
|
+
}
|
|
1352
|
+
catch (err) {
|
|
1353
|
+
if (!(err instanceof ConsentError))
|
|
1354
|
+
throw err;
|
|
1355
|
+
log(` ✖ consent screen: ${err.code}: ${err.message}`);
|
|
1356
|
+
return html(res, 400, consentProblemPage(err.message, err.hint, err.code));
|
|
1357
|
+
}
|
|
1358
|
+
const params = {};
|
|
1359
|
+
for (const k of CONSENT_PARAMS)
|
|
1360
|
+
if (q[k] !== undefined)
|
|
1361
|
+
params[k] = q[k];
|
|
1362
|
+
const projects = DEV_PROJECTS.map((p) => {
|
|
1363
|
+
const i = installs.get(p.ref);
|
|
1364
|
+
return { ref: p.ref, name: p.name, plan: p.plan, installed: !!i, connected: !!i && mode === 'oauth' && isConnected(i) };
|
|
1365
|
+
});
|
|
1366
|
+
const selected = c.project && projectOf(c.project) ? c.project : projects.length === 1 ? projects[0].ref : null;
|
|
1367
|
+
return html(res, 200, consentPage({
|
|
1368
|
+
extensionName,
|
|
1369
|
+
publisher,
|
|
1370
|
+
logoUrl,
|
|
1371
|
+
scopes: c.scopes.map((s) => EXTENSION_SCOPE_INFO[s]),
|
|
1372
|
+
dataShared,
|
|
1373
|
+
events: c.scopes.includes('events:read') ? listedEvents : [],
|
|
1374
|
+
projects,
|
|
1375
|
+
selected,
|
|
1376
|
+
params,
|
|
1377
|
+
account: account ? { name: DEV_PERSON.name, email: DEV_PERSON.email, sso: !!account.ssoUrl } : null,
|
|
1378
|
+
}));
|
|
1379
|
+
}
|
|
1380
|
+
case 'POST /oauth/authorize': {
|
|
1381
|
+
const q = await read();
|
|
1382
|
+
let c;
|
|
1383
|
+
try {
|
|
1384
|
+
c = resolveConsent(q);
|
|
1385
|
+
}
|
|
1386
|
+
catch (err) {
|
|
1387
|
+
if (!(err instanceof ConsentError))
|
|
1388
|
+
throw err;
|
|
1389
|
+
return html(res, 400, consentProblemPage(err.message, err.hint, err.code));
|
|
1390
|
+
}
|
|
1391
|
+
const back = new URL(c.redirectUri);
|
|
1392
|
+
if (q.decision !== 'allow') {
|
|
1393
|
+
back.searchParams.set('error', 'access_denied');
|
|
1394
|
+
back.searchParams.set('error_description', 'The customer did not allow access.');
|
|
1395
|
+
if (c.state)
|
|
1396
|
+
back.searchParams.set('state', c.state);
|
|
1397
|
+
log(' · consent screen: Cancel');
|
|
1398
|
+
return redirect(res, back.toString());
|
|
1399
|
+
}
|
|
1400
|
+
if (!c.project)
|
|
1401
|
+
return html(res, 400, errorHtml('Choose the project to connect.', 'Pick one of the projects, then click Allow.'));
|
|
1402
|
+
const project = projectOf(c.project);
|
|
1403
|
+
if (!project)
|
|
1404
|
+
return html(res, 404, errorHtml('Project not found.', 'Pick one of the projects on the consent screen.'));
|
|
1405
|
+
const existing = installs.get(project.ref);
|
|
1406
|
+
// Allowing again (a reconnect) grants the listing's current scopes and events, like usebecky's re-consent.
|
|
1407
|
+
const install = existing ?? { id: crypto.randomUUID(), project, scopes: c.scopes, events: allowedEvents(c.scopes), settings: {}, status: 'active', lastError: null, installedAt: new Date().toISOString(), plan: newPlan(project.ref) };
|
|
1408
|
+
if (existing)
|
|
1409
|
+
Object.assign(existing, { scopes: c.scopes, events: allowedEvents(c.scopes), status: 'active', lastError: null });
|
|
1410
|
+
else
|
|
1411
|
+
installs.set(project.ref, install);
|
|
1412
|
+
const code = `${TOKEN_PREFIXES.authorizationCode}${randomAlnum(40)}`;
|
|
1413
|
+
codes.set(code, { install: install.id, redirectUri: c.redirectUri, challenge: c.codeChallenge, expiresAt: Date.now() + AUTHORIZATION_CODE_TTL_SECONDS * 1000, used: false, oidc: c.oidc, nonce: c.nonce });
|
|
1414
|
+
back.searchParams.set('code', code);
|
|
1415
|
+
if (c.state)
|
|
1416
|
+
back.searchParams.set('state', c.state);
|
|
1417
|
+
log(` · consent screen: Allow on ${project.name} (${project.ref}): ${existing ? 'connected again' : 'added'}, allowed ${c.scopes.join(', ') || 'no permissions'}`);
|
|
1418
|
+
redirect(res, back.toString());
|
|
1419
|
+
// usebecky queues extension.installed when the install is made; its worker delivers it moments later.
|
|
1420
|
+
if (!existing)
|
|
1421
|
+
void deliver(deliveryEvent('extension.installed', sampleInstall(install)));
|
|
1422
|
+
return;
|
|
1423
|
+
}
|
|
1424
|
+
case 'POST /extensions/v1/oauth/token':
|
|
1425
|
+
return tokenRoute(req, res, 'token');
|
|
1426
|
+
case 'POST /extensions/v1/oauth/revoke':
|
|
1427
|
+
return tokenRoute(req, res, 'revoke');
|
|
1428
|
+
case 'GET /extensions/v1/installation': {
|
|
1429
|
+
const p = partnerAuth(req, res);
|
|
1430
|
+
if (!p)
|
|
1431
|
+
return;
|
|
1432
|
+
return json(res, 200, installationOf(p.install));
|
|
1433
|
+
}
|
|
1434
|
+
case 'PUT /extensions/v1/installation/settings':
|
|
1435
|
+
case 'DELETE /extensions/v1/installation/settings': {
|
|
1436
|
+
const p = partnerAuth(req, res);
|
|
1437
|
+
if (!p)
|
|
1438
|
+
return;
|
|
1439
|
+
if (!capabilities.includes('sgtm_forwarding')) {
|
|
1440
|
+
return apiError(res, 403, 'capability_required', 'Only extensions that usebecky set up for server-side tagging can change these settings (capability "sgtm_forwarding").', 'usebecky sets capabilities after review. If your extension sends events to a Google Tag Manager tagging server, ask usebecky to turn it on. Dev server: --capability sgtm_forwarding.', { required_capability: 'sgtm_forwarding' });
|
|
1441
|
+
}
|
|
1442
|
+
let next = null;
|
|
1443
|
+
if (method === 'PUT') {
|
|
1444
|
+
let body;
|
|
1445
|
+
try {
|
|
1446
|
+
body = JSON.parse(await readBody(req));
|
|
1447
|
+
}
|
|
1448
|
+
catch {
|
|
1449
|
+
body = undefined;
|
|
1450
|
+
}
|
|
1451
|
+
try {
|
|
1452
|
+
next = checkTaggingSettings(body);
|
|
1453
|
+
}
|
|
1454
|
+
catch (err) {
|
|
1455
|
+
if (!(err instanceof TaggingSettingsError))
|
|
1456
|
+
throw err;
|
|
1457
|
+
log(` ✖ PUT /installation/settings: ${err.message}`);
|
|
1458
|
+
return apiError(res, 400, 'invalid_settings', err.message, err.hint, err.field ? { field: err.field } : undefined);
|
|
1459
|
+
}
|
|
1460
|
+
}
|
|
1461
|
+
for (const k of TAGGING_KEYS)
|
|
1462
|
+
delete p.install.settings[k];
|
|
1463
|
+
if (next)
|
|
1464
|
+
Object.assign(p.install.settings, next);
|
|
1465
|
+
log(next ? ` · ${p.install.project.name}: server-side tagging to ${next.tagging_server_url} (${next.measurement_id})` : ` · ${p.install.project.name}: server-side tagging turned off`);
|
|
1466
|
+
return json(res, 200, { settings: publicSettings(p.install) });
|
|
1467
|
+
}
|
|
1468
|
+
case 'GET /extensions/v1/project': {
|
|
1469
|
+
const p = partnerAuth(req, res);
|
|
1470
|
+
if (!p || !requireScope(res, p.scopes, 'project:read'))
|
|
1471
|
+
return;
|
|
1472
|
+
const { ref, name, api_url, publishable_key, allowed_hosts } = p.install.project;
|
|
1473
|
+
return json(res, 200, { ref, name, api_url, publishable_key, allowed_hosts: [...allowed_hosts] });
|
|
1474
|
+
}
|
|
1475
|
+
case 'GET /extensions/v1/analytics/summary': {
|
|
1476
|
+
const p = partnerAuth(req, res);
|
|
1477
|
+
if (!p || !requireScope(res, p.scopes, 'analytics:read'))
|
|
1478
|
+
return;
|
|
1479
|
+
return summary(res, p.install.project, url.searchParams);
|
|
1480
|
+
}
|
|
1481
|
+
case 'GET /dev/install': {
|
|
1482
|
+
const project = projectOf(url.searchParams.get('project'));
|
|
1483
|
+
if (mode !== 'fields')
|
|
1484
|
+
return html(res, 400, errorHtml('Not a fields extension', 'This extension connects with OAuth: click Install on the dev server home page.'));
|
|
1485
|
+
if (!project)
|
|
1486
|
+
return html(res, 404, errorHtml('Project not found.', 'Pick one of the projects on the dev server home page.'));
|
|
1487
|
+
const install = installs.get(project.ref);
|
|
1488
|
+
// account.provision "url": the account is created first (one click), then its settings are confirmed.
|
|
1489
|
+
const prov = provisioned.get(project.ref);
|
|
1490
|
+
if (!install && account?.provision === 'url' && !prov)
|
|
1491
|
+
return html(res, 200, provisionPage({ extensionName, logoUrl, project, person: DEV_PERSON, error: null }));
|
|
1492
|
+
const values = install ? publicSettings(install) : {};
|
|
1493
|
+
if (!install && prov)
|
|
1494
|
+
for (const f of fields)
|
|
1495
|
+
if (f.type !== 'secret' && prov.settings[f.key] !== undefined)
|
|
1496
|
+
values[f.key] = prov.settings[f.key];
|
|
1497
|
+
const secretsSet = fields.filter((f) => f.type === 'secret' && (install ? !!install.settings[f.key] : !!prov?.settings[f.key])).map((f) => f.key);
|
|
1498
|
+
return html(res, 200, settingsPage({ extensionName, logoUrl, project, fields, values, secretsSet, installed: !!install, error: null, filledBy: !install && prov ? extensionName : null }));
|
|
1499
|
+
}
|
|
1500
|
+
case 'POST /dev/install': {
|
|
1501
|
+
const form = await read();
|
|
1502
|
+
const project = projectOf(form.project);
|
|
1503
|
+
if (mode !== 'fields' || !project)
|
|
1504
|
+
return html(res, 400, errorHtml('Not possible', 'Use the Install button on the dev server home page.'));
|
|
1505
|
+
const existing = installs.get(project.ref);
|
|
1506
|
+
const prov = existing ? undefined : provisioned.get(project.ref);
|
|
1507
|
+
if (!existing && account?.provision === 'url' && !prov)
|
|
1508
|
+
return html(res, 409, provisionPage({ extensionName, logoUrl, project, person: DEV_PERSON, error: 'Create the account first: usebecky calls your provision URL before the extension is added.' }));
|
|
1509
|
+
// An HTML form sends a checked box as "true" and leaves an unchecked one out: yes/no fields become true or false.
|
|
1510
|
+
const input = {};
|
|
1511
|
+
for (const f of fields)
|
|
1512
|
+
input[f.key] = f.type === 'boolean' ? form[f.key] === 'true' || form[f.key] === 'on' : form[f.key];
|
|
1513
|
+
let settings;
|
|
1514
|
+
try {
|
|
1515
|
+
settings = validateSettings(input, existing?.settings ?? prov?.settings ?? {});
|
|
1516
|
+
}
|
|
1517
|
+
catch (err) {
|
|
1518
|
+
if (!(err instanceof SettingsError))
|
|
1519
|
+
throw err;
|
|
1520
|
+
const values = {};
|
|
1521
|
+
for (const f of fields)
|
|
1522
|
+
if (f.type !== 'secret' && input[f.key] !== undefined)
|
|
1523
|
+
values[f.key] = input[f.key];
|
|
1524
|
+
return html(res, 400, settingsPage({ extensionName, logoUrl, project, fields, values, secretsSet: fields.filter((f) => f.type === 'secret' && !!(existing ?? prov)?.settings[f.key]).map((f) => f.key), installed: !!existing, error: { field: err.field, message: err.message, hint: err.hint }, filledBy: prov ? extensionName : null }));
|
|
1525
|
+
}
|
|
1526
|
+
if (existing) {
|
|
1527
|
+
existing.settings = settings;
|
|
1528
|
+
log(` · settings changed on ${project.name} (usebecky sends no event for that: read them with GET /extensions/v1/installation)`);
|
|
1529
|
+
return send(res, 303, '', 'text/plain', { location: `${extensionPath(project.ref)}?saved=1` });
|
|
1530
|
+
}
|
|
1531
|
+
// The install takes the id your provision endpoint got as its idempotency key.
|
|
1532
|
+
const install = { id: prov?.installId ?? crypto.randomUUID(), project, scopes: [...listedScopes], events: allowedEvents(listedScopes), settings, status: 'active', lastError: null, installedAt: new Date().toISOString(), plan: newPlan(project.ref), ...(prov ? { partnerAccountId: prov.accountId } : {}) };
|
|
1533
|
+
installs.set(project.ref, install);
|
|
1534
|
+
provisioned.delete(project.ref);
|
|
1535
|
+
log(` · installed on ${project.name} (${project.ref}) with the settings form${prov ? ` (account ${prov.accountId})` : ''}`);
|
|
1536
|
+
await deliver(deliveryEvent('extension.installed', sampleInstall(install)));
|
|
1537
|
+
return send(res, 303, '', 'text/plain', { location: extensionPath(project.ref) });
|
|
1538
|
+
}
|
|
1539
|
+
case 'GET /dev/start': {
|
|
1540
|
+
const project = projectOf(url.searchParams.get('project'));
|
|
1541
|
+
const href = project ? installHref(project.ref) : null;
|
|
1542
|
+
if (!project || !href)
|
|
1543
|
+
return html(res, 404, errorHtml('Project not found.', 'Pick one of the projects on the dev server home page.'));
|
|
1544
|
+
const plan = url.searchParams.get('plan');
|
|
1545
|
+
if (plan && devPlans.some((p) => p.id === plan))
|
|
1546
|
+
pendingPlan.set(project.ref, plan);
|
|
1547
|
+
return redirect(res, href);
|
|
1548
|
+
}
|
|
1549
|
+
case 'POST /dev/plan':
|
|
1550
|
+
case 'POST /dev/plan-change': {
|
|
1551
|
+
const wantsJson = !!(req.headers.accept?.includes('application/json') || req.headers['content-type']?.includes('application/json'));
|
|
1552
|
+
const raw = await readBody(req);
|
|
1553
|
+
let b;
|
|
1554
|
+
if (req.headers['content-type']?.includes('application/json')) {
|
|
1555
|
+
try {
|
|
1556
|
+
const v = JSON.parse(raw || '{}');
|
|
1557
|
+
b = v && typeof v === 'object' && !Array.isArray(v) ? v : {};
|
|
1558
|
+
}
|
|
1559
|
+
catch {
|
|
1560
|
+
return apiError(res, 400, 'invalid_json', 'The body must be JSON.');
|
|
1561
|
+
}
|
|
1562
|
+
}
|
|
1563
|
+
else {
|
|
1564
|
+
b = Object.fromEntries(new URLSearchParams(raw));
|
|
1565
|
+
// An HTML form leaves an unchecked box out: here that means "no".
|
|
1566
|
+
if (route === 'POST /dev/plan' && b.renew === undefined)
|
|
1567
|
+
b.cancel_at_period_end = b.cancel_at_period_end === 'true' ? 'true' : 'false';
|
|
1568
|
+
}
|
|
1569
|
+
const ref = typeof b.project === 'string' && b.project ? b.project : undefined;
|
|
1570
|
+
try {
|
|
1571
|
+
if (route === 'POST /dev/plan') {
|
|
1572
|
+
const out = await setPlan(ref, b);
|
|
1573
|
+
return wantsJson ? json(res, 200, out) : redirect(res, `/?plan=1`);
|
|
1574
|
+
}
|
|
1575
|
+
const out = await changeTo(ref, typeof b.plan === 'string' ? b.plan : '');
|
|
1576
|
+
if (wantsJson)
|
|
1577
|
+
return json(res, 200, out);
|
|
1578
|
+
const toast = out.effect === 'period_end' ? `${out.plan?.next_plan?.name ?? 'The new plan'} starts at the end of the period.` : out.effect === 'undone' ? 'You keep your plan.' : out.effect === 'now' ? `You're on ${out.plan?.name} now.` : 'Nothing changed.';
|
|
1579
|
+
return redirect(res, `${extensionPath(ref ?? [...installs.keys()][0] ?? '')}?_toast=${encodeURIComponent(toast)}#plan`);
|
|
1580
|
+
}
|
|
1581
|
+
catch (err) {
|
|
1582
|
+
if (!(err instanceof DevPlanError))
|
|
1583
|
+
throw err;
|
|
1584
|
+
return wantsJson ? apiError(res, 400, 'invalid_plan', err.message, undefined, { field: err.field }) : html(res, 400, errorHtml('Not possible', err.message));
|
|
1585
|
+
}
|
|
1586
|
+
}
|
|
1587
|
+
case 'POST /dev/send': {
|
|
1588
|
+
const b = await read();
|
|
1589
|
+
const type = b.type ?? '';
|
|
1590
|
+
if (!ALL_EVENT_TYPES.includes(type))
|
|
1591
|
+
return apiError(res, 400, 'unknown_event', `"${type}" is not an event type.`);
|
|
1592
|
+
const d = await sendEvent(type, b.project || undefined);
|
|
1593
|
+
if (req.headers.accept?.includes('application/json') || req.headers['content-type']?.includes('application/json'))
|
|
1594
|
+
return json(res, 200, d);
|
|
1595
|
+
return redirect(res, '/?sent=1');
|
|
1596
|
+
}
|
|
1597
|
+
case 'POST /dev/uninstall': {
|
|
1598
|
+
const b = await read();
|
|
1599
|
+
const install = installs.get(b.project ?? '');
|
|
1600
|
+
if (install) {
|
|
1601
|
+
// Like Disconnect in the dashboard: tokens, codes and settings go now; extension.uninstalled is the last event.
|
|
1602
|
+
const event = deliveryEvent('extension.uninstalled', sampleInstall(install), { reason: 'customer' });
|
|
1603
|
+
revokeAll(install.id, null);
|
|
1604
|
+
for (const [k, c] of codes)
|
|
1605
|
+
if (c.install === install.id)
|
|
1606
|
+
codes.delete(k);
|
|
1607
|
+
installs.delete(install.project.ref);
|
|
1608
|
+
provisioned.delete(install.project.ref);
|
|
1609
|
+
pendingPlan.delete(install.project.ref);
|
|
1610
|
+
log(` · disconnected from ${install.project.name}`);
|
|
1611
|
+
await deliver(event);
|
|
1612
|
+
}
|
|
1613
|
+
return redirect(res, '/?disconnected=1');
|
|
1614
|
+
}
|
|
1615
|
+
default:
|
|
1616
|
+
if (pathname.startsWith('/extensions/') || pathname.startsWith('/platform/') || pathname.startsWith('/dev/')) {
|
|
1617
|
+
return apiError(res, 404, 'route_not_found', `No endpoint at ${method} ${url.pathname}.`, 'Check the URL. The API reference is at https://usebecky.com/docs.');
|
|
1618
|
+
}
|
|
1619
|
+
return html(res, 404, errorHtml('Not found', `The dev server has no page at ${url.pathname}.`));
|
|
1620
|
+
}
|
|
1621
|
+
}
|
|
1622
|
+
const server = http.createServer((req, res) => {
|
|
1623
|
+
handle(req, res).catch((err) => {
|
|
1624
|
+
log(` ✖ ${req.method} ${req.url}: ${err.message}`);
|
|
1625
|
+
if (!res.headersSent)
|
|
1626
|
+
json(res, 500, { error: { code: 'internal_error', message: escapeHtml(err.message) } });
|
|
1627
|
+
else
|
|
1628
|
+
res.end();
|
|
1629
|
+
});
|
|
1630
|
+
});
|
|
1631
|
+
await new Promise((resolve, reject) => {
|
|
1632
|
+
server.once('error', reject);
|
|
1633
|
+
server.listen(options.port ?? DEV_PORT, bindHost, () => {
|
|
1634
|
+
server.off('error', reject);
|
|
1635
|
+
resolve();
|
|
1636
|
+
});
|
|
1637
|
+
});
|
|
1638
|
+
ownPort = server.address().port;
|
|
1639
|
+
const shownHost = bindHost === '127.0.0.1' || bindHost === '::1' || WILDCARD_HOSTS.has(bindHost) ? 'localhost' : bindHost.includes(':') ? `[${bindHost}]` : bindHost;
|
|
1640
|
+
const url = `http://${shownHost}:${ownPort}`;
|
|
1641
|
+
base = url;
|
|
1642
|
+
return {
|
|
1643
|
+
url,
|
|
1644
|
+
credentials,
|
|
1645
|
+
installs: () => [...installs.values()].map((i) => ({ ...installationOf(i), status: i.status, connected: isConnected(i) })),
|
|
1646
|
+
sendEvent,
|
|
1647
|
+
deliveries,
|
|
1648
|
+
issuer: url,
|
|
1649
|
+
launchUrl: (project) => launchFor(project),
|
|
1650
|
+
setPlan: (project, patch) => setPlan(project, patch),
|
|
1651
|
+
changePlan: (project, plan) => changeTo(project, plan),
|
|
1652
|
+
close: () => new Promise((resolve) => {
|
|
1653
|
+
server.closeAllConnections?.();
|
|
1654
|
+
server.close(() => resolve());
|
|
1655
|
+
}),
|
|
1656
|
+
};
|
|
1657
|
+
}
|