@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.
Files changed (65) hide show
  1. package/README.md +223 -2
  2. package/dist/accounts.d.ts +85 -0
  3. package/dist/accounts.js +149 -0
  4. package/dist/cli/index.d.ts +2 -0
  5. package/dist/cli/index.js +9 -0
  6. package/dist/cli/run.d.ts +25 -0
  7. package/dist/cli/run.js +330 -0
  8. package/dist/cli/skill.d.ts +16 -0
  9. package/dist/cli/skill.js +106 -0
  10. package/dist/crypto.d.ts +12 -0
  11. package/dist/crypto.js +56 -0
  12. package/dist/dev/pages.d.ts +155 -0
  13. package/dist/dev/pages.js +243 -0
  14. package/dist/dev/plans.d.ts +45 -0
  15. package/dist/dev/plans.js +135 -0
  16. package/dist/dev/samples.d.ts +61 -0
  17. package/dist/dev/samples.js +191 -0
  18. package/dist/dev/server.d.ts +120 -0
  19. package/dist/dev/server.js +1657 -0
  20. package/dist/dev/tagging.d.ts +16 -0
  21. package/dist/dev/tagging.js +81 -0
  22. package/dist/dev/ui-render.d.ts +25 -0
  23. package/dist/dev/ui-render.js +256 -0
  24. package/dist/dev/wordmark.d.ts +1 -0
  25. package/dist/dev/wordmark.js +2 -0
  26. package/dist/errors.d.ts +98 -0
  27. package/dist/errors.js +110 -0
  28. package/dist/events.d.ts +92 -0
  29. package/dist/events.js +54 -0
  30. package/dist/extension.d.ts +214 -0
  31. package/dist/extension.js +497 -0
  32. package/dist/handlers.d.ts +39 -0
  33. package/dist/handlers.js +113 -0
  34. package/dist/identity.d.ts +99 -0
  35. package/dist/identity.js +134 -0
  36. package/dist/index.d.ts +14 -0
  37. package/dist/index.js +17 -0
  38. package/dist/jwt.d.ts +62 -0
  39. package/dist/jwt.js +152 -0
  40. package/dist/manifest.d.ts +42 -0
  41. package/dist/manifest.js +785 -0
  42. package/dist/node.d.ts +10 -0
  43. package/dist/node.js +56 -0
  44. package/dist/pkce.d.ts +9 -0
  45. package/dist/pkce.js +16 -0
  46. package/dist/stores.d.ts +100 -0
  47. package/dist/stores.js +159 -0
  48. package/dist/types.d.ts +346 -0
  49. package/dist/types.js +70 -0
  50. package/dist/ui/handler.d.ts +66 -0
  51. package/dist/ui/handler.js +105 -0
  52. package/dist/ui/schema.d.ts +423 -0
  53. package/dist/ui/schema.js +666 -0
  54. package/dist/webhooks.d.ts +26 -0
  55. package/dist/webhooks.js +99 -0
  56. package/package.json +57 -4
  57. package/skill/usebecky-extension/SKILL.md +181 -0
  58. package/skill/usebecky-extension/references/accounts.md +125 -0
  59. package/skill/usebecky-extension/references/dev-server.md +102 -0
  60. package/skill/usebecky-extension/references/manifest.md +104 -0
  61. package/skill/usebecky-extension/references/oauth-and-tokens.md +179 -0
  62. package/skill/usebecky-extension/references/partner-api.md +87 -0
  63. package/skill/usebecky-extension/references/submit-and-pricing.md +31 -0
  64. package/skill/usebecky-extension/references/ui.md +172 -0
  65. package/skill/usebecky-extension/references/webhooks.md +97 -0
