@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/dist/errors.js ADDED
@@ -0,0 +1,110 @@
1
+ // Every error the kit throws is an ExtensionError with a stable snake_case `code`, a plain-English
2
+ // `message`, an optional `hint` (what to do next) and an HTTP `status` (0: usebecky was never reached).
3
+ // Subclasses say where it came from, so `instanceof` is enough to decide what to do.
4
+ export class ExtensionError extends Error {
5
+ code;
6
+ status;
7
+ hint;
8
+ details;
9
+ constructor(init) {
10
+ super(init.message);
11
+ this.name = new.target.name;
12
+ this.code = init.code;
13
+ this.status = init.status ?? 0;
14
+ if (init.hint)
15
+ this.hint = init.hint;
16
+ if (init.details)
17
+ this.details = init.details;
18
+ }
19
+ toJSON() {
20
+ const out = { code: this.code, message: this.message, status: this.status };
21
+ if (this.hint)
22
+ out.hint = this.hint;
23
+ if (this.details)
24
+ out.details = this.details;
25
+ return out;
26
+ }
27
+ }
28
+ /**
29
+ * The OAuth callback could not finish: the customer pressed Cancel (`access_denied`), the link was old
30
+ * or opened twice (`invalid_state`), or a parameter was missing (`invalid_request`). Show a friendly page
31
+ * with a link back to the install route.
32
+ */
33
+ export class OAuthCallbackError extends ExtensionError {
34
+ }
35
+ /**
36
+ * usebecky's token endpoint refused a code or refresh token (`invalid_grant`, `invalid_client`, ...).
37
+ * `invalid_client` means the client id or secret is wrong: check your environment variables.
38
+ * `extension_suspended` (during an install) means usebecky suspended your extension. A refused refresh never
39
+ * arrives as a TokenError: the kit turns `invalid_grant` and `extension_suspended` into InstallationRevokedError.
40
+ */
41
+ export class TokenError extends ExtensionError {
42
+ }
43
+ /**
44
+ * The install is gone, and the kit already deleted its stored tokens. Stop working for this project until the customer
45
+ * connects it again. `code`:
46
+ * - `installation_revoked`: the customer removed the extension, or its tokens were revoked.
47
+ * - `not_connected`: no tokens are stored for this project.
48
+ * - `extension_suspended`: usebecky's team suspended your extension, which revokes every token for good. Check your
49
+ * email from usebecky; once the suspension ends, each customer connects the extension again.
50
+ */
51
+ export class InstallationRevokedError extends ExtensionError {
52
+ }
53
+ /** What to do next, for usebecky's codes whose answer may come without a hint of its own. */
54
+ export const PARTNER_ERROR_HINTS = {
55
+ insufficient_scope: 'Add the scope to "scopes" in usebecky-extension.json and submit it for review; customers then reconnect to allow it.',
56
+ rate_limited: 'Slow down and retry after the number of seconds in the Retry-After header.',
57
+ extension_suspended: 'usebecky suspended this extension; check your email from usebecky.',
58
+ capability_required: 'usebecky sets capabilities after review. If your extension sends events to a Google Tag Manager tagging server, ask usebecky to turn on "sgtm_forwarding".',
59
+ };
60
+ /** The kit's hint for a code, if it has one (never something inherited, like "toString"). */
61
+ export function partnerErrorHint(code) {
62
+ return Object.hasOwn(PARTNER_ERROR_HINTS, code) ? PARTNER_ERROR_HINTS[code] : undefined;
63
+ }
64
+ /**
65
+ * A partner API call failed. `code` is one of PartnerApiErrorCode, e.g. `insufficient_scope` (403,
66
+ * `details.required_scope`), `capability_required` (403, `details.required_capability`), `invalid_settings` (400),
67
+ * `installation_inactive` (403), `rate_limited` (429), `plan_required` (403), `invalid_range` (400),
68
+ * `project_unavailable` (503), `project_paused` (402), `route_not_found`, `network_error`...
69
+ */
70
+ export class PartnerApiError extends ExtensionError {
71
+ }
72
+ /**
73
+ * A webhook request did not come from usebecky, or was changed or replayed: `missing_signature`,
74
+ * `invalid_signature`, `stale_signature` or `invalid_payload`. Answer 400 and do nothing.
75
+ */
76
+ export class WebhookVerificationError extends ExtensionError {
77
+ }
78
+ /** Wrong options passed to the kit (a missing client id, an http redirect URI in production...). */
79
+ export class ConfigError extends ExtensionError {
80
+ }
81
+ /**
82
+ * An id_token or launch token from usebecky was refused: `invalid_token` (not a JWT), `wrong_token_type` (an id_token
83
+ * where a launch token belongs, or the other way round), `unknown_key`, `invalid_signature`, `invalid_issuer`,
84
+ * `invalid_audience` (issued to another extension), `expired_token`, `token_not_yet_valid`, `invalid_nonce`,
85
+ * `replayed_token` (a launch link opened twice) or `jwks_unavailable` (usebecky's keys could not be loaded). Sign
86
+ * nobody in; for a launch, send the person back to usebecky to open your service again.
87
+ */
88
+ export class TokenVerificationError extends ExtensionError {
89
+ }
90
+ /**
91
+ * A provision request (usebecky creating a customer's account at your service) was refused: `missing_signature`,
92
+ * `invalid_signature`, `stale_signature`, `invalid_payload` or `idempotency_mismatch`. Answer 400 and create nothing.
93
+ */
94
+ export class ProvisionRequestError extends ExtensionError {
95
+ }
96
+ /** Pull `{ error: { code, message, hint } }` (usebecky) or `{ error, error_description }` (OAuth) out of a body. */
97
+ export function readErrorBody(body) {
98
+ if (!body || typeof body !== 'object')
99
+ return {};
100
+ const b = body;
101
+ if (b.error && typeof b.error === 'object') {
102
+ const e = b.error;
103
+ const details = e.details && typeof e.details === 'object' && !Array.isArray(e.details) ? e.details : undefined;
104
+ return { code: str(e.code), message: str(e.message), hint: str(e.hint), details };
105
+ }
106
+ return { code: str(b.error), message: str(b.error_description) ?? str(b.message), hint: str(b.hint) };
107
+ }
108
+ function str(v) {
109
+ return typeof v === 'string' && v ? v : undefined;
110
+ }
@@ -0,0 +1,92 @@
1
+ import type { ExtensionScope, ExtensionSettings } from './types.ts';
2
+ import type { Plan } from './ui/schema.ts';
3
+ /**
4
+ * Every usebecky event type (packages/server/src/core/events.ts EVENT_TYPES, in the same order).
5
+ * test/webhooks.test.ts fails when the two lists drift apart.
6
+ */
7
+ export declare const USEBECKY_EVENT_TYPES: readonly ["user.created", "user.updated", "user.deleted", "user.signed_in", "subscription.created", "subscription.updated", "subscription.canceled", "subscription.trial_will_end", "subscription.gifted", "subscription.gift_updated", "subscription.gift_ended", "purchase.completed", "purchase.refunded", "order.paid", "order.refunded", "order.canceled", "order.shipped", "order.delivered", "payment.failed", "payment.disputed", "payment.dispute_closed", "payment.fraud_warning", "storage.object.created", "storage.object.deleted", "form.submitted", "email.sent", "email.delivered", "email.bounced", "email.complained", "email.delayed", "email.suppressed", "email.failed", "quota.warning", "quota.exceeded", "newsletter.subscribed", "newsletter.unsubscribed", "test.ping", "job.failed", "function.failed", "certificate.renewed"];
8
+ export type UsebeckyEventType = (typeof USEBECKY_EVENT_TYPES)[number];
9
+ /** Event types a listing may put in `events`: every usebecky event type except test.ping. */
10
+ export declare const SUBSCRIBABLE_EVENT_TYPES: readonly UsebeckyEventType[];
11
+ /** Sent to every extension with a webhook_url, whatever its `events` say. */
12
+ export declare const EXTENSION_EVENT_TYPES: readonly ["extension.installed", "extension.uninstalled", "extension.plan_changed"];
13
+ export type ExtensionLifecycleEventType = (typeof EXTENSION_EVENT_TYPES)[number];
14
+ export type ExtensionEventType = ExtensionLifecycleEventType | UsebeckyEventType;
15
+ export declare const ALL_EVENT_TYPES: readonly ExtensionEventType[];
16
+ /** Why an install ended: the customer disconnected it, or its paid subscription ran out. */
17
+ export type UninstallReason = 'customer' | 'subscription_ended';
18
+ /** `data` of extension.installed: the install is usable (the customer allowed access, filled in the settings, or paid). */
19
+ export interface ExtensionInstalledData {
20
+ /** Your extension's slug. */
21
+ extension: string;
22
+ installation_id: string;
23
+ project: {
24
+ ref: string;
25
+ name: string;
26
+ };
27
+ scopes: ExtensionScope[];
28
+ /** The non-secret settings (fields mode; boolean fields are true or false). `{}` for oauth extensions. */
29
+ settings: ExtensionSettings;
30
+ /** Your account id for this install, as your provision endpoint returned it (account.provision "url"). */
31
+ account_id?: string;
32
+ /** The install's price plan (null for a free extension). */
33
+ plan: Plan | null;
34
+ }
35
+ /**
36
+ * `data` of extension.plan_changed: the install's plan changed its id (an upgrade now, a downgrade at the period end),
37
+ * its status (the trial ended, a payment failed or went through), cancel_at_period_end (the customer disconnected, or
38
+ * reinstalled before the end) or next_plan (a downgrade was scheduled or undone).
39
+ */
40
+ export interface ExtensionPlanChangedData {
41
+ extension: string;
42
+ installation_id: string;
43
+ project: {
44
+ ref: string;
45
+ name: string;
46
+ };
47
+ scopes: ExtensionScope[];
48
+ /** The plan before the change (null when it had none). */
49
+ previous: Plan | null;
50
+ plan: Plan | null;
51
+ }
52
+ /** `data` of extension.uninstalled: the last event for that install. Its tokens are already revoked. */
53
+ export interface ExtensionUninstalledData {
54
+ extension: string;
55
+ installation_id: string;
56
+ project: {
57
+ ref: string;
58
+ name: string;
59
+ };
60
+ scopes: ExtensionScope[];
61
+ reason: UninstallReason;
62
+ /** Your account id for this install (account.provision "url"): you decide what happens to the account. */
63
+ account_id?: string;
64
+ }
65
+ /** `data` of the extension's own events. Other usebecky events: see docs/guide/guides/webhooks.md. */
66
+ export interface ExtensionEventDataMap {
67
+ 'extension.installed': ExtensionInstalledData;
68
+ 'extension.uninstalled': ExtensionUninstalledData;
69
+ 'extension.plan_changed': ExtensionPlanChangedData;
70
+ }
71
+ export type ExtensionEventData<K extends string> = K extends keyof ExtensionEventDataMap ? ExtensionEventDataMap[K] : Record<string, unknown>;
72
+ /** The JSON body of every delivery (the same envelope as usebecky's developer events). */
73
+ export interface ExtensionEvent<K extends ExtensionEventType = ExtensionEventType> {
74
+ /** Unique (`evt_...`). The same event can arrive more than once: use it to skip duplicates. */
75
+ id: string;
76
+ type: K;
77
+ created_at: string;
78
+ /** The customer's project ref. One install per project, so this tells you which install it is about. */
79
+ project: string;
80
+ data: ExtensionEventData<K>;
81
+ /**
82
+ * `true` for an install in a test project (a developer's free project for trying extensions): handle it as usual,
83
+ * but never bill or count it. Also `true` on "Send test event" from the Developer area, whose project is
84
+ * `sampleproject` (nothing is installed there). Missing (or false) for real projects.
85
+ */
86
+ test?: boolean;
87
+ }
88
+ /** Any delivered event, narrowed by `switch (event.type)`. */
89
+ export type AnyExtensionEvent = {
90
+ [K in ExtensionEventType]: ExtensionEvent<K>;
91
+ }[ExtensionEventType];
92
+ export declare function isKnownEventType(type: string): type is ExtensionEventType;
package/dist/events.js ADDED
@@ -0,0 +1,54 @@
1
+ /**
2
+ * Every usebecky event type (packages/server/src/core/events.ts EVENT_TYPES, in the same order).
3
+ * test/webhooks.test.ts fails when the two lists drift apart.
4
+ */
5
+ export const USEBECKY_EVENT_TYPES = [
6
+ 'user.created',
7
+ 'user.updated',
8
+ 'user.deleted',
9
+ 'user.signed_in',
10
+ 'subscription.created',
11
+ 'subscription.updated',
12
+ 'subscription.canceled',
13
+ 'subscription.trial_will_end',
14
+ 'subscription.gifted',
15
+ 'subscription.gift_updated',
16
+ 'subscription.gift_ended',
17
+ 'purchase.completed',
18
+ 'purchase.refunded',
19
+ 'order.paid',
20
+ 'order.refunded',
21
+ 'order.canceled',
22
+ 'order.shipped',
23
+ 'order.delivered',
24
+ 'payment.failed',
25
+ 'payment.disputed',
26
+ 'payment.dispute_closed',
27
+ 'payment.fraud_warning',
28
+ 'storage.object.created',
29
+ 'storage.object.deleted',
30
+ 'form.submitted',
31
+ 'email.sent',
32
+ 'email.delivered',
33
+ 'email.bounced',
34
+ 'email.complained',
35
+ 'email.delayed',
36
+ 'email.suppressed',
37
+ 'email.failed',
38
+ 'quota.warning',
39
+ 'quota.exceeded',
40
+ 'newsletter.subscribed',
41
+ 'newsletter.unsubscribed',
42
+ 'test.ping',
43
+ 'job.failed',
44
+ 'function.failed',
45
+ 'certificate.renewed',
46
+ ];
47
+ /** Event types a listing may put in `events`: every usebecky event type except test.ping. */
48
+ export const SUBSCRIBABLE_EVENT_TYPES = USEBECKY_EVENT_TYPES.filter((t) => t !== 'test.ping');
49
+ /** Sent to every extension with a webhook_url, whatever its `events` say. */
50
+ export const EXTENSION_EVENT_TYPES = ['extension.installed', 'extension.uninstalled', 'extension.plan_changed'];
51
+ export const ALL_EVENT_TYPES = [...EXTENSION_EVENT_TYPES, ...USEBECKY_EVENT_TYPES];
52
+ export function isKnownEventType(type) {
53
+ return ALL_EVENT_TYPES.includes(type);
54
+ }
@@ -0,0 +1,214 @@
1
+ import { type IdempotencyStore, type ProvisionRequest, type ProvisionResult, type SsoHandlerOptions } from './accounts.ts';
2
+ import { ExtensionError } from './errors.ts';
3
+ import { type IdTokenClaims, type LaunchClaims, type ReplayGuard } from './identity.ts';
4
+ import { type JwksClient } from './jwt.ts';
5
+ import type { AnyExtensionEvent, ExtensionEvent, ExtensionEventType } from './events.ts';
6
+ import { type FetchHandler } from './handlers.ts';
7
+ import { type StateStore, type StoredTokens, type TokenStore } from './stores.ts';
8
+ import { type AnalyticsSummary, type ExtensionScope, type Installation, type InstallationSettings, type Project, type TaggingSettings } from './types.ts';
9
+ import { type HeaderSource, type VerifyOptions } from './webhooks.ts';
10
+ import { type ActionHandler, type PageHandler, type UiActionContext, type UiContext } from './ui/handler.ts';
11
+ /** usebecky's API. */
12
+ export declare const DEFAULT_API_URL = "https://api.usebecky.com";
13
+ /** usebecky's dashboard: the consent screen is `<dashboard>/oauth/authorize`. */
14
+ export declare const DEFAULT_DASHBOARD_URL = "https://app.usebecky.com";
15
+ /** Path of the partner API (OAuth token endpoint included) under the API URL. */
16
+ export declare const PARTNER_API_PATH = "/extensions/v1";
17
+ /** Path of the consent screen under the dashboard URL. */
18
+ export declare const AUTHORIZE_PATH = "/oauth/authorize";
19
+ /** How long a started sign-in may take before its state expires. */
20
+ export declare const STATE_TTL_SECONDS = 600;
21
+ /**
22
+ * The cookie the install handler sets with the sign-in's state, so the callback only finishes in the browser
23
+ * that started it (an attacker can't send a victim a callback link for the attacker's project).
24
+ */
25
+ export declare const STATE_COOKIE = "usebecky_oauth_state";
26
+ /** Webhook bodies above this are refused before verifying (usebecky's are a few KB). */
27
+ export declare const MAX_WEBHOOK_BYTES: number;
28
+ export interface ExtensionOptions {
29
+ /** `ub_ci_...`, from Developer → your extension → Credentials and testing → Create credentials (env USEBECKY_CLIENT_ID). */
30
+ clientId: string;
31
+ /** `ub_cs_...`, shown once (env USEBECKY_CLIENT_SECRET). Server only. */
32
+ clientSecret: string;
33
+ /** `whsec_...`: signs every webhook (env USEBECKY_WEBHOOK_SECRET). Pass [new, old] while you rotate it. */
34
+ webhookSecret?: string | readonly string[];
35
+ /** Your callback address, exactly as listed in usebecky-extension.json (connect.redirect_uris). */
36
+ redirectUri: string;
37
+ /** usebecky's API (env USEBECKY_API_URL). Default https://api.usebecky.com; a local usebecky http://localhost:4300; the dev server http://localhost:4400. */
38
+ apiUrl?: string;
39
+ /**
40
+ * usebecky's dashboard, where the consent screen is (env USEBECKY_DASHBOARD_URL). Default https://app.usebecky.com
41
+ * for the hosted API, else the API URL itself (the dev server serves both). A local usebecky: http://localhost:5300.
42
+ */
43
+ dashboardUrl?: string;
44
+ tokenStore: TokenStore;
45
+ /** Default: in memory (one server process). */
46
+ stateStore?: StateStore;
47
+ /**
48
+ * Remembers used launch tokens ("Open in"). Default: in memory, right for one server process only. With more than
49
+ * one instance you must share one: sqlReplayGuard() in your token store's database.
50
+ */
51
+ replayGuard?: ReplayGuard;
52
+ /** Scopes to ask for. Default: the ones in your listing. */
53
+ scopes?: ExtensionScope[];
54
+ /** Refresh this many seconds before the access token expires (default 60). */
55
+ refreshMarginSeconds?: number;
56
+ fetch?: typeof fetch;
57
+ /** ms since 1970 (tests). */
58
+ now?: () => number;
59
+ }
60
+ /** What handleCallback() hands back once the install is connected. */
61
+ export interface CallbackResult {
62
+ installation: Installation;
63
+ /** The project ref, the key of everything the kit stores. */
64
+ project: string;
65
+ scopes: ExtensionScope[];
66
+ /** The OAuth state of this sign-in (yours, if you passed one to authorizeUrl). */
67
+ state: string;
68
+ /**
69
+ * The extension's page in the customer's project in usebecky, when the install started from the store (install_url's
70
+ * `return_url`, kept only when it is on the dashboard's address). Link back to it ("Back to usebecky").
71
+ */
72
+ returnUrl?: string;
73
+ /**
74
+ * Who allowed access, from the verified OpenID id_token (listings that create accounts from the sign-in:
75
+ * account.provision "oauth"). Create or link the account by `identity.sub`: customers never sign up by hand.
76
+ */
77
+ identity?: IdTokenClaims;
78
+ }
79
+ /** A Request, a URL (string or URL, relative works), its query, or Node's `req` (anything with `url`). */
80
+ export type CallbackInput = Request | URL | string | URLSearchParams | {
81
+ url?: string;
82
+ originalUrl?: string;
83
+ headers?: Record<string, string | string[] | undefined>;
84
+ };
85
+ /** Typed calls to the partner API for one install. Every method refreshes the token when needed. */
86
+ export interface PartnerApi {
87
+ /** The install: id, extension, project, scopes, events, settings, installed_at, test (a test project). Needs no scope. */
88
+ installation(): Promise<Installation>;
89
+ /** The project's name, API address, publishable key and allowed websites (needs 'project:read'). */
90
+ project(): Promise<Project>;
91
+ /**
92
+ * Visitor and revenue totals (needs 'analytics:read'). Days as YYYY-MM-DD (UTC, both included): pass both or
93
+ * neither (the last 30 days). The project's plan limits how far back (`plan_required`).
94
+ */
95
+ analyticsSummary(range?: {
96
+ from?: string;
97
+ to?: string;
98
+ }): Promise<AnalyticsSummary>;
99
+ /**
100
+ * Server-side tagging: set where usebecky's servers send the project's sales, sign-ups and form leads (PUT
101
+ * /installation/settings). Only for extensions usebecky gave the capability `sgtm_forwarding` (else
102
+ * `capability_required`); checked like the customer's settings form (`invalid_settings`). Returns the settings as
103
+ * stored (tidied: `https://host`, `G-…` upper case). The same values again change nothing.
104
+ */
105
+ updateSettings(settings: TaggingSettings): Promise<InstallationSettings>;
106
+ /** Server-side tagging off for this project (DELETE /installation/settings), e.g. when its tagging server is deleted. */
107
+ clearSettings(): Promise<InstallationSettings>;
108
+ /** Any other partner API route, e.g. request('GET', '/installation'). */
109
+ request<T = unknown>(method: string, path: string, init?: {
110
+ query?: Record<string, string | undefined>;
111
+ body?: unknown;
112
+ }): Promise<T>;
113
+ }
114
+ export type WebhookHandlers = {
115
+ [K in ExtensionEventType]?: (event: ExtensionEvent<K>) => unknown;
116
+ } & {
117
+ /** Every event, after its own handler (if any). */
118
+ '*'?: (event: AnyExtensionEvent) => unknown;
119
+ };
120
+ export interface WebhookHandlerOptions {
121
+ /** On extension.uninstalled, delete the stored tokens of that install (default true). */
122
+ forgetOnUninstall?: boolean;
123
+ }
124
+ export interface OAuthHandlerOptions {
125
+ /** After a successful install. Return a Response (e.g. a redirect to your settings page, with a session cookie). */
126
+ onInstalled?: (result: CallbackResult, request: Request) => Response | void | Promise<Response | void>;
127
+ /** When the callback fails. Default: a plain page with a "Try again" link to `installPath`. */
128
+ onError?: (error: ExtensionError, request: Request) => Response | void | Promise<Response | void>;
129
+ /** Where to send the customer after a successful install when onInstalled returns nothing (default "/"). */
130
+ successUrl?: string;
131
+ /** Your install route, for "Try again" links (default "/install"). */
132
+ installPath?: string;
133
+ }
134
+ export interface AuthorizeOptions {
135
+ /** The project ref from install_url's `?project=`: preselects it on the consent screen. */
136
+ project?: string;
137
+ /** Your own random state (at least 16 characters). Default: a new one. */
138
+ state?: string;
139
+ /** Fewer scopes than the listing has. Default: the `scopes` option, else all the listing's scopes. */
140
+ scopes?: ExtensionScope[];
141
+ /** The callback must carry the state cookie of the install handler (set by `oauthHandlers().install`). */
142
+ bindToBrowser?: boolean;
143
+ /** install_url's `return_url`; kept (and handed back by handleCallback) only when it is on the dashboard's address. */
144
+ returnUrl?: string;
145
+ }
146
+ export interface Extension {
147
+ readonly clientId: string;
148
+ readonly apiUrl: string;
149
+ /** usebecky's dashboard (the consent screen and the customer's extension pages). */
150
+ readonly dashboardUrl: string;
151
+ /** The consent screen address authorizeUrl() builds on: `<dashboardUrl>/oauth/authorize`. */
152
+ readonly authorizeEndpoint: string;
153
+ readonly tokenStore: TokenStore;
154
+ /** The consent screen URL for a new sign-in (PKCE S256; the verifier goes to the state store). */
155
+ authorizeUrl(options?: AuthorizeOptions): Promise<string>;
156
+ /**
157
+ * Finish the sign-in on your redirect URI: check the state, swap the code, store the tokens. Pass the Request
158
+ * (or Node's `req`): sign-ins started by the install handler only finish with its state cookie.
159
+ */
160
+ handleCallback(input: CallbackInput): Promise<CallbackResult>;
161
+ /** The partner API for one install. Throws InstallationRevokedError when nothing is stored for the project. */
162
+ api(project: string): PartnerApi;
163
+ /** A valid access token for the project (refreshed when it is about to expire). */
164
+ accessToken(project: string): Promise<string>;
165
+ /** Refresh now. Concurrent calls for the same project share one refresh. */
166
+ refresh(project: string): Promise<StoredTokens>;
167
+ /** Disconnect: revoke the tokens at usebecky (best effort) and delete them here. True when usebecky confirmed. */
168
+ revoke(project: string): Promise<boolean>;
169
+ /** Delete the stored tokens of a project (after extension.uninstalled, the kit does this for you). */
170
+ forget(project: string): Promise<void>;
171
+ verifyWebhook(rawBody: string | Uint8Array | ArrayBuffer, headers: HeaderSource, options?: VerifyOptions): Promise<AnyExtensionEvent>;
172
+ /** `install` (GET, redirects to the consent screen) and `callback` (GET, your redirect URI), fetch-style. */
173
+ oauthHandlers(options?: OAuthHandlerOptions): {
174
+ install: FetchHandler;
175
+ callback: FetchHandler;
176
+ };
177
+ /** A fetch-style POST handler for your webhook_url: verifies, then calls your handler for the event type. */
178
+ webhookHandler(handlers: WebhookHandlers | ((event: AnyExtensionEvent) => unknown), options?: WebhookHandlerOptions): FetchHandler;
179
+ /** usebecky's public signing keys (cached; refetched for a new key id). */
180
+ readonly jwks: JwksClient;
181
+ /** Verify an id_token for this extension (handleCallback() already does). */
182
+ verifyIdToken(token: string, options?: {
183
+ nonce?: string;
184
+ }): Promise<IdTokenClaims>;
185
+ /** Verify the launch token of "Open in" (`?launch=` on your sso_url): signature, audience, 60 seconds, single use. */
186
+ verifyLaunchToken(token: string): Promise<LaunchClaims>;
187
+ /**
188
+ * A fetch-style POST handler for your provision_url (account.provision "url"): usebecky asks you to create the
189
+ * customer's account; return its id (and settings for your setup fields). Retries never create a second account.
190
+ */
191
+ provisionHandler(provision: (request: ProvisionRequest, raw: Request) => ProvisionResult | Promise<ProvisionResult>, options?: {
192
+ idempotency?: IdempotencyStore;
193
+ }): FetchHandler;
194
+ /** A fetch-style GET handler for your sso_url: verifies `?launch=` and calls `createSession` with the claims. */
195
+ ssoHandler(options: Pick<SsoHandlerOptions, 'createSession' | 'onError' | 'serviceName'>): FetchHandler;
196
+ /**
197
+ * A fetch-style POST handler for your ui.url (your pages inside usebecky): verifies the request and calls the page or
198
+ * action handler with a context that has `api` (the partner API for that project). Answer with blocks: usebecky
199
+ * draws them in its own design.
200
+ */
201
+ uiHandler(options: {
202
+ pages: Record<string, PageHandler<ExtensionUiContext>>;
203
+ actions?: Record<string, ActionHandler<ExtensionUiActionContext>>;
204
+ log?: (message: string) => void;
205
+ }): FetchHandler;
206
+ }
207
+ /** A UI request's context, with the partner API for its project (OAuth extensions: needs the install's tokens). */
208
+ export type ExtensionUiContext = UiContext & {
209
+ readonly api: PartnerApi;
210
+ };
211
+ export type ExtensionUiActionContext = UiActionContext & {
212
+ readonly api: PartnerApi;
213
+ };
214
+ export declare function createExtension(options: ExtensionOptions): Extension;