@kaperkunde/tokens 0.0.0-stage → 0.1.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 (50) hide show
  1. package/README.md +415 -2
  2. package/dist/browser-api.d.mts +56 -0
  3. package/dist/browser-api.mjs +75 -0
  4. package/dist/errors.d.mts +41 -0
  5. package/dist/errors.mjs +97 -0
  6. package/dist/index.d.mts +5 -0
  7. package/dist/index.mjs +5 -0
  8. package/dist/react/autorefill.d.mts +21 -0
  9. package/dist/react/autorefill.mjs +269 -0
  10. package/dist/react/balance.d.mts +23 -0
  11. package/dist/react/balance.mjs +116 -0
  12. package/dist/react/buy.d.mts +27 -0
  13. package/dist/react/buy.mjs +175 -0
  14. package/dist/react/history.d.mts +23 -0
  15. package/dist/react/history.mjs +102 -0
  16. package/dist/react/hooks.d.mts +52 -0
  17. package/dist/react/hooks.mjs +150 -0
  18. package/dist/react/index.d.mts +11 -0
  19. package/dist/react/index.mjs +10 -0
  20. package/dist/react/labels.d.mts +114 -0
  21. package/dist/react/labels.mjs +125 -0
  22. package/dist/react/own-model.d.mts +31 -0
  23. package/dist/react/own-model.mjs +358 -0
  24. package/dist/react/ui.d.mts +61 -0
  25. package/dist/react/ui.mjs +128 -0
  26. package/dist/react/usage.d.mts +21 -0
  27. package/dist/react/usage.mjs +137 -0
  28. package/dist/server/client.d.mts +76 -0
  29. package/dist/server/client.mjs +137 -0
  30. package/dist/server/error-of.d.mts +12 -0
  31. package/dist/server/error-of.mjs +63 -0
  32. package/dist/server/gateway.d.mts +62 -0
  33. package/dist/server/gateway.mjs +110 -0
  34. package/dist/server/index.d.mts +7 -0
  35. package/dist/server/index.mjs +7 -0
  36. package/dist/server/node.d.mts +23 -0
  37. package/dist/server/node.mjs +81 -0
  38. package/dist/server/routes.d.mts +56 -0
  39. package/dist/server/routes.mjs +257 -0
  40. package/dist/server/webhook.d.mts +47 -0
  41. package/dist/server/webhook.mjs +99 -0
  42. package/dist/styles.css +380 -0
  43. package/dist/types.d.mts +635 -0
  44. package/dist/types.mjs +142 -0
  45. package/dist/units.d.mts +37 -0
  46. package/dist/units.mjs +76 -0
  47. package/package.json +73 -4
  48. package/stub/cli.mjs +8 -0
  49. package/stub/server.d.mts +36 -0
  50. package/stub/server.mjs +1385 -0