@@ -0,0 +1,26 @@
1
+ import type { AnyExtensionEvent } from './events.ts';
2
+ export declare const SIGNATURE_HEADER = "usebecky-signature";
3
+ /** Five minutes, both ways: older (or future) timestamps are refused so a captured request can't be replayed. */
4
+ export declare const DEFAULT_TOLERANCE_SECONDS = 300;
5
+ /** Request headers in any shape: fetch `Headers`, Node's `req.headers`, or the signature header value itself. */
6
+ export type HeaderSource = Headers | Record<string, string | string[] | undefined> | string | null | undefined;
7
+ export interface VerifyOptions {
8
+ /** Seconds a timestamp may be off (default 300). */
9
+ toleranceSeconds?: number;
10
+ /** Unix seconds "now" (tests). */
11
+ now?: number;
12
+ }
13
+ /** The usebecky-signature header out of any header shape. */
14
+ export declare function signatureHeaderFrom(headers: HeaderSource): string | undefined;
15
+ /** `t=1700000000,v1=ab..,v1=cd..` → the timestamp and every v1 value. */
16
+ export declare function parseSignatureHeader(header: string): {
17
+ timestamp: number;
18
+ signatures: string[];
19
+ } | null;
20
+ /**
21
+ * Check that a webhook really came from usebecky, unchanged and recent, and return the parsed event.
22
+ * Pass the raw body exactly as received (not re-serialized JSON). Throws WebhookVerificationError.
23
+ */
24
+ export declare function verifyWebhook(rawBody: string | Uint8Array | ArrayBuffer, headers: HeaderSource, secret: string | readonly string[] | undefined, options?: VerifyOptions): Promise<AnyExtensionEvent>;
25
+ /** The usebecky-signature value for a body: what usebecky sends (the dev server and your tests use it). */
26
+ export declare function signWebhook(rawBody: string, secret: string, timestamp?: number): Promise<string>;
@@ -0,0 +1,99 @@
1
+ // Verifying webhooks from usebecky. Exactly how usebecky signs (packages/server/src/core/events.ts):
2
+ // usebecky-signature: t=<unix seconds>,v1=<hex HMAC-SHA256(secret, `${t}.${rawBody}`)>
3
+ // The header may carry several v1 values (one per secret while usebecky rotates it), and you may pass
4
+ // several secrets (old and new while you rotate yours): any match is enough.
5
+ import { hmacSha256Hex, hmacSha256Verify } from "./crypto.js";
6
+ import { ConfigError, WebhookVerificationError } from "./errors.js";
7
+ export const SIGNATURE_HEADER = 'usebecky-signature';
8
+ /** Five minutes, both ways: older (or future) timestamps are refused so a captured request can't be replayed. */
9
+ export const DEFAULT_TOLERANCE_SECONDS = 300;
10
+ const fail = (code, message, hint) => new WebhookVerificationError({ code, message, hint, status: 400 });
11
+ /** The usebecky-signature header out of any header shape. */
12
+ export function signatureHeaderFrom(headers) {
13
+ if (headers == null)
14
+ return undefined;
15
+ if (typeof headers === 'string')
16
+ return headers;
17
+ if (typeof headers.get === 'function')
18
+ return headers.get(SIGNATURE_HEADER) ?? undefined;
19
+ const rec = headers;
20
+ const key = Object.keys(rec).find((k) => k.toLowerCase() === SIGNATURE_HEADER);
21
+ const v = key ? rec[key] : undefined;
22
+ return Array.isArray(v) ? v.join(',') : v;
23
+ }
24
+ /** `t=1700000000,v1=ab..,v1=cd..` → the timestamp and every v1 value. */
25
+ export function parseSignatureHeader(header) {
26
+ let timestamp = null;
27
+ const signatures = [];
28
+ for (const part of header.split(',')) {
29
+ const i = part.indexOf('=');
30
+ if (i < 0)
31
+ continue;
32
+ const k = part.slice(0, i).trim();
33
+ const v = part.slice(i + 1).trim();
34
+ if (k === 't' && /^\d{1,12}$/.test(v))
35
+ timestamp = Number(v);
36
+ else if (k === 'v1' && v)
37
+ signatures.push(v);
38
+ }
39
+ if (timestamp === null || !signatures.length)
40
+ return null;
41
+ return { timestamp, signatures };
42
+ }
43
+ function bodyText(raw) {
44
+ if (typeof raw === 'string')
45
+ return raw;
46
+ return new TextDecoder().decode(raw instanceof ArrayBuffer ? new Uint8Array(raw) : raw);
47
+ }
48
+ /**
49
+ * Check that a webhook really came from usebecky, unchanged and recent, and return the parsed event.
50
+ * Pass the raw body exactly as received (not re-serialized JSON). Throws WebhookVerificationError.
51
+ */
52
+ export async function verifyWebhook(rawBody, headers, secret, options = {}) {
53
+ const secrets = (Array.isArray(secret) ? secret : [secret]).filter((s) => typeof s === 'string' && s.length > 0);
54
+ if (!secrets.length) {
55
+ throw new ConfigError({
56
+ code: 'missing_webhook_secret',
57
+ message: 'No webhook secret is set, so webhooks cannot be verified.',
58
+ hint: 'Set USEBECKY_WEBHOOK_SECRET to the webhook secret from usebecky (Developer → your extension → Credentials and testing → Create credentials).',
59
+ status: 500,
60
+ });
61
+ }
62
+ const header = signatureHeaderFrom(headers);
63
+ if (!header)
64
+ throw fail('missing_signature', 'This request has no usebecky-signature header.', 'Only usebecky should call this address. To test, run: npx @usebecky/extension send test.ping');
65
+ const parsed = parseSignatureHeader(header);
66
+ if (!parsed)
67
+ throw fail('invalid_signature', 'The usebecky-signature header is malformed.', 'Expected "t=<unix time>,v1=<hex>".');
68
+ const body = bodyText(rawBody);
69
+ const message = `${parsed.timestamp}.${body}`;
70
+ let valid = false;
71
+ for (const s of secrets) {
72
+ for (const sig of parsed.signatures) {
73
+ if (await hmacSha256Verify(s, message, sig))
74
+ valid = true;
75
+ }
76
+ }
77
+ if (!valid) {
78
+ throw fail('invalid_signature', 'The webhook signature does not match.', 'Check that USEBECKY_WEBHOOK_SECRET is the webhook secret of this extension, and that the body reaches the kit unchanged (raw, before any JSON parser).');
79
+ }
80
+ const now = options.now ?? Math.floor(Date.now() / 1000);
81
+ if (Math.abs(now - parsed.timestamp) > (options.toleranceSeconds ?? DEFAULT_TOLERANCE_SECONDS)) {
82
+ throw fail('stale_signature', 'The webhook timestamp is more than 5 minutes off, so it was refused (it may be a replay).', "Check your server's clock. usebecky signs every retry afresh.");
83
+ }
84
+ let event;
85
+ try {
86
+ event = JSON.parse(body);
87
+ }
88
+ catch {
89
+ throw fail('invalid_payload', 'The webhook body is not valid JSON.');
90
+ }
91
+ if (!event || typeof event !== 'object' || typeof event.type !== 'string' || typeof event.id !== 'string') {
92
+ throw fail('invalid_payload', 'The webhook body has no "id" and "type".');
93
+ }
94
+ return event;
95
+ }
96
+ /** The usebecky-signature value for a body: what usebecky sends (the dev server and your tests use it). */
97
+ export async function signWebhook(rawBody, secret, timestamp = Math.floor(Date.now() / 1000)) {
98
+ return `t=${timestamp},v1=${await hmacSha256Hex(secret, `${timestamp}.${rawBody}`)}`;
99
+ }
package/package.json CHANGED
@@ -1,6 +1,59 @@
1
1
  {
2
2
  "name": "@usebecky/extension",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.2.0",
4
+ "description": "Build extensions for the usebecky store: OAuth with PKCE, automatic accounts (OpenID id_tokens, provision requests) and single sign-on, a typed partner API client, verified webhooks, ready-made handlers and a local dev server that imitates usebecky.",
5
+ "type": "module",
6
+ "license": "MIT",
7
+ "main": "./dist/index.js",
8
+ "types": "./dist/index.d.ts",
9
+ "exports": {
10
+ ".": {
11
+ "types": "./dist/index.d.ts",
12
+ "default": "./dist/index.js"
13
+ },
14
+ "./node": {
15
+ "types": "./dist/node.d.ts",
16
+ "default": "./dist/node.js"
17
+ },
18
+ "./dev": {
19
+ "types": "./dist/dev/server.d.ts",
20
+ "default": "./dist/dev/server.js"
21
+ },
22
+ "./package.json": "./package.json"
23
+ },
24
+ "bin": {
25
+ "usebecky-extension": "./dist/cli/index.js"
26
+ },
27
+ "files": [
28
+ "dist",
29
+ "skill",
30
+ "README.md"
31
+ ],
32
+ "scripts": {
33
+ "build": "node scripts/build.mjs",
34
+ "prepack": "npm run build",
35
+ "test": "node --test 'test/**/*.test.ts'",
36
+ "typecheck": "tsc -p ."
37
+ },
38
+ "devDependencies": {
39
+ "@types/node": "^26.6.6",
40
+ "typescript": "5.9"
41
+ },
42
+ "keywords": [
43
+ "usebecky",
44
+ "extension",
45
+ "plugin",
46
+ "integration",
47
+ "oauth",
48
+ "pkce",
49
+ "webhooks",
50
+ "marketplace",
51
+ "openid-connect",
52
+ "single-sign-on",
53
+ "provisioning"
54
+ ],
55
+ "sideEffects": false,
56
+ "engines": {
57
+ "node": ">=20"
58
+ }
59
+ }
@@ -0,0 +1,181 @@
1
+ ---
2
+ name: usebecky-extension
3
+ description: "Use when building, changing, testing or submitting an extension (plugin, integration, add-on, app) for the usebecky store with the @usebecky/extension kit: usebecky-extension.json (the listing), OAuth with PKCE, setup fields, accounts at the extension's service (automatic provisioning from the id_token or a provision URL, never a sign-up form), single sign-on ('Open in'), tokens, the partner API, verified webhooks, pages inside usebecky (sidebar menu rows, dashboards and settings drawn by usebecky from blocks via uiHandler), usebecky's look for the extension's own pages, the dev server, scopes, security, review, pricing and payouts. Load it before writing any code that talks to usebecky from an extension, even when the request only says 'connect to usebecky', 'add a login', 'create user accounts', 'handle the webhook', 'add a menu entry', 'show a dashboard in usebecky' or 'make it look like usebecky'."
4
+ ---
5
+
6
+ # Build a usebecky extension
7
+
8
+ An **extension** is a separate web app (yours) that usebecky customers install on one of their projects from the store (dashboard → **Extensions** → **Install**). It connects one of two ways (`connect.mode` in the listing):
9
+
10
+ - **`oauth`** ("Sign in with usebecky"): Install opens your `install_url`; your server sends the customer to usebecky's consent screen; after **Allow** your callback gets a code, which the kit swaps for tokens. With them your server reads what the customer allowed (the **partner API**).
11
+ - **`fields`** ("Setup fields"): the customer fills in a few settings in usebecky (text, url, secret, or a yes/no checkbox). No OAuth; the settings arrive in the `extension.installed` webhook.
12
+
13
+ Either way usebecky sends your server signed **webhooks**: always `extension.installed` / `extension.uninstalled`, plus the events you list.
14
+
15
+ Like a WordPress plugin, an extension can also add **its own pages inside usebecky** (`ui` in the listing): rows in the project's sidebar and a settings view, which usebecky draws from the blocks your server answers with (see below).
16
+
17
+ ## The rule: never build a sign-up or login form for usebecky customers
18
+
19
+ **Customers never sign up at the extension's service by hand.** If the service needs an account per customer, the extension creates it automatically and opens it with single sign-on:
20
+
21
+ 1. Set `"account"` in the listing: `{ "required": true, "provision": "oauth", "sso_url": "https://you.example/sso" }` (OAuth extensions: the account comes from the OpenID **id_token**) or `{ "required": true, "provision": "url", "provision_url": "https://api.you.example/usebecky/provision", "sso_url": "https://you.example/sso" }` (setup-field extensions: usebecky POSTs a signed **provision request**).
22
+ 2. Create the account from `identity` in the OAuth callback (`const { identity } = await ext.handleCallback(request)`), or answer the provision request with `ext.provisionHandler(fn)` → `{ account_id, settings? }`. Key users by `identity.sub` / `request.user.sub` (pairwise, stable), the workspace by the install id.
23
+ 3. Serve `sso_url` with `ext.ssoHandler({ createSession })`: it verifies the launch token ("Open in" in usebecky: signed, 60 seconds, single use) and you start your session.
24
+
25
+ Never write a registration page, a password field, an "create your account" step, an email-confirmation gate or a separate login for people who come from usebecky, even when the user asks for "a login": build the provisioning + SSO above instead and explain why (review rejects manual sign-ups). Link an existing account by email only when `email_verified` is true. Details and code: `references/accounts.md`.
26
+
27
+ ## Pages inside usebecky: blocks, never HTML
28
+
29
+ Dashboards, lists and settings that customers should see in their project go into **`ui` pages**, not onto your website and never into an iframe. Answer with blocks and usebecky draws them with its own components, so they always match its design (light, dark, phones), and none of your code runs in the dashboard:
30
+
31
+ ```ts
32
+ // src/ui.ts
33
+ import type { Extension } from '@usebecky/extension'
34
+ import type { Hono } from 'hono'
35
+
36
+ export function mountUi(app: Hono, ext: Extension) {
37
+ const ui = ext.uiHandler({
38
+ pages: { overview: async () => ({ blocks: [{ type: 'stats', items: [{ label: 'Visitors', value: '1,204', change: 12.5 }] }] }) },
39
+ actions: { save: async () => ({ toast: 'Saved.' }) },
40
+ })
41
+ app.post('/usebecky/ui', (c) => ui(c.req.raw))
42
+ }
43
+ ```
44
+
45
+ Never generate HTML, CSS, scripts or images of charts for usebecky: there is no way to show them, and you don't need one (`stats`, `chart`, `bars`, `table` with paging, `form`, `notice`, `tabs`, `section`, `columns`…). Format numbers yourself in `stats`, page long lists on your server (cursor, at most 100 rows), answer in under 3 seconds, one primary button per page, words for beginners. Your own web pages that customers reach from usebecky (install, "Open in") use usebecky's look with **your** name and logo (never usebecky's wordmark): the starter's `src/pages.ts`. Everything: `references/ui.md`.
46
+
47
+ usebecky is a hosted service: never clone, build or run usebecky itself. Locally, `npm run dev` starts a **pretend usebecky** (the dev server) with fake projects and test credentials. It answers like usebecky: same parameters, prefixes, checks and error messages.
48
+
49
+ ## The kit does the protocol: never hand-roll it
50
+
51
+ | Need | Use (`@usebecky/extension`) | Never |
52
+ |---|---|---|
53
+ | Send the customer to the consent screen | `oauthHandlers().install` or `await ext.authorizeUrl({ project })` | build the URL, PKCE or state yourself |
54
+ | Finish the install | `await ext.handleCallback(request)` | call `/oauth/token` with `fetch` |
55
+ | Call usebecky | `ext.api(project).project()`, `.installation()`, `.analyticsSummary()` | store or refresh tokens yourself |
56
+ | Receive webhooks | `ext.webhookHandler({ ... })` or `await ext.verifyWebhook(rawBody, headers)` | compare signatures, `JSON.parse` before verifying |
57
+ | Pages inside usebecky | `ext.uiHandler({ pages, actions })` answering blocks | HTML, an iframe, your own CSS or scripts, verifying the request yourself |
58
+ | Store tokens | `fileTokenStore()` (one server), `sqlTokenStore()` or your own `TokenStore` | keep tokens in cookies, `localStorage` or logs |
59
+ | Create the customer's account | `identity` from `handleCallback()` (id_token, verified) or `ext.provisionHandler(fn)` | a sign-up form, passwords, decoding a JWT without verifying it |
60
+ | "Open in" sign-in | `ext.ssoHandler({ createSession })` or `await ext.verifyLaunchToken(token)` | a login form, trusting `?launch=` without the kit, accepting a token twice |
61
+
62
+ Everything is keyed by the **project ref** (one install per project). Webhook events carry it as `event.project`.
63
+
64
+ ## Workflow
65
+
66
+ 1. **Start from the starter** if there is no project yet: `npx create-usebecky@latest my-extension --template extension` (Hono, install route, callback, settings page, webhooks, tests, this skill). In an existing Node app: `npm install @usebecky/extension`.
67
+ 2. **Describe the extension** in `usebecky-extension.json` (name, summary, scopes, `data_shared`, addresses, and `account` if the service needs accounts). Ask for the fewest scopes that work. Details: `references/manifest.md`.
68
+ 3. **Write the routes** with the kit: install, callback, webhook, for accounts the provision endpoint and `sso_url`, and for pages inside usebecky the `ui.url` handler. Patterns for Hono, Express, Next.js and node:http: `references/oauth-and-tokens.md`, `references/webhooks.md`, `references/accounts.md`, `references/ui.md`.
69
+ 4. **Use the data** through `ext.api(project)`; handle `InstallationRevokedError` (uninstalled) and `PartnerApiError` (`insufficient_scope`...): `references/partner-api.md`.
70
+ 5. **Test** with `npm run dev` (open http://localhost:4400, click **Install**, then **Open in …** and your pages) and `npm test`; send events with `npx @usebecky/extension send user.created`: `references/dev-server.md`.
71
+ 6. **Check** `npx @usebecky/extension validate` (usebecky's own checks and messages) and the security checklist below, then submit in the Developer area: `references/submit-and-pricing.md`.
72
+
73
+ ## The smallest complete server (Hono)
74
+
75
+ ```ts
76
+ // src/server.ts
77
+ import { serve } from '@hono/node-server'
78
+ import { createExtension, ExtensionError } from '@usebecky/extension'
79
+ import { fileTokenStore } from '@usebecky/extension/node'
80
+ import { Hono } from 'hono'
81
+ import { getSignedCookie, setSignedCookie } from 'hono/cookie'
82
+
83
+ const ext = createExtension({
84
+ clientId: process.env.USEBECKY_CLIENT_ID!,
85
+ clientSecret: process.env.USEBECKY_CLIENT_SECRET!,
86
+ webhookSecret: process.env.USEBECKY_WEBHOOK_SECRET,
87
+ redirectUri: `${process.env.PUBLIC_URL}/oauth/callback`,
88
+ apiUrl: process.env.USEBECKY_API_URL, // unset = https://api.usebecky.com; `npm run dev` sets the dev server
89
+ dashboardUrl: process.env.USEBECKY_DASHBOARD_URL, // unset = https://app.usebecky.com (the consent screen)
90
+ tokenStore: fileTokenStore('.data/tokens.json'),
91
+ })
92
+ const secret = process.env.SESSION_SECRET!
93
+ const app = new Hono()
94
+
95
+ // 1. usebecky's Install opens install_url (?project=<ref>&return_url=...): go on to the consent screen.
96
+ const { install } = ext.oauthHandlers()
97
+ app.get('/install', (c) => install(c.req.raw))
98
+
99
+ // 2. Back from the consent screen: store the tokens, create the account (no sign-up form), sign in with a signed cookie.
100
+ app.get('/oauth/callback', async (c) => {
101
+ try {
102
+ const { project, identity } = await ext.handleCallback(c.req.raw)
103
+ // With "account": { "provision": "oauth" } the verified id_token says who allowed access: create or find the user.
104
+ if (identity) console.log('account for', identity.sub, identity.email, 'in', identity.usebecky_install)
105
+ await setSignedCookie(c, 'session', project, secret, { httpOnly: true, sameSite: 'Lax', secure: true, path: '/' })
106
+ return c.redirect('/settings')
107
+ } catch (err) {
108
+ if (err instanceof ExtensionError) return c.text(err.message, 400)
109
+ throw err
110
+ }
111
+ })
112
+
113
+ // 3. A page for the signed-in customer, with data from the partner API.
114
+ app.get('/settings', async (c) => {
115
+ const project = await getSignedCookie(c, secret, 'session')
116
+ if (!project) return c.redirect('/install')
117
+ const info = await ext.api(project).project()
118
+ return c.text(`Connected to ${info.name} (${info.allowed_hosts.join(', ')})`)
119
+ })
120
+
121
+ // 4. "Open in" from usebecky (account.sso_url): the kit verifies the launch token (once), you sign the person in.
122
+ const sso = ext.ssoHandler({
123
+ createSession: async (claims) => {
124
+ console.log('sign in', claims.sub, 'as', claims.usebecky_role, 'in project', claims.usebecky_project)
125
+ return '/settings' // a real app sets its session cookie in a Response here
126
+ },
127
+ })
128
+ app.get('/sso', (c) => sso(c.req.raw))
129
+
130
+ // 5. Webhooks, verified by the kit before your handler runs.
131
+ const webhook = ext.webhookHandler({
132
+ 'extension.installed': (event) => console.log('installed on', event.data.project.name, event.data.settings),
133
+ 'extension.uninstalled': (event) => console.log('now delete what you stored for', event.project),
134
+ })
135
+ app.post('/webhooks/usebecky', (c) => webhook(c.req.raw))
136
+
137
+ serve({ fetch: app.fetch, port: Number(process.env.PORT ?? 3000) })
138
+ ```
139
+
140
+ Never take the project ref from a query string for anything private: only from the signed cookie set in the callback, or from a verified webhook.
141
+
142
+ ## Environment variables
143
+
144
+ | Variable | What | Where from |
145
+ |---|---|---|
146
+ | `USEBECKY_CLIENT_ID` | the extension's client id (`ub_ci_...`) | Developer → your extension → Credentials and testing → **Create credentials** |
147
+ | `USEBECKY_CLIENT_SECRET` | server only, shown once (`ub_cs_...`) | same |
148
+ | `USEBECKY_WEBHOOK_SECRET` | signs webhooks (`whsec_...`) | same |
149
+ | `PUBLIC_URL` | your server's https address; `PUBLIC_URL/oauth/callback` must be in `connect.redirect_uris` | your host |
150
+ | `USEBECKY_API_URL`, `USEBECKY_DASHBOARD_URL` | leave unset in production; `npm run dev` points both at the dev server | — |
151
+
152
+ `npm run dev` sets all of them to test values; `.env` is only for `npm start` against the real usebecky.
153
+
154
+ ## Security checklist (reviewers check these)
155
+
156
+ 1. Secrets and tokens only in environment variables and the token store. Never in code, git, logs, URLs, HTML or the browser. Log event ids and types, never payloads with personal data or tokens.
157
+ 2. Verify **every** webhook with the kit, on the **raw** body (no JSON parser before it). Answer 2xx only after the work is done; usebecky retries otherwise. Skip duplicates by `event.id`.
158
+ 3. On `extension.uninstalled`, delete everything you stored for `event.project` (the kit deletes the tokens).
159
+ 4. Ask only for scopes you use, and describe each in `data_shared` in plain words. Analytics are totals only; never try to identify visitors.
160
+ 5. No sign-up or login form for usebecky customers: accounts come from the verified id_token or provision request, "Open in" from a verified launch token (`ssoHandler`, single use). Key users by `sub`; link by email only when `email_verified`.
161
+ 6. Start installs with `oauthHandlers().install` (it ties the sign-in to the browser) and pass the Request to `handleCallback`. Settings pages: a signed httpOnly session cookie set in the callback (`SameSite=Lax`, `Secure` on https) holding the project and its install id; check the install still exists on every request. Escape everything you put into HTML.
162
+ 7. With more than one server instance, all of these are required: a database token store with a `lock` (refresh tokens rotate; a reused one disconnects the install), a shared `StateStore`, a shared replay guard for launch tokens (`replayGuard: sqlReplayGuard({ query })` in the token store's database: the memory default only knows one process, so a link would work once per instance) and a database idempotency store for provisioning.
163
+ 8. Pages inside usebecky (`ui`) go through `ext.uiHandler` (it verifies the request); actions that delete or change billing check `ctx.user.role`; no secrets in blocks (every team member sees them, viewers too).
164
+ 9. `npx @usebecky/extension validate` passes with no warnings about placeholders.
165
+
166
+ ## Pricing in one paragraph
167
+
168
+ Extensions are free, a monthly price per project, or 2–6 plans the customer picks from (3–999 USD before tax each, optional 0–30 day trial; your code reads the install’s plan as `ctx.plan` / `installation().plan` and gets `extension.plan_changed`). usebecky bills the customer and keeps 20% of the price before tax; the rest is paid out to you through Stripe (set up payouts in the Developer area before submitting a paid extension). More: `references/submit-and-pricing.md`.
169
+
170
+ ## References
171
+
172
+ | File | Read when |
173
+ |---|---|
174
+ | `references/manifest.md` | writing or changing usebecky-extension.json, choosing scopes, setup fields, `data_shared` |
175
+ | `references/accounts.md` | the service needs user accounts or a login: `account` in the listing, id_token, provision endpoint, "Open in" SSO, replay guard |
176
+ | `references/ui.md` | pages, menu rows, dashboards or settings inside usebecky (`ui`, `uiHandler`, every block, actions, paging), and usebecky's look for your own web pages |
177
+ | `references/oauth-and-tokens.md` | install/callback routes in Hono, Express, Next.js, node:http; token stores; errors |
178
+ | `references/webhooks.md` | handling events, raw bodies per framework, retries, duplicates, uninstall cleanup |
179
+ | `references/partner-api.md` | calling `ext.api(project)`: shapes, scopes, errors |
180
+ | `references/dev-server.md` | running and testing locally, sending test events, writing tests |
181
+ | `references/submit-and-pricing.md` | the Developer area, the test project, review, pricing, payouts |
@@ -0,0 +1,125 @@
1
+ # Accounts at your service: provisioning and single sign-on
2
+
3
+ **Rule: customers never sign up at an extension's service by hand.** Never build a registration page, password field, "create your account" step, email-confirmation gate or separate login for people who come from usebecky. If the service needs accounts, use the kit's helpers below. Review rejects manual sign-ups.
4
+
5
+ ## Pick the listing
6
+
7
+ | Connect mode | `account` in usebecky-extension.json | The account is made in |
8
+ |---|---|---|
9
+ | `oauth` | `{ "required": true, "provision": "oauth", "sso_url": "https://you.example/sso" }` | the OAuth callback, from `identity` (the verified id_token) |
10
+ | `fields` | `{ "required": true, "provision": "url", "provision_url": "https://api.you.example/usebecky/provision", "sso_url": "https://you.example/sso" }` | your provision endpoint (`ext.provisionHandler`) |
11
+
12
+ - `provision_url`: https, public host name (like `webhook_url`). `sso_url`: https (`http://localhost` while testing).
13
+ - `"members_can_open": true` lets every team member use "Open in" (default: owners and admins). The token carries `usebecky_role`.
14
+ - Add a `data_shared` line: "Your name and email address, for your account".
15
+ - Needs credentials (client id = token audience, webhook secret signs provision requests).
16
+ - No account needed? Leave `account` out.
17
+
18
+ ## What usebecky tells you
19
+
20
+ `sub` (pairwise: stable for this person and this extension only; key users by it), `email`, `email_verified` (true only when usebecky proved it; link existing accounts by email only then), `name` (may be missing), `usebecky_project` (ref), `usebecky_install` (install id: key the workspace by it), `usebecky_role` (`owner` | `admin` | `developer` | `viewer`). A teammate opening later has another `sub` in the same install.
21
+
22
+ ## OAuth: create the account in the callback
23
+
24
+ usebecky adds `openid email profile` on the consent screen; the code exchange returns an id_token (10 minutes; never on refresh). `handleCallback()` verifies it (signature, issuer, audience, expiry, the nonce the kit sent, same install) and returns `identity`:
25
+
26
+ ```ts
27
+ // src/callback.ts
28
+ import { ExtensionError } from '@usebecky/extension'
29
+ import { Hono } from 'hono'
30
+ import { setSignedCookie } from 'hono/cookie'
31
+ import { ext } from './extension.ts'
32
+
33
+ const app = new Hono()
34
+ const users = new Map<string, { workspace: string; email: string; name: string | null; role: string }>()
35
+
36
+ app.get('/oauth/callback', async (c) => {
37
+ try {
38
+ const { installation, identity } = await ext.handleCallback(c.req.raw)
39
+ if (!identity) throw new Error('Set "account": { "required": true, "provision": "oauth", ... } in the listing.')
40
+ users.set(identity.sub, { workspace: installation.id, email: identity.email ?? '', name: identity.name ?? null, role: identity.usebecky_role })
41
+ await setSignedCookie(c, 'session', identity.sub, process.env.SESSION_SECRET!, { httpOnly: true, secure: true, sameSite: 'Lax', path: '/' })
42
+ return c.redirect('/settings')
43
+ } catch (err) {
44
+ if (err instanceof ExtensionError) return c.text(`${err.message} ${err.hint ?? ''}`, 400)
45
+ throw err
46
+ }
47
+ })
48
+
49
+ export default app
50
+ ```
51
+
52
+ ```ts
53
+ // src/extension.ts
54
+ import { createExtension } from '@usebecky/extension'
55
+ import { fileTokenStore } from '@usebecky/extension/node'
56
+
57
+ export const ext = createExtension({
58
+ clientId: process.env.USEBECKY_CLIENT_ID!,
59
+ clientSecret: process.env.USEBECKY_CLIENT_SECRET!,
60
+ webhookSecret: process.env.USEBECKY_WEBHOOK_SECRET,
61
+ redirectUri: `${process.env.PUBLIC_URL}/oauth/callback`,
62
+ apiUrl: process.env.USEBECKY_API_URL, // also the token issuer: the dev server, a local usebecky and the hosted one each sign their own
63
+ dashboardUrl: process.env.USEBECKY_DASHBOARD_URL,
64
+ tokenStore: fileTokenStore('.data/tokens.json'),
65
+ })
66
+ ```
67
+
68
+ Standalone: `await verifyIdToken(token, { clientId, nonce })`.
69
+
70
+ ## Setup fields: the provision endpoint
71
+
72
+ usebecky POSTs `{ id, type: 'extension.provision', created_at, extension, install, project: { ref, name }, user: { sub, email, email_verified, name }, test? }`, signed with `usebecky-signature` (webhook secret), `Idempotency-Key: <install id>`. Answer `{ account_id, settings? }`: settings fill the customer's setup fields (they confirm). 10 s per attempt, 3 attempts on network errors/timeouts/408/429/5xx; redirects never followed.
73
+
74
+ ```ts
75
+ // src/provision.ts
76
+ import { ExtensionError } from '@usebecky/extension'
77
+ import { ext } from './extension.ts'
78
+
79
+ const accounts = new Map<string, string>() // usebecky install id → your account id
80
+
81
+ export const provision = ext.provisionHandler(async (request) => {
82
+ if (!request.user.email) throw new ExtensionError({ code: 'no_email', message: 'An email address is needed for the account.', status: 422 })
83
+ const accountId = accounts.get(request.install) ?? `acct_${request.install.slice(0, 8)}`
84
+ accounts.set(request.install, accountId)
85
+ return { account_id: accountId, settings: { site_id: accountId.slice(5) } }
86
+ })
87
+ // Hono: app.post('/usebecky/provision', (c) => provision(c.req.raw))
88
+ // Express: app.post('/usebecky/provision', toNodeHandler(provision)) before express.json()
89
+ ```
90
+
91
+ - The kit verifies the signature on the raw body and answers a repeated install id from its idempotency store (never two accounts). Several instances: `ext.provisionHandler(fn, { idempotency })` with a store in your database (`get(installId)`, `set(installId, result)`).
92
+ - Throw `ExtensionError` with a 4xx `status` to refuse (usebecky shows the message, no retry); other errors → 500 → usebecky retries.
93
+ - Settings keys must be your listing's field keys; values like customer input. Secret settings are stored encrypted and never sent back.
94
+ - `extension.installed` / `extension.uninstalled` carry `data.account_id`.
95
+
96
+ ## "Open in": the sso_url
97
+
98
+ usebecky opens `sso_url?launch=<token>` (JWT `typ: usebecky-launch+jwt`, 60 seconds, single use, claims above plus `jti` and `partner_account_id`). Verify with the kit, then start your session:
99
+
100
+ ```ts
101
+ // src/sso.ts
102
+ import { ext } from './extension.ts'
103
+
104
+ export const sso = ext.ssoHandler({
105
+ serviceName: 'My Extension',
106
+ createSession: async (claims) => {
107
+ // find or create the user by claims.sub in the workspace of claims.usebecky_install, role claims.usebecky_role
108
+ const cookie = `session=${encodeURIComponent(claims.sub)}; Path=/; HttpOnly; Secure; SameSite=Lax`
109
+ return new Response(null, { status: 303, headers: { location: '/settings', 'set-cookie': cookie } })
110
+ },
111
+ })
112
+ // Hono: app.get('/sso', (c) => sso(c.req.raw))
113
+ ```
114
+
115
+ Or in your own route: `const claims = await ext.verifyLaunchToken(c.req.query('launch') ?? '')` (throws `TokenVerificationError`: `expired_token`, `replayed_token`, `invalid_audience`, `invalid_signature`, `wrong_token_type`...). Sign your session cookie as your framework does (Hono: `setSignedCookie`).
116
+
117
+ - Used `jti`s are remembered in memory by default: right for **one** server process only. With more than one instance, a shared replay guard is required (otherwise a link works once on every instance): `createExtension({ ..., replayGuard: sqlReplayGuard({ query }) })` with the same `query` as `sqlTokenStore` (Postgres, or SQLite with `dialect: 'sqlite'`), after creating its table once with `replayTableSql()`. Redis instead: implement `use(jti, expiresAt)` with `SET used:<jti> 1 NX EXAT <expiresAt>`.
118
+ - Redirect at once; no third-party scripts on the sso page; never log the URL.
119
+ - The kit fetches usebecky's keys (`<apiUrl>/.well-known/jwks.json`), caches them and refetches for a new `kid` (key rotation): never pin a key.
120
+
121
+ ## Test it
122
+
123
+ - `npm run dev`: the dev server signs id_tokens with its own keys (issuer `http://localhost:4400`), calls your `provision_url` (mapped onto `--app`) when you install a fields extension and shows the form filled in, and has **Open in …** next to each install (`/dev/launch?project=<ref>`). In tests: `await dev.launchUrl('devshop00001')`.
124
+ - Test project on usebecky: Developer tools → **Open in …**; the install dialog's **Create my account** calls your provision endpoint with `"test": true`.
125
+ - Open a launch link twice: the second must be refused.
@@ -0,0 +1,102 @@
1
+ # Testing locally: the dev server
2
+
3
+ The dev server is a pretend usebecky on your computer. It answers like usebecky, with the same parameters, prefixes (`ub_ac_`, `ub_it_`, `ub_ir_`), checks, error codes and messages: the store's **Install**, the consent screen with two fake projects (Acme Shop on Pro, Side Project Blog on Free), the token endpoint (PKCE, single-use codes, rotation, reuse detection), the partner API with fake numbers (including the Free plan's 7 days of analytics and the 300 calls a minute), signed webhooks, the settings form for setup fields, and accounts: its own ES256 keys (`/.well-known/openid-configuration`, `/.well-known/jwks.json`; issuer `http://localhost:4400`), id_tokens for `"provision": "oauth"` listings, a signed provision request to your `provision_url` for `"provision": "url"` listings (then the form filled in for you to confirm), an **Open in …** button per install (`/dev/launch?project=<ref>` → your `sso_url?launch=<token>`), and your pages inside usebecky (listing `ui`): sidebar rows and each page at `/project/<ref>/x/<page>`, drawn from the blocks your `ui.url` answers, buttons and forms sent as `ui.action`, the settings view on the extension's page, and the exact reason when usebecky would refuse a page. No account needed.
4
+
5
+ ## Run it
6
+
7
+ In the starter, one command starts the dev server and your extension (restarting on every change):
8
+
9
+ ```bash
10
+ npm run dev
11
+ ```
12
+
13
+ Then open http://localhost:4400 and click **Install** next to Acme Shop: it opens your `install_url` (with `?project` and `?return_url`), the consent screen (**Allow**) and your callback, exactly like a customer. A `fields` extension opens the settings form instead (a checkbox for each yes/no field). On that page you can also send any event to your webhook and **Disconnect**.
14
+
15
+ Outside the starter:
16
+
17
+ ```bash
18
+ npx @usebecky/extension dev -- node --watch src/server.ts
19
+ ```
20
+
21
+ Everything after `--` starts your extension with these variables set (they win over `.env`):
22
+
23
+ | Variable | Value |
24
+ |---|---|
25
+ | `USEBECKY_API_URL`, `USEBECKY_DASHBOARD_URL` | `http://localhost:4400` (the API and the consent screen) |
26
+ | `USEBECKY_CLIENT_ID` | `ub_ci_DevServerTestClient00000` |
27
+ | `USEBECKY_CLIENT_SECRET` | `ub_cs_DevServerTestSecretNeverUseInProduction0` |
28
+ | `USEBECKY_WEBHOOK_SECRET` | `whsec_DevServerWebhookSecretNotReal000` |
29
+ | `PUBLIC_URL`, `PORT` | from `--app` (default `http://localhost:3000`) |
30
+
31
+ Options: `--port 4400`, `--app http://localhost:3000` (where your extension runs; the manifest's addresses, `provision_url` and `sso_url` included, are mapped onto it), `--token-ttl 120` (two-minute access tokens: the kit refreshes a minute before expiry, so you see it happen), `--test-project` (the fake projects act as test projects: `"test": true` on `GET /installation` and on every event and provision request; without it they act like real projects), `--capability sgtm_forwarding` (act as if usebecky gave your extension that capability: `PUT /extensions/v1/installation/settings` then works), `--manifest path/to/usebecky-extension.json`.
32
+
33
+ It is only for your computer: it listens on 127.0.0.1, answers only requests addressed to `localhost`, `127.0.0.1` or `[::1]` (403 `host_not_allowed` otherwise: a web page can't point its own domain at it), and refuses a POST or "Open in" (`/dev/launch`) that a browser says comes from another website (403 `cross_site_request`). Its own pages, your extension's server, `curl` and your tests are not affected.
34
+
35
+ It checks like usebecky: unknown client ids, a `redirect_uri` not in `connect.redirect_uris` (exactly), missing PKCE, scopes not in the manifest, codes used twice, reused refresh tokens (every token of the install is revoked and it shows **Reconnect**). Not imitated: payments (a paid extension installs at once, in its free trial), retries of failed webhooks (one try), the plan's limit on the number of extensions. Restarting it forgets installs: install again.
36
+
37
+ ## Plans and pages that refresh
38
+
39
+ With `pricing` in the manifest, every install gets the plan object usebecky gives it (on `GET /installation`, in `extension.installed`, as `ctx.plan` on every page request). For example:
40
+
41
+ ```json
42
+ "pricing": {
43
+ "model": "plans",
44
+ "trial_days": 7,
45
+ "plans": [
46
+ { "id": "business", "name": "Business", "amount": 900, "summary": "250,000 requests a month, 1 container" },
47
+ { "id": "pro", "name": "Pro", "amount": 2900, "summary": "2.5 million requests a month" },
48
+ { "id": "agency", "name": "Agency", "amount": 5900, "summary": "For agencies with many sites" },
49
+ { "id": "enterprise", "name": "Enterprise", "amount": 25900, "summary": "Dedicated containers" }
50
+ ]
51
+ }
52
+ ```
53
+
54
+ - **Install** asks for the plan first; the install starts in the trial.
55
+ - The extension's page (`/project/<ref>/extensions/<slug>`, also what a `plan` button and `?plan=pro` open) is usebecky's plan dialog: **Change plan** follows usebecky's rules (in the trial: now; upgrade: now; downgrade: at the period end, as `next_plan`).
56
+ - The home page's **Plan** panel per install sets plan, status (`trialing`, `active`, `past_due`, `canceled`), trial days left, next plan, cancel at period end and a discount code (upper case, 3–30 letters, digits or `-`; percent or cents off; once, some months or forever, like a real code); **Start next period** lets a downgrade take over (or ends a plan set to end).
57
+ - `extension.plan_changed` goes to your webhook whenever the plan's id, status, end, next plan or discount change. In tests: `dev.setPlan(project, { status: 'past_due' })`, `dev.changePlan(project, 'pro')`, or `POST /dev/plan` with JSON.
58
+ - A page whose view has `refresh_seconds` is asked for again like the dashboard does it: every N seconds while the tab is visible, not while a form has unsaved input, for at most 30 minutes, until an answer leaves `refresh_seconds` out.
59
+
60
+ ## Send events
61
+
62
+ ```bash
63
+ npx @usebecky/extension send test.ping
64
+ npx @usebecky/extension send user.created
65
+ npx @usebecky/extension send extension.uninstalled --project devshop00001
66
+ ```
67
+
68
+ With the dev server running, it sends through it: a real delivery for an installed project. Without, it sends what the Developer area's **Send test event** sends (`"test": true`, project `sampleproject`), signed with the dev secret (or `--secret`, or `USEBECKY_WEBHOOK_SECRET`), to `webhook_url` mapped onto `--app`, or to `--url`.
69
+
70
+ ## Write tests
71
+
72
+ Start the dev server in a test, point your app at it, and click through with `fetch`. The starter's `test/app.test.ts` does the whole flow; the core of it:
73
+
74
+ ```ts
75
+ // test/install.test.ts
76
+ import assert from 'node:assert/strict'
77
+ import { test } from 'node:test'
78
+ import { createExtension, memoryTokenStore } from '@usebecky/extension'
79
+ import { DEV_CREDENTIALS, startDevServer } from '@usebecky/extension/dev'
80
+
81
+ test('the partner API answers after an install', async () => {
82
+ const dev = await startDevServer({ port: 0, appUrl: 'http://localhost:3999', log: () => {} })
83
+ try {
84
+ const tokens = memoryTokenStore()
85
+ const ext = createExtension({ ...DEV_CREDENTIALS, redirectUri: 'http://localhost:3999/oauth/callback', apiUrl: dev.url, tokenStore: tokens })
86
+ // What the customer does: open the consent screen, press Allow.
87
+ const consent = new URL(await ext.authorizeUrl({ project: 'devshop00001' }))
88
+ const form = new URLSearchParams({ ...Object.fromEntries(consent.searchParams), decision: 'allow' })
89
+ const back = await fetch(`${dev.url}/oauth/authorize`, { method: 'POST', body: form, redirect: 'manual' })
90
+ const { project } = await ext.handleCallback(back.headers.get('location')!)
91
+ assert.equal((await ext.api(project).project()).name, 'Acme Shop')
92
+ } finally {
93
+ await dev.close()
94
+ }
95
+ })
96
+ ```
97
+
98
+ `dev.sendEvent(type, project)` posts a signed event to the webhook and returns `{ status, ms, error }`; `dev.installs()` lists installs (as `GET /installation` shows them, plus `status` and `connected`); `await dev.launchUrl(project)` gives the "Open in" link (`sso_url?launch=<token>`) for an installed project.
99
+
100
+ ## Then on the real usebecky
101
+
102
+ The Developer area gives every developer a free **test project** (**Open test project** on your extension's page). Install your own draft extension there, before review, and simulate sign-ups and purchases to fire real events. Run your extension on an https address for that (`npm start` with `.env` filled in), with `PUBLIC_URL/oauth/callback` in `connect.redirect_uris`.