@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,104 @@
|
|
|
1
|
+
# usebecky-extension.json: the listing
|
|
2
|
+
|
|
3
|
+
The file describes the extension for the store and the consent screen: the store listing without what usebecky manages. In the Developer area, the editor's **Import usebecky-extension.json** fills the draft from it (then **Save draft**); the logo is uploaded separately under **Store listing**. Check it any time:
|
|
4
|
+
|
|
5
|
+
```bash
|
|
6
|
+
npx @usebecky/extension validate
|
|
7
|
+
```
|
|
8
|
+
|
|
9
|
+
It runs usebecky's own checks and prints usebecky's messages, with the same field paths (`connect.redirect_uris.0`): errors are what usebecky would refuse when you import or submit the listing. Warnings point at placeholders, localhost addresses and the logo file: fix them before you submit. `--local` checks `webhook_url` like a usebecky on your computer does (plain http and local addresses allowed).
|
|
10
|
+
|
|
11
|
+
## A complete example
|
|
12
|
+
|
|
13
|
+
```json
|
|
14
|
+
{
|
|
15
|
+
"slug": "cookie-helper",
|
|
16
|
+
"name": "Cookie Helper",
|
|
17
|
+
"publisher": { "name": "Helper GmbH", "website": "https://helper.io", "email": "hello@helper.io" },
|
|
18
|
+
"logo_url": "logo.svg",
|
|
19
|
+
"summary": "A friendly cookie banner that remembers what visitors chose.",
|
|
20
|
+
"description": "Cookie Helper shows a cookie banner on your website...\n\n**What it needs:** your project's name and visitor totals.",
|
|
21
|
+
"category": "consent",
|
|
22
|
+
"pricing": { "model": "monthly", "amount": 900, "trial_days": 14 },
|
|
23
|
+
"links": { "privacy": "https://helper.io/privacy", "support": "mailto:help@helper.io", "dpa": "https://helper.io/dpa" },
|
|
24
|
+
"connect": {
|
|
25
|
+
"mode": "oauth",
|
|
26
|
+
"install_url": "https://helper.io/install",
|
|
27
|
+
"redirect_uris": ["https://helper.io/oauth/callback"]
|
|
28
|
+
},
|
|
29
|
+
"scopes": ["project:read", "analytics:read"],
|
|
30
|
+
"webhook_url": "https://helper.io/webhooks/usebecky",
|
|
31
|
+
"data_shared": ["Your project's name and the websites it allows", "Visitor numbers for your website (totals only)", "Your name and email address, for your Cookie Helper account"],
|
|
32
|
+
"account": { "required": true, "provision": "oauth", "sso_url": "https://helper.io/sso" }
|
|
33
|
+
}
|
|
34
|
+
```
|
|
35
|
+
|
|
36
|
+
## Fields
|
|
37
|
+
|
|
38
|
+
| Field | Rules |
|
|
39
|
+
|---|---|
|
|
40
|
+
| `slug` | the id you chose when you created the extension: 3-40 characters `a-z`, `0-9` and single `-`, not at the start or end; a few words (`store`, `api`, `test`...) are reserved. It never changes, and usebecky refuses a file with another one |
|
|
41
|
+
| `name` | 2-60 characters (store cards fit about 30) |
|
|
42
|
+
| `publisher` | `name`, `website` (https), `email` (usebecky writes to it about reviews and payouts) |
|
|
43
|
+
| `logo_url` | the logo file next to this file (`"logo.svg"`). The import ignores it: upload the PNG, SVG or JPEG (at most 200 KB) under Store listing |
|
|
44
|
+
| `summary` | at most 90 characters, one sentence |
|
|
45
|
+
| `description` | Markdown, at most 5000 characters: what it does, for whom, what it needs |
|
|
46
|
+
| `category` | `consent`, `tags`, `marketing`, `support` or `other` |
|
|
47
|
+
| `pricing` | `{ "model": "free" }`, `{ "model": "monthly", "amount": <US cents, 300–99900>, "trial_days": <0–30> }` or `{ "model": "plans", "trial_days": <0–30>, "plans": [{ "id", "name", "amount", "summary"? }, …] }` (2–6 plans; see submit-and-pricing.md) |
|
|
48
|
+
| `links` | `privacy` and `support` required (support may be `mailto:you@example.com`); `dpa`, `terms`, `docs` optional; all https, no `#…` |
|
|
49
|
+
| `connect` | `oauth`: `install_url` (usebecky's Install opens it with `?project=<ref>&return_url=<the extension's page in the project>`) and `redirect_uris` (1-10 exact callback addresses). Both https; `http://localhost` and `http://127.0.0.1` work too, for testing. `fields`: 1-20 settings the customer fills in instead (below) |
|
|
50
|
+
| `scopes` | what the extension may read (below). `[]` when it needs none |
|
|
51
|
+
| `events` | usebecky event types delivered to `webhook_url` (needs `events:read` and `webhook_url`), e.g. `["user.created", "purchase.completed"]`. Any developer event type except `test.ping`; never `extension.installed`/`extension.uninstalled` (those always come) |
|
|
52
|
+
| `webhook_url` | https and a public host name (no IP addresses, no `localhost` or `.internal` names); gets `extension.installed`, `extension.uninstalled` and your `events` |
|
|
53
|
+
| `data_shared` | 1-20 plain sentences for the consent screen, at most 200 characters each; one line per kind of data |
|
|
54
|
+
| `account` | only when the service needs an account per customer (customers never sign up by hand): `{ "required": true, "provision": "oauth", "sso_url" }` (oauth mode: account from the id_token) or `{ "required": true, "provision": "url", "provision_url", "sso_url" }` (fields mode: usebecky calls `provision_url`); optional `"members_can_open": true`. `provision_url` like `webhook_url`; `sso_url` https (`http://localhost` for testing). Needs credentials. See `accounts.md` |
|
|
55
|
+
| `ui` | optional: your own pages inside usebecky, drawn by usebecky from your blocks. `{ "url": "https://api.you.example/usebecky/ui", "pages": [{ "id": "reviews", "label": "Reviews", "section": "website" }], "settings": true }`. `url` like `webhook_url`; at most 3 `pages` (`id` `[a-z][a-z0-9-]`, not `settings`; `label` ≤ 24 characters; `section` `backend`, `website`, `messages` or `project`); `settings: true` shows your page `settings` on your extension's page. At least one page or `settings`. Needs credentials. See `ui.md` |
|
|
56
|
+
| `$schema`, `capabilities` | ignored (`capabilities` are set by usebecky only) |
|
|
57
|
+
|
|
58
|
+
## Setup fields (`connect.mode: "fields"`)
|
|
59
|
+
|
|
60
|
+
```json
|
|
61
|
+
{
|
|
62
|
+
"connect": {
|
|
63
|
+
"mode": "fields",
|
|
64
|
+
"fields": [
|
|
65
|
+
{ "key": "site_id", "label": "Site ID", "type": "text", "required": true, "pattern": "^[a-z0-9]{6}$", "placeholder": "abc123", "help": "In your Helper dashboard under Sites." },
|
|
66
|
+
{ "key": "api_key", "label": "API key", "type": "secret", "required": true },
|
|
67
|
+
{ "key": "dark_banner", "label": "Dark banner", "type": "boolean", "required": false },
|
|
68
|
+
{ "key": "accept_terms", "label": "I accept the Helper terms", "type": "boolean", "required": true }
|
|
69
|
+
]
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
```
|
|
73
|
+
|
|
74
|
+
| Property | Rules |
|
|
75
|
+
|---|---|
|
|
76
|
+
| `key` | `a-z`, `0-9`, `_`, starting with a letter, at most 40 characters, unique |
|
|
77
|
+
| `label` | at most 80 characters; `help` at most 300 |
|
|
78
|
+
| `type` | `text`; `url` (https; usebecky never opens it); `secret` (stored encrypted, shown masked, **never sent to you**); `boolean` (a yes/no checkbox) |
|
|
79
|
+
| `required` | `true` or `false`. A required `boolean` must be turned on (for "I accept ...") |
|
|
80
|
+
| `pattern` | a regular expression the value must match (at most 200 characters). Not for `boolean` |
|
|
81
|
+
| `placeholder` | example text in the empty box (at most 120 characters). Not for `boolean` |
|
|
82
|
+
|
|
83
|
+
You get the settings without secret fields in `extension.installed` (`event.data.settings`) and from `GET /installation` (`settings`). A `boolean` field's value is `true` or `false` (never a string); treat a missing key as `false`.
|
|
84
|
+
|
|
85
|
+
## Scopes and data minimisation
|
|
86
|
+
|
|
87
|
+
| Scope | Gives | Partner API |
|
|
88
|
+
|---|---|---|
|
|
89
|
+
| (none) | the install itself | `GET /installation` |
|
|
90
|
+
| `project:read` | the project's name, API address, publishable key and the websites it allows | `GET /project` |
|
|
91
|
+
| `analytics:read` | totals: visitors, visits, page views, conversions, top pages, channels, revenue per channel | `GET /analytics/summary` |
|
|
92
|
+
| `events:read` | the usebecky events listed in `events` | webhooks |
|
|
93
|
+
|
|
94
|
+
Rules for choosing:
|
|
95
|
+
|
|
96
|
+
1. Start with none and add a scope only when a feature needs it. Customers see every scope before they allow access, and reviewers ask why each one is there.
|
|
97
|
+
2. Every scope needs a matching line in `data_shared`, in words a non-developer understands ("Visitor numbers for your website (totals only)"), not scope names.
|
|
98
|
+
3. List only the events you handle. Each event may carry personal data (an email address, a name): store only what the feature needs and delete it on uninstall.
|
|
99
|
+
4. Adding a scope later means a new review, and customers connect again to allow it (until then the API answers `insufficient_scope`).
|
|
100
|
+
5. `openid`, `email`, `profile` are not listing scopes: usebecky adds them on the consent screen for `"account": { "provision": "oauth" }` listings.
|
|
101
|
+
|
|
102
|
+
## Addresses while developing
|
|
103
|
+
|
|
104
|
+
Keep the real https addresses in the file. The dev server maps them onto your local server (`--app http://localhost:3000`, the default): `https://helper.io/oauth/callback` becomes `http://localhost:3000/oauth/callback`; the same for `webhook_url`, `account.provision_url` and `account.sso_url`. So `validate` stays clean and you never forget to switch back.
|
|
@@ -0,0 +1,179 @@
|
|
|
1
|
+
# Installing: OAuth, PKCE and tokens with the kit
|
|
2
|
+
|
|
3
|
+
## How an install works
|
|
4
|
+
|
|
5
|
+
1. The customer clicks **Install** in the store. usebecky opens your `install_url` with `?project=<ref>&return_url=<the extension's page in their project>` (also when they come back to connect again).
|
|
6
|
+
2. Your install route redirects to usebecky's consent screen (`https://app.usebecky.com/oauth/authorize?client_id&redirect_uri&response_type=code&state&code_challenge&code_challenge_method=S256&project&nonce`): `oauthHandlers().install`. The kit makes the state and the PKCE S256 verifier, keeps the verifier (and a `return_url` on usebecky's dashboard) in the state store for 10 minutes, and sets a short cookie (`usebecky_oauth_state`) that ties the sign-in to this browser. (`await ext.authorizeUrl({ project })` builds the URL without that cookie: only for flows without a browser, like tests.)
|
|
7
|
+
3. The customer picks the project (they must be an owner or admin of it) and clicks **Allow**. usebecky redirects to your redirect URI with `?code=ub_ac_...&state=...` (or `?error=access_denied&error_description=...&state=...` after **Cancel**). A wrong client id, a `redirect_uri` that isn't listed exactly, missing PKCE or an unlisted scope stops on usebecky's screen: nothing is redirected.
|
|
8
|
+
4. Your callback calls `await ext.handleCallback(request)`: it checks the state (once, and against the browser's cookie), swaps the code (single use, 10 minutes) with the verifier, loads the install (`GET /installation`) and stores the tokens under the project ref. Pass the Request (or Node's `req`), not only the URL, so the cookie can be checked; a callback link opened in another browser is refused. The result has `returnUrl`: link back to it ("Back to usebecky"). With `"account": { "provision": "oauth" }` the token response also has an id_token; the kit verifies it (signature, issuer, audience, expiry, the nonce it sent) and returns its claims as `identity`: create the customer's account from it right there (`identity.sub`, `identity.email`, `identity.name`, `identity.usebecky_role`). Never a sign-up form: see `accounts.md`.
|
|
9
|
+
5. usebecky sends `extension.installed` to your `webhook_url` (when the customer clicks Allow, so it may arrive before your callback runs).
|
|
10
|
+
|
|
11
|
+
Access tokens (`ub_it_...`) live 1 hour, refresh tokens (`ub_ir_...`) 90 days. The kit refreshes a minute before expiry and on a 401, one refresh per install at a time. Refresh tokens rotate: a reused one makes usebecky revoke every token of that install, and the customer has to connect again.
|
|
12
|
+
|
|
13
|
+
## createExtension
|
|
14
|
+
|
|
15
|
+
```ts
|
|
16
|
+
// src/extension.ts
|
|
17
|
+
import { createExtension } from '@usebecky/extension'
|
|
18
|
+
import { fileTokenStore } from '@usebecky/extension/node'
|
|
19
|
+
|
|
20
|
+
export const ext = createExtension({
|
|
21
|
+
clientId: process.env.USEBECKY_CLIENT_ID!,
|
|
22
|
+
clientSecret: process.env.USEBECKY_CLIENT_SECRET!,
|
|
23
|
+
webhookSecret: process.env.USEBECKY_WEBHOOK_SECRET,
|
|
24
|
+
redirectUri: `${process.env.PUBLIC_URL}/oauth/callback`,
|
|
25
|
+
apiUrl: process.env.USEBECKY_API_URL, // unset: usebecky; `npm run dev` sets both to the dev server
|
|
26
|
+
dashboardUrl: process.env.USEBECKY_DASHBOARD_URL,
|
|
27
|
+
tokenStore: fileTokenStore('.data/tokens.json'),
|
|
28
|
+
})
|
|
29
|
+
```
|
|
30
|
+
|
|
31
|
+
Options: `scopes` (ask for fewer than the listing has), `stateStore` (shared store for several instances), `replayGuard` (used launch tokens: required with several instances, `sqlReplayGuard({ query })` in the token store's database), `dashboardUrl` (where the consent screen is: https://app.usebecky.com unless `apiUrl` points elsewhere; env `USEBECKY_DASHBOARD_URL`), `refreshMarginSeconds`, `fetch`. Missing options throw a `ConfigError` whose `hint` names the variable.
|
|
32
|
+
|
|
33
|
+
## Routes per framework
|
|
34
|
+
|
|
35
|
+
Hono (`c.req.raw` is the fetch Request):
|
|
36
|
+
|
|
37
|
+
```ts
|
|
38
|
+
// src/routes.ts
|
|
39
|
+
import { Hono } from 'hono'
|
|
40
|
+
import { ext } from './extension.ts'
|
|
41
|
+
|
|
42
|
+
const app = new Hono()
|
|
43
|
+
const { install, callback } = ext.oauthHandlers({ successUrl: '/settings' })
|
|
44
|
+
app.get('/install', (c) => install(c.req.raw))
|
|
45
|
+
app.get('/oauth/callback', (c) => callback(c.req.raw))
|
|
46
|
+
export default app
|
|
47
|
+
```
|
|
48
|
+
|
|
49
|
+
Next.js App Router (route handlers are fetch handlers):
|
|
50
|
+
|
|
51
|
+
```ts
|
|
52
|
+
// lib/extension.ts
|
|
53
|
+
import { createExtension, sqlTokenStore } from '@usebecky/extension'
|
|
54
|
+
|
|
55
|
+
export const ext = createExtension({
|
|
56
|
+
clientId: process.env.USEBECKY_CLIENT_ID!,
|
|
57
|
+
clientSecret: process.env.USEBECKY_CLIENT_SECRET!,
|
|
58
|
+
webhookSecret: process.env.USEBECKY_WEBHOOK_SECRET,
|
|
59
|
+
redirectUri: `${process.env.PUBLIC_URL}/oauth/callback`,
|
|
60
|
+
tokenStore: sqlTokenStore({ query: async () => [] }), // your database here (see "Token stores")
|
|
61
|
+
})
|
|
62
|
+
export const oauth = ext.oauthHandlers({ successUrl: '/settings' })
|
|
63
|
+
```
|
|
64
|
+
|
|
65
|
+
```ts
|
|
66
|
+
// app/install/route.ts
|
|
67
|
+
import { oauth } from '@/lib/extension'
|
|
68
|
+
|
|
69
|
+
export const GET = oauth.install
|
|
70
|
+
```
|
|
71
|
+
|
|
72
|
+
```ts
|
|
73
|
+
// app/oauth/callback/route.ts
|
|
74
|
+
import { oauth } from '@/lib/extension'
|
|
75
|
+
|
|
76
|
+
export const GET = oauth.callback
|
|
77
|
+
```
|
|
78
|
+
|
|
79
|
+
Serverless hosts (Vercel, Netlify) have no shared memory or disk: use a database token store and a `stateStore` backed by your database or Redis.
|
|
80
|
+
|
|
81
|
+
Express and node:http (`toNodeHandler` adapts any fetch handler):
|
|
82
|
+
|
|
83
|
+
```ts
|
|
84
|
+
// server.ts
|
|
85
|
+
import express from 'express'
|
|
86
|
+
import { toNodeHandler } from '@usebecky/extension'
|
|
87
|
+
import { ext } from './src/extension.ts'
|
|
88
|
+
|
|
89
|
+
const app = express()
|
|
90
|
+
const { install, callback } = ext.oauthHandlers({ successUrl: '/settings' })
|
|
91
|
+
app.get('/install', toNodeHandler(install))
|
|
92
|
+
app.get('/oauth/callback', toNodeHandler(callback))
|
|
93
|
+
app.listen(3000)
|
|
94
|
+
```
|
|
95
|
+
|
|
96
|
+
## Your own callback (to set a session cookie)
|
|
97
|
+
|
|
98
|
+
`oauthHandlers({ onInstalled })` can return a Response, or write the route yourself:
|
|
99
|
+
|
|
100
|
+
```ts
|
|
101
|
+
// inside an async function:
|
|
102
|
+
import { ExtensionError, OAuthCallbackError } from '@usebecky/extension'
|
|
103
|
+
import { ext } from './extension.ts'
|
|
104
|
+
|
|
105
|
+
const request = new Request('https://helper.io/oauth/callback?code=c&state=s')
|
|
106
|
+
try {
|
|
107
|
+
const { project, installation, scopes, returnUrl, identity } = await ext.handleCallback(request)
|
|
108
|
+
console.log(`Connected to ${installation.project.name} (${project}) with ${scopes.join(', ')}; back to usebecky: ${returnUrl ?? 'none'}`)
|
|
109
|
+
if (identity) console.log(`create or find the account of ${identity.sub} (${identity.email ?? 'no email'})`)
|
|
110
|
+
// set a signed, httpOnly session cookie holding `project`, then redirect to your settings page
|
|
111
|
+
} catch (err) {
|
|
112
|
+
if (err instanceof OAuthCallbackError && err.code === 'access_denied') {
|
|
113
|
+
// the customer pressed Cancel: show a friendly page with a link to /install
|
|
114
|
+
} else if (err instanceof ExtensionError) {
|
|
115
|
+
// invalid_state (old or reused link), invalid_grant (code expired or used), invalid_client (wrong secret)...
|
|
116
|
+
} else throw err
|
|
117
|
+
}
|
|
118
|
+
```
|
|
119
|
+
|
|
120
|
+
## Errors
|
|
121
|
+
|
|
122
|
+
| Class | When | Codes |
|
|
123
|
+
|---|---|---|
|
|
124
|
+
| `OAuthCallbackError` | the callback can't finish | `access_denied`, `invalid_state`, `invalid_request` |
|
|
125
|
+
| `TokenError` | usebecky's token endpoint said no (RFC 6749 `error`, `error_description` as the message) | `invalid_grant` (code expired or used, wrong `redirect_uri` or verifier, revoked or reused refresh token), `invalid_client` (wrong client id or secret), `extension_suspended` (during an install: usebecky suspended your extension), `invalid_request`, `invalid_scope`, `slow_down` (429), `network_error` |
|
|
126
|
+
| `InstallationRevokedError` | uninstalled, revoked or suspended; the kit deleted the tokens | `installation_revoked`, `not_connected`, `extension_suspended` (usebecky suspended your extension: check your email from usebecky) |
|
|
127
|
+
| `PartnerApiError` | an API call failed | `insufficient_scope`, `installation_inactive`, `rate_limited`, `plan_required`, `invalid_range`, `network_error` |
|
|
128
|
+
| `TokenVerificationError` | an id_token or launch token was refused | `invalid_signature`, `invalid_audience`, `invalid_issuer`, `expired_token`, `invalid_nonce`, `replayed_token`, `wrong_token_type`, `unknown_key`, `jwks_unavailable` |
|
|
129
|
+
| `ProvisionRequestError` | a provision request was refused | `missing_signature`, `invalid_signature`, `stale_signature`, `invalid_payload`, `idempotency_mismatch` |
|
|
130
|
+
| `ConfigError` | a missing or wrong option | `missing_option`, `invalid_option`, `missing_webhook_secret` |
|
|
131
|
+
|
|
132
|
+
All extend `ExtensionError` (`code`, `message`, `hint`, `status`, and usebecky's `details` when it sends any).
|
|
133
|
+
|
|
134
|
+
## Token stores
|
|
135
|
+
|
|
136
|
+
| Store | Use |
|
|
137
|
+
|---|---|
|
|
138
|
+
| `memoryTokenStore()` | tests |
|
|
139
|
+
| `fileTokenStore('.data/tokens.json')` from `@usebecky/extension/node` | development and one small server with a disk; keep `.data/` out of git |
|
|
140
|
+
| `sqlTokenStore({ query, dialect })` | Postgres or SQLite; create the table with `tokenTableSql()` |
|
|
141
|
+
| your own `TokenStore` | `get(project)`, `set(tokens)`, `delete(project)`, optional `lock(project, fn)` |
|
|
142
|
+
|
|
143
|
+
With a database, keep the used launch tokens of "Open in" there too: `sqlReplayGuard({ query, dialect })` (table: `replayTableSql()`), passed to `createExtension({ tokenStore, replayGuard })`. Required as soon as more than one instance runs.
|
|
144
|
+
|
|
145
|
+
Postgres with `pg`:
|
|
146
|
+
|
|
147
|
+
```ts
|
|
148
|
+
// src/tokens.ts
|
|
149
|
+
import { replayTableSql, sqlReplayGuard, sqlTokenStore, tokenTableSql } from '@usebecky/extension'
|
|
150
|
+
import pg from 'pg'
|
|
151
|
+
|
|
152
|
+
const pool = new pg.Pool({ connectionString: process.env.DATABASE_URL })
|
|
153
|
+
const query = async (sql: string, params: unknown[]) => (await pool.query(sql, params)).rows
|
|
154
|
+
export const tokenStore = sqlTokenStore({ query })
|
|
155
|
+
export const replayGuard = sqlReplayGuard({ query })
|
|
156
|
+
|
|
157
|
+
/** Run once at start-up (or put the statements in a migration). */
|
|
158
|
+
export async function createTables() {
|
|
159
|
+
await pool.query(tokenTableSql())
|
|
160
|
+
await pool.query(replayTableSql())
|
|
161
|
+
}
|
|
162
|
+
```
|
|
163
|
+
|
|
164
|
+
SQLite with Node's built-in `node:sqlite`:
|
|
165
|
+
|
|
166
|
+
```ts
|
|
167
|
+
// src/tokens.ts
|
|
168
|
+
import { DatabaseSync } from 'node:sqlite'
|
|
169
|
+
import { replayTableSql, sqlReplayGuard, sqlTokenStore, tokenTableSql } from '@usebecky/extension'
|
|
170
|
+
|
|
171
|
+
const db = new DatabaseSync('.data/extension.db')
|
|
172
|
+
db.exec(tokenTableSql())
|
|
173
|
+
db.exec(replayTableSql())
|
|
174
|
+
const query = (sql: string, params: unknown[]) => db.prepare(sql).all(...(params as Array<string | number>))
|
|
175
|
+
export const tokenStore = sqlTokenStore({ dialect: 'sqlite', query })
|
|
176
|
+
export const replayGuard = sqlReplayGuard({ dialect: 'sqlite', query })
|
|
177
|
+
```
|
|
178
|
+
|
|
179
|
+
More than one server instance: add `lock` so two instances never refresh the same install at once (a Postgres advisory lock in a transaction, or a Redis lock). The kit already serialises refreshes inside one process and re-reads the store before refreshing. Share the `replayGuard` too (above).
|
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
# The partner API
|
|
2
|
+
|
|
3
|
+
`ext.api(project)` calls `https://api.usebecky.com/extensions/v1` for one install, with its access token (`Authorization: Bearer ub_it_...`). It refreshes the token when needed and throws typed errors. Never call these URLs with `fetch` yourself. A token is not a project key: it never reaches the project's database, `/rest/v1` or `/storage/v1`.
|
|
4
|
+
|
|
5
|
+
```ts
|
|
6
|
+
// inside an async function:
|
|
7
|
+
import { createExtension, InstallationRevokedError, memoryTokenStore, PartnerApiError } from '@usebecky/extension'
|
|
8
|
+
|
|
9
|
+
const ext = createExtension({
|
|
10
|
+
clientId: process.env.USEBECKY_CLIENT_ID!,
|
|
11
|
+
clientSecret: process.env.USEBECKY_CLIENT_SECRET!,
|
|
12
|
+
redirectUri: `${process.env.PUBLIC_URL}/oauth/callback`,
|
|
13
|
+
tokenStore: memoryTokenStore(),
|
|
14
|
+
})
|
|
15
|
+
const project = 'k3x9m2p7q1zt' // from your session cookie or a verified webhook
|
|
16
|
+
|
|
17
|
+
try {
|
|
18
|
+
const install = await ext.api(project).installation()
|
|
19
|
+
const info = await ext.api(project).project()
|
|
20
|
+
const visits = await ext.api(project).analyticsSummary({ from: '2026-11-01', to: '2026-11-30' })
|
|
21
|
+
console.log(install.installed_at, info.name, info.allowed_hosts, visits.visitors, visits.top_pages[0]?.path, visits.revenue.total)
|
|
22
|
+
} catch (err) {
|
|
23
|
+
if (err instanceof InstallationRevokedError) {
|
|
24
|
+
// uninstalled or revoked: stop working for this project (the kit deleted the tokens)
|
|
25
|
+
} else if (err instanceof PartnerApiError && err.code === 'insufficient_scope') {
|
|
26
|
+
// the customer didn't allow err.details?.required_scope: hide the feature, or ask them to connect again
|
|
27
|
+
} else throw err
|
|
28
|
+
}
|
|
29
|
+
```
|
|
30
|
+
|
|
31
|
+
## Calls
|
|
32
|
+
|
|
33
|
+
| Method | Route | Scope | Returns |
|
|
34
|
+
|---|---|---|---|
|
|
35
|
+
| `installation()` | `GET /installation` | none | `{ id, extension, project: { ref, name, api_url }, scopes, events, settings, installed_at, test, plan }` |
|
|
36
|
+
| `project()` | `GET /project` | `project:read` | `{ ref, name, api_url, publishable_key, allowed_hosts }` |
|
|
37
|
+
| `analyticsSummary({ from?, to? })` | `GET /analytics/summary` | `analytics:read` | `{ from, to, visitors, visits, page_views, conversions, top_pages: [{ path, page_views, visitors }], channels: [{ channel, visitors, visits }], revenue: { currency, total, purchases, by_channel: [{ channel, revenue, purchases }] } }` |
|
|
38
|
+
| `updateSettings({ tagging_server_url, measurement_id, send_client_id? })` | `PUT /installation/settings` | capability `sgtm_forwarding` | `{ settings }` as stored |
|
|
39
|
+
| `clearSettings()` | `DELETE /installation/settings` | capability `sgtm_forwarding` | `{ settings: {} }` |
|
|
40
|
+
| `request(method, path, { query, body })` | any other route | | the JSON body |
|
|
41
|
+
|
|
42
|
+
- `installation().scopes`: what the customer allowed that your live listing still has. `events`: the event types this install receives (`[]` without `events:read`); when your listing adds events, customers allow them first, so they show up here (and get delivered) only after that. `settings`: the non-secret setup fields (fields mode; `boolean` fields are `true`/`false`), `{}` for oauth extensions (or the server-side tagging settings your server set). `test`: `true` for an install in a test project (payments there are simulated: don't bill or count it). `plan`: the install's price plan (`null` for a free extension; a monthly listing's is `monthly`); changes arrive as `extension.plan_changed`.
|
|
43
|
+
- `project().api_url` is the project's custom domain when it has one; `publishable_key` (`ub_pk_...`) is safe in browsers, for example for a script on the customer's website; `allowed_hosts` are host names like `shop.example.com` (may be empty).
|
|
44
|
+
- `analyticsSummary`: days as `YYYY-MM-DD` (UTC, both included). Send both `from` and `to`, or neither for the last 30 days. Totals only, never single visitors: an extension must never try to identify visitors. Channels are `direct`, `organic_search`, `social`, `email`, `paid` and `referral`. Revenue counts live-mode sales, in the smallest currency unit (cents). The project's plan limits how far back you can look (Free 7 days, Pro 90): a longer range answers `plan_required`.
|
|
45
|
+
|
|
46
|
+
## Server-side tagging (capability `sgtm_forwarding`)
|
|
47
|
+
|
|
48
|
+
Only for an extension usebecky gave the capability `sgtm_forwarding` (usebecky sets it after review; the manifest can't). Its server tells usebecky where to send the project's sales, sign-ups and form leads (GA4 hits on the customer's Google Tag Manager tagging server):
|
|
49
|
+
|
|
50
|
+
```ts
|
|
51
|
+
// inside an async function:
|
|
52
|
+
import { createExtension, memoryTokenStore } from '@usebecky/extension'
|
|
53
|
+
|
|
54
|
+
const ext = createExtension({
|
|
55
|
+
clientId: process.env.USEBECKY_CLIENT_ID!,
|
|
56
|
+
clientSecret: process.env.USEBECKY_CLIENT_SECRET!,
|
|
57
|
+
redirectUri: `${process.env.PUBLIC_URL}/oauth/callback`,
|
|
58
|
+
tokenStore: memoryTokenStore(),
|
|
59
|
+
})
|
|
60
|
+
const { settings } = await ext.api('k3x9m2p7q1zt').updateSettings({ tagging_server_url: 'https://abc123.signalhost.io', measurement_id: 'G-AB12CD34', send_client_id: true })
|
|
61
|
+
console.log(settings.tagging_server_url) // "https://abc123.signalhost.io"
|
|
62
|
+
await ext.api('k3x9m2p7q1zt').clearSettings() // stop forwarding (the tagging server was deleted)
|
|
63
|
+
```
|
|
64
|
+
|
|
65
|
+
- Send all three every time (`send_client_id` defaults to `false`); no other keys. The same values again change nothing.
|
|
66
|
+
- Checked like the customer's form: `https://` and a public host name (no IP, port, query, credentials; `…/g/collect` is trimmed), usebecky resolves it and refuses a private address; `G-…` (stored upper case). A wrong value: `invalid_settings` with the reason in `message`.
|
|
67
|
+
- The dev server answers it only with `--capability sgtm_forwarding` (`startDevServer({ capabilities: ['sgtm_forwarding'] })`); it checks the form but doesn't look the name up.
|
|
68
|
+
|
|
69
|
+
## Errors
|
|
70
|
+
|
|
71
|
+
Every error has usebecky's `code`, `message`, `hint` and, for some, `details`.
|
|
72
|
+
|
|
73
|
+
| Error | Meaning | Do |
|
|
74
|
+
|---|---|---|
|
|
75
|
+
| `InstallationRevokedError` `not_connected` | no tokens stored for that project | it was never installed here, or was uninstalled |
|
|
76
|
+
| `InstallationRevokedError` `installation_revoked` | usebecky refused the tokens (uninstalled, revoked, a reused refresh token) | stop; it works again after the customer connects again |
|
|
77
|
+
| `InstallationRevokedError` `extension_suspended` | usebecky's team suspended the extension: every token is revoked for good (the kit deleted the stored ones) | stop; check your email from usebecky. Once the suspension ends, customers connect it again |
|
|
78
|
+
| `PartnerApiError` `insufficient_scope` (403) | the scope isn't allowed (`details.required_scope`) | add it to `scopes`, submit, customers connect again |
|
|
79
|
+
| `PartnerApiError` `installation_inactive` (403) | the install needs a reconnect | ask the customer to connect again from their project |
|
|
80
|
+
| `PartnerApiError` `capability_required` (403) | server-side tagging settings without the capability `sgtm_forwarding` (`details.required_capability`) | ask usebecky; until then don't call it |
|
|
81
|
+
| `PartnerApiError` `invalid_settings` (400) | a server-side tagging setting is wrong (`message` says which) | fix the value; `details.field` names an unknown key |
|
|
82
|
+
| `PartnerApiError` `invalid_range` (400), `plan_required` (403) | a wrong date range, or longer than the plan keeps | send both dates, a shorter range |
|
|
83
|
+
| `PartnerApiError` `rate_limited` (429) | more than 300 calls a minute for this install | wait for `Retry-After` (60) seconds; cache results |
|
|
84
|
+
| `PartnerApiError` `project_unavailable` (503), `project_paused` (402) | the project is paused | try again later |
|
|
85
|
+
| `PartnerApiError` `network_error` (status 0) | usebecky unreachable | retry later |
|
|
86
|
+
|
|
87
|
+
Cache what you read (a project's name rarely changes) instead of calling on every page view.
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
# Submitting, review, pricing and payouts
|
|
2
|
+
|
|
3
|
+
## From the starter to the store
|
|
4
|
+
|
|
5
|
+
1. **Create the extension** in usebecky: **Build an extension** at the bottom of a project's Extensions page, **New extension** under **Developer**, or https://app.usebecky.com/developer/extensions/new. Pick the same id (slug) as in `usebecky-extension.json` and click **Create extension**; the id can't change later.
|
|
6
|
+
2. **Fill in the listing**: in the editor, **Import usebecky-extension.json**, then upload the logo under **Store listing** and **Save draft**. The editor's sections are Store listing, About you, How customers connect ("Sign in with usebecky (OAuth)" or "Setup fields"), Accounts at your service, Permissions and events, Data you receive and Pricing.
|
|
7
|
+
3. **Get credentials**: under **Credentials and testing**, **Create credentials**. Copy the client id, client secret and webhook signing secret into your host's environment (`USEBECKY_CLIENT_ID`, `USEBECKY_CLIENT_SECRET`, `USEBECKY_WEBHOOK_SECRET`). The secrets are shown once; **Rotate secrets** makes new ones (the client id stays, the old client secret stops working at once).
|
|
8
|
+
4. **Deploy** the extension on an https address and set `PUBLIC_URL` and `SESSION_SECRET`. Use a database token store unless it is one server with a disk.
|
|
9
|
+
5. **Try it on the test project**: **Open test project** (the Developer overview says **Create test project** the first time). Install it, open your settings page, click **Open in …** in Developer tools, simulate sign-ups and purchases, disconnect it. **Open demo site** opens the test project's demo shop for website snippets; **Send test event** sends a signed sample event (`"test": true`) to your webhook.
|
|
10
|
+
6. **Check**: `npx @usebecky/extension validate` (no placeholder warnings), the security checklist in SKILL.md, a real privacy policy at `links.privacy`.
|
|
11
|
+
7. **Submit for review**. usebecky's team approves it or explains what to change (you get an email either way). After approval it is listed in the store. Later changes go live after another review; the approved version stays live meanwhile.
|
|
12
|
+
|
|
13
|
+
## What reviewers look at
|
|
14
|
+
|
|
15
|
+
- **No manual sign-up.** If the service needs accounts, the listing has `account`, accounts are created automatically (id_token or provision request) and **Open in** signs straight in. Any sign-up or login form for usebecky customers is rejected.
|
|
16
|
+
- The listing is honest: the summary and description say what it does; `data_shared` covers every scope.
|
|
17
|
+
- Only the scopes it uses; the events it lists are handled.
|
|
18
|
+
- Installing, the settings page and disconnecting work on the test project, with clear words for non-developers.
|
|
19
|
+
- Pages inside usebecky (`ui`): every page loads in under 3 seconds on the test project, says what it is in a line, has one main action, words for beginners, an empty state with the next step, long lists paged on your server, and no secrets in blocks. Your own pages that customers reach from usebecky use its look with your own name and logo, never usebecky's wordmark.
|
|
20
|
+
- Disconnecting deletes the customer's data; the privacy policy says so.
|
|
21
|
+
- No secrets or tokens in the browser, URLs or logs; every webhook verified.
|
|
22
|
+
|
|
23
|
+
## Pricing and payouts
|
|
24
|
+
|
|
25
|
+
- **Free**, a **monthly price per project** from 3 to 999 USD before tax (`"pricing": { "model": "monthly", "amount": 900, "trial_days": 14 }`, amount in US cents), or **2 to 6 plans** (`"model": "plans"`, below), with an optional free trial of 0–30 days (once per extension and project, not again after a plan change).
|
|
26
|
+
- **Plans**: `"pricing": { "model": "plans", "trial_days": 7, "plans": [{ "id": "business", "name": "Business", "amount": 900, "summary": "250,000 requests a month" }, { "id": "pro", "name": "Pro", "amount": 2900 }] }`. `id` is `[a-z0-9-]{1,30}`, unique, and how your code recognises the plan (keep it when the price changes); `name` at most 30 characters, `summary` (optional) at most 80, `amount` 300–99900 cents. The customer picks a plan before checkout and changes it on your extension's page: an upgrade takes effect now (the prorated difference is charged at once), a downgrade at the end of the paid month (`plan.next_plan`), in the trial any change now and free. Removing a plan hides it from new customers; installs on it keep it until they change. Read the plan from `ctx.plan`, `installation().plan`, `extension.installed` and `extension.plan_changed`; `plan.status` is `trialing`, `active`, `past_due` (a payment failed, Stripe retries: keep working for now) or `canceled`. A button `{ label: 'Upgrade', plan: 'pro' }` on your pages, or the link `https://app.usebecky.com/project/<ref>/extensions/<slug>?plan=pro&code=LAUNCH50`, opens the plan dialog (`code` fills in a discount code).
|
|
27
|
+
- **Discount codes**: make them in the Developer area → your extension → Discount codes, or `POST /platform/v1/developer/extensions/<slug>/discount-codes` `{ code, percent_off | amount_off, duration: 'once' | 'repeating' | 'forever', duration_months?, plans?, max_redemptions?, expires_at?, first_purchase_only? }` (code `[A-Z0-9-]{3,30}`, upper case). Customers type them in the install or plan dialog. The install's plan carries it as `plan.discount = { code, percent_off | amount_off, duration, ends_at }` (`null` without one); `extension.plan_changed` fires when a discount appears or ends. A change to a plan the code isn't for ends the discount. You get 80% of what was actually paid. Codes work with the simulated plan in test projects (never counted).
|
|
28
|
+
- usebecky sells the extension to the customer (one invoice from usebecky) and keeps a **20% commission** of the price before tax (VAT and Stripe’s fees are usebecky’s). The rest goes to your own **Stripe** account (set it up under **Developer → Payouts**; developers in the EEA, the UK and Switzerland; you get your own Stripe login): each share is sent right after the payment, then Stripe pays out to your bank on the schedule you set in your Stripe dashboard. Guide: https://usebecky.com/docs/guides/extension-payouts
|
|
29
|
+
- A paid extension can only be submitted once payouts are set up. Refunds and lost disputes come off your share proportionally (from your Stripe account, or from your next payments if your balance is too low).
|
|
30
|
+
- `extension.installed` arrives after the customer paid (or started the trial). When a customer disconnects, you get `extension.uninstalled` (`reason: "customer"`) at once; a paid subscription then runs to the end of the period it was paid for and isn't renewed. When a subscription ends, `reason` is `"subscription_ended"`.
|
|
31
|
+
- The Developer area shows installs, active installs, trials, paying customers, revenue (gross, fee, net), refunds and payouts.
|
|
@@ -0,0 +1,172 @@
|
|
|
1
|
+
# Pages inside usebecky (`ui`)
|
|
2
|
+
|
|
3
|
+
Like a WordPress plugin's menu pages: an extension adds its own rows to the customer's project sidebar and a settings view on its page under Extensions. usebecky asks your server for each page and **draws your blocks with its own components**, so your pages look and behave exactly like the rest of usebecky (light and dark, phones, keyboard, contrast). You never write HTML, CSS or JavaScript for them, and nothing of yours runs in the dashboard (no iframe either).
|
|
4
|
+
|
|
5
|
+
Use pages for what customers check or change often: numbers, lists, settings. Keep your own website for big editors and anything that needs its own screen ("Open in", `references/accounts.md`).
|
|
6
|
+
|
|
7
|
+
## The listing
|
|
8
|
+
|
|
9
|
+
```json
|
|
10
|
+
"ui": {
|
|
11
|
+
"url": "https://api.you.example/usebecky/ui",
|
|
12
|
+
"pages": [{ "id": "reviews", "label": "Reviews", "section": "website" }],
|
|
13
|
+
"settings": true
|
|
14
|
+
}
|
|
15
|
+
```
|
|
16
|
+
|
|
17
|
+
| Field | Rules |
|
|
18
|
+
|---|---|
|
|
19
|
+
| `url` | https and a public host name, like `webhook_url` (`npm run dev` maps it to your local server). usebecky POSTs a signed request there for every page and every button. |
|
|
20
|
+
| `pages` | At most 3 sidebar rows. `id`: `[a-z][a-z0-9-]`, at most 32, unique, not `settings` (it is part of the address). `label`: at most 24 characters, the words on the row. `section`: the sidebar group, `backend`, `website` (Website & sales), `messages` or `project` (default). The row shows your logo. |
|
|
21
|
+
| `settings` | `true`: your page `settings` shows on your extension's page under Extensions (for settings customers change after installing). |
|
|
22
|
+
|
|
23
|
+
At least one page or `settings: true`. `ui` needs credentials (the requests are signed with the webhook secret). A new `ui` goes live with the next approved listing version; it needs no new consent.
|
|
24
|
+
|
|
25
|
+
## The handler
|
|
26
|
+
|
|
27
|
+
```ts
|
|
28
|
+
// src/ui.ts
|
|
29
|
+
import type { Extension, View } from '@usebecky/extension'
|
|
30
|
+
import type { Hono } from 'hono'
|
|
31
|
+
|
|
32
|
+
/** Your own storage, keyed by the install. */
|
|
33
|
+
export interface ReviewStore {
|
|
34
|
+
list(install: string, q: { q?: string; cursor?: string; limit: number }): Promise<{ items: Array<{ id: string; name: string; stars: number }>; total: number; next: string | null }>
|
|
35
|
+
hide(install: string, id: string): Promise<void>
|
|
36
|
+
greeting(install: string): Promise<string>
|
|
37
|
+
setGreeting(install: string, greeting: string): Promise<void>
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
export function mountUi(app: Hono, ext: Extension, store: ReviewStore) {
|
|
41
|
+
const ui = ext.uiHandler({
|
|
42
|
+
pages: {
|
|
43
|
+
reviews: async (ctx): Promise<View> => {
|
|
44
|
+
const page = await store.list(ctx.install, { q: ctx.params.q, cursor: ctx.params.cursor, limit: 25 })
|
|
45
|
+
return {
|
|
46
|
+
title: 'Reviews',
|
|
47
|
+
description: 'What your customers say.',
|
|
48
|
+
blocks: [
|
|
49
|
+
{ type: 'stats', items: [{ label: 'Reviews', value: page.total.toLocaleString('en'), change: 12.5 }] },
|
|
50
|
+
{
|
|
51
|
+
type: 'table',
|
|
52
|
+
columns: [{ key: 'name', label: 'Customer' }, { key: 'stars', label: 'Stars', align: 'right' }],
|
|
53
|
+
rows: page.items.map((r) => ({ id: r.id, cells: { name: r.name, stars: r.stars }, actions: [{ label: 'Hide', action: 'hide' }] })),
|
|
54
|
+
search: { placeholder: 'Search reviews' },
|
|
55
|
+
next_cursor: page.next ?? undefined,
|
|
56
|
+
total: page.total,
|
|
57
|
+
empty: 'No reviews yet. They show up here when customers write one.',
|
|
58
|
+
},
|
|
59
|
+
],
|
|
60
|
+
}
|
|
61
|
+
},
|
|
62
|
+
settings: async (ctx) => ({
|
|
63
|
+
blocks: [{ type: 'form', action: 'save', submit: 'Save', fields: [{ key: 'greeting', label: 'Heading', type: 'text', required: true }], values: { greeting: await store.greeting(ctx.install) } }],
|
|
64
|
+
}),
|
|
65
|
+
},
|
|
66
|
+
actions: {
|
|
67
|
+
hide: async (ctx) => {
|
|
68
|
+
await store.hide(ctx.install, ctx.action.row!)
|
|
69
|
+
return { toast: 'Hidden.' }
|
|
70
|
+
},
|
|
71
|
+
save: async (ctx) => {
|
|
72
|
+
const greeting = String(ctx.action.values.greeting ?? '').trim()
|
|
73
|
+
if (!greeting) return { errors: { greeting: 'Write a heading.' } }
|
|
74
|
+
await store.setGreeting(ctx.install, greeting)
|
|
75
|
+
return { toast: 'Saved.' }
|
|
76
|
+
},
|
|
77
|
+
},
|
|
78
|
+
})
|
|
79
|
+
// Hono. Express and node:http: app.post('/usebecky/ui', toNodeHandler(ui)), no body parser before it.
|
|
80
|
+
app.post('/usebecky/ui', (c) => ui(c.req.raw))
|
|
81
|
+
}
|
|
82
|
+
```
|
|
83
|
+
|
|
84
|
+
Express and node:http: `toNodeHandler(ui)` (no body parser before it: the signature is checked on the raw body). Next.js: `export const POST = (req: Request) => ui(req)` in `app/usebecky/ui/route.ts`.
|
|
85
|
+
|
|
86
|
+
The handler verifies the signature, picks the page or action handler and answers. Key everything by `ctx.install` (or `ctx.project.ref`): one install per project.
|
|
87
|
+
|
|
88
|
+
| `ctx` | |
|
|
89
|
+
|---|---|
|
|
90
|
+
| `project` | `{ ref, name }` |
|
|
91
|
+
| `install` | the install's id (the same as in webhooks and tokens) |
|
|
92
|
+
| `user` | `{ sub, role, locale }`: who is looking. `sub` is pairwise (the same as in the id_token and "Open in"), `role` is `owner`, `admin`, `developer` or `viewer`, `locale` like `de-DE`. No name, no email. |
|
|
93
|
+
| `page`, `params` | the page id and its state from the dashboard's address (`cursor`, `q`, `sort`, your tabs and filters), text only |
|
|
94
|
+
| `plan` | the install's price plan (`{ id, name, amount, status, trial_ends_at, current_period_end, cancel_at_period_end, next_plan, … }`), `null` for a free extension |
|
|
95
|
+
| `test` | a developer's test project |
|
|
96
|
+
| `api` | the partner API for this project (OAuth extensions; made only when you use it) |
|
|
97
|
+
| `action` | actions only: `{ id, row?, rows?, values }` |
|
|
98
|
+
|
|
99
|
+
## Blocks
|
|
100
|
+
|
|
101
|
+
A view is `{ title?, description?, actions?, blocks }`. `title` defaults to the page's label; `actions` are up to 3 buttons next to the title.
|
|
102
|
+
|
|
103
|
+
| Block | Use it for | Shape |
|
|
104
|
+
|---|---|---|
|
|
105
|
+
| `stats` | 1 to 8 numbers at the top | `items: [{ label, value: "1,204", change?: 12.5, good?: 'up' \| 'down', hint? }]`. `value` is text: format it yourself (currency, units). `change` is percent against the previous period; `good: 'down'` when less is better (errors, costs). |
|
|
106
|
+
| `chart` | a trend or a comparison | `kind: 'line' \| 'column'`, `labels: string[]`, `series: [{ name, values: (number \| null)[] }]` (one value per label, at most 6 series and 400 labels), `format?: 'number' \| 'percent' \| 'currency'` (+ `currency: 'EUR'`). usebecky adds the tooltip, the legend and a table view. |
|
|
107
|
+
| `bars` | a ranked list (top pages, products) | `items: [{ label, value, display? }]`, at most 50, `label_header?`, `value_header?` |
|
|
108
|
+
| `table` | records | `columns: [{ key, label, align?, sortable? }]`, `rows: [{ id, cells, actions? }]` (at most 100 a page), `search?`, `filters?: [{ param, label, options }]`, `sort?: { column, direction }`, `next_cursor?`, `prev_cursor?`, `total?`, `bulk?: [action buttons]` (checkboxes; you get `action.rows`), `empty?` |
|
|
109
|
+
| `form` | settings, a short input | `action`, `submit`, `fields: [{ key, label, type, help?, placeholder?, required?, options?, min?, max?, max_length? }]`, `values?`. Types: `text`, `textarea`, `number`, `email`, `url`, `password`, `select`, `checkbox`. |
|
|
110
|
+
| `list` | label/value pairs (ids, keys to copy) | `items: [{ label, value, copy? }]` |
|
|
111
|
+
| `notice` | one thing that needs attention | `tone: 'info' \| 'success' \| 'warning' \| 'danger'`, `title?`, `text`, `action?` |
|
|
112
|
+
| `empty` | nothing there yet, with the next step | `title`, `text?`, `action?` |
|
|
113
|
+
| `tabs` | 2 to 8 views of one page | `param`, `items: [{ id, label }]`, `active` |
|
|
114
|
+
| `section` | a group with a title (a panel) | `title?`, `description?`, `blocks` |
|
|
115
|
+
| `columns` | 2 or 3 things side by side (stacked on phones) | `columns: Block[][]` |
|
|
116
|
+
| `text`, `heading`, `code`, `buttons` | words, a heading, a snippet with a copy button, buttons | `text` understands `**bold**`, `` `code` `` and `[label](https://…)`, nothing else |
|
|
117
|
+
|
|
118
|
+
Cells: text, a number, `null` (shows "—"), `{ text, tone }` (a badge), `{ text, url }` (opens in a new tab) or `{ text, page, params? }` (one of your pages).
|
|
119
|
+
|
|
120
|
+
Buttons: `{ label, action }` (runs an action; `row` is filled in on a row; `confirm: "Delete it?"` asks first), `{ label, page, params? }` (opens one of your pages), `{ label, url }` (https, a new tab), `{ label, plan }` (opens usebecky's plan dialog with that plan of your listing selected; not as a bulk action). A view with `refresh_seconds: 5`–`60` is asked for again every that many seconds while it is open and the tab is visible (it waits while a form has unsaved input or a dialog is open, stops after 30 minutes, and stops when an answer leaves `refresh_seconds` out): use it while something is being set up, not as a clock. `variant: 'primary' | 'secondary' | 'danger'`; at most one primary per group.
|
|
121
|
+
|
|
122
|
+
Nesting: sections and columns two levels deep (a section with columns in it). A page holds at most 1500 parts (blocks, rows, items, buttons, fields together) and 512 KB.
|
|
123
|
+
|
|
124
|
+
## Actions
|
|
125
|
+
|
|
126
|
+
Return any of:
|
|
127
|
+
|
|
128
|
+
- nothing (or `{}`): usebecky asks for the page again;
|
|
129
|
+
- `{ toast: 'Saved.' }`: a short confirmation;
|
|
130
|
+
- `{ errors: { field_key: 'Plain words.' } }`: shown under the fields; nothing else changes;
|
|
131
|
+
- `{ view: {...} }`: show this instead of asking again;
|
|
132
|
+
- `{ go: { page, params? } }`: open another of your pages (or the same with other params).
|
|
133
|
+
|
|
134
|
+
Viewers can't run actions (usebecky disables the buttons and refuses the request); developers, admins and owners can. Check `ctx.user.role` yourself for anything stronger (`owner`/`admin` only for deleting, billing). Every action is in the project's audit log.
|
|
135
|
+
|
|
136
|
+
## Lists at scale
|
|
137
|
+
|
|
138
|
+
Never load everything. Tables page on your server: read `ctx.params.cursor`, `q`, `sort` (`name` or `-name`) and your filters, answer at most 100 rows with `next_cursor`/`prev_cursor`, and `total` when you know it. Search, filters, sort and tabs drop the cursor, so a new view starts on its first page. Index what you sort and filter by.
|
|
139
|
+
|
|
140
|
+
## Look and words (usebecky checks these in review)
|
|
141
|
+
|
|
142
|
+
usebecky draws every block in its design. What you control is what is on the page:
|
|
143
|
+
|
|
144
|
+
- **One page, one job.** The most important thing first (numbers, then the list). No walls of text: a description of one short line, explanations behind a link.
|
|
145
|
+
- **Words for beginners.** "Reviews waiting for an answer", not "pending moderation queue items". Button labels are verbs ("Hide", "Save"). Errors say what to do: "Write a heading."
|
|
146
|
+
- **One primary action** per page (`variant: 'primary'`), the rest secondary. `danger` and `confirm` for anything that deletes.
|
|
147
|
+
- **Empty states with the next step** (`empty` with an action), never a blank table.
|
|
148
|
+
- **Notices only when something needs attention**, one at a time.
|
|
149
|
+
- **Fast.** Answer in under 3 seconds; usebecky waits 8 (15 for actions) and then says the page couldn't be shown. Cache what is slow to compute.
|
|
150
|
+
- **No secrets in blocks.** Every team member who can open the project sees the page (viewers too). Show a key's last characters, never the whole key.
|
|
151
|
+
|
|
152
|
+
## Your own pages outside usebecky
|
|
153
|
+
|
|
154
|
+
Pages on your own website that customers reach from usebecky (the install page, the page "Open in" lands on, a settings page there) use usebecky's look too, so the switch doesn't feel like leaving: an aubergine bar (`#2C001E`) with **your own** logo and name (never usebecky's wordmark or logo), Figtree or the system font, square controls (4–6 px corners, no pills), the primary button in orange `#FF6A2C` with aubergine text (white on that orange is too faint), links and focus rings in burnt orange `#B8420F` (light) / `#FF6A2C` (dark), page `#F6F7FA`, cards white with `#E0E4EC` hairlines, text `#141B33`, a dark mode (`#0E121B` page, `#151B28` cards, `#ECEEF5` text), fine at 390 px. The starter's `src/pages.ts` does all of this; keep it.
|
|
155
|
+
|
|
156
|
+
## Testing
|
|
157
|
+
|
|
158
|
+
- `npm run dev`: the dev server shows your pages at `/project/<ref>/x/<page>` (and the settings view on the extension's page), sends the same signed requests and says exactly what usebecky would refuse.
|
|
159
|
+
- In usebecky: your test project shows your draft's pages before review; when a page fails there, the message says why.
|
|
160
|
+
- Unit tests: `checkView(view)` and `checkActionAnswer(result)` from `@usebecky/extension` give the same verdict as usebecky (`{ ok: false, problem: { path, message } }`).
|
|
161
|
+
|
|
162
|
+
## When usebecky says "couldn't show this page"
|
|
163
|
+
|
|
164
|
+
| Reason (test project, dev server) | Fix |
|
|
165
|
+
|---|---|
|
|
166
|
+
| `… must be text (got a number)` | Format numbers yourself in `stats` values: `value: count.toLocaleString('en')`. |
|
|
167
|
+
| `… opens the page "x", which isn't in the listing's ui.pages` | Add the page to the listing, or link to one that is there. |
|
|
168
|
+
| `… has 3 values for 4 labels` | One chart value per label; `null` for a gap. |
|
|
169
|
+
| `its server answered HTTP 404` | The route isn't `POST` at your `ui.url`, or `pages` has no handler for that id (the kit logs which). |
|
|
170
|
+
| `its server answered HTTP 400` (`invalid_signature`) | A body parser ran before the handler, or the webhook secret is wrong/rotated. |
|
|
171
|
+
| `didn't answer within 8 seconds` | Page the list (fewer rows), cache, answer first and compute later. |
|
|
172
|
+
| `answered with a redirect` | Use the final address as `ui.url`; usebecky never follows redirects. |
|