@@ -0,0 +1,110 @@
1
+ import { TOKEN_HEADERS } from "../types.mjs";
2
+ // src/server/gateway.ts
3
+ /** `https://center/` and `https://center/v1` both mean `https://center`. */
4
+ const trimBaseUrl = (baseUrl) => baseUrl.replace(/\/+$/, "").replace(/\/v1$/, "");
5
+ const enc = (value) => encodeURIComponent(value.slice(0, 200));
6
+ /**
7
+ * The `x-token-*` request headers: who pays and what the call is for. Values
8
+ * are `encodeURIComponent`-encoded (an activity line names characters) and cut
9
+ * to 200 characters, as the center decodes them. Merge per call into the AI
10
+ * SDK's `headers` option; the app key rides on the provider, not here.
11
+ */
12
+ function gatewayHeaders(input) {
13
+ if (!input.user) throw new Error("gatewayHeaders: user is required.");
14
+ const headers = { [TOKEN_HEADERS.user]: enc(input.user) };
15
+ if (input.email) headers[TOKEN_HEADERS.email] = enc(input.email);
16
+ const a = input.attribution ?? {};
17
+ for (const key of [
18
+ "purpose",
19
+ "activity",
20
+ "scope",
21
+ "job",
22
+ "subject",
23
+ "correlation"
24
+ ]) if (a[key]) headers[TOKEN_HEADERS[key]] = enc(a[key]);
25
+ if (input.backend && input.backend !== "tokens") headers[TOKEN_HEADERS.backend] = input.backend;
26
+ if (input.trailer) headers[TOKEN_HEADERS.trailer] = "event";
27
+ return headers;
28
+ }
29
+ /**
30
+ * Provider settings pointing an AI SDK provider at the center:
31
+ *
32
+ * ```ts
33
+ * createAnthropic(gatewayConfig({ baseUrl, apiKey, user: host.id }))
34
+ * createOpenAICompatible({ name: "tokens", ...gatewayConfig({ … }) })
35
+ * ```
36
+ *
37
+ * Providers are cheap to make, so make one per payer. For attribution that
38
+ * changes per call (purpose, activity, job) pass `gatewayHeaders({ … })` as
39
+ * the call's `headers` instead, or build the provider per call.
40
+ */
41
+ function gatewayConfig(input) {
42
+ const { baseUrl, apiKey, ...rest } = input;
43
+ return {
44
+ baseURL: `${trimBaseUrl(baseUrl)}/v1`,
45
+ apiKey,
46
+ headers: gatewayHeaders(rest)
47
+ };
48
+ }
49
+ function headerOf(headers, name) {
50
+ if (typeof headers.get === "function") return headers.get(name) ?? null;
51
+ const record = headers;
52
+ for (const key of Object.keys(record)) if (key.toLowerCase() === name) {
53
+ const value = record[key];
54
+ return (Array.isArray(value) ? value[0] : value) ?? null;
55
+ }
56
+ return null;
57
+ }
58
+ const micros = (value) => {
59
+ if (value === null || value === "") return null;
60
+ const n = Number(value);
61
+ return Number.isFinite(n) ? n : null;
62
+ };
63
+ /** The call id a gateway response carries up front (streams have it before any cost is known), or `null`. */
64
+ function callIdFromHeaders(headers) {
65
+ return headerOf(headers, TOKEN_HEADERS.callId);
66
+ }
67
+ /**
68
+ * The charge from a non-streamed response's headers (`x-token-call-id`,
69
+ * `-source`, `-model`, `-cost-micros`, `-fee-micros`, `-charged-micros`,
70
+ * `-balance-micros`), or `null` when the answer did not come through the
71
+ * gateway or carries no cost yet (a stream: take the id with
72
+ * {@link callIdFromHeaders}, then `center.call(id, { wait })` or the opt-in
73
+ * trailer, {@link parseTrailer}). Accepts `Headers`, a Node header record, or
74
+ * the AI SDK's `response.headers`.
75
+ */
76
+ function chargeFromHeaders(headers) {
77
+ const callId = callIdFromHeaders(headers);
78
+ const cost = micros(headerOf(headers, TOKEN_HEADERS.costMicros));
79
+ const fee = micros(headerOf(headers, TOKEN_HEADERS.feeMicros));
80
+ const charged = micros(headerOf(headers, TOKEN_HEADERS.chargedMicros));
81
+ const balance = micros(headerOf(headers, TOKEN_HEADERS.balanceMicros));
82
+ const source = headerOf(headers, TOKEN_HEADERS.source);
83
+ const model = headerOf(headers, TOKEN_HEADERS.model);
84
+ if (!callId || cost === null || fee === null || charged === null || balance === null || source !== "tokens" && source !== "own" || !model) return null;
85
+ return {
86
+ callId,
87
+ source,
88
+ model,
89
+ costMicros: cost,
90
+ feeMicros: fee,
91
+ chargedMicros: charged,
92
+ balanceAfterMicros: balance
93
+ };
94
+ }
95
+ /** The `event: token_center` trailer of a stream read as text, parsed; `null` when absent. */
96
+ function parseTrailer(sse) {
97
+ const blocks = sse.split(/\r?\n\r?\n/);
98
+ for (let i = blocks.length - 1; i >= 0; i--) {
99
+ const block = blocks[i];
100
+ if (!/^event:\s*token_center\s*$/m.test(block)) continue;
101
+ const data = [...block.matchAll(/^data:\s?(.*)$/gm)].map((m) => m[1]).join("\n");
102
+ try {
103
+ return JSON.parse(data);
104
+ } catch {
105
+ return null;
106
+ }
107
+ }
108
+ return null;
109
+ }
110
+ export { callIdFromHeaders, chargeFromHeaders, gatewayConfig, gatewayHeaders, parseTrailer, trimBaseUrl };
@@ -0,0 +1,7 @@
1
+ import { CallsFilter, SpeechResult, TokenCenter, TokenCenterOptions, createTokenCenter } from "./client.mjs";
2
+ import { GatewayConfig, GatewayConfigInput, GatewayHeaderInput, callIdFromHeaders, chargeFromHeaders, gatewayConfig, gatewayHeaders, parseTrailer, trimBaseUrl } from "./gateway.mjs";
3
+ import { tokenErrorOf } from "./error-of.mjs";
4
+ import { VerifyWebhookOptions, WebhookFailure, WebhookHandlers, WebhookRouteOptions, WebhookVerificationError, parseWebhookEvent, signWebhook, verifyWebhook, webhookRoute } from "./webhook.mjs";
5
+ import { ReturnKind, TokenRoutesOptions, TokenUser, safeReturnPath, tokenRoutes } from "./routes.mjs";
6
+ import { NodeHandlerOptions, nodeHandler, requestFromNode, sendResponse } from "./node.mjs";
7
+ export { CallsFilter, GatewayConfig, GatewayConfigInput, GatewayHeaderInput, NodeHandlerOptions, ReturnKind, SpeechResult, TokenCenter, TokenCenterOptions, TokenRoutesOptions, TokenUser, VerifyWebhookOptions, WebhookFailure, WebhookHandlers, WebhookRouteOptions, WebhookVerificationError, callIdFromHeaders, chargeFromHeaders, createTokenCenter, gatewayConfig, gatewayHeaders, nodeHandler, parseTrailer, parseWebhookEvent, requestFromNode, safeReturnPath, sendResponse, signWebhook, tokenErrorOf, tokenRoutes, trimBaseUrl, verifyWebhook, webhookRoute };
@@ -0,0 +1,7 @@
1
+ import { createTokenCenter } from "./client.mjs";
2
+ import { callIdFromHeaders, chargeFromHeaders, gatewayConfig, gatewayHeaders, parseTrailer, trimBaseUrl } from "./gateway.mjs";
3
+ import { tokenErrorOf } from "./error-of.mjs";
4
+ import { WebhookVerificationError, parseWebhookEvent, signWebhook, verifyWebhook, webhookRoute } from "./webhook.mjs";
5
+ import { safeReturnPath, tokenRoutes } from "./routes.mjs";
6
+ import { nodeHandler, requestFromNode, sendResponse } from "./node.mjs";
7
+ export { WebhookVerificationError, callIdFromHeaders, chargeFromHeaders, createTokenCenter, gatewayConfig, gatewayHeaders, nodeHandler, parseTrailer, parseWebhookEvent, requestFromNode, safeReturnPath, sendResponse, signWebhook, tokenErrorOf, tokenRoutes, trimBaseUrl, verifyWebhook, webhookRoute };
@@ -0,0 +1,23 @@
1
+ import { IncomingMessage, ServerResponse } from "node:http";
2
+ export type NodeHandlerOptions = {
3
+ /** Trust `x-forwarded-proto` / `x-forwarded-host` for the request's URL (behind your own proxy). Default true. */
4
+ trustForwarded?: boolean;
5
+ };
6
+ /** A Node `IncomingMessage` as a Web `Request`. */
7
+ export declare function requestFromNode(req: IncomingMessage, options?: NodeHandlerOptions): Promise<Request>;
8
+ /** Write a Web `Response` to a Node `ServerResponse`. */
9
+ export declare function sendResponse(response: Response, res: ServerResponse): Promise<void>;
10
+ /**
11
+ * Bridge a Web handler (`tokenRoutes(…)`, `webhookRoute(…)`) into a Next
12
+ * **pages router** API route:
13
+ *
14
+ * ```ts
15
+ * // pages/api/tokens/[...op].ts
16
+ * export const config = { api: { bodyParser: false } }
17
+ * export default nodeHandler(tokenRoutes(center, { userOf }))
18
+ * ```
19
+ *
20
+ * Turn the body parser off for a webhook (the signature is over the raw
21
+ * bytes); for `tokenRoutes` it may stay on, a parsed body is re-serialised.
22
+ */
23
+ export declare function nodeHandler(handler: (request: Request) => Promise<Response> | Response, options?: NodeHandlerOptions): (req: IncomingMessage, res: ServerResponse) => Promise<void>;
@@ -0,0 +1,81 @@
1
+ // src/server/node.ts
2
+ async function readBody(req) {
3
+ const parsed = req.body;
4
+ if (parsed !== void 0 && parsed !== null) {
5
+ if (typeof parsed === "string") return parsed;
6
+ if (parsed instanceof Uint8Array) return parsed;
7
+ if (typeof parsed === "object" && Object.keys(parsed).length === 0 && req.readableEnded) return void 0;
8
+ return JSON.stringify(parsed);
9
+ }
10
+ const chunks = [];
11
+ for await (const chunk of req) chunks.push(Buffer.from(chunk));
12
+ return chunks.length ? Buffer.concat(chunks) : void 0;
13
+ }
14
+ /** A Node `IncomingMessage` as a Web `Request`. */
15
+ async function requestFromNode(req, options = {}) {
16
+ const first = (v) => (Array.isArray(v) ? v[0] : v)?.split(",")[0]?.trim();
17
+ const trust = options.trustForwarded !== false;
18
+ const proto = trust && first(req.headers["x-forwarded-proto"]) || (req.socket.encrypted ? "https" : "http");
19
+ const host = trust && first(req.headers["x-forwarded-host"]) || req.headers.host || "localhost";
20
+ const headers = new Headers();
21
+ for (const [key, value] of Object.entries(req.headers)) {
22
+ if (value === void 0) continue;
23
+ if (Array.isArray(value)) for (const v of value) headers.append(key, v);
24
+ else headers.set(key, value);
25
+ }
26
+ const method = req.method ?? "GET";
27
+ const body = method === "GET" || method === "HEAD" ? void 0 : await readBody(req);
28
+ return new Request(`${proto}://${host}${req.url ?? "/"}`, {
29
+ method,
30
+ headers,
31
+ body
32
+ });
33
+ }
34
+ /** Write a Web `Response` to a Node `ServerResponse`. */
35
+ async function sendResponse(response, res) {
36
+ res.statusCode = response.status;
37
+ response.headers.forEach((value, key) => {
38
+ if (key.toLowerCase() !== "set-cookie") res.setHeader(key, value);
39
+ });
40
+ const cookies = response.headers.getSetCookie?.() ?? [];
41
+ if (cookies.length) res.setHeader("set-cookie", cookies);
42
+ if (!response.body) return void res.end();
43
+ const reader = response.body.getReader();
44
+ for (;;) {
45
+ const { done, value } = await reader.read();
46
+ if (done) break;
47
+ res.write(value);
48
+ }
49
+ res.end();
50
+ }
51
+ /**
52
+ * Bridge a Web handler (`tokenRoutes(…)`, `webhookRoute(…)`) into a Next
53
+ * **pages router** API route:
54
+ *
55
+ * ```ts
56
+ * // pages/api/tokens/[...op].ts
57
+ * export const config = { api: { bodyParser: false } }
58
+ * export default nodeHandler(tokenRoutes(center, { userOf }))
59
+ * ```
60
+ *
61
+ * Turn the body parser off for a webhook (the signature is over the raw
62
+ * bytes); for `tokenRoutes` it may stay on, a parsed body is re-serialised.
63
+ */
64
+ function nodeHandler(handler, options = {}) {
65
+ return async (req, res) => {
66
+ try {
67
+ await sendResponse(await handler(await requestFromNode(req, options)), res);
68
+ } catch (error) {
69
+ console.error("[tokens] handler failed", error);
70
+ if (!res.headersSent) {
71
+ res.statusCode = 500;
72
+ res.setHeader("content-type", "application/json");
73
+ }
74
+ res.end(JSON.stringify({ error: {
75
+ code: "internal_error",
76
+ message: "Something went wrong."
77
+ } }));
78
+ }
79
+ };
80
+ }
81
+ export { nodeHandler, requestFromNode, sendResponse };
@@ -0,0 +1,56 @@
1
+ import { TokenCenter } from "./client.mjs";
2
+ /** The signed-in person a request belongs to, as the app knows them. */
3
+ export type TokenUser = {
4
+ /** The app's own user id: the payer. */
5
+ id: string;
6
+ /** The **verified** email, stored on the center's user row. Leave out if unverified. */
7
+ email?: string | null;
8
+ displayName?: string | null;
9
+ };
10
+ export type ReturnKind = "checkout" | "card";
11
+ export type TokenRoutesOptions = {
12
+ /**
13
+ * Who is asking: read the app's own session off the request (cookie or
14
+ * bearer). `null` answers 401. The browser never says who it is, so no
15
+ * body or query can name another user.
16
+ */
17
+ userOf: (request: Request) => TokenUser | null | Promise<TokenUser | null>;
18
+ /** Where the handler is mounted, to find the operation in the URL. Default `/api/tokens`. */
19
+ basePath?: string;
20
+ /**
21
+ * The app's public origin for the return URLs Stripe sends the browser back
22
+ * to (must be one of the app's registered `returnOrigins` on the center).
23
+ * Set it behind a proxy: the request's own URL may be an internal one.
24
+ */
25
+ origin?: string | ((request: Request) => string);
26
+ /** Replace the default return URLs (`<origin><returnPath>?tokens=…`). */
27
+ returnUrls?: (context: {
28
+ request: Request;
29
+ kind: ReturnKind;
30
+ returnPath: string;
31
+ origin: string;
32
+ }) => {
33
+ successUrl: string;
34
+ cancelUrl: string;
35
+ };
36
+ /** Keep the center's user row (email, name) up to date on first sight. Default true. */
37
+ syncUser?: boolean;
38
+ };
39
+ /** Only a path on this app's own origin comes back as a return path. */
40
+ export declare function safeReturnPath(value: unknown): string;
41
+ /**
42
+ * The browser-facing half of the center, for an app to mount: a Web
43
+ * `Request → Response` handler that authenticates the **app's own** session
44
+ * (`userOf`), puts that user in, and calls the center with the app key, so the
45
+ * browser never holds the key and can never name another user.
46
+ *
47
+ * Operations (under `basePath`, default `/api/tokens`):
48
+ * `GET app | models | balance | calls | history | sale-prices | autorefill |
49
+ * own-endpoint | purchase/:id`, `POST checkout | card | own-endpoint/test`,
50
+ * `PUT autorefill | own-endpoint | backend-order`, `DELETE card | own-endpoint`.
51
+ *
52
+ * App router: `export const GET = handler` (and POST, PUT, DELETE) in
53
+ * `app/api/tokens/[...op]/route.ts`. Pages router: wrap with `nodeHandler`
54
+ * (`@kaperkunde/tokens/server`).
55
+ */
56
+ export declare function tokenRoutes(center: TokenCenter, options: TokenRoutesOptions): (request: Request) => Promise<Response>;
@@ -0,0 +1,257 @@
1
+ import { TokenCenterError, isTokenError } from "../errors.mjs";
2
+ // src/server/routes.ts
3
+ const CURRENCIES = ["eur", "usd"];
4
+ const ORDERS = [
5
+ "tokens_then_own",
6
+ "own_then_tokens",
7
+ "tokens_only",
8
+ "own_only"
9
+ ];
10
+ const bad = (message, path) => new TokenCenterError({
11
+ code: "invalid_request",
12
+ message,
13
+ ...path ? { path } : {}
14
+ });
15
+ /** Only a path on this app's own origin comes back as a return path. */
16
+ function safeReturnPath(value) {
17
+ return typeof value === "string" && /^\/(?![/\\])/.test(value) ? value : "/";
18
+ }
19
+ const withQuery = (path, query) => `${path}${path.includes("?") ? "&" : "?"}${query}`;
20
+ const pick = (source, keys) => Object.fromEntries(keys.filter((k) => source[k] !== void 0).map((k) => [k, source[k]]));
21
+ /**
22
+ * The browser-facing half of the center, for an app to mount: a Web
23
+ * `Request → Response` handler that authenticates the **app's own** session
24
+ * (`userOf`), puts that user in, and calls the center with the app key, so the
25
+ * browser never holds the key and can never name another user.
26
+ *
27
+ * Operations (under `basePath`, default `/api/tokens`):
28
+ * `GET app | models | balance | calls | history | sale-prices | autorefill |
29
+ * own-endpoint | purchase/:id`, `POST checkout | card | own-endpoint/test`,
30
+ * `PUT autorefill | own-endpoint | backend-order`, `DELETE card | own-endpoint`.
31
+ *
32
+ * App router: `export const GET = handler` (and POST, PUT, DELETE) in
33
+ * `app/api/tokens/[...op]/route.ts`. Pages router: wrap with `nodeHandler`
34
+ * (`@kaperkunde/tokens/server`).
35
+ */
36
+ function tokenRoutes(center, options) {
37
+ const basePath = (options.basePath ?? "/api/tokens").replace(/\/+$/, "");
38
+ const synced = /* @__PURE__ */ new Map();
39
+ const routes = {
40
+ app: { GET: ({ center }) => center.app() },
41
+ models: { GET: async ({ center }) => ({ models: await center.models() }) },
42
+ balance: { GET: ({ center, user }) => center.balance(user.id) },
43
+ calls: { GET: ({ center, user, query }) => {
44
+ const q = {};
45
+ const limit = Number(query.get("limit"));
46
+ if (query.has("limit")) {
47
+ if (!Number.isInteger(limit) || limit < 1 || limit > 200) throw bad("limit must be 1..200.", "limit");
48
+ q.limit = limit;
49
+ }
50
+ for (const k of [
51
+ "cursor",
52
+ "since",
53
+ "scope",
54
+ "job",
55
+ "correlation",
56
+ "purpose"
57
+ ]) {
58
+ const v = query.get(k);
59
+ if (v) q[k] = v;
60
+ }
61
+ const source = query.get("source");
62
+ if (source === "tokens" || source === "own") q.source = source;
63
+ return center.calls(user.id, q);
64
+ } },
65
+ history: { GET: ({ center, user, query }) => {
66
+ const limit = Number(query.get("limit"));
67
+ return center.history(user.id, {
68
+ ...query.has("limit") && Number.isInteger(limit) && limit > 0 ? { limit: Math.min(limit, 200) } : {},
69
+ ...query.get("cursor") ? { cursor: query.get("cursor") } : {}
70
+ });
71
+ } },
72
+ "sale-prices": { GET: ({ center }) => center.salePrices() },
73
+ purchase: { GET: ({ center, user, segments }) => {
74
+ if (!segments[1]) throw bad("A purchase id is needed.", "purchaseId");
75
+ return center.purchase(user.id, decodeURIComponent(segments[1]));
76
+ } },
77
+ checkout: { POST: async ({ center, user, body, returnUrls, idempotencyKey }) => {
78
+ const b = await body();
79
+ if (typeof b.currency !== "string" || !CURRENCIES.includes(b.currency)) throw bad("currency must be eur or usd.", "currency");
80
+ if (!Number.isInteger(b.amountCents) || b.amountCents <= 0) throw bad("amountCents must be a positive whole number of cents.", "amountCents");
81
+ const urls = returnUrls("checkout", b.returnPath);
82
+ const session = await center.checkout(user.id, {
83
+ currency: b.currency,
84
+ amountCents: b.amountCents,
85
+ ...urls,
86
+ ...b.saveCard === true ? { saveCard: true } : {},
87
+ ...typeof b.locale === "string" ? { locale: b.locale } : {}
88
+ }, { idempotencyKey });
89
+ return new Response(JSON.stringify(session), {
90
+ status: 201,
91
+ headers: { "content-type": "application/json" }
92
+ });
93
+ } },
94
+ autorefill: {
95
+ GET: ({ center, user }) => center.autoRefill(user.id),
96
+ PUT: async ({ center, user, body }) => center.setAutoRefill(user.id, pick(await body(), [
97
+ "enabled",
98
+ "thresholdMicros",
99
+ "amountCents",
100
+ "currency",
101
+ "monthlyMaxCents"
102
+ ]))
103
+ },
104
+ card: {
105
+ POST: async ({ center, user, body, returnUrls, idempotencyKey }) => {
106
+ const b = await body();
107
+ if (b.currency !== void 0 && !CURRENCIES.includes(String(b.currency))) throw bad("currency must be eur or usd.", "currency");
108
+ const session = await center.setupCard(user.id, {
109
+ ...returnUrls("card", b.returnPath),
110
+ ...b.currency ? { currency: b.currency } : {}
111
+ }, { idempotencyKey });
112
+ return new Response(JSON.stringify(session), {
113
+ status: 201,
114
+ headers: { "content-type": "application/json" }
115
+ });
116
+ },
117
+ DELETE: async ({ center, user }) => {
118
+ await center.removeCard(user.id);
119
+ return new Response(null, { status: 204 });
120
+ }
121
+ },
122
+ "own-endpoint": {
123
+ GET: async ({ center, user, segments }) => {
124
+ if (segments[1]) return void 0;
125
+ return await center.ownEndpoint(user.id);
126
+ },
127
+ PUT: async ({ center, user, body }) => center.saveOwnEndpoint(user.id, pick(await body(), [
128
+ "baseUrl",
129
+ "apiKey",
130
+ "models",
131
+ "defaultModel",
132
+ "capabilities",
133
+ "toolChoice",
134
+ "monthlyTokenLimit",
135
+ "order"
136
+ ])),
137
+ DELETE: async ({ center, user }) => {
138
+ await center.removeOwnEndpoint(user.id);
139
+ return new Response(null, { status: 204 });
140
+ },
141
+ POST: async ({ center, user, segments }) => {
142
+ if (segments[1] !== "test") return void 0;
143
+ return center.testOwnEndpoint(user.id);
144
+ }
145
+ },
146
+ "backend-order": { PUT: async ({ center, user, body }) => {
147
+ const { order } = await body();
148
+ if (typeof order !== "string" || !ORDERS.includes(order)) throw bad("order is not one of the four orders.", "order");
149
+ return center.setBackendOrder(user.id, { order });
150
+ } }
151
+ };
152
+ const originOf = (request) => typeof options.origin === "function" ? options.origin(request) : options.origin ?? new URL(request.url).origin;
153
+ const json = (status, body, headers = {}) => new Response(status === 204 ? null : JSON.stringify(body), {
154
+ status,
155
+ headers: {
156
+ "content-type": "application/json",
157
+ "cache-control": "no-store",
158
+ ...headers
159
+ }
160
+ });
161
+ const fail = (detail, status, headers) => json(status, { error: detail }, {
162
+ "x-token-error": detail.code,
163
+ ...headers
164
+ });
165
+ return async (request) => {
166
+ try {
167
+ const url = new URL(request.url);
168
+ let path = url.pathname;
169
+ if (path.startsWith(basePath)) path = path.slice(basePath.length);
170
+ else {
171
+ const parts = path.split("/").filter(Boolean);
172
+ const at = parts.findIndex((p) => p in routes);
173
+ path = at < 0 ? "" : "/" + parts.slice(at).join("/");
174
+ }
175
+ const segments = path.split("/").filter(Boolean);
176
+ const route = segments[0] && Object.hasOwn(routes, segments[0]) ? routes[segments[0]] : void 0;
177
+ if (!route) return fail({
178
+ code: "not_found",
179
+ message: "No such endpoint."
180
+ }, 404);
181
+ const handler = route[request.method];
182
+ if (!handler) return fail({
183
+ code: "invalid_request",
184
+ message: "Method not allowed."
185
+ }, 405, { allow: Object.keys(route).join(", ") });
186
+ const user = await options.userOf(request);
187
+ if (!user?.id) return fail({
188
+ code: "unauthenticated",
189
+ message: "Sign in to continue."
190
+ }, 401);
191
+ if (options.syncUser !== false && (user.email || user.displayName)) {
192
+ const stamp = `${user.email ?? ""}\n${user.displayName ?? ""}`;
193
+ if (synced.get(user.id) !== stamp) try {
194
+ await center.upsertUser(user.id, {
195
+ ...user.email ? { email: user.email } : {},
196
+ ...user.displayName ? { displayName: user.displayName } : {}
197
+ });
198
+ synced.set(user.id, stamp);
199
+ } catch {}
200
+ }
201
+ const origin = originOf(request);
202
+ const out = await handler({
203
+ request,
204
+ user,
205
+ center,
206
+ query: url.searchParams,
207
+ segments,
208
+ idempotencyKey: request.headers.get("idempotency-key") ?? void 0,
209
+ body: async () => {
210
+ let parsed;
211
+ try {
212
+ parsed = await request.json();
213
+ } catch {
214
+ throw bad("Body is not JSON.");
215
+ }
216
+ if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) throw bad("Body must be a JSON object.");
217
+ return parsed;
218
+ },
219
+ returnUrls: (kind, returnPath) => {
220
+ const safe = safeReturnPath(returnPath);
221
+ if (options.returnUrls) return options.returnUrls({
222
+ request,
223
+ kind,
224
+ returnPath: safe,
225
+ origin
226
+ });
227
+ return kind === "checkout" ? {
228
+ successUrl: `${origin}${withQuery(safe, "tokens=purchased&purchase={PURCHASE_ID}")}`,
229
+ cancelUrl: `${origin}${withQuery(safe, "tokens=cancelled")}`
230
+ } : {
231
+ successUrl: `${origin}${withQuery(safe, "tokens=card")}`,
232
+ cancelUrl: `${origin}${withQuery(safe, "tokens=cancelled")}`
233
+ };
234
+ }
235
+ });
236
+ if (out === void 0) return fail({
237
+ code: "not_found",
238
+ message: "No such endpoint."
239
+ }, 404);
240
+ if (out instanceof Response) return out;
241
+ return json(200, out);
242
+ } catch (error) {
243
+ if (isTokenError(error)) {
244
+ const headers = {};
245
+ if (error.detail.retryAfterSeconds) headers["retry-after"] = String(error.detail.retryAfterSeconds);
246
+ if (error.detail.callId) headers["x-token-call-id"] = error.detail.callId;
247
+ return fail(error.detail, error.status, headers);
248
+ }
249
+ console.error("[tokens] route failed", error);
250
+ return fail({
251
+ code: "internal_error",
252
+ message: "Something went wrong."
253
+ }, 500);
254
+ }
255
+ };
256
+ }
257
+ export { safeReturnPath, tokenRoutes };
@@ -0,0 +1,47 @@
1
+ import { WebhookEvent, WebhookEventType } from "../types.mjs";
2
+ export type WebhookFailure = "malformed" | "signature" | "stale" | "body";
3
+ /** The delivery is not from the center, is too old, or is not an event. Answer 400. */
4
+ export declare class WebhookVerificationError extends Error {
5
+ readonly reason: WebhookFailure;
6
+ constructor(reason: WebhookFailure, message: string);
7
+ }
8
+ /** `t=<unix>,v1=<hex HMAC-SHA256(secret, "<t>.<rawBody>")>`, as the center signs it. */
9
+ export declare function signWebhook(rawBody: string, secret: string, timestamp?: number): string;
10
+ export type VerifyWebhookOptions = {
11
+ /** Default 300 (`WEBHOOK_TOLERANCE_SECONDS`). */
12
+ toleranceSeconds?: number;
13
+ /** Unix seconds; for tests. */
14
+ now?: number;
15
+ };
16
+ /**
17
+ * Check a delivery and return its typed event. `rawBody` must be the bytes as
18
+ * received (not re-serialised JSON); `signatureHeader` the `token-signature`
19
+ * header; `secret` the app's webhook secret (an array while rotating: any one
20
+ * that matches is enough). Throws `WebhookVerificationError` on a malformed
21
+ * header, a wrong signature (constant-time compare), a timestamp more than the
22
+ * tolerance from now, or a body that is not a known event.
23
+ *
24
+ * Deliveries repeat and arrive out of order: handlers dedupe on `event.id`.
25
+ */
26
+ export declare function verifyWebhook(rawBody: string | Uint8Array, signatureHeader: string | null | undefined, secret: string | readonly string[], options?: VerifyWebhookOptions): WebhookEvent;
27
+ /** A body that is a known webhook event, typed; throws `WebhookVerificationError("body")` otherwise. */
28
+ export declare function parseWebhookEvent(body: string | unknown): WebhookEvent;
29
+ export type WebhookHandlers = { [T in WebhookEventType]?: (event: Extract<WebhookEvent, {
30
+ type: T;
31
+ }>) => void | Promise<void>; };
32
+ export type WebhookRouteOptions = {
33
+ /** The app's webhook secret (a function, so env is read at request time; an array while rotating). */
34
+ secret: string | readonly string[] | (() => string | readonly string[]);
35
+ /** One handler per event type; types without one are acknowledged and ignored. Idempotent on `event.id`. */
36
+ handlers: WebhookHandlers;
37
+ toleranceSeconds?: number;
38
+ /** Where a handler's failure goes (it answers 500 so the center retries). */
39
+ onError?: (error: unknown, event: WebhookEvent) => void;
40
+ };
41
+ /**
42
+ * A Web `Request → Response` handler for the center's webhook: verifies, calls
43
+ * the handler for the type, answers 200 (even for a type with no handler),
44
+ * 400 for a bad signature or body and 500 when a handler throws (the center
45
+ * retries 1 m … 24 h, so a handler must be idempotent on `event.id`).
46
+ */
47
+ export declare function webhookRoute(options: WebhookRouteOptions): (request: Request) => Promise<Response>;