@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
package/README.md CHANGED
@@ -1,3 +1,224 @@
1
- # Temporary Holding Version
1
+ # @usebecky/extension
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Build extensions for the [usebecky](https://usebecky.com) store. The kit does usebecky's side of every flow, so your code only says what your extension does:
4
+
5
+ - **OAuth with PKCE** (S256): the install route, the callback, tokens stored per project.
6
+ - **Tokens that look after themselves**: refreshed before they expire, rotated safely, one refresh per install at a time.
7
+ - **A typed partner API client**: the install and its settings, the project, visitor and revenue totals.
8
+ - **Verified webhooks** with typed events: timing-safe, 5 minutes of replay protection, secret rotation.
9
+ - **Accounts without a sign-up form**: the OpenID Connect id_token verified in the callback (`identity`), `provisionHandler()` for provision requests, and `ssoHandler()` / `verifyLaunchToken()` for "Open in" (single use, usebecky's keys fetched and rotated for you). Customers never sign up at your service by hand.
10
+ - **Pages inside usebecky**, like a WordPress plugin's menu pages: `uiHandler()` answers usebecky's signed requests with blocks (stat tiles, charts, tables with paging, forms…), and usebecky draws them in its own design, in the customer's sidebar and on your extension's page. No HTML, no iframe.
11
+ - **Ready-made handlers** for Hono, Next.js route handlers, Express and plain `node:http`.
12
+ - **`validate`**: checks `usebecky-extension.json` with usebecky's own rules and messages.
13
+ - **A dev server** that answers like usebecky (the store's Install, the consent screen, tokens, the partner API with fake data, webhooks, the settings form of setup fields, your pages inside usebecky), with the same checks and error messages, so you can build without an account.
14
+
15
+ TypeScript, ESM, no dependencies. Node.js 20+, Bun, Deno and edge runtimes (the core uses Web Crypto and fetch).
16
+
17
+ ## Start
18
+
19
+ The quickest way is the starter: a small Hono server with everything wired up, tests and an AI skill for Claude Code.
20
+
21
+ ```bash
22
+ npx create-usebecky@latest my-extension --template extension
23
+ cd my-extension
24
+ npm run dev
25
+ ```
26
+
27
+ Open http://localhost:4400 (the pretend usebecky) and click **Install**. The guide "Build an extension" walks through the rest: https://usebecky.com/docs/guides/build-an-extension
28
+
29
+ In an app you already have:
30
+
31
+ ```bash
32
+ npm install @usebecky/extension
33
+ ```
34
+
35
+ ## Use
36
+
37
+ ```ts
38
+ // src/extension.ts
39
+ import { createExtension } from '@usebecky/extension'
40
+ import { fileTokenStore } from '@usebecky/extension/node'
41
+
42
+ export const ext = createExtension({
43
+ clientId: process.env.USEBECKY_CLIENT_ID!,
44
+ clientSecret: process.env.USEBECKY_CLIENT_SECRET!,
45
+ webhookSecret: process.env.USEBECKY_WEBHOOK_SECRET,
46
+ redirectUri: `${process.env.PUBLIC_URL}/oauth/callback`,
47
+ apiUrl: process.env.USEBECKY_API_URL, // unset: https://api.usebecky.com
48
+ dashboardUrl: process.env.USEBECKY_DASHBOARD_URL, // unset: https://app.usebecky.com (the consent screen)
49
+ tokenStore: fileTokenStore('.data/tokens.json'),
50
+ })
51
+ ```
52
+
53
+ `clientId` (`ub_ci_...`), `clientSecret` (`ub_cs_...`) and `webhookSecret` (`whsec_...`) come from the Developer area: your extension → **Credentials and testing** → **Create credentials**. `npm run dev` (the dev server) sets all five variables to test values; the API and the consent screen are then both on http://localhost:4400.
54
+
55
+ Routes (Hono shown; any framework with fetch Requests works the same, `toNodeHandler()` adapts them for Express and `node:http`):
56
+
57
+ ```ts
58
+ // src/server.ts
59
+ import { serve } from '@hono/node-server'
60
+ import { Hono } from 'hono'
61
+ import { ext } from './extension.ts'
62
+
63
+ const app = new Hono()
64
+ const { install, callback } = ext.oauthHandlers({ successUrl: '/settings' })
65
+ const webhook = ext.webhookHandler({
66
+ 'extension.installed': (event) => console.log('installed on', event.data.project.name, event.data.settings),
67
+ 'extension.uninstalled': (event) => console.log('delete what you stored for', event.project, event.data.reason),
68
+ })
69
+
70
+ app.get('/install', (c) => install(c.req.raw))
71
+ app.get('/oauth/callback', (c) => callback(c.req.raw))
72
+ app.post('/webhooks/usebecky', (c) => webhook(c.req.raw))
73
+
74
+ serve({ fetch: app.fetch, port: 3000 })
75
+ ```
76
+
77
+ Then, for any installed project:
78
+
79
+ ```ts
80
+ // inside an async function:
81
+ import { ext } from './extension.ts'
82
+
83
+ const info = await ext.api('k3x9m2p7q1zt').project()
84
+ const visits = await ext.api('k3x9m2p7q1zt').analyticsSummary({ from: '2026-11-01', to: '2026-11-30' })
85
+ console.log(info.name, info.allowed_hosts, visits.visitors, visits.revenue.total)
86
+ ```
87
+
88
+ ## Accounts and "Open in"
89
+
90
+ If your service needs an account per customer, never build a sign-up form: set `"account"` in `usebecky-extension.json` and let the kit do usebecky's side.
91
+
92
+ ```ts
93
+ // src/accounts.ts
94
+ import { ext } from './extension.ts'
95
+
96
+ // OAuth extensions ("provision": "oauth"): in your callback, `identity` is the verified id_token.
97
+ // const { identity } = await ext.handleCallback(request) → create the account for identity.sub
98
+
99
+ // Setup-field extensions ("provision": "url"): usebecky POSTs a signed request when the customer installs.
100
+ export const provision = ext.provisionHandler(async (request) => ({ account_id: `acct_${request.install.slice(0, 8)}` }))
101
+
102
+ // "Open in <your service>" (sso_url): a 60-second, single-use launch token.
103
+ export const sso = ext.ssoHandler({ createSession: (claims) => `/welcome?user=${encodeURIComponent(claims.sub)}` })
104
+ ```
105
+
106
+ (A real `createSession` sets your signed session cookie in a Response.) Guide: https://usebecky.com/docs/extensions/accounts
107
+
108
+ ## Pages inside usebecky
109
+
110
+ Add `"ui"` to `usebecky-extension.json` and answer with blocks; usebecky draws them with its own components, so they look like the rest of usebecky in light, dark and on phones:
111
+
112
+ ```json
113
+ "ui": { "url": "https://api.you.example/usebecky/ui", "pages": [{ "id": "reviews", "label": "Reviews", "section": "website" }], "settings": true }
114
+ ```
115
+
116
+ ```ts
117
+ // src/ui.ts
118
+ import type { Extension } from '@usebecky/extension'
119
+ import type { Hono } from 'hono'
120
+
121
+ export function mountUi(app: Hono, ext: Extension) {
122
+ const ui = ext.uiHandler({
123
+ pages: {
124
+ reviews: async () => ({ title: 'Reviews', blocks: [{ type: 'stats', items: [{ label: 'Reviews', value: '1,204', change: 12.5 }] }] }),
125
+ settings: async () => ({ blocks: [{ type: 'form', action: 'save', submit: 'Save', fields: [{ key: 'greeting', label: 'Heading', type: 'text' }] }] }),
126
+ },
127
+ actions: { save: async (ctx) => ({ toast: ctx.action.values.greeting ? 'Saved.' : 'Heading removed.' }) },
128
+ })
129
+ app.post('/usebecky/ui', (c) => ui(c.req.raw))
130
+ }
131
+ ```
132
+
133
+ `ctx` has the project, the install, who is looking (pairwise `sub`, role, language), the page's params (cursor, search, sort, tabs) and `api` for the partner API. `checkView()` and `checkActionAnswer()` give usebecky's verdict in your tests. Guide: https://usebecky.com/docs/extensions/ui
134
+
135
+ ## More than one server instance
136
+
137
+ The defaults keep things in memory or in a file: right for one server process. As soon as more than one instance runs (several servers, containers or serverless functions), keep the tokens in your database, and the used launch tokens of "Open in" next to them. The replay guard must be shared: in memory, each instance only knows its own, so a stolen link would work once on every instance.
138
+
139
+ ```ts
140
+ // src/extension.ts
141
+ import { createExtension, replayTableSql, sqlReplayGuard, sqlTokenStore, tokenTableSql } from '@usebecky/extension'
142
+ import pg from 'pg'
143
+
144
+ const pool = new pg.Pool({ connectionString: process.env.DATABASE_URL })
145
+ const query = async (sql: string, params: unknown[]) => (await pool.query(sql, params)).rows
146
+
147
+ /** Run once, at start-up or in a migration: the tokens' table and the used launch tokens' table. */
148
+ export async function createTables() {
149
+ await pool.query(tokenTableSql())
150
+ await pool.query(replayTableSql())
151
+ }
152
+
153
+ export const ext = createExtension({
154
+ clientId: process.env.USEBECKY_CLIENT_ID!,
155
+ clientSecret: process.env.USEBECKY_CLIENT_SECRET!,
156
+ webhookSecret: process.env.USEBECKY_WEBHOOK_SECRET,
157
+ redirectUri: `${process.env.PUBLIC_URL}/oauth/callback`,
158
+ tokenStore: sqlTokenStore({ query }),
159
+ replayGuard: sqlReplayGuard({ query }),
160
+ })
161
+ ```
162
+
163
+ SQLite works the same with `dialect: 'sqlite'` on both. Share the pending sign-ins too (a `stateStore` on your database or Redis), and give the token store a `lock` so two instances never refresh the same install at once.
164
+
165
+ ## Test projects
166
+
167
+ Developers try extensions in a free **test project**. Its installs say so: `(await ext.api(project).installation()).test` is `true`, and every webhook event from it carries `"test": true` (so does **Send test event** in the Developer area, with the project `sampleproject`). Handle them like real ones, but never bill or count them. `installation().events` lists the event types the install receives: the ones the customer allowed.
168
+
169
+ ## Setup fields
170
+
171
+ An extension that needs no sign-in on your website connects with setup fields (`"connect": { "mode": "fields", "fields": [...] }`): the customer fills them in when they install, and you get them in `extension.installed` (`event.data.settings`) and from `ext.api(project).installation()`. Field types: `text`, `url` (https), `secret` (stored encrypted, never sent to you) and `boolean` (a yes/no checkbox: its value is `true` or `false`, never a string; a missing key means `false`; `required: true` means it must be turned on, like "I accept the terms"; no `pattern` or `placeholder`).
172
+
173
+ ## API
174
+
175
+ | Export | What it does |
176
+ |---|---|
177
+ | `createExtension(options)` | the kit for one extension: everything below hangs off it |
178
+ | `ext.authorizeUrl({ project?, state?, scopes?, returnUrl? })` | the consent screen URL (PKCE S256; the verifier goes to the state store) |
179
+ | `ext.handleCallback(request)` | finishes the install: checks the state, swaps the code, verifies the id_token, stores the tokens; returns `{ installation, project, scopes, state, returnUrl?, identity? }` (`returnUrl`: the extension's page in the customer's project, from install_url's `return_url`; `identity`: the id_token's claims for `"provision": "oauth"` listings) |
180
+ | `ext.provisionHandler(fn, { idempotency? })` | a fetch handler for your `provision_url`: verifies the signature, answers a repeated install id from the store, calls `fn(request)` → `{ account_id, settings? }` |
181
+ | `ext.ssoHandler({ createSession })` / `ext.verifyLaunchToken(token)` | "Open in": verifies the launch token (signature, audience, 60 seconds, single use through the `replayGuard`) |
182
+ | `ext.verifyIdToken(token, { nonce? })` | verifies an id_token for this extension |
183
+ | `ext.api(project)` | `installation()` (with `events` and `test`), `project()`, `analyticsSummary(range)`, `updateSettings(settings)` / `clearSettings()` (server-side tagging, capability `sgtm_forwarding`), `request(method, path)`, refreshing tokens as needed |
184
+ | `ext.accessToken(project)` / `ext.refresh(project)` | a valid token / refresh now (shared when concurrent) |
185
+ | `ext.revoke(project)` / `ext.forget(project)` | disconnect at usebecky and delete / only delete locally |
186
+ | `ext.verifyWebhook(rawBody, headers)` | the verified, typed event, or a `WebhookVerificationError` |
187
+ | `ext.oauthHandlers(options)` | `{ install, callback }` fetch handlers; `install` ties the sign-in to the browser with a short cookie |
188
+ | `ext.webhookHandler(handlers, options)` | a fetch handler that verifies and dispatches by event type |
189
+ | `ext.uiHandler({ pages, actions })` | a fetch handler for your `ui.url`: verifies usebecky's request, calls the page or action handler with `ctx` (and `ctx.api`), answers its blocks; logs what usebecky would refuse |
190
+ | `uiHandler()`, `verifyUiRequest()`, `checkView()`, `checkRenderAnswer()`, `checkActionAnswer()`, `UI_LIMITS` | standalone page helpers and usebecky's checks |
191
+ | `toNodeHandler(handler)` | any fetch handler as a `node:http` / Express handler |
192
+ | `memoryTokenStore()`, `sqlTokenStore()`, `fileTokenStore()` (`/node`) | token stores; or implement `TokenStore` (with an optional `lock`) |
193
+ | `sqlReplayGuard({ query, dialect? })`, `replayTableSql()` | used launch tokens in your database (Postgres or SQLite), shared by every instance: required with more than one |
194
+ | `memoryStateStore()` | where pending sign-ins wait (implement `StateStore` for several instances) |
195
+ | `verifyWebhook()`, `signWebhook()` | standalone verification / signing (tests) |
196
+ | `verifyIdToken()`, `verifyLaunchToken()`, `memoryReplayGuard()`, `createJwks()` | standalone token verification, the in-memory replay guard (one process only), usebecky's cached JWKS |
197
+ | `provisionHandler()`, `ssoHandler()`, `verifyProvisionRequest()`, `memoryIdempotencyStore()` | standalone account helpers |
198
+ | `createPkcePair()`, `codeChallengeFor()` | PKCE helpers |
199
+ | `validateManifest(manifest, { allowPrivateWebhookUrl? })` | checks a parsed `usebecky-extension.json` like usebecky does |
200
+ | `TOKEN_PREFIXES`, `LISTING_LIMITS`, `EXTENSION_SCOPE_INFO`, `SUBSCRIBABLE_EVENT_TYPES` | usebecky's prefixes, listing limits, consent-screen words and event types |
201
+ | `startDevServer()` (`/dev`) | the dev server, for your tests |
202
+
203
+ Errors are classes with a stable `code`, a `message`, a `hint` and usebecky's `details` (like `required_scope`): `OAuthCallbackError`, `TokenError`, `InstallationRevokedError`, `PartnerApiError`, `WebhookVerificationError`, `TokenVerificationError`, `ProvisionRequestError`, `ConfigError` (all extend `ExtensionError`). `PartnerApiErrorCode` lists the partner API's codes. When usebecky suspends your extension, every token is revoked for good: `ext.api()` throws `InstallationRevokedError` with the code `extension_suspended` (its hint: check your email from usebecky), and the kit deletes the stored tokens. Once the suspension ends, customers connect the extension again.
204
+
205
+ ## CLI
206
+
207
+ ```bash
208
+ npx @usebecky/extension validate # check usebecky-extension.json like usebecky does (--local: allow an http webhook_url)
209
+ npx @usebecky/extension dev # the pretend usebecky on http://localhost:4400
210
+ npx @usebecky/extension dev -- node --watch src/server.ts # and start your extension with test credentials
211
+ npx @usebecky/extension dev --test-project # the fake projects act as test projects ("test": true)
212
+ npx @usebecky/extension dev --capability sgtm_forwarding # as if usebecky gave you server-side tagging (PUT /installation/settings)
213
+ npx @usebecky/extension send user.created # a signed event to your webhook (through the dev server, else like "Send test event")
214
+ npx @usebecky/extension ai # the Claude Code skill (.claude/skills/usebecky-extension)
215
+ npx @usebecky/extension init # how to start from the starter
216
+ ```
217
+
218
+ The dev server is only for your computer: it listens on 127.0.0.1, answers only requests addressed to `localhost`, `127.0.0.1` or `[::1]` (so a web page can't point its own domain at it), and refuses actions (a POST, or "Open in") that a browser says come from another website. Its own pages, your extension, `curl` and your tests work as before.
219
+
220
+ ## The API reference
221
+
222
+ The partner API, OAuth and webhook protocol are documented in usebecky's HTTP API reference: https://usebecky.com/docs/reference/http-api
223
+
224
+ MIT licensed. usebecky is a service of Algorithmo GmbH.
@@ -0,0 +1,85 @@
1
+ import { ExtensionError } from './errors.ts';
2
+ import { type FetchHandler } from './handlers.ts';
3
+ import { type LaunchClaims, type LaunchVerifyOptions } from './identity.ts';
4
+ import type { Awaitable } from './stores.ts';
5
+ import type { ExtensionSettings } from './types.ts';
6
+ import { type HeaderSource, type VerifyOptions } from './webhooks.ts';
7
+ /** The `type` of a provision request (also in the usebecky-event-type header). */
8
+ export declare const PROVISION_EVENT_TYPE = "extension.provision";
9
+ /** Provision requests are a few hundred bytes; anything above this is refused before verifying. */
10
+ export declare const MAX_PROVISION_BYTES: number;
11
+ /** What usebecky POSTs to your provision_url. */
12
+ export interface ProvisionRequest {
13
+ /** `prv_<install id>`: the same for every retry. */
14
+ id: string;
15
+ type: typeof PROVISION_EVENT_TYPE;
16
+ created_at: string;
17
+ /** Your extension's slug. */
18
+ extension: string;
19
+ /** The install's id (uuid): the idempotency key (also in the Idempotency-Key header), and `installation_id` later on. */
20
+ install: string;
21
+ project: {
22
+ ref: string;
23
+ name: string;
24
+ };
25
+ /** Who is installing. Link by `sub` (pairwise, stable); trust `email` for linking only when `email_verified` is true. */
26
+ user: {
27
+ sub: string;
28
+ email: string;
29
+ email_verified: boolean;
30
+ name: string | null;
31
+ };
32
+ /** `true` when sent from a test project (also by the dev server with --test-project). Missing for real projects. */
33
+ test?: boolean;
34
+ }
35
+ /** Your answer: the account's id at your service, and settings for your listing's setup fields (the customer confirms them). */
36
+ export interface ProvisionResult {
37
+ /** 1 to 200 characters. usebecky shows it to the customer and puts it in launch tokens (`partner_account_id`). */
38
+ account_id: string;
39
+ /** By setup field key: text for text/url/secret fields, true/false for boolean ones. Unknown keys are refused. */
40
+ settings?: ExtensionSettings;
41
+ }
42
+ /** Answers already given, by install id, so a retry gets the same account. Use your database with several instances. */
43
+ export interface IdempotencyStore {
44
+ get(installId: string): Awaitable<ProvisionResult | null | undefined>;
45
+ set(installId: string, result: ProvisionResult): Awaitable<void>;
46
+ }
47
+ /** In memory: one process, lost on restart. Your own accounts table (keyed by install id or sub) is the real store. */
48
+ export declare function memoryIdempotencyStore(options?: {
49
+ max?: number;
50
+ }): IdempotencyStore;
51
+ /**
52
+ * Check that a provision request really came from usebecky (usebecky-signature, recent) and return it. Pass the raw
53
+ * body exactly as received. Throws ProvisionRequestError (or ConfigError without a secret).
54
+ */
55
+ export declare function verifyProvisionRequest(rawBody: string | Uint8Array | ArrayBuffer, headers: HeaderSource, secret: string | readonly string[] | undefined, options?: VerifyOptions): Promise<ProvisionRequest>;
56
+ export interface ProvisionHandlerOptions {
57
+ /** `whsec_...` (pass [new, old] while you rotate it). */
58
+ webhookSecret: string | readonly string[] | undefined;
59
+ /** Create (or find) the account and return its id. Throw an ExtensionError with a 4xx status to refuse (usebecky shows the message and doesn't retry); anything else is a 500 and usebecky retries. */
60
+ provision: (request: ProvisionRequest, raw: Request) => Awaitable<ProvisionResult>;
61
+ /** Default: in memory. */
62
+ idempotency?: IdempotencyStore;
63
+ /** Signature tolerance (default 300 seconds). */
64
+ verify?: VerifyOptions;
65
+ /** Unix seconds "now", asked on every request (tests). */
66
+ clock?: () => number;
67
+ }
68
+ /**
69
+ * A fetch-style POST handler for your provision_url: verifies the signature, answers a repeated install id from the
70
+ * idempotency store (never creating a second account), calls `provision` once per install otherwise.
71
+ */
72
+ export declare function provisionHandler(options: ProvisionHandlerOptions): FetchHandler;
73
+ export interface SsoHandlerOptions extends LaunchVerifyOptions {
74
+ /**
75
+ * Sign the person in: find the account by `claims.sub` (or `claims.partner_account_id`), start your session, and
76
+ * return a Response (with your session cookie) or a path to redirect to (303).
77
+ */
78
+ createSession: (claims: LaunchClaims, request: Request) => Awaitable<Response | string>;
79
+ /** When the link is invalid, expired or used. Default: a plain page asking to open the service from usebecky again. */
80
+ onError?: (error: ExtensionError, request: Request) => Awaitable<Response | void>;
81
+ /** Your service's name for the default error page. */
82
+ serviceName?: string;
83
+ }
84
+ /** A fetch-style GET handler for your sso_url: verifies `?launch=` and calls createSession. */
85
+ export declare function ssoHandler(options: SsoHandlerOptions): FetchHandler;
@@ -0,0 +1,149 @@
1
+ // Accounts at your service, without a sign-up form: usebecky creates them (provisioning) and opens them (single sign-on).
2
+ //
3
+ // provisionHandler() POST <provision_url>: usebecky asks you to create the customer's account when they install a
4
+ // fields-mode extension (account.provision "url"). Signed like webhooks (usebecky-signature with
5
+ // your webhook secret); the install id is the idempotency key, so a retry never makes a second
6
+ // account. Answer { account_id, settings? }: the settings fill the install's setup fields.
7
+ // ssoHandler() GET <sso_url>?launch=<token>: "Open in <your service>" from usebecky. The kit verifies the
8
+ // launch token (signature, audience, 60 seconds, single use) and you start the session.
9
+ import { ExtensionError, ProvisionRequestError } from "./errors.js";
10
+ import { errorPage, jsonResponse } from "./handlers.js";
11
+ import { LAUNCH_PARAM, verifyLaunchToken } from "./identity.js";
12
+ import { verifyWebhook } from "./webhooks.js";
13
+ /** The `type` of a provision request (also in the usebecky-event-type header). */
14
+ export const PROVISION_EVENT_TYPE = 'extension.provision';
15
+ /** Provision requests are a few hundred bytes; anything above this is refused before verifying. */
16
+ export const MAX_PROVISION_BYTES = 64 * 1024;
17
+ /** In memory: one process, lost on restart. Your own accounts table (keyed by install id or sub) is the real store. */
18
+ export function memoryIdempotencyStore(options = {}) {
19
+ const max = options.max ?? 10_000;
20
+ const map = new Map();
21
+ return {
22
+ get: (id) => (map.has(id) ? structuredClone(map.get(id)) : null),
23
+ set: (id, result) => {
24
+ while (map.size >= max)
25
+ map.delete(map.keys().next().value);
26
+ map.set(id, structuredClone(result));
27
+ },
28
+ };
29
+ }
30
+ const bad = (code, message, hint) => new ProvisionRequestError({ code, message, hint, status: 400 });
31
+ function header(headers, name) {
32
+ if (headers == null || typeof headers === 'string')
33
+ return undefined;
34
+ if (typeof headers.get === 'function')
35
+ return headers.get(name) ?? undefined;
36
+ const rec = headers;
37
+ const key = Object.keys(rec).find((k) => k.toLowerCase() === name);
38
+ const v = key ? rec[key] : undefined;
39
+ return Array.isArray(v) ? v[0] : v;
40
+ }
41
+ /**
42
+ * Check that a provision request really came from usebecky (usebecky-signature, recent) and return it. Pass the raw
43
+ * body exactly as received. Throws ProvisionRequestError (or ConfigError without a secret).
44
+ */
45
+ export async function verifyProvisionRequest(rawBody, headers, secret, options = {}) {
46
+ let event;
47
+ try {
48
+ event = (await verifyWebhook(rawBody, headers, secret, options));
49
+ }
50
+ catch (err) {
51
+ if (err instanceof ExtensionError && err.status === 400)
52
+ throw new ProvisionRequestError({ code: err.code, message: err.message.replace(/webhook/g, 'provision request'), hint: err.hint, status: 400 });
53
+ throw err;
54
+ }
55
+ const user = event.user;
56
+ const project = event.project;
57
+ if (event.type !== PROVISION_EVENT_TYPE)
58
+ throw bad('invalid_payload', `This is a "${String(event.type).slice(0, 40)}" event, not a provision request.`, 'Point account.provision_url at its own route (not your webhook_url).');
59
+ if (typeof event.install !== 'string' || !user || typeof user.sub !== 'string' || typeof user.email !== 'string' || !project || typeof project.ref !== 'string') {
60
+ throw bad('invalid_payload', 'The provision request has no install, project or user.');
61
+ }
62
+ const key = header(headers, 'idempotency-key');
63
+ if (key !== undefined && key !== event.install)
64
+ throw bad('idempotency_mismatch', 'The Idempotency-Key header does not match the install id.');
65
+ return event;
66
+ }
67
+ /**
68
+ * A fetch-style POST handler for your provision_url: verifies the signature, answers a repeated install id from the
69
+ * idempotency store (never creating a second account), calls `provision` once per install otherwise.
70
+ */
71
+ export function provisionHandler(options) {
72
+ const store = options.idempotency ?? memoryIdempotencyStore();
73
+ const inflight = new Map();
74
+ return async (request) => {
75
+ if (request.method !== 'POST')
76
+ return jsonResponse(405, { error: { code: 'method_not_allowed', message: 'usebecky sends provision requests with POST.' } }, { allow: 'POST' });
77
+ if (Number(request.headers.get('content-length') ?? 0) > MAX_PROVISION_BYTES)
78
+ return jsonResponse(413, { error: { code: 'payload_too_large', message: 'Provision requests are far smaller than this.' } });
79
+ let req;
80
+ try {
81
+ const raw = new Uint8Array(await request.arrayBuffer());
82
+ if (raw.length > MAX_PROVISION_BYTES)
83
+ return jsonResponse(413, { error: { code: 'payload_too_large', message: 'Provision requests are far smaller than this.' } });
84
+ req = await verifyProvisionRequest(raw, request.headers, options.webhookSecret, { ...options.verify, ...(options.clock ? { now: options.clock() } : {}) });
85
+ }
86
+ catch (err) {
87
+ if (err instanceof ExtensionError) {
88
+ if (err.status >= 500)
89
+ console.error(`[usebecky-extension] ${err.message} ${err.hint ?? ''}`);
90
+ return jsonResponse(err.status >= 400 ? err.status : 400, { error: err.toJSON() });
91
+ }
92
+ throw err;
93
+ }
94
+ try {
95
+ const done = await store.get(req.install);
96
+ if (done)
97
+ return jsonResponse(200, done);
98
+ // Two deliveries of the same install at once (a retry racing the first): one call to your code.
99
+ let p = inflight.get(req.install);
100
+ if (!p) {
101
+ p = (async () => {
102
+ const result = await options.provision(req, request);
103
+ if (!result || typeof result.account_id !== 'string' || !result.account_id.trim() || result.account_id.length > 200) {
104
+ throw new ExtensionError({ code: 'invalid_result', message: 'provision() must return { account_id: string (1 to 200 characters), settings? }.', status: 500 });
105
+ }
106
+ const out = result.settings ? { account_id: result.account_id, settings: result.settings } : { account_id: result.account_id };
107
+ await store.set(req.install, out);
108
+ return out;
109
+ })().finally(() => inflight.delete(req.install));
110
+ inflight.set(req.install, p);
111
+ }
112
+ return jsonResponse(200, await p);
113
+ }
114
+ catch (err) {
115
+ if (err instanceof ExtensionError && err.status >= 400 && err.status < 500)
116
+ return jsonResponse(err.status, { error: err.toJSON() });
117
+ console.error(`[usebecky-extension] provision() failed for install ${req.install}: ${err?.message ?? err}`);
118
+ return jsonResponse(500, { error: { code: 'provision_failed', message: 'The account could not be created. usebecky will try again.' } });
119
+ }
120
+ };
121
+ }
122
+ /** A fetch-style GET handler for your sso_url: verifies `?launch=` and calls createSession. */
123
+ export function ssoHandler(options) {
124
+ return async (request) => {
125
+ if (request.method !== 'GET' && request.method !== 'HEAD')
126
+ return jsonResponse(405, { error: { code: 'method_not_allowed', message: 'Open this address with GET.' } }, { allow: 'GET' });
127
+ let claims;
128
+ try {
129
+ const token = new URL(request.url).searchParams.get(LAUNCH_PARAM);
130
+ if (!token)
131
+ throw new ExtensionError({ code: 'invalid_token', message: 'This address needs the launch token usebecky adds.', status: 400 });
132
+ claims = await verifyLaunchToken(token, options);
133
+ }
134
+ catch (err) {
135
+ const e = err instanceof ExtensionError ? err : new ExtensionError({ code: 'internal_error', message: 'Something went wrong while signing you in.', status: 500 });
136
+ if (!(err instanceof ExtensionError))
137
+ console.error(`[usebecky-extension] SSO failed: ${err?.message ?? err}`);
138
+ const custom = options.onError ? await options.onError(e, request) : undefined;
139
+ if (custom)
140
+ return custom;
141
+ const name = options.serviceName ?? 'this service';
142
+ return errorPage(e.status >= 500 ? 502 : 401, 'Open it from usebecky again', `${e.message} Go back to usebecky and choose "Open in ${name}" again.`);
143
+ }
144
+ const out = await options.createSession(claims, request);
145
+ if (typeof out === 'string')
146
+ return new Response(null, { status: 303, headers: { location: out, 'cache-control': 'no-store', 'referrer-policy': 'no-referrer' } });
147
+ return out;
148
+ };
149
+ }
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ export {};
@@ -0,0 +1,9 @@
1
+ #!/usr/bin/env node
2
+ // Entry point for `npx @usebecky/extension` (bin: usebecky-extension).
3
+ import { run } from "./run.js";
4
+ run(process.argv.slice(2)).then((code) => {
5
+ process.exitCode = code;
6
+ }, (err) => {
7
+ console.error(`\n✖ Something went wrong: ${err?.message ?? err}`);
8
+ process.exitCode = 1;
9
+ });
@@ -0,0 +1,25 @@
1
+ import { type DevServer } from '../dev/server.ts';
2
+ export declare const VERSION = "0.2.0";
3
+ export declare const STARTER_COMMAND = "npx create-usebecky@latest my-extension --template extension";
4
+ export interface CliContext {
5
+ cwd?: string;
6
+ env?: Record<string, string | undefined>;
7
+ out?: {
8
+ write(s: string): unknown;
9
+ };
10
+ err?: {
11
+ write(s: string): unknown;
12
+ };
13
+ fetch?: typeof fetch;
14
+ /** Where the bundled skill is (tests). */
15
+ skillDir?: string;
16
+ /** `dev`: called with the running server instead of waiting for Ctrl+C (tests). */
17
+ onDevStarted?: (server: DevServer) => Promise<void> | void;
18
+ }
19
+ export declare function parseArgs(argv: string[]): {
20
+ command: string | undefined;
21
+ positionals: string[];
22
+ flags: Record<string, string | true>;
23
+ rest: string[];
24
+ };
25
+ export declare function run(argv: string[], ctx?: CliContext): Promise<number>;