@buildbase/sdk 0.0.48 → 0.0.50
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/AGENTS.md +119 -0
- package/CHANGELOG.md +42 -0
- package/README.md +203 -0
- package/dist/data/index.cjs +1 -0
- package/dist/data/index.mjs +1 -1
- package/dist/index.cjs +1 -0
- package/dist/index.d.ts +469 -4
- package/dist/index.mjs +1 -1
- package/dist/react/chunks/SubscriptionDialog-A6oETKbb.cjs +2 -0
- package/dist/react/chunks/SubscriptionDialog-nuMunBn4.mjs +2 -0
- package/dist/react/chunks/ar-BRvKHRYS.cjs +2 -0
- package/dist/react/chunks/ar-IhPhJAZA.mjs +2 -0
- package/dist/react/chunks/de-D3q0vQBG.cjs +2 -0
- package/dist/react/chunks/de-bvh5IFSx.mjs +2 -0
- package/dist/react/chunks/es-B9kiwJmF.cjs +2 -0
- package/dist/react/chunks/es-TyUz4_E1.mjs +2 -0
- package/dist/react/chunks/fr-C500Ytao.cjs +2 -0
- package/dist/react/chunks/fr-CKm-bSvG.mjs +2 -0
- package/dist/react/chunks/hi-CfFhH2uQ.cjs +2 -0
- package/dist/react/chunks/hi-Ck9cPpd-.mjs +2 -0
- package/dist/react/chunks/ja-AM4H1tXw.mjs +2 -0
- package/dist/react/chunks/ja-DfROrx_j.cjs +2 -0
- package/dist/react/chunks/react-CTX0_nOV.cjs +2 -0
- package/dist/react/chunks/react-DzQupoqH.mjs +2 -0
- package/dist/react/chunks/zh-CLmBh-it.cjs +2 -0
- package/dist/react/chunks/zh-DCVPxie-.mjs +2 -0
- package/dist/react/index.cjs +2 -0
- package/dist/react/index.d.ts +9 -1
- package/dist/react/index.mjs +1 -35
- package/package.json +25 -9
- package/dist/data/index.js +0 -1
- package/dist/index.js +0 -1
- package/dist/react/index.js +0 -36
package/dist/index.d.ts
CHANGED
|
@@ -1112,6 +1112,8 @@ declare abstract class BaseApi {
|
|
|
1112
1112
|
protected url(path: string): string;
|
|
1113
1113
|
/** Merge auth + custom + per-request headers. */
|
|
1114
1114
|
private buildHeaders;
|
|
1115
|
+
/** Fire the onError callback exactly once per error, regardless of call path. */
|
|
1116
|
+
private reportError;
|
|
1115
1117
|
/** Execute fetch with timeout, retries, debug logging, and error callback. */
|
|
1116
1118
|
private executeFetch;
|
|
1117
1119
|
/** Internal: execute fetch against a resolved URL with timeout, retries, debug logging, and error callback. */
|
|
@@ -1858,8 +1860,14 @@ declare function validateRedirectUrl(url: string | null | undefined): string | n
|
|
|
1858
1860
|
/**
|
|
1859
1861
|
* Safely redirect to a URL after validating it.
|
|
1860
1862
|
* Falls back to fallbackUrl if the target URL is invalid.
|
|
1863
|
+
*
|
|
1864
|
+
* Browser-only: navigation requires `window.location`. On non-browser runtimes
|
|
1865
|
+
* (Node, edge, Deno, Bun) there is nothing to navigate, so this is a no-op that
|
|
1866
|
+
* returns `false`. Returns `true` when a navigation was initiated. Server code
|
|
1867
|
+
* that needs the resolved target should call {@link validateRedirectUrl} and
|
|
1868
|
+
* issue the redirect with its own framework (e.g. `Response.redirect`).
|
|
1861
1869
|
*/
|
|
1862
|
-
declare function safeRedirect(url: string | null | undefined, fallbackUrl?: string):
|
|
1870
|
+
declare function safeRedirect(url: string | null | undefined, fallbackUrl?: string): boolean;
|
|
1863
1871
|
|
|
1864
1872
|
/**
|
|
1865
1873
|
* Auth intent preservation — saves and restores the URL the user was on
|
|
@@ -2209,7 +2217,10 @@ interface BetaFormResponse {
|
|
|
2209
2217
|
* Verify that a webhook request came from BuildBase.
|
|
2210
2218
|
*
|
|
2211
2219
|
* Uses HMAC-SHA256 signature verification with timing-safe comparison
|
|
2212
|
-
* to prevent timing attacks.
|
|
2220
|
+
* to prevent timing attacks. Runtime-agnostic: the HMAC is a dependency-free
|
|
2221
|
+
* pure-JS implementation (shared with the OAuth app-bridge), so it behaves
|
|
2222
|
+
* identically under CJS, ESM, bundlers, edge runtimes, Deno, Bun, and browsers —
|
|
2223
|
+
* no Node `crypto`/`require`/`Buffer`.
|
|
2213
2224
|
*
|
|
2214
2225
|
* @example
|
|
2215
2226
|
* ```ts
|
|
@@ -2285,6 +2296,460 @@ declare function parseWebhookEvent(options: {
|
|
|
2285
2296
|
data: Record<string, any>;
|
|
2286
2297
|
} | null;
|
|
2287
2298
|
|
|
2299
|
+
/**
|
|
2300
|
+
* Agent-readiness discovery toolkit (server-side, framework-agnostic).
|
|
2301
|
+
*
|
|
2302
|
+
* Makes a consuming app "agent ready" (see https://isitagentready.com) by
|
|
2303
|
+
* serving the standard machine-readable discovery documents an AI agent looks
|
|
2304
|
+
* for — with the BuildBase server as the source of truth.
|
|
2305
|
+
*
|
|
2306
|
+
* The heavy lifting already lives on the platform: an org admin configures
|
|
2307
|
+
* agent readiness once (protected resources, scopes, llms.txt) and the server
|
|
2308
|
+
* publishes the OAuth2 authorization-server metadata (RFC 8414) and the
|
|
2309
|
+
* per-resource protected-resource metadata (RFC 9728). This module lets an app
|
|
2310
|
+
* re-serve those documents from its own origin — where agents actually look —
|
|
2311
|
+
* plus generate the static discovery documents (Agent Card, Agent Skills,
|
|
2312
|
+
* security.txt) from local config. The result: an org admin adds full agent
|
|
2313
|
+
* support to their app in a couple of lines, and never hand-writes a
|
|
2314
|
+
* `.well-known` route.
|
|
2315
|
+
*
|
|
2316
|
+
* Zero React and no framework types — every function returns plain data. The
|
|
2317
|
+
* only runtime dependency is `fetch`; SHA-256 (for Agent Skills digests) is a
|
|
2318
|
+
* dependency-free pure-JS implementation, so there is no Web Crypto / Node
|
|
2319
|
+
* `crypto` requirement and output is identical on every runtime (browser, edge,
|
|
2320
|
+
* Node 18+). Wire the returned documents into your router yourself (Next.js,
|
|
2321
|
+
* Hono, Express, …).
|
|
2322
|
+
*
|
|
2323
|
+
* @example Next.js App Router — the entire integration:
|
|
2324
|
+
* ```ts
|
|
2325
|
+
* // lib/agent-ready.ts
|
|
2326
|
+
* import type { AgentReadyConfig } from "@buildbase/sdk";
|
|
2327
|
+
* export const agentConfig: AgentReadyConfig = {
|
|
2328
|
+
* serverUrl: process.env.BUILDBASE_URL!,
|
|
2329
|
+
* orgId: process.env.BUILDBASE_ORG_ID!,
|
|
2330
|
+
* siteUrl: "https://imejis.io",
|
|
2331
|
+
* site: { name: "Imejis", description: "Generate images from templates via API." },
|
|
2332
|
+
* };
|
|
2333
|
+
*
|
|
2334
|
+
* // app/.well-known/[...path]/route.ts
|
|
2335
|
+
* import { resolveWellKnown } from "@buildbase/sdk";
|
|
2336
|
+
* import { agentConfig } from "@/lib/agent-ready";
|
|
2337
|
+
* export async function GET(req: Request) {
|
|
2338
|
+
* const doc = await resolveWellKnown(new URL(req.url).pathname, agentConfig);
|
|
2339
|
+
* if (!doc) return new Response('{"error":"not_found"}', { status: 404 });
|
|
2340
|
+
* return new Response(doc.body, {
|
|
2341
|
+
* status: doc.status,
|
|
2342
|
+
* headers: { "Content-Type": doc.contentType, "Cache-Control": doc.cacheControl },
|
|
2343
|
+
* });
|
|
2344
|
+
* }
|
|
2345
|
+
*
|
|
2346
|
+
* // app/llms.txt/route.ts
|
|
2347
|
+
* import { buildLlmsTxt, fetchAgentReadiness } from "@buildbase/sdk";
|
|
2348
|
+
* import { agentConfig } from "@/lib/agent-ready";
|
|
2349
|
+
* export async function GET() {
|
|
2350
|
+
* const doc = buildLlmsTxt(agentConfig, await fetchAgentReadiness(agentConfig));
|
|
2351
|
+
* if (!doc) return new Response("Not found", { status: 404 });
|
|
2352
|
+
* return new Response(doc.body, { headers: { "Content-Type": doc.contentType } });
|
|
2353
|
+
* }
|
|
2354
|
+
* ```
|
|
2355
|
+
*/
|
|
2356
|
+
/**
|
|
2357
|
+
* The agent-readiness bundle the BuildBase server publishes for an org at
|
|
2358
|
+
* `GET /api/v1/public/:orgId/agent-readiness`. This is the single source of
|
|
2359
|
+
* truth an org admin edits; everything org-specific below is derived from it.
|
|
2360
|
+
*/
|
|
2361
|
+
interface AgentReadinessBundle {
|
|
2362
|
+
/** False when the org has not enabled agent readiness — everything else absent. */
|
|
2363
|
+
enabled: boolean;
|
|
2364
|
+
/** Pointer to the org's RFC 8414 authorization-server metadata. */
|
|
2365
|
+
authorizationServer?: {
|
|
2366
|
+
issuer: string;
|
|
2367
|
+
metadataUrl: string;
|
|
2368
|
+
};
|
|
2369
|
+
/**
|
|
2370
|
+
* RFC 9728 protected-resource metadata objects, ready to serve. Each `metadata`
|
|
2371
|
+
* is a complete document; `resource` is the canonical resource URI it describes.
|
|
2372
|
+
*/
|
|
2373
|
+
protectedResources?: Array<{
|
|
2374
|
+
resource: string;
|
|
2375
|
+
metadata: Record<string, unknown>;
|
|
2376
|
+
}>;
|
|
2377
|
+
/** Org-authored llms.txt content, or null when unset. */
|
|
2378
|
+
llmsTxt?: string | null;
|
|
2379
|
+
}
|
|
2380
|
+
/** An Agent Skill (Agent Skills Discovery RFC v0.2.0) published by this app. */
|
|
2381
|
+
interface AgentSkill {
|
|
2382
|
+
/** Stable slug, e.g. `imejis-api`. */
|
|
2383
|
+
name: string;
|
|
2384
|
+
/** One-line human/agent-readable summary. */
|
|
2385
|
+
description: string;
|
|
2386
|
+
/** Full markdown content of the SKILL.md served for this skill. */
|
|
2387
|
+
content: string;
|
|
2388
|
+
/**
|
|
2389
|
+
* Path the SKILL.md is served from. Defaults to
|
|
2390
|
+
* `/.well-known/agent-skills/<name>/SKILL.md`.
|
|
2391
|
+
*/
|
|
2392
|
+
path?: string;
|
|
2393
|
+
/** Skill artifact kind. Defaults to `skill-md`. */
|
|
2394
|
+
type?: 'skill-md' | 'archive';
|
|
2395
|
+
}
|
|
2396
|
+
/** One API described in an API Catalog (RFC 9727 / RFC 9264 linkset). */
|
|
2397
|
+
interface ApiCatalogApi {
|
|
2398
|
+
/** Anchor URL identifying the API, e.g. `https://api.imejis.io`. */
|
|
2399
|
+
anchor: string;
|
|
2400
|
+
/** OpenAPI / machine-readable description URL (link rel `service-desc`). */
|
|
2401
|
+
serviceDesc?: string;
|
|
2402
|
+
/** Human documentation URL (link rel `service-doc`). */
|
|
2403
|
+
serviceDoc?: string;
|
|
2404
|
+
/** Health / status endpoint URL (link rel `status`). */
|
|
2405
|
+
status?: string;
|
|
2406
|
+
/** Optional human title for the API. */
|
|
2407
|
+
title?: string;
|
|
2408
|
+
}
|
|
2409
|
+
/** MCP Server Card (SEP-1649 / SEP-2127), advertising a live MCP server. */
|
|
2410
|
+
interface McpServerCard {
|
|
2411
|
+
/** Server name. */
|
|
2412
|
+
name: string;
|
|
2413
|
+
/** Server version. */
|
|
2414
|
+
version: string;
|
|
2415
|
+
/** MCP transport endpoint URL the agent connects to. */
|
|
2416
|
+
endpoint: string;
|
|
2417
|
+
/** Transport type. Defaults to `"streamable-http"`. */
|
|
2418
|
+
transport?: string;
|
|
2419
|
+
/** Capabilities object, e.g. `{ tools: {}, resources: {} }`. */
|
|
2420
|
+
capabilities?: Record<string, unknown>;
|
|
2421
|
+
/** Optional human description. */
|
|
2422
|
+
description?: string;
|
|
2423
|
+
/** Documentation URL. */
|
|
2424
|
+
documentationUrl?: string;
|
|
2425
|
+
}
|
|
2426
|
+
/** Configuration for the agent-readiness discovery layer. */
|
|
2427
|
+
interface AgentReadyConfig {
|
|
2428
|
+
/** BuildBase server base URL, e.g. `https://api.buildbase.app` (no trailing slash needed). */
|
|
2429
|
+
serverUrl: string;
|
|
2430
|
+
/** The org id (24-hex) whose agent-readiness config to serve. */
|
|
2431
|
+
orgId: string;
|
|
2432
|
+
/**
|
|
2433
|
+
* This app's public origin, e.g. `https://imejis.io`. Used to build absolute
|
|
2434
|
+
* URLs in the Agent Card and to match RFC 9728 resource paths.
|
|
2435
|
+
*/
|
|
2436
|
+
siteUrl: string;
|
|
2437
|
+
/** Static metadata for the Agent Card (`/.well-known/agent.json`). */
|
|
2438
|
+
site: {
|
|
2439
|
+
name: string;
|
|
2440
|
+
description?: string;
|
|
2441
|
+
/** Absolute URL to human/agent documentation. */
|
|
2442
|
+
documentationUrl?: string;
|
|
2443
|
+
/** Support/contact email surfaced on the Agent Card. */
|
|
2444
|
+
contactEmail?: string;
|
|
2445
|
+
/** Provider block; defaults to `{ name: site.name, url: siteUrl }`. */
|
|
2446
|
+
provider?: {
|
|
2447
|
+
name: string;
|
|
2448
|
+
url: string;
|
|
2449
|
+
};
|
|
2450
|
+
};
|
|
2451
|
+
/** Agent Skills to publish. Omit to skip the Agent Skills documents. */
|
|
2452
|
+
skills?: AgentSkill[];
|
|
2453
|
+
/** security.txt fields (RFC 9116). Omit to skip serving security.txt. */
|
|
2454
|
+
security?: {
|
|
2455
|
+
/** Contact URI(s) — email (`mailto:`) or URL. */
|
|
2456
|
+
contact: string | string[];
|
|
2457
|
+
/** ISO-8601 expiry; strongly recommended by RFC 9116. */
|
|
2458
|
+
expires?: string;
|
|
2459
|
+
/** Security policy URL. */
|
|
2460
|
+
policy?: string;
|
|
2461
|
+
};
|
|
2462
|
+
/**
|
|
2463
|
+
* API Catalog entries (RFC 9727), served at `/.well-known/api-catalog` as
|
|
2464
|
+
* `application/linkset+json`. Omit to skip.
|
|
2465
|
+
*/
|
|
2466
|
+
apiCatalog?: ApiCatalogApi[];
|
|
2467
|
+
/**
|
|
2468
|
+
* MCP Server Card (SEP-1649), served at `/.well-known/mcp/server-card.json`.
|
|
2469
|
+
* Only set this when you actually run an MCP server — the card advertises a
|
|
2470
|
+
* live transport endpoint. Omit to skip.
|
|
2471
|
+
*/
|
|
2472
|
+
mcpServerCard?: McpServerCard;
|
|
2473
|
+
/**
|
|
2474
|
+
* Raw `/auth.md` content (agent registration/auth instructions). If omitted,
|
|
2475
|
+
* `buildAuthMd` generates one from the OAuth metadata + site config.
|
|
2476
|
+
*/
|
|
2477
|
+
authMd?: string;
|
|
2478
|
+
/** TTL (seconds) for cached platform fetches. Default 300 (5 min). */
|
|
2479
|
+
cacheTtlSeconds?: number;
|
|
2480
|
+
/** Injectable fetch, mainly for testing. Defaults to the global `fetch`. */
|
|
2481
|
+
fetch?: typeof fetch;
|
|
2482
|
+
}
|
|
2483
|
+
/** A rendered discovery document ready to become an HTTP response. */
|
|
2484
|
+
interface DiscoveryDocument {
|
|
2485
|
+
status: number;
|
|
2486
|
+
contentType: string;
|
|
2487
|
+
body: string;
|
|
2488
|
+
cacheControl: string;
|
|
2489
|
+
}
|
|
2490
|
+
/**
|
|
2491
|
+
* SHA-256 of `content` as `sha256:<hex>`, via the shared pure-JS hash (no Web
|
|
2492
|
+
* Crypto / Node `crypto`), so output is identical on every runtime.
|
|
2493
|
+
*/
|
|
2494
|
+
declare function sha256Digest(content: string): string;
|
|
2495
|
+
/**
|
|
2496
|
+
* Fetch (and cache) an org's agent-readiness bundle from the BuildBase server.
|
|
2497
|
+
*
|
|
2498
|
+
* Fail-soft: any network/HTTP/parse error resolves to `{ enabled: false }` so a
|
|
2499
|
+
* discovery route never 500s and never leaks the platform being down — agents
|
|
2500
|
+
* simply see the app as not (yet) agent-ready.
|
|
2501
|
+
*/
|
|
2502
|
+
declare function fetchAgentReadiness(config: AgentReadyConfig): Promise<AgentReadinessBundle>;
|
|
2503
|
+
/** Clear the in-memory agent-readiness cache (mainly for tests). */
|
|
2504
|
+
declare function clearAgentReadinessCache(): void;
|
|
2505
|
+
/**
|
|
2506
|
+
* The Agent Card served at `/.well-known/agent.json`. A stable, machine-readable
|
|
2507
|
+
* entry point advertising who this app is and where agents can discover more.
|
|
2508
|
+
*/
|
|
2509
|
+
declare function buildAgentCard(config: AgentReadyConfig, bundle: AgentReadinessBundle): DiscoveryDocument;
|
|
2510
|
+
/**
|
|
2511
|
+
* Resolve the RFC 9728 protected-resource metadata for a request path, or null
|
|
2512
|
+
* if no configured resource maps to it.
|
|
2513
|
+
*/
|
|
2514
|
+
declare function buildProtectedResourceMetadata(requestPath: string, config: AgentReadyConfig, bundle: AgentReadinessBundle): DiscoveryDocument | null;
|
|
2515
|
+
/** Agent Skills discovery index (Agent Skills Discovery RFC v0.2.0). */
|
|
2516
|
+
declare function buildAgentSkillsIndex(config: AgentReadyConfig): DiscoveryDocument | null;
|
|
2517
|
+
/** Serve a single skill's SKILL.md by request path, or null if none matches. */
|
|
2518
|
+
declare function buildSkillMd(requestPath: string, config: AgentReadyConfig): DiscoveryDocument | null;
|
|
2519
|
+
/** security.txt (RFC 9116), or null when not configured. */
|
|
2520
|
+
declare function buildSecurityTxt(config: AgentReadyConfig): DiscoveryDocument | null;
|
|
2521
|
+
/** The org-authored llms.txt, or null when the org hasn't set one. */
|
|
2522
|
+
declare function buildLlmsTxt(config: AgentReadyConfig, bundle: AgentReadinessBundle): DiscoveryDocument | null;
|
|
2523
|
+
/**
|
|
2524
|
+
* API Catalog (RFC 9727) as a `linkset+json` document for
|
|
2525
|
+
* `/.well-known/api-catalog`. Returns null when no APIs are configured.
|
|
2526
|
+
*/
|
|
2527
|
+
declare function buildApiCatalog(config: AgentReadyConfig): DiscoveryDocument | null;
|
|
2528
|
+
/**
|
|
2529
|
+
* MCP Server Card (SEP-1649) for `/.well-known/mcp/server-card.json`. Returns
|
|
2530
|
+
* null when no card is configured (i.e. no MCP server is running).
|
|
2531
|
+
*/
|
|
2532
|
+
declare function buildMcpServerCard(config: AgentReadyConfig): DiscoveryDocument | null;
|
|
2533
|
+
/**
|
|
2534
|
+
* The `/auth.md` document (agent registration + authentication instructions).
|
|
2535
|
+
* Uses `config.authMd` verbatim when provided; otherwise generates one from the
|
|
2536
|
+
* OAuth authorization-server metadata + site config. Returns null only when
|
|
2537
|
+
* there is nothing to describe (no authorizationServer and no override).
|
|
2538
|
+
*/
|
|
2539
|
+
declare function buildAuthMd(config: AgentReadyConfig, bundle: AgentReadinessBundle): DiscoveryDocument | null;
|
|
2540
|
+
/**
|
|
2541
|
+
* Resolve any `.well-known` request path to its discovery document, or null if
|
|
2542
|
+
* this app serves nothing there (caller should 404).
|
|
2543
|
+
*
|
|
2544
|
+
* Handles: agent.json, oauth-protected-resource (+ per-resource paths),
|
|
2545
|
+
* oauth-authorization-server (pointer), agent-skills index + SKILL.md,
|
|
2546
|
+
* security.txt, api-catalog (RFC 9727), and the MCP server card.
|
|
2547
|
+
*
|
|
2548
|
+
* Root-level docs are served via their own builders (they aren't under
|
|
2549
|
+
* `.well-known`): `buildLlmsTxt` for `/llms.txt` and `buildAuthMd` for `/auth.md`.
|
|
2550
|
+
*/
|
|
2551
|
+
declare function resolveWellKnown(requestPath: string, config: AgentReadyConfig): Promise<DiscoveryDocument | null>;
|
|
2552
|
+
/** A WebMCP tool definition exposed to in-page agents via `navigator.modelContext`. */
|
|
2553
|
+
interface WebMcpTool {
|
|
2554
|
+
name: string;
|
|
2555
|
+
description: string;
|
|
2556
|
+
/** JSON Schema for the tool's input. */
|
|
2557
|
+
inputSchema: Record<string, unknown>;
|
|
2558
|
+
/** Called when an agent invokes the tool. */
|
|
2559
|
+
execute: (input: any) => unknown | Promise<unknown>;
|
|
2560
|
+
}
|
|
2561
|
+
/**
|
|
2562
|
+
* Register WebMCP tools with the browser so in-page AI agents can invoke your
|
|
2563
|
+
* site's actions (WebMCP `navigator.modelContext.provideContext`). Client-side
|
|
2564
|
+
* only — a no-op returning `false` when the API is unavailable, so it's safe to
|
|
2565
|
+
* call unconditionally in a browser effect.
|
|
2566
|
+
*/
|
|
2567
|
+
declare function provideWebMcpTools(tools: WebMcpTool[]): boolean;
|
|
2568
|
+
|
|
2569
|
+
/**
|
|
2570
|
+
* OAuth2 app-bridge toolkit (server-side).
|
|
2571
|
+
*
|
|
2572
|
+
* BuildBase runs the OAuth2 authorization flow (login, consent, code, PKCE,
|
|
2573
|
+
* refresh rotation) but it never mints the access token itself — on the token
|
|
2574
|
+
* grant it calls the org's own backend to mint the token the agent will carry.
|
|
2575
|
+
* Concretely, the platform makes signed webhook-style calls to two endpoints an
|
|
2576
|
+
* OAuth2 client registers:
|
|
2577
|
+
*
|
|
2578
|
+
* • applicationTokenUrl — mint an access token for a user (required)
|
|
2579
|
+
* • applicationRevokeUrl — invalidate a user's token on revocation (optional)
|
|
2580
|
+
*
|
|
2581
|
+
* Both requests carry an `Authorization: Bearer <JWT>` where the JWT is HS256,
|
|
2582
|
+
* signed with the client's secret (so possession of the secret authenticates
|
|
2583
|
+
* the platform). This module verifies those requests and shapes the responses,
|
|
2584
|
+
* so an implementor writes only the part that is theirs: minting/invalidating a
|
|
2585
|
+
* token in their own format.
|
|
2586
|
+
*
|
|
2587
|
+
* HMAC verification uses the SDK's dependency-free pure-JS HMAC-SHA256 (no Web
|
|
2588
|
+
* Crypto, no Node `crypto`, no `require`), so it behaves identically whether the
|
|
2589
|
+
* bundle is loaded as ESM or CJS, under a bundler or on bare Node.
|
|
2590
|
+
*
|
|
2591
|
+
* @example applicationTokenUrl handler (Next.js Pages Router):
|
|
2592
|
+
* ```ts
|
|
2593
|
+
* import { handleAppTokenRequest } from "@buildbase/sdk";
|
|
2594
|
+
* export default async function handler(req, res) {
|
|
2595
|
+
* const { status, body } = await handleAppTokenRequest({
|
|
2596
|
+
* authorization: req.headers.authorization,
|
|
2597
|
+
* clientSecret: process.env.BUILDBASE_CLIENT_SECRET!,
|
|
2598
|
+
* mintToken: (user) => ({
|
|
2599
|
+
* token: signMyAccessToken(user, { aud: user.resource }), // your token, your format
|
|
2600
|
+
* expiresIn: 3600,
|
|
2601
|
+
* }),
|
|
2602
|
+
* });
|
|
2603
|
+
* res.status(status).json(body);
|
|
2604
|
+
* }
|
|
2605
|
+
* ```
|
|
2606
|
+
*/
|
|
2607
|
+
/** Thrown when an incoming platform request fails verification. */
|
|
2608
|
+
declare class AppBridgeError extends Error {
|
|
2609
|
+
/** Machine-readable reason, e.g. `invalid_signature`, `token_expired`. */
|
|
2610
|
+
readonly code: string;
|
|
2611
|
+
constructor(code: string, message: string);
|
|
2612
|
+
}
|
|
2613
|
+
/**
|
|
2614
|
+
* The user + grant context BuildBase sends to `applicationTokenUrl`. The app
|
|
2615
|
+
* mints a token for this user; `resource` is the RFC 8707 audience(s) the token
|
|
2616
|
+
* should be bound to (stamp them as `aud`), and `scope` is what the user granted.
|
|
2617
|
+
* Unknown claims are preserved for forward-compatibility.
|
|
2618
|
+
*/
|
|
2619
|
+
interface AppTokenRequestClaims {
|
|
2620
|
+
/** The user's id in the org. */
|
|
2621
|
+
id: string;
|
|
2622
|
+
email: string;
|
|
2623
|
+
name?: string;
|
|
2624
|
+
role?: string;
|
|
2625
|
+
emailVerified?: boolean;
|
|
2626
|
+
image?: string;
|
|
2627
|
+
blocked?: boolean;
|
|
2628
|
+
blockedReason?: string;
|
|
2629
|
+
blockedAt?: string;
|
|
2630
|
+
/** Which grant triggered this mint. */
|
|
2631
|
+
grantType?: 'authorization_code' | 'refresh_token';
|
|
2632
|
+
/** Scopes granted at authorization time. */
|
|
2633
|
+
scope?: string[];
|
|
2634
|
+
/** RFC 8707 resource indicator(s) — bind the minted token's `aud` to these. */
|
|
2635
|
+
resource?: string[];
|
|
2636
|
+
/** The OAuth2 client's display title. */
|
|
2637
|
+
clientTitle?: string;
|
|
2638
|
+
[claim: string]: unknown;
|
|
2639
|
+
}
|
|
2640
|
+
/** The payload BuildBase sends to `applicationRevokeUrl`. */
|
|
2641
|
+
interface AppRevokeRequestClaims {
|
|
2642
|
+
userId: string;
|
|
2643
|
+
clientId: string;
|
|
2644
|
+
reason: string;
|
|
2645
|
+
[claim: string]: unknown;
|
|
2646
|
+
}
|
|
2647
|
+
/**
|
|
2648
|
+
* Verify a BuildBase-issued HS256 JWT (signed with the client secret) and return
|
|
2649
|
+
* its payload. Checks the signature (timing-safe), the algorithm, and `exp`/`nbf`.
|
|
2650
|
+
* Throws {@link AppBridgeError} on any failure.
|
|
2651
|
+
*/
|
|
2652
|
+
declare function verifyClientJwt(token: string, clientSecret: string, clockToleranceSec?: number): Record<string, any>;
|
|
2653
|
+
/** Extract the token from an `Authorization: Bearer <token>` header. */
|
|
2654
|
+
declare function extractBearerToken(authorization: string | null | undefined): string | null;
|
|
2655
|
+
interface VerifyOptions {
|
|
2656
|
+
/** The `Authorization` header value from the incoming request. */
|
|
2657
|
+
authorization: string | null | undefined;
|
|
2658
|
+
/** Your OAuth2 client's secret (the signing key). */
|
|
2659
|
+
clientSecret: string;
|
|
2660
|
+
/** Allowed clock skew in seconds for exp/nbf. Default 60. */
|
|
2661
|
+
clockToleranceSec?: number;
|
|
2662
|
+
}
|
|
2663
|
+
/** Verify an `applicationTokenUrl` request and return the user + grant context. */
|
|
2664
|
+
declare function verifyAppTokenRequest(options: VerifyOptions): AppTokenRequestClaims;
|
|
2665
|
+
/** Verify an `applicationRevokeUrl` request and return the revocation context. */
|
|
2666
|
+
declare function verifyAppRevokeRequest(options: VerifyOptions): AppRevokeRequestClaims;
|
|
2667
|
+
/** What your `mintToken` returns: an access token and, ideally, its lifetime. */
|
|
2668
|
+
interface AppTokenResult {
|
|
2669
|
+
/** The access token your app minted (its own format). */
|
|
2670
|
+
token: string;
|
|
2671
|
+
/** Token lifetime in seconds; the platform surfaces it as `expires_in`. */
|
|
2672
|
+
expiresIn?: number;
|
|
2673
|
+
/** Optional human-readable message. */
|
|
2674
|
+
message?: string;
|
|
2675
|
+
}
|
|
2676
|
+
/**
|
|
2677
|
+
* The exact body shape the platform expects from `applicationTokenUrl`
|
|
2678
|
+
* (`{ success, token, message }`, plus optional `expiresIn`; no other keys).
|
|
2679
|
+
*/
|
|
2680
|
+
interface AppTokenResponseBody {
|
|
2681
|
+
success: boolean;
|
|
2682
|
+
token: string;
|
|
2683
|
+
message: string;
|
|
2684
|
+
expiresIn?: number;
|
|
2685
|
+
}
|
|
2686
|
+
/** Build a success body for `applicationTokenUrl`. */
|
|
2687
|
+
declare function appTokenSuccess(result: AppTokenResult): AppTokenResponseBody;
|
|
2688
|
+
/** Build a failure body for `applicationTokenUrl`. */
|
|
2689
|
+
declare function appTokenFailure(message: string): AppTokenResponseBody;
|
|
2690
|
+
/** The `{ status, body }` a framework-agnostic handler returns. */
|
|
2691
|
+
interface HandlerResult<T> {
|
|
2692
|
+
status: number;
|
|
2693
|
+
body: T;
|
|
2694
|
+
}
|
|
2695
|
+
/**
|
|
2696
|
+
* Verify an `applicationTokenUrl` request, mint via your callback, and return
|
|
2697
|
+
* the exact response the platform expects. Returns 401 with a failure body when
|
|
2698
|
+
* verification fails; errors thrown by `mintToken` propagate to you.
|
|
2699
|
+
*
|
|
2700
|
+
* @example
|
|
2701
|
+
* ```ts
|
|
2702
|
+
* const { status, body } = await handleAppTokenRequest({
|
|
2703
|
+
* authorization: req.headers.authorization,
|
|
2704
|
+
* clientSecret: process.env.BUILDBASE_CLIENT_SECRET!,
|
|
2705
|
+
* mintToken: (user) => ({ token: signMyJwt(user, { aud: user.resource }), expiresIn: 3600 }),
|
|
2706
|
+
* });
|
|
2707
|
+
* res.status(status).json(body);
|
|
2708
|
+
* ```
|
|
2709
|
+
*/
|
|
2710
|
+
declare function handleAppTokenRequest(options: {
|
|
2711
|
+
authorization: string | null | undefined;
|
|
2712
|
+
clientSecret: string;
|
|
2713
|
+
mintToken: (claims: AppTokenRequestClaims) => AppTokenResult | Promise<AppTokenResult>;
|
|
2714
|
+
clockToleranceSec?: number;
|
|
2715
|
+
}): Promise<HandlerResult<AppTokenResponseBody>>;
|
|
2716
|
+
/**
|
|
2717
|
+
* Verify an `applicationRevokeUrl` request and run your invalidation callback.
|
|
2718
|
+
* Returns 401 on verification failure; errors thrown by `onRevoke` propagate.
|
|
2719
|
+
*/
|
|
2720
|
+
declare function handleAppRevokeRequest(options: {
|
|
2721
|
+
authorization: string | null | undefined;
|
|
2722
|
+
clientSecret: string;
|
|
2723
|
+
onRevoke: (claims: AppRevokeRequestClaims) => void | Promise<void>;
|
|
2724
|
+
clockToleranceSec?: number;
|
|
2725
|
+
}): Promise<HandlerResult<{
|
|
2726
|
+
success: boolean;
|
|
2727
|
+
message?: string;
|
|
2728
|
+
}>>;
|
|
2729
|
+
/**
|
|
2730
|
+
* Build the 401 an agent should receive when it calls your protected API without
|
|
2731
|
+
* a valid token. The `WWW-Authenticate: Bearer resource_metadata=...` header
|
|
2732
|
+
* points the agent at your `/.well-known/oauth-protected-resource` document,
|
|
2733
|
+
* bootstrapping the OAuth discovery flow (RFC 9728 §5.1, RFC 6750 §3).
|
|
2734
|
+
*
|
|
2735
|
+
* @example
|
|
2736
|
+
* ```ts
|
|
2737
|
+
* if (!isValid(token)) {
|
|
2738
|
+
* const c = bearerChallenge({ resourceMetadataUrl: "https://imejis.io/.well-known/oauth-protected-resource" });
|
|
2739
|
+
* res.writeHead(c.status, c.headers).end(c.body);
|
|
2740
|
+
* }
|
|
2741
|
+
* ```
|
|
2742
|
+
*/
|
|
2743
|
+
declare function bearerChallenge(options: {
|
|
2744
|
+
resourceMetadataUrl: string;
|
|
2745
|
+
error?: 'invalid_token' | 'insufficient_scope' | string;
|
|
2746
|
+
errorDescription?: string;
|
|
2747
|
+
}): {
|
|
2748
|
+
status: number;
|
|
2749
|
+
headers: Record<string, string>;
|
|
2750
|
+
body: string;
|
|
2751
|
+
};
|
|
2752
|
+
|
|
2288
2753
|
interface BuildBaseConfig {
|
|
2289
2754
|
/** Base URL of the BuildBase API server */
|
|
2290
2755
|
serverUrl: string;
|
|
@@ -2569,5 +3034,5 @@ interface BuildBaseResult extends ScopedActions {
|
|
|
2569
3034
|
}
|
|
2570
3035
|
declare function BuildBase(config: BuildBaseConfig): BuildBaseResult;
|
|
2571
3036
|
|
|
2572
|
-
export { ApiVersion, AuthApi, AuthStatus, BBAction, BBScreen, BBStatus, BB_PARAM, BaseApi, BetaForm, BillingIntervals, BuildBase, CURRENCY_DISPLAY, CURRENCY_FLAG, CreditBucketSource, CreditBucketStatus, CreditTransactionType, DEFAULT_ROLE_PERMISSIONS, DunningState, EventEmitter, InvoiceStatuses, PLAN_CURRENCY_CODES, PLAN_CURRENCY_OPTIONS, PUSH_SERVICE_WORKER_SCRIPT, Permission, PushApi, SDKEvent, SettingsApi, SubscriptionItemType, SubscriptionStatus, UserApi, WorkspaceApi, calculateBillableSeats, calculateSeatOverageCents, calculateTotalSubscriptionCents, cleanBBParams, clearAuthIntent, consumeAuthIntent, createBBUrl, createCheckoutRedirectUrls, createCreditPurchaseRedirectUrls, BuildBase as default, eventEmitter, formatCents, formatOverageRate, formatOverageRateWithLabel, formatQuotaIncludedOverage, formatQuotaWithPrice, getAvailableCurrenciesFromPlans, getBasePriceCents, getBillingIntervalAndCurrencyFromPriceId, getCurrencyFlag, getCurrencySymbol, getDisplayCurrency, getPerSeatPriceCents, getPricingVariant, getQuotaDisplayValue, getQuotaDisplayWithVariant, getQuotaOverageCents, getQuotaUnitLabelFromName, getSeatPricing, getStripePriceIdForInterval, hasPermission, invalidateCreditBalance, invalidateQuotaUsage, invalidateSubscription, parseWebhookEvent, readBBParams, resolveMaxUsers, resolvePermissions, safeRedirect, saveAuthIntent, validateInvite, validateRedirectUrl, verifyWebhookSignature };
|
|
2573
|
-
export type { BBActionType, BBScreenType, BBStatusType, BetaFormData, BetaFormResponse, BillingInterval, BuildBaseConfig, BuildBaseResult, BuildBaseSession, CheckoutResult, CreditActions, CreditBucketSourceType, CreditBucketStatusType, CreditTransactionTypeValue, DunningStateType, EventData, EventType, FeatureActions, FormatQuotaWithPriceOptions, GetCheckoutStripeParams, IAllQuotaUsageResponse, IBaseApiConfig, IBasePricing, IBetaConfig, ICheckoutSessionRequest, ICheckoutSessionResponse, ICheckoutStripeOptions, IConsumeCreditsRequest, IConsumeCreditsResponse, ICreditBalance, ICreditBucket, ICreditBucketsQuery, ICreditBucketsResponse, ICreditPackage, ICreditPackagePricingVariant, ICreditPurchaseRequest, ICreditPurchaseResponse, ICreditTransaction, ICreditTransactionsQuery, ICreditTransactionsResponse, IEventCallbacks, IExpiringCreditsResponse, IInvoice, IInvoiceListResponse, IInvoiceResponse, IOsConfig, IOsState, IPlan, IPlanGroup, IPlanGroupInfo, IPlanGroupLatestVersion, IPlanGroupResponse, IPlanGroupVersion, IPlanGroupVersionWithPlans, IPlanGroupVersionsResponse, IPlanVersion, IPlanVersionSummary, IPlanVersionWithPlan, IPricingVariant, IPublicCreditPackage, IPublicCreditPackagesResponse, IPublicPlanItem, IPublicPlanItemCategory, IPublicPlanVersion, IPublicPlansResponse, IQuotaByInterval, IQuotaIntervalValue, IQuotaOveragePriceIdsByInterval, IQuotaOveragesByInterval, IQuotaUsageStatus, IQuotaUsageStatusResponse, IRecordUsageRequest, IRecordUsageResponse, IStripePricesByInterval, ISubscription, ISubscriptionItem, ISubscriptionResponse, ISubscriptionUpdateRequest, ISubscriptionUpdateResponse, IUsageLogEntry, IUsageLogsQuery, IUsageLogsResponse, InviteBlockReason, InviteValidation, InvoiceActions, InvoiceStatus, InvoiceStatusType, MaxUsersConfig, NotificationData, NotificationEvent, NotificationResult, OnWorkspaceChangeParams, PermissionActions, PermissionContext, PermissionKey, PlanActions, PlanVersionWithPricingVariants, QuotaDisplayValue, QuotaDisplayWithOverage, RolePermissionMap, ScopedActions, SettingsActions, SubscriptionActions, SubscriptionItemTypeValue, SubscriptionStatusType, UsageActions, UserActions, UserCreatedEventData, UserUpdatedEventData, WorkspaceActions, WorkspaceChangedEventData, WorkspaceCreatedEventData, WorkspaceDeletedEventData, WorkspaceUpdatedEventData, WorkspaceUserAddedEventData, WorkspaceUserRemovedEventData, WorkspaceUserRoleChangedEventData };
|
|
3037
|
+
export { ApiVersion, AppBridgeError, AuthApi, AuthStatus, BBAction, BBScreen, BBStatus, BB_PARAM, BaseApi, BetaForm, BillingIntervals, BuildBase, CURRENCY_DISPLAY, CURRENCY_FLAG, CreditBucketSource, CreditBucketStatus, CreditTransactionType, DEFAULT_ROLE_PERMISSIONS, DunningState, EventEmitter, InvoiceStatuses, PLAN_CURRENCY_CODES, PLAN_CURRENCY_OPTIONS, PUSH_SERVICE_WORKER_SCRIPT, Permission, PushApi, SDKEvent, SettingsApi, SubscriptionItemType, SubscriptionStatus, UserApi, WorkspaceApi, appTokenFailure, appTokenSuccess, bearerChallenge, buildAgentCard, buildAgentSkillsIndex, buildApiCatalog, buildAuthMd, buildLlmsTxt, buildMcpServerCard, buildProtectedResourceMetadata, buildSecurityTxt, buildSkillMd, calculateBillableSeats, calculateSeatOverageCents, calculateTotalSubscriptionCents, cleanBBParams, clearAgentReadinessCache, clearAuthIntent, consumeAuthIntent, createBBUrl, createCheckoutRedirectUrls, createCreditPurchaseRedirectUrls, BuildBase as default, eventEmitter, extractBearerToken, fetchAgentReadiness, formatCents, formatOverageRate, formatOverageRateWithLabel, formatQuotaIncludedOverage, formatQuotaWithPrice, getAvailableCurrenciesFromPlans, getBasePriceCents, getBillingIntervalAndCurrencyFromPriceId, getCurrencyFlag, getCurrencySymbol, getDisplayCurrency, getPerSeatPriceCents, getPricingVariant, getQuotaDisplayValue, getQuotaDisplayWithVariant, getQuotaOverageCents, getQuotaUnitLabelFromName, getSeatPricing, getStripePriceIdForInterval, handleAppRevokeRequest, handleAppTokenRequest, hasPermission, invalidateCreditBalance, invalidateQuotaUsage, invalidateSubscription, parseWebhookEvent, provideWebMcpTools, readBBParams, resolveMaxUsers, resolvePermissions, resolveWellKnown, safeRedirect, saveAuthIntent, sha256Digest, validateInvite, validateRedirectUrl, verifyAppRevokeRequest, verifyAppTokenRequest, verifyClientJwt, verifyWebhookSignature };
|
|
3038
|
+
export type { AgentReadinessBundle, AgentReadyConfig, AgentSkill, ApiCatalogApi, AppRevokeRequestClaims, AppTokenRequestClaims, AppTokenResponseBody, AppTokenResult, BBActionType, BBScreenType, BBStatusType, BetaFormData, BetaFormResponse, BillingInterval, BuildBaseConfig, BuildBaseResult, BuildBaseSession, CheckoutResult, CreditActions, CreditBucketSourceType, CreditBucketStatusType, CreditTransactionTypeValue, DiscoveryDocument, DunningStateType, EventData, EventType, FeatureActions, FormatQuotaWithPriceOptions, GetCheckoutStripeParams, HandlerResult, IAllQuotaUsageResponse, IBaseApiConfig, IBasePricing, IBetaConfig, ICheckoutSessionRequest, ICheckoutSessionResponse, ICheckoutStripeOptions, IConsumeCreditsRequest, IConsumeCreditsResponse, ICreditBalance, ICreditBucket, ICreditBucketsQuery, ICreditBucketsResponse, ICreditPackage, ICreditPackagePricingVariant, ICreditPurchaseRequest, ICreditPurchaseResponse, ICreditTransaction, ICreditTransactionsQuery, ICreditTransactionsResponse, IEventCallbacks, IExpiringCreditsResponse, IInvoice, IInvoiceListResponse, IInvoiceResponse, IOsConfig, IOsState, IPlan, IPlanGroup, IPlanGroupInfo, IPlanGroupLatestVersion, IPlanGroupResponse, IPlanGroupVersion, IPlanGroupVersionWithPlans, IPlanGroupVersionsResponse, IPlanVersion, IPlanVersionSummary, IPlanVersionWithPlan, IPricingVariant, IPublicCreditPackage, IPublicCreditPackagesResponse, IPublicPlanItem, IPublicPlanItemCategory, IPublicPlanVersion, IPublicPlansResponse, IQuotaByInterval, IQuotaIntervalValue, IQuotaOveragePriceIdsByInterval, IQuotaOveragesByInterval, IQuotaUsageStatus, IQuotaUsageStatusResponse, IRecordUsageRequest, IRecordUsageResponse, IStripePricesByInterval, ISubscription, ISubscriptionItem, ISubscriptionResponse, ISubscriptionUpdateRequest, ISubscriptionUpdateResponse, IUsageLogEntry, IUsageLogsQuery, IUsageLogsResponse, InviteBlockReason, InviteValidation, InvoiceActions, InvoiceStatus, InvoiceStatusType, MaxUsersConfig, McpServerCard, NotificationData, NotificationEvent, NotificationResult, OnWorkspaceChangeParams, PermissionActions, PermissionContext, PermissionKey, PlanActions, PlanVersionWithPricingVariants, QuotaDisplayValue, QuotaDisplayWithOverage, RolePermissionMap, ScopedActions, SettingsActions, SubscriptionActions, SubscriptionItemTypeValue, SubscriptionStatusType, UsageActions, UserActions, UserCreatedEventData, UserUpdatedEventData, WebMcpTool, WorkspaceActions, WorkspaceChangedEventData, WorkspaceCreatedEventData, WorkspaceDeletedEventData, WorkspaceUpdatedEventData, WorkspaceUserAddedEventData, WorkspaceUserRemovedEventData, WorkspaceUserRoleChangedEventData };
|