@usebillow/sdk 0.8.0 → 0.10.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +22 -0
- package/dist/{billing-B-VyZCXV.d.cts → billing-8ug1Gw05.d.cts} +14 -10
- package/dist/{billing-CgjcWmvb.d.ts → billing-Bs10EcjR.d.ts} +14 -10
- package/dist/{billing-status-BZQN_gm7.d.cts → billing-status-DZkB0VPK.d.cts} +5 -5
- package/dist/{billing-status-BZQN_gm7.d.ts → billing-status-DZkB0VPK.d.ts} +5 -5
- package/dist/{chunk-CCG4F5FK.js → chunk-47J7FYM5.js} +2 -2
- package/dist/chunk-47J7FYM5.js.map +1 -0
- package/dist/{chunk-J6JIZGWB.js → chunk-XKN7ZRAR.js} +81 -22
- package/dist/chunk-XKN7ZRAR.js.map +1 -0
- package/dist/config.cjs +3 -3
- package/dist/config.cjs.map +1 -1
- package/dist/config.d.cts +10 -10
- package/dist/config.d.ts +10 -10
- package/dist/config.js +3 -3
- package/dist/config.js.map +1 -1
- package/dist/{hosted-domains-BbuyxnuH.d.cts → hosted-domains-Ci6jeNAe.d.cts} +124 -17
- package/dist/{hosted-domains-BP91tg9P.d.ts → hosted-domains-DSs5Iw9U.d.ts} +124 -17
- package/dist/index.cjs +79 -20
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +89 -55
- package/dist/index.d.ts +89 -55
- package/dist/index.js +2 -2
- package/dist/ingestion.cjs.map +1 -1
- package/dist/ingestion.d.cts +19 -19
- package/dist/ingestion.d.ts +19 -19
- package/dist/ingestion.js.map +1 -1
- package/dist/react.cjs +28 -5
- package/dist/react.cjs.map +1 -1
- package/dist/react.d.cts +7 -7
- package/dist/react.d.ts +7 -7
- package/dist/react.js +2 -2
- package/dist/react.js.map +1 -1
- package/dist/server.cjs.map +1 -1
- package/dist/server.d.cts +12 -12
- package/dist/server.d.ts +12 -12
- package/dist/server.js.map +1 -1
- package/dist/status.cjs.map +1 -1
- package/dist/status.d.cts +1 -1
- package/dist/status.d.ts +1 -1
- package/dist/status.js +1 -1
- package/dist/webhooks.cjs.map +1 -1
- package/dist/webhooks.d.cts +27 -14
- package/dist/webhooks.d.ts +27 -14
- package/dist/webhooks.js.map +1 -1
- package/package.json +1 -1
- package/dist/chunk-CCG4F5FK.js.map +0 -1
- package/dist/chunk-J6JIZGWB.js.map +0 -1
- package/dist/{index.d-CKQAhQfJ.d.ts → index.d-DSEYhV2c.d.cts} +2 -2
- package/dist/{index.d-CKQAhQfJ.d.cts → index.d-DSEYhV2c.d.ts} +2 -2
package/dist/server.d.cts
CHANGED
|
@@ -1,16 +1,16 @@
|
|
|
1
1
|
import { Billow } from './index.cjs';
|
|
2
|
-
import './index.d-
|
|
2
|
+
import './index.d-DSEYhV2c.cjs';
|
|
3
3
|
import 'zod';
|
|
4
|
-
import './billing-status-
|
|
4
|
+
import './billing-status-DZkB0VPK.cjs';
|
|
5
5
|
import './status.cjs';
|
|
6
|
-
import './billing-
|
|
7
|
-
import './hosted-domains-
|
|
6
|
+
import './billing-8ug1Gw05.cjs';
|
|
7
|
+
import './hosted-domains-Ci6jeNAe.cjs';
|
|
8
8
|
|
|
9
9
|
/**
|
|
10
10
|
* Backend handler for the browser-facing surface (the React hooks talk to this,
|
|
11
11
|
* never to billow directly). Mount it at `/api/billow/*` in your app; it holds the
|
|
12
12
|
* secret key server-side and resolves the customer from *your* session via
|
|
13
|
-
* `identify`
|
|
13
|
+
* `identify` - so the browser can never choose which customer it is.
|
|
14
14
|
*
|
|
15
15
|
* // Next.js app/api/billow/[...billow]/route.ts
|
|
16
16
|
* import { Billow } from "@usebillow/sdk";
|
|
@@ -22,13 +22,13 @@ import './hosted-domains-BbuyxnuH.cjs';
|
|
|
22
22
|
* export { handler as GET, handler as POST };
|
|
23
23
|
*
|
|
24
24
|
* Exposed (all customer-scoped except the public catalog):
|
|
25
|
-
* GET /products
|
|
26
|
-
* GET /entitlements
|
|
27
|
-
* POST /check
|
|
28
|
-
* POST /attach
|
|
25
|
+
* GET /products - catalog for pricing tables (no customer needed)
|
|
26
|
+
* GET /entitlements - the identified customer's live entitlements
|
|
27
|
+
* POST /check - gate one feature for the identified customer
|
|
28
|
+
* POST /attach - start a subscription the customer pays for
|
|
29
29
|
*
|
|
30
30
|
* **Not** exposed by default: `track`. Recording usage from the browser would let
|
|
31
|
-
* a user forge their own balance (`value: -999999`)
|
|
31
|
+
* a user forge their own balance (`value: -999999`) - it is a server-trust verb.
|
|
32
32
|
* Call `billow.track(...)` from your backend when the metered event happens. If you
|
|
33
33
|
* accept the risk for a low-stakes counter, opt in with `allowClientTrack: true`.
|
|
34
34
|
*/
|
|
@@ -36,7 +36,7 @@ import './hosted-domains-BbuyxnuH.cjs';
|
|
|
36
36
|
interface BillowHandlerOptions {
|
|
37
37
|
/**
|
|
38
38
|
* Resolve the **trusted** customer id from the request (your own session/auth).
|
|
39
|
-
* Return `null` when unauthenticated
|
|
39
|
+
* Return `null` when unauthenticated - customer-scoped routes then 401.
|
|
40
40
|
*/
|
|
41
41
|
identify: (req: Request) => Promise<string | null> | string | null;
|
|
42
42
|
/** Path the handler is mounted under. Default `/api/billow`. */
|
|
@@ -44,7 +44,7 @@ interface BillowHandlerOptions {
|
|
|
44
44
|
/** Fixed post-checkout return URL (the client cannot override it). */
|
|
45
45
|
checkoutReturnUrl?: string;
|
|
46
46
|
/**
|
|
47
|
-
* Allow the browser to POST `/track`. Off by default
|
|
47
|
+
* Allow the browser to POST `/track`. Off by default - see the file header.
|
|
48
48
|
* Only enable for usage a malicious client forging is acceptable for.
|
|
49
49
|
*/
|
|
50
50
|
allowClientTrack?: boolean;
|
package/dist/server.d.ts
CHANGED
|
@@ -1,16 +1,16 @@
|
|
|
1
1
|
import { Billow } from './index.js';
|
|
2
|
-
import './index.d-
|
|
2
|
+
import './index.d-DSEYhV2c.js';
|
|
3
3
|
import 'zod';
|
|
4
|
-
import './billing-status-
|
|
4
|
+
import './billing-status-DZkB0VPK.js';
|
|
5
5
|
import './status.js';
|
|
6
|
-
import './billing-
|
|
7
|
-
import './hosted-domains-
|
|
6
|
+
import './billing-Bs10EcjR.js';
|
|
7
|
+
import './hosted-domains-DSs5Iw9U.js';
|
|
8
8
|
|
|
9
9
|
/**
|
|
10
10
|
* Backend handler for the browser-facing surface (the React hooks talk to this,
|
|
11
11
|
* never to billow directly). Mount it at `/api/billow/*` in your app; it holds the
|
|
12
12
|
* secret key server-side and resolves the customer from *your* session via
|
|
13
|
-
* `identify`
|
|
13
|
+
* `identify` - so the browser can never choose which customer it is.
|
|
14
14
|
*
|
|
15
15
|
* // Next.js app/api/billow/[...billow]/route.ts
|
|
16
16
|
* import { Billow } from "@usebillow/sdk";
|
|
@@ -22,13 +22,13 @@ import './hosted-domains-BP91tg9P.js';
|
|
|
22
22
|
* export { handler as GET, handler as POST };
|
|
23
23
|
*
|
|
24
24
|
* Exposed (all customer-scoped except the public catalog):
|
|
25
|
-
* GET /products
|
|
26
|
-
* GET /entitlements
|
|
27
|
-
* POST /check
|
|
28
|
-
* POST /attach
|
|
25
|
+
* GET /products - catalog for pricing tables (no customer needed)
|
|
26
|
+
* GET /entitlements - the identified customer's live entitlements
|
|
27
|
+
* POST /check - gate one feature for the identified customer
|
|
28
|
+
* POST /attach - start a subscription the customer pays for
|
|
29
29
|
*
|
|
30
30
|
* **Not** exposed by default: `track`. Recording usage from the browser would let
|
|
31
|
-
* a user forge their own balance (`value: -999999`)
|
|
31
|
+
* a user forge their own balance (`value: -999999`) - it is a server-trust verb.
|
|
32
32
|
* Call `billow.track(...)` from your backend when the metered event happens. If you
|
|
33
33
|
* accept the risk for a low-stakes counter, opt in with `allowClientTrack: true`.
|
|
34
34
|
*/
|
|
@@ -36,7 +36,7 @@ import './hosted-domains-BP91tg9P.js';
|
|
|
36
36
|
interface BillowHandlerOptions {
|
|
37
37
|
/**
|
|
38
38
|
* Resolve the **trusted** customer id from the request (your own session/auth).
|
|
39
|
-
* Return `null` when unauthenticated
|
|
39
|
+
* Return `null` when unauthenticated - customer-scoped routes then 401.
|
|
40
40
|
*/
|
|
41
41
|
identify: (req: Request) => Promise<string | null> | string | null;
|
|
42
42
|
/** Path the handler is mounted under. Default `/api/billow`. */
|
|
@@ -44,7 +44,7 @@ interface BillowHandlerOptions {
|
|
|
44
44
|
/** Fixed post-checkout return URL (the client cannot override it). */
|
|
45
45
|
checkoutReturnUrl?: string;
|
|
46
46
|
/**
|
|
47
|
-
* Allow the browser to POST `/track`. Off by default
|
|
47
|
+
* Allow the browser to POST `/track`. Off by default - see the file header.
|
|
48
48
|
* Only enable for usage a malicious client forging is acceptable for.
|
|
49
49
|
*/
|
|
50
50
|
allowClientTrack?: boolean;
|
package/dist/server.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/server.ts"],"names":[],"mappings":";AA+CO,SAAS,mBAAA,CAAoB,QAAgB,IAAA,EAAqC;AACvF,EAAA,MAAM,YAAY,IAAA,CAAK,QAAA,IAAY,aAAA,EAAe,OAAA,CAAQ,OAAO,EAAE,CAAA;AAEnE,EAAA,OAAO,eAAe,QAAQ,GAAA,EAAiC;AAC7D,IAAA,MAAM,KAAA,GAAQ,SAAS,IAAI,GAAA,CAAI,IAAI,GAAG,CAAA,CAAE,UAAU,QAAQ,CAAA;AAC1D,IAAA,MAAM,MAAA,GAAS,GAAA,CAAI,MAAA,CAAO,WAAA,EAAY;AACtC,IAAA,IAAI,UAAU,IAAA,EAAM;AAClB,MAAA,OAAO,IAAA,CAAK,EAAE,KAAA,EAAO,EAAE,IAAA,EAAM,aAAa,OAAA,EAAS,oBAAA,EAAqB,EAAE,EAAG,GAAG,CAAA;AAAA,IAClF;AAEA,IAAA,IAAI;AAEF,MAAA,IAAI,MAAA,KAAW,KAAA,IAAS,KAAA,KAAU,WAAA,EAAa;AAC7C,QAAA,OAAO,IAAA,CAAK,EAAE,QAAA,EAAU,MAAM,OAAO,QAAA,CAAS,IAAA,IAAQ,CAAA;AAAA,MAC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* Backend handler for the browser-facing surface (the React hooks talk to this,\n * never to billow directly). Mount it at `/api/billow/*` in your app; it holds the\n * secret key server-side and resolves the customer from *your* session via\n * `identify` — so the browser can never choose which customer it is.\n *\n * // Next.js app/api/billow/[...billow]/route.ts\n * import { Billow } from \"@usebillow/sdk\";\n * import { createBillowHandler } from \"@usebillow/sdk/server\";\n * const billow = new Billow(process.env.BILLOW_SECRET_KEY!);\n * const handler = createBillowHandler(billow, {\n * identify: async (req) => (await getSession(req))?.customerId ?? null,\n * });\n * export { handler as GET, handler as POST };\n *\n * Exposed (all customer-scoped except the public catalog):\n * GET /products — catalog for pricing tables (no customer needed)\n * GET /entitlements — the identified customer's live entitlements\n * POST /check — gate one feature for the identified customer\n * POST /attach — start a subscription the customer pays for\n *\n * **Not** exposed by default: `track`. Recording usage from the browser would let\n * a user forge their own balance (`value: -999999`) — it is a server-trust verb.\n * Call `billow.track(...)` from your backend when the metered event happens. If you\n * accept the risk for a low-stakes counter, opt in with `allowClientTrack: true`.\n */\nimport type { Billow } from \"./index\";\n\nexport interface BillowHandlerOptions {\n /**\n * Resolve the **trusted** customer id from the request (your own session/auth).\n * Return `null` when unauthenticated — customer-scoped routes then 401.\n */\n identify: (req: Request) => Promise<string | null> | string | null;\n /** Path the handler is mounted under. Default `/api/billow`. */\n basePath?: string;\n /** Fixed post-checkout return URL (the client cannot override it). */\n checkoutReturnUrl?: string;\n /**\n * Allow the browser to POST `/track`. Off by default — see the file header.\n * Only enable for usage a malicious client forging is acceptable for.\n */\n allowClientTrack?: boolean;\n}\n\ntype Handler = (req: Request) => Promise<Response>;\n\nexport function createBillowHandler(billow: Billow, opts: BillowHandlerOptions): Handler {\n const basePath = (opts.basePath ?? \"/api/billow\").replace(/\\/$/, \"\");\n\n return async function handler(req: Request): Promise<Response> {\n const route = subRoute(new URL(req.url).pathname, basePath);\n const method = req.method.toUpperCase();\n if (route === null) {\n return json({ error: { code: \"not_found\", message: \"Not a billow route\" } }, 404);\n }\n\n try {\n // Public catalog — no customer needed (pricing tables).\n if (method === \"GET\" && route === \"/products\") {\n return json({ products: await billow.products.list() });\n }\n\n // Everything else is scoped to the server-identified customer.\n const customerId = await opts.identify(req);\n if (!customerId) {\n return json({ error: { code: \"unauthenticated\", message: \"No customer\" } }, 401);\n }\n\n if (method === \"GET\" && route === \"/entitlements\") {\n return json(await billow.entitlements(customerId));\n }\n if (method === \"POST\" && route === \"/check\") {\n const body = await readJson<{ featureId?: unknown }>(req);\n return json(await billow.check({ customerId, featureId: String(body.featureId) }));\n }\n if (method === \"POST\" && route === \"/attach\") {\n const body = await readJson<{ productId?: unknown; couponCode?: unknown }>(req);\n const input: Parameters<typeof billow.attach>[0] = {\n customerId,\n productId: String(body.productId),\n };\n // Only a user-entered promo is forwarded; trial/card policy is the\n // merchant's, not the client's — set those in a server-side route.\n if (body.couponCode) input.couponCode = String(body.couponCode);\n if (opts.checkoutReturnUrl) input.redirectionUrl = opts.checkoutReturnUrl;\n return json(await billow.attach(input));\n }\n if (method === \"POST\" && route === \"/track\") {\n if (!opts.allowClientTrack) {\n return json({ error: { code: \"not_found\", message: \"track is server-only\" } }, 404);\n }\n const body = await readJson<{\n featureId?: unknown;\n value?: unknown;\n idempotencyKey?: unknown;\n }>(req);\n const input: Parameters<typeof billow.track>[0] = {\n customerId,\n featureId: String(body.featureId),\n };\n if (typeof body.value === \"number\") input.value = body.value;\n if (body.idempotencyKey) input.idempotencyKey = String(body.idempotencyKey);\n return json(await billow.track(input));\n }\n\n return json(\n { error: { code: \"not_found\", message: `No billow route ${method} ${route}` } },\n 404,\n );\n } catch (err) {\n return json(\n { error: { code: errorCode(err), message: errorMessage(err) } },\n errorStatus(err),\n );\n }\n };\n}\n\n/** The path under `basePath`, or `null` when the request isn't under it at all. */\nfunction subRoute(pathname: string, basePath: string): string | null {\n if (pathname === basePath) return \"/\";\n if (!pathname.startsWith(`${basePath}/`)) return null;\n return pathname.slice(basePath.length).replace(/\\/+$/, \"\") || \"/\";\n}\n\nfunction json(data: unknown, status = 200): Response {\n return new Response(JSON.stringify(data), {\n status,\n headers: { \"content-type\": \"application/json\" },\n });\n}\n\nasync function readJson<T = Record<string, unknown>>(req: Request): Promise<T> {\n try {\n return (await req.json()) as T;\n } catch {\n return {} as T;\n }\n}\n\nfunction errorStatus(err: unknown): number {\n if (err && typeof err === \"object\" && \"status\" in err) {\n const status = Number((err as { status: unknown }).status);\n if (Number.isInteger(status) && status >= 400 && status <= 599) return status;\n }\n return 500;\n}\n\nfunction errorCode(err: unknown): string {\n if (err && typeof err === \"object\" && \"code\" in err)\n return String((err as { code: unknown }).code);\n return \"error\";\n}\n\nfunction errorMessage(err: unknown): string {\n return err instanceof Error ? err.message : \"billow handler error\";\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/server.ts"],"names":[],"mappings":";AA+CO,SAAS,mBAAA,CAAoB,QAAgB,IAAA,EAAqC;AACvF,EAAA,MAAM,YAAY,IAAA,CAAK,QAAA,IAAY,aAAA,EAAe,OAAA,CAAQ,OAAO,EAAE,CAAA;AAEnE,EAAA,OAAO,eAAe,QAAQ,GAAA,EAAiC;AAC7D,IAAA,MAAM,KAAA,GAAQ,SAAS,IAAI,GAAA,CAAI,IAAI,GAAG,CAAA,CAAE,UAAU,QAAQ,CAAA;AAC1D,IAAA,MAAM,MAAA,GAAS,GAAA,CAAI,MAAA,CAAO,WAAA,EAAY;AACtC,IAAA,IAAI,UAAU,IAAA,EAAM;AAClB,MAAA,OAAO,IAAA,CAAK,EAAE,KAAA,EAAO,EAAE,IAAA,EAAM,aAAa,OAAA,EAAS,oBAAA,EAAqB,EAAE,EAAG,GAAG,CAAA;AAAA,IAClF;AAEA,IAAA,IAAI;AAEF,MAAA,IAAI,MAAA,KAAW,KAAA,IAAS,KAAA,KAAU,WAAA,EAAa;AAC7C,QAAA,OAAO,IAAA,CAAK,EAAE,QAAA,EAAU,MAAM,OAAO,QAAA,CAAS,IAAA,IAAQ,CAAA;AAAA,MACxD;AAGA,MAAA,MAAM,UA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ks talk to this,\n * never to billow directly). Mount it at `/api/billow/*` in your app; it holds the\n * secret key server-side and resolves the customer from *your* session via\n * `identify` - so the browser can never choose which customer it is.\n *\n * // Next.js app/api/billow/[...billow]/route.ts\n * import { Billow } from \"@usebillow/sdk\";\n * import { createBillowHandler } from \"@usebillow/sdk/server\";\n * const billow = new Billow(process.env.BILLOW_SECRET_KEY!);\n * const handler = createBillowHandler(billow, {\n * identify: async (req) => (await getSession(req))?.customerId ?? null,\n * });\n * export { handler as GET, handler as POST };\n *\n * Exposed (all customer-scoped except the public catalog):\n * GET /products - catalog for pricing tables (no customer needed)\n * GET /entitlements - the identified customer's live entitlements\n * POST /check - gate one feature for the identified customer\n * POST /attach - start a subscription the customer pays for\n *\n * **Not** exposed by default: `track`. Recording usage from the browser would let\n * a user forge their own balance (`value: -999999`) - it is a server-trust verb.\n * Call `billow.track(...)` from your backend when the metered event happens. If you\n * accept the risk for a low-stakes counter, opt in with `allowClientTrack: true`.\n */\nimport type { Billow } from \"./index\";\n\nexport interface BillowHandlerOptions {\n /**\n * Resolve the **trusted** customer id from the request (your own session/auth).\n * Return `null` when unauthenticated - customer-scoped routes then 401.\n */\n identify: (req: Request) => Promise<string | null> | string | null;\n /** Path the handler is mounted under. Default `/api/billow`. */\n basePath?: string;\n /** Fixed post-checkout return URL (the client cannot override it). */\n checkoutReturnUrl?: string;\n /**\n * Allow the browser to POST `/track`. Off by default - see the file header.\n * Only enable for usage a malicious client forging is acceptable for.\n */\n allowClientTrack?: boolean;\n}\n\ntype Handler = (req: Request) => Promise<Response>;\n\nexport function createBillowHandler(billow: Billow, opts: BillowHandlerOptions): Handler {\n const basePath = (opts.basePath ?? \"/api/billow\").replace(/\\/$/, \"\");\n\n return async function handler(req: Request): Promise<Response> {\n const route = subRoute(new URL(req.url).pathname, basePath);\n const method = req.method.toUpperCase();\n if (route === null) {\n return json({ error: { code: \"not_found\", message: \"Not a billow route\" } }, 404);\n }\n\n try {\n // Public catalog - no customer needed (pricing tables).\n if (method === \"GET\" && route === \"/products\") {\n return json({ products: await billow.products.list() });\n }\n\n // Everything else is scoped to the server-identified customer.\n const customerId = await opts.identify(req);\n if (!customerId) {\n return json({ error: { code: \"unauthenticated\", message: \"No customer\" } }, 401);\n }\n\n if (method === \"GET\" && route === \"/entitlements\") {\n return json(await billow.entitlements(customerId));\n }\n if (method === \"POST\" && route === \"/check\") {\n const body = await readJson<{ featureId?: unknown }>(req);\n return json(await billow.check({ customerId, featureId: String(body.featureId) }));\n }\n if (method === \"POST\" && route === \"/attach\") {\n const body = await readJson<{ productId?: unknown; couponCode?: unknown }>(req);\n const input: Parameters<typeof billow.attach>[0] = {\n customerId,\n productId: String(body.productId),\n };\n // Only a user-entered promo is forwarded; trial/card policy is the\n // merchant's, not the client's - set those in a server-side route.\n if (body.couponCode) input.couponCode = String(body.couponCode);\n if (opts.checkoutReturnUrl) input.redirectionUrl = opts.checkoutReturnUrl;\n return json(await billow.attach(input));\n }\n if (method === \"POST\" && route === \"/track\") {\n if (!opts.allowClientTrack) {\n return json({ error: { code: \"not_found\", message: \"track is server-only\" } }, 404);\n }\n const body = await readJson<{\n featureId?: unknown;\n value?: unknown;\n idempotencyKey?: unknown;\n }>(req);\n const input: Parameters<typeof billow.track>[0] = {\n customerId,\n featureId: String(body.featureId),\n };\n if (typeof body.value === \"number\") input.value = body.value;\n if (body.idempotencyKey) input.idempotencyKey = String(body.idempotencyKey);\n return json(await billow.track(input));\n }\n\n return json(\n { error: { code: \"not_found\", message: `No billow route ${method} ${route}` } },\n 404,\n );\n } catch (err) {\n return json(\n { error: { code: errorCode(err), message: errorMessage(err) } },\n errorStatus(err),\n );\n }\n };\n}\n\n/** The path under `basePath`, or `null` when the request isn't under it at all. */\nfunction subRoute(pathname: string, basePath: string): string | null {\n if (pathname === basePath) return \"/\";\n if (!pathname.startsWith(`${basePath}/`)) return null;\n return pathname.slice(basePath.length).replace(/\\/+$/, \"\") || \"/\";\n}\n\nfunction json(data: unknown, status = 200): Response {\n return new Response(JSON.stringify(data), {\n status,\n headers: { \"content-type\": \"application/json\" },\n });\n}\n\nasync function readJson<T = Record<string, unknown>>(req: Request): Promise<T> {\n try {\n return (await req.json()) as T;\n } catch {\n return {} as T;\n }\n}\n\nfunction errorStatus(err: unknown): number {\n if (err && typeof err === \"object\" && \"status\" in err) {\n const status = Number((err as { status: unknown }).status);\n if (Number.isInteger(status) && status >= 400 && status <= 599) return status;\n }\n return 500;\n}\n\nfunction errorCode(err: unknown): string {\n if (err && typeof err === \"object\" && \"code\" in err)\n return String((err as { code: unknown }).code);\n return \"error\";\n}\n\nfunction errorMessage(err: unknown): string {\n return err instanceof Error ? err.message : \"billow handler error\";\n}\n"]}
|
package/dist/status.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/billing-status.ts","../src/subscription-status.ts"],"names":[],"mappings":";;;AASO,IAAM,eAAA,GAAkB;AAAA,EAC7B,SAAA;AAAA,EACA,YAAA;AAAA,EACA,WAAA;AAAA,EACA,QAAA;AAAA,EACA,yBAAA;AAAA,EACA;AACF;AAIO,IAAM,mBAAmB,CAAC,OAAA,EAAS,MAAA,EAAQ,MAAA,EAAQ,iBAAiB,MAAM;AAI1E,IAAM,eAAA,GAAkB,CAAC,SAAA,EAAW,WAAA,EAAa,QAAQ;AAIzD,IAAM,uBAAA,GAA0B,CAAC,QAAA,EAAU,SAAA,EAAW,SAAS;AAS/D,IAAM,yBAAA,GAA4B,CAAC,WAAA,EAAa,QAAQ;;;ACxBxD,IAAM,qBAAA,GAAwB;AAAA,EACnC,YAAA;AAAA,EACA,oBAAA;AAAA,EACA,UAAA;AAAA,EACA,QAAA;AAAA,EACA,UAAA;AAAA,EACA,QAAA;AAAA,EACA,UAAA;AAAA,EACA;AACF;AAQO,IAAM,4BAAA,GAA8D;AAAA,EACzE,UAAA;AAAA,EACA,QAAA;AAAA,EACA;AACF;AAGO,IAAM,8BAAA,GAAgE;AAAA,EAC3E,oBAAA;AAAA,EACA;AACF;AAGO,IAAM,qCAAA,GAAuE;AAAA,EAClF,YAAA;AAAA,EACA;AACF;AAGO,SAAS,aAAa,MAAA,EAAqC;AAChE,EAAA,OAAO,4BAAA,CAA6B,SAAS,MAAM,CAAA;AACrD;AAGO,SAAS,WAAW,MAAA,EAAqC;AAC9D,EAAA,OAAO,8BAAA,CAA+B,SAAS,MAAM,CAAA;AACvD","file":"status.cjs","sourcesContent":["/**\n * Charge / invoice / refund / payment-method / webhook-delivery status vocabularies,\n * mirrored for the SDK (which cannot import the server-side `@billow/core`). The DB-enum\n * ones (charge, invoice, refund, payment method) mirror core enums and are parity-tested\n * against it (see billing-status.test.ts); webhook-delivery status is a free-text column\n * server-side with a fixed vocabulary, documented here.\n */\n\n/** A charge's lifecycle status
|
|
1
|
+
{"version":3,"sources":["../src/billing-status.ts","../src/subscription-status.ts"],"names":[],"mappings":";;;AASO,IAAM,eAAA,GAAkB;AAAA,EAC7B,SAAA;AAAA,EACA,YAAA;AAAA,EACA,WAAA;AAAA,EACA,QAAA;AAAA,EACA,yBAAA;AAAA,EACA;AACF;AAIO,IAAM,mBAAmB,CAAC,OAAA,EAAS,MAAA,EAAQ,MAAA,EAAQ,iBAAiB,MAAM;AAI1E,IAAM,eAAA,GAAkB,CAAC,SAAA,EAAW,WAAA,EAAa,QAAQ;AAIzD,IAAM,uBAAA,GAA0B,CAAC,QAAA,EAAU,SAAA,EAAW,SAAS;AAS/D,IAAM,yBAAA,GAA4B,CAAC,WAAA,EAAa,QAAQ;;;ACxBxD,IAAM,qBAAA,GAAwB;AAAA,EACnC,YAAA;AAAA,EACA,oBAAA;AAAA,EACA,UAAA;AAAA,EACA,QAAA;AAAA,EACA,UAAA;AAAA,EACA,QAAA;AAAA,EACA,UAAA;AAAA,EACA;AACF;AAQO,IAAM,4BAAA,GAA8D;AAAA,EACzE,UAAA;AAAA,EACA,QAAA;AAAA,EACA;AACF;AAGO,IAAM,8BAAA,GAAgE;AAAA,EAC3E,oBAAA;AAAA,EACA;AACF;AAGO,IAAM,qCAAA,GAAuE;AAAA,EAClF,YAAA;AAAA,EACA;AACF;AAGO,SAAS,aAAa,MAAA,EAAqC;AAChE,EAAA,OAAO,4BAAA,CAA6B,SAAS,MAAM,CAAA;AACrD;AAGO,SAAS,WAAW,MAAA,EAAqC;AAC9D,EAAA,OAAO,8BAAA,CAA+B,SAAS,MAAM,CAAA;AACvD","file":"status.cjs","sourcesContent":["/**\n * Charge / invoice / refund / payment-method / webhook-delivery status vocabularies,\n * mirrored for the SDK (which cannot import the server-side `@billow/core`). The DB-enum\n * ones (charge, invoice, refund, payment method) mirror core enums and are parity-tested\n * against it (see billing-status.test.ts); webhook-delivery status is a free-text column\n * server-side with a fixed vocabulary, documented here.\n */\n\n/** A charge's lifecycle status - mirrors `@billow/core` `CHARGE_STATUSES`. */\nexport const CHARGE_STATUSES = [\n \"pending\",\n \"processing\",\n \"succeeded\",\n \"failed\",\n \"requires_reconciliation\",\n \"disputed\",\n] as const;\nexport type ChargeStatus = (typeof CHARGE_STATUSES)[number];\n\n/** An invoice's lifecycle status - mirrors `@billow/core` `INVOICE_STATUSES`. */\nexport const INVOICE_STATUSES = [\"draft\", \"open\", \"paid\", \"uncollectible\", \"void\"] as const;\nexport type InvoiceStatus = (typeof INVOICE_STATUSES)[number];\n\n/** A refund's lifecycle status - mirrors `@billow/core` `REFUND_STATUSES`. */\nexport const REFUND_STATUSES = [\"pending\", \"succeeded\", \"failed\"] as const;\nexport type RefundStatus = (typeof REFUND_STATUSES)[number];\n\n/** A saved payment method's status - mirrors `@billow/core` `PAYMENT_METHOD_STATUSES`. */\nexport const PAYMENT_METHOD_STATUSES = [\"active\", \"expired\", \"removed\"] as const;\nexport type PaymentMethodStatus = (typeof PAYMENT_METHOD_STATUSES)[number];\n\n/**\n * A webhook delivery attempt's status. Not a DB enum (a free-text column); the dispatcher\n * inserts one row per attempt with exactly `delivered` (a 2xx) or `failed` (anything else) -\n * see `packages/server/src/jobs/outbox.ts`. (Retry/backoff state lives on the outbox event,\n * a separate table, not on the delivery record.)\n */\nexport const WEBHOOK_DELIVERY_STATUSES = [\"delivered\", \"failed\"] as const;\nexport type WebhookDeliveryStatus = (typeof WEBHOOK_DELIVERY_STATUSES)[number];\n","/**\n * The subscription status vocabulary + access predicate, mirrored from @billow/core\n * (`enums.ts` + `billing/subscription-state.ts`) so SDK consumers can type and branch on\n * billow's own model instead of hand-maintaining a union that drifts (a real bug: an app\n * copy once carried a non-existent `ended` status - that string is a webhook event type,\n * not a subscription status).\n *\n * Mirrored, not imported: @billow/core is a server package the published SDK cannot depend\n * on (the same reason @billow/contracts mirrors core's pure logic). The parity test\n * `subscription-status.test.ts` imports @billow/core and fails CI on any drift.\n */\n\n/** The 8 canonical subscription statuses, in lifecycle order. */\nexport const SUBSCRIPTION_STATUSES = [\n \"incomplete\",\n \"incomplete_expired\",\n \"trialing\",\n \"active\",\n \"past_due\",\n \"paused\",\n \"canceled\",\n \"unpaid\",\n] as const;\n\nexport type SubscriptionStatus = (typeof SUBSCRIPTION_STATUSES)[number];\n\n/**\n * Statuses that currently grant access (a live commitment): `trialing`, `active`, and\n * `past_due` (access is retained through dunning). Note `paused` does NOT grant access.\n */\nexport const ACTIVE_SUBSCRIPTION_STATUSES: readonly SubscriptionStatus[] = [\n \"trialing\",\n \"active\",\n \"past_due\",\n];\n\n/** Statuses a subscription can never leave: `incomplete_expired` and `canceled`. */\nexport const TERMINAL_SUBSCRIPTION_STATUSES: readonly SubscriptionStatus[] = [\n \"incomplete_expired\",\n \"canceled\",\n];\n\n/** Statuses in which a subscription never activated (no access was ever granted). */\nexport const NEVER_ACTIVATED_SUBSCRIPTION_STATUSES: readonly SubscriptionStatus[] = [\n \"incomplete\",\n \"incomplete_expired\",\n];\n\n/** Whether access should currently be granted for a subscription in this state. */\nexport function grantsAccess(status: SubscriptionStatus): boolean {\n return ACTIVE_SUBSCRIPTION_STATUSES.includes(status);\n}\n\n/** Whether this is a terminal status the subscription can never leave. */\nexport function isTerminal(status: SubscriptionStatus): boolean {\n return TERMINAL_SUBSCRIPTION_STATUSES.includes(status);\n}\n"]}
|
package/dist/status.d.cts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
export { a as CHARGE_STATUSES, C as ChargeStatus, b as INVOICE_STATUSES, I as InvoiceStatus, c as PAYMENT_METHOD_STATUSES, P as PaymentMethodStatus, d as REFUND_STATUSES, R as RefundStatus, e as WEBHOOK_DELIVERY_STATUSES, W as WebhookDeliveryStatus } from './billing-status-
|
|
1
|
+
export { a as CHARGE_STATUSES, C as ChargeStatus, b as INVOICE_STATUSES, I as InvoiceStatus, c as PAYMENT_METHOD_STATUSES, P as PaymentMethodStatus, d as REFUND_STATUSES, R as RefundStatus, e as WEBHOOK_DELIVERY_STATUSES, W as WebhookDeliveryStatus } from './billing-status-DZkB0VPK.cjs';
|
|
2
2
|
|
|
3
3
|
/**
|
|
4
4
|
* The subscription status vocabulary + access predicate, mirrored from @billow/core
|
package/dist/status.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
export { a as CHARGE_STATUSES, C as ChargeStatus, b as INVOICE_STATUSES, I as InvoiceStatus, c as PAYMENT_METHOD_STATUSES, P as PaymentMethodStatus, d as REFUND_STATUSES, R as RefundStatus, e as WEBHOOK_DELIVERY_STATUSES, W as WebhookDeliveryStatus } from './billing-status-
|
|
1
|
+
export { a as CHARGE_STATUSES, C as ChargeStatus, b as INVOICE_STATUSES, I as InvoiceStatus, c as PAYMENT_METHOD_STATUSES, P as PaymentMethodStatus, d as REFUND_STATUSES, R as RefundStatus, e as WEBHOOK_DELIVERY_STATUSES, W as WebhookDeliveryStatus } from './billing-status-DZkB0VPK.js';
|
|
2
2
|
|
|
3
3
|
/**
|
|
4
4
|
* The subscription status vocabulary + access predicate, mirrored from @billow/core
|
package/dist/status.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
export { ACTIVE_SUBSCRIPTION_STATUSES, CHARGE_STATUSES, INVOICE_STATUSES, NEVER_ACTIVATED_SUBSCRIPTION_STATUSES, PAYMENT_METHOD_STATUSES, REFUND_STATUSES, SUBSCRIPTION_STATUSES, TERMINAL_SUBSCRIPTION_STATUSES, WEBHOOK_DELIVERY_STATUSES, grantsAccess, isTerminal } from './chunk-
|
|
1
|
+
export { ACTIVE_SUBSCRIPTION_STATUSES, CHARGE_STATUSES, INVOICE_STATUSES, NEVER_ACTIVATED_SUBSCRIPTION_STATUSES, PAYMENT_METHOD_STATUSES, REFUND_STATUSES, SUBSCRIPTION_STATUSES, TERMINAL_SUBSCRIPTION_STATUSES, WEBHOOK_DELIVERY_STATUSES, grantsAccess, isTerminal } from './chunk-47J7FYM5.js';
|
|
2
2
|
//# sourceMappingURL=status.js.map
|
|
3
3
|
//# sourceMappingURL=status.js.map
|
package/dist/webhooks.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/webhook-event-types.ts","../src/webhooks.ts"],"names":[],"mappings":";;;AASO,IAAM,mBAAA,GAAsB;AAAA,EACjC,kBAAA;AAAA,EACA,eAAA;AAAA,EACA,iBAAA;AAAA,EACA,iBAAA;AAAA,EACA,yBAAA;AAAA,EACA,cAAA;AAAA,EACA,wBAAA;AAAA,EACA,4BAAA;AAAA,EACA,wBAAA;AAAA,EACA,gCAAA;AAAA,EACA,sBAAA;AAAA,EACA,uBAAA;AAAA,EACA,6BAAA;AAAA,EACA,sCAAA;AAAA,EACA,qBAAA;AAAA,EACA,qBAAA;AAAA,EACA,sBAAA;AAAA,EACA,sBAAA;AAAA,EACA,+BAAA;AAAA,EACA,6BAAA;AAAA,EACA,kCAAA;AAAA,EACA,iCAAA;AAAA,EACA,uBAAA;AAAA,EACA,oBAAA;AAAA,EACA,qBAAA;AAAA,EACA,mBAAA;AAAA,EACA,yBAAA;AAAA,EACA,aAAA;AAAA,EACA,mBAAA;AAAA,EACA,kCAAA;AAAA,EACA,sBAAA;AAAA,EACA,sBAAA;AAAA,EACA,4BAAA;AAAA,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;AAAA,EACT,CAAA;AACF;AAEA,SAAS,eAAe,KAAA,EAAuC;AAC7D,EAAA,IAAI,OAAO,KAAA,KAAU,QAAA,IAAY,KAAA,KAAU,MAAM,OAAO,KAAA;AACxD,EAAA,MAAM,CAAA,GAAI,KAAA;AAOV,EAAA,OACE,OAAO,EAAE,EAAA,KAAO,QAAA,IAChB,OAAO,CAAA,CAAE,OAAA,KAAY,YACrB,OAAO,CAAA,CAAE,SAAS,QAAA,IAClB,OAAO,EAAE,SAAA,KAAc,QAAA,IACvB,OAAO,CAAA,CAAE,IAAA,KAAS,QAAA,IAClB,CAAA,CAAE,IAAA,KAAS,IAAA;AAEf","file":"webhooks.cjs","sourcesContent":["/**\n * The webhook event catalog: every event type billow emits, and its families as types and runtime\n * arrays (for subscription pickers and exhaustive routing). Re-exported by ./webhooks.ts.\n */\n\n/**\n * Every event type billow emits, in contract order. Mirrors `@billow/core`'s\n * EVENT_TYPES - exported as a runtime array so UIs can render a subscription picker.\n */\nexport const WEBHOOK_EVENT_TYPES = [\n \"charge.succeeded\",\n \"charge.failed\",\n \"charge.refunded\",\n \"charge.disputed\",\n \"charge.dispute_resolved\",\n \"invoice.paid\",\n \"invoice.payment_failed\",\n \"subscription.trial_started\",\n \"subscription.activated\",\n \"subscription.activation_failed\",\n \"subscription.renewed\",\n \"subscription.past_due\",\n \"subscription.payment_failed\",\n \"subscription.requires_payment_method\",\n \"subscription.unpaid\",\n \"subscription.paused\",\n \"subscription.resumed\",\n \"subscription.updated\",\n \"subscription.cancel_scheduled\",\n \"subscription.cancel_resumed\",\n \"subscription.downgrade_scheduled\",\n \"subscription.downgrade_canceled\",\n \"subscription.canceled\",\n \"subscription.ended\",\n \"entitlement.granted\",\n \"entitlement.reset\",\n \"usage.threshold_reached\",\n \"usage.alert\",\n \"usage.cap_reached\",\n \"credit_balance.threshold_crossed\",\n \"credit_grant.created\",\n \"credit_grant.expired\",\n \"credit_reservation.expired\",\n \"credit_top_up.succeeded\",\n \"credit_top_up.failed\",\n \"credit_top_up.refunded\",\n \"credit_top_up.unfulfilled\",\n \"hosted_domain.activated\",\n \"hosted_domain.dns_failing\",\n \"hosted_domain.reassignment_pending\",\n \"hosted_domain.disabled\",\n] as const;\n\n/** A valid billow event type (the compile-time freeze derived from the array above). */\nexport type BillowEventType = (typeof WEBHOOK_EVENT_TYPES)[number];\n\n/** The `charge.*` subset of {@link BillowEventType}. */\nexport type ChargeEventType = Extract<BillowEventType, `charge.${string}`>;\n/** The `invoice.*` subset of {@link BillowEventType}. */\nexport type InvoiceEventType = Extract<BillowEventType, `invoice.${string}`>;\n/** The `subscription.*` subset of {@link BillowEventType} - the events that change a subscription. */\nexport type SubscriptionEventType = Extract<BillowEventType, `subscription.${string}`>;\n/** The `entitlement.*` subset of {@link BillowEventType}. */\nexport type EntitlementEventType = Extract<BillowEventType, `entitlement.${string}`>;\n/** The `usage.*` subset of {@link BillowEventType}. */\nexport type UsageEventType = Extract<BillowEventType, `usage.${string}`>;\n/** The prepaid credits subset of {@link BillowEventType} (`credit_balance.*`, `credit_grant.*`, ...). */\nexport type CreditEventType = Extract<BillowEventType, `credit_${string}`>;\n/** The `hosted_domain.*` subset of {@link BillowEventType}: custom portal domains. */\nexport type HostedDomainEventType = Extract<BillowEventType, `hosted_domain.${string}`>;\n\n/** The subset of {@link WEBHOOK_EVENT_TYPES} sharing `prefix`, as a runtime array (order preserved). */\nfunction eventTypesWithPrefix<P extends string>(\n prefix: P,\n): readonly Extract<BillowEventType, `${P}${string}`>[] {\n return WEBHOOK_EVENT_TYPES.filter((type): type is Extract<BillowEventType, `${P}${string}`> =>\n type.startsWith(prefix),\n );\n}\n\n/** The `charge.*` event types, as a runtime array (for pickers / exhaustive routing). */\nexport const CHARGE_EVENT_TYPES: readonly ChargeEventType[] = eventTypesWithPrefix(\"charge.\");\n/** The `invoice.*` event types, as a runtime array. */\nexport const INVOICE_EVENT_TYPES: readonly InvoiceEventType[] = eventTypesWithPrefix(\"invoice.\");\n/**\n * The subscription lifecycle event types - the `subscription.*` subset of\n * {@link WEBHOOK_EVENT_TYPES}, as a runtime array. Use it (or {@link isSubscriptionEvent})\n * to select the events that affect a subscription mirror without a brittle string match.\n */\nexport const SUBSCRIPTION_EVENT_TYPES: readonly SubscriptionEventType[] =\n eventTypesWithPrefix(\"subscription.\");\n/** The `entitlement.*` event types, as a runtime array. */\nexport const ENTITLEMENT_EVENT_TYPES: readonly EntitlementEventType[] =\n eventTypesWithPrefix(\"entitlement.\");\n/** The `usage.*` event types, as a runtime array. */\nexport const USAGE_EVENT_TYPES: readonly UsageEventType[] = eventTypesWithPrefix(\"usage.\");\n/** The prepaid credits event types, as a runtime array. */\nexport const CREDIT_EVENT_TYPES: readonly CreditEventType[] = eventTypesWithPrefix(\"credit_\");\n/** The `hosted_domain.*` event types, as a runtime array. */\nexport const HOSTED_DOMAIN_EVENT_TYPES: readonly HostedDomainEventType[] =\n eventTypesWithPrefix(\"hosted_domain.\");\n\n/** Whether `type` is a subscription lifecycle event (`subscription.*`); narrows the type. */\nexport function isSubscriptionEvent(type: string): type is SubscriptionEventType {\n return type.startsWith(\"subscription.\");\n}\n","/**\n * Verify and parse billow webhook deliveries.\n *\n * billow signs each delivery with HMAC-SHA256 over `\"<timestamp>.<rawBody>\"` and\n * sends it in the `billow-signature` header as `t=<unix-seconds>,v1=<hex>`. The\n * timestamp lets you reject replays outside a freshness window.\n *\n * Verification is async and uses the Web Crypto API (`globalThis.crypto.subtle`),\n * so the same code runs in Node 20+, edge runtimes, Cloudflare Workers, Deno, and\n * Bun — it never imports `node:crypto`.\n *\n * import { constructEvent } from \"@usebillow/sdk/webhooks\";\n *\n * const event = await constructEvent(rawBody, req.headers[\"billow-signature\"], secret);\n * switch (event.type) {\n * case \"invoice.paid\": // …\n * }\n */\n\nimport type { CreditGrantKind, CreditThresholdLevel } from \"./types/credits\";\nimport type {\n HostedDomainActivatedData,\n HostedDomainDisabledData,\n HostedDomainDnsFailingData,\n HostedDomainReassignmentPendingData,\n} from \"./types/hosted-domains\";\nimport type {\n BillowEventType,\n EntitlementEventType,\n InvoiceEventType,\n SubscriptionEventType,\n} from \"./webhook-event-types\";\n\nexport * from \"./webhook-event-types\";\n\n/**\n * The fields every webhook envelope carries. Each {@link WebhookEvent} variant intersects\n * this with its own `type` + payload-typed `data`.\n */\nexport interface WebhookEventEnvelope {\n /** Stable event id — your idempotency key (delivery is at-least-once). */\n id: string;\n /** Envelope schema version. */\n version: number;\n /** ISO-8601 timestamp of when the event was recorded. */\n createdAt: string;\n}\n\n// --- Per-event-group payloads -------------------------------------------------------------\n// Shapes mirror what the server emits (packages/server/src/services: charges.ts, billing.ts,\n// renewal/*, subscriptions/*, entitlements/*). Grouped where a group's emitters are uniform;\n// `usage.*` is split per event because its emitters diverge. `customerExternalId` is added to\n// every customer-scoped payload by the server's outbox emitter (events.ts).\n\n/** `charge.succeeded` / `charge.failed`. */\nexport interface ChargeEventData {\n chargeId: string;\n /**\n * `false` on a `charge.failed` that closed a checkout its customer abandoned long before: no\n * \"payment failed\" email was sent to the customer. Absent otherwise.\n */\n notifyCustomer?: false;\n}\n/** `charge.refunded`, emitted once for each succeeded refund transition. */\nexport interface ChargeRefundedEventData {\n chargeId: string;\n refundId: string;\n amount: number;\n cumulativeAmount: number;\n currency: string;\n}\n/** Stable dispute facts shared by the opened and resolved events. */\nexport interface ChargeDisputeEventData {\n chargeId: string;\n disputeId: string;\n amount: number;\n currency: string;\n reason: string | null;\n state: \"open\" | \"won\" | \"lost\";\n}\n/** `invoice.paid` / `invoice.payment_failed`. */\nexport interface InvoiceEventData {\n invoiceId: string;\n chargeId: string;\n /**\n * `false` on an `invoice.payment_failed` that closed a checkout its customer abandoned long\n * before: no \"payment failed\" email was sent to the customer. Absent otherwise.\n */\n notifyCustomer?: false;\n}\n/** Any `subscription.*` lifecycle event. */\nexport interface SubscriptionEventData {\n subscriptionId: string;\n customerId: string;\n customerExternalId: string;\n /** The subscription's plan — so a consumer knows which product the event is about. */\n productId: string;\n productSlug: string;\n /** The product's metadata map (Stripe-style); `{}` when the plan carries none. */\n productMetadata: Record<string, string>;\n /** Set on dunning events that reference the unpaid invoice (`unpaid`, `requires_payment_method`). */\n invoiceId?: string;\n /** Set on lifecycle-ending events (`ended`, downgrade-driven `updated`). */\n reason?: string;\n /** Present when a downgrade is scheduled; null when that schedule is cleared. */\n scheduledChange?: {\n productVersionId: string;\n productId: string;\n productSlug: string;\n productName: string;\n effectiveAt: string | null;\n } | null;\n}\n/** `entitlement.granted` / `entitlement.reset`. */\nexport interface EntitlementEventData {\n subscriptionId: string;\n customerId: string;\n customerExternalId: string;\n featureId: string;\n /** Remaining allowance; `null` when the feature is unlimited. */\n balance: number | null;\n /** Whether the feature grants unlimited usage. */\n unlimited: boolean;\n}\n/** Fields shared by every `usage.*` event. */\nexport interface UsageEventBase {\n subscriptionId: string;\n customerId: string;\n customerExternalId: string;\n /** Feature slug. */\n feature: string;\n featureName: string;\n /** Aggregate usage after this step. */\n used: number;\n /** Included allowance; `null` when unlimited. */\n allowance: number | null;\n /** Remaining allowance; `null` when unlimited. */\n balance: number | null;\n}\n/** `usage.threshold_reached` — a built-in usage threshold was crossed. */\nexport interface UsageThresholdReachedData extends UsageEventBase {\n featureId: string;\n /** The threshold crossed (currently only the included allowance being exhausted). */\n level: \"exhausted\";\n}\n/** `usage.alert` — a configured usage alert fired. */\nexport interface UsageAlertData extends UsageEventBase {\n metric: string;\n threshold: number;\n recurring: boolean;\n notifyCustomer: boolean;\n}\n/** `usage.cap_reached` — a configured spend/usage cap was reached. */\nexport interface UsageCapReachedData extends UsageEventBase {\n metric: string;\n cap: number;\n capAt: number;\n}\n\n// Prepaid credits: every credit quantity is a decimal string of microcredits, never a number.\n// Payloads carry ids, codes and quantities, never a grant's, reservation's or top-up's reason or\n// metadata.\n\n/** Fields shared by every prepaid credits event. */\nexport interface CreditEventBase {\n customerId: string;\n customerExternalId: string;\n}\n/**\n * `credit_balance.threshold_crossed` - the balance moved to another level, in either direction\n * (raise a low-balance banner, or clear it). `exhausted` when nothing is spendable; otherwise\n * `critical` / `low` at or below the percentages of `thresholds.reference`, else `normal`.\n */\nexport interface CreditThresholdCrossedData extends CreditEventBase {\n level: CreditThresholdLevel;\n previousLevel: CreditThresholdLevel;\n /** The balance the level was judged on, as of `asOf`; re-read the balance for truth. */\n balance: { spendable: string; held: string; asOf: string };\n thresholds: { lowPercent: number; criticalPercent: number; reference: string | null };\n}\n/** `credit_grant.created` - credits were granted. */\nexport interface CreditGrantCreatedData extends CreditEventBase {\n grantId: string;\n kind: CreditGrantKind;\n amount: string;\n expiresAt: string | null;\n eligibility: string[] | null;\n topUpId: string | null;\n}\n/**\n * `credit_grant.expired` - one expiry took `expired` credits off a grant: its unheld credits when\n * it expired, or a held part that came back to it afterwards (one more event each).\n */\nexport interface CreditGrantExpiredData extends CreditEventBase {\n grantId: string;\n kind: CreditGrantKind;\n expiresAt: string | null;\n expired: string;\n /** The `expire` ledger transaction. */\n transactionId: string;\n}\n/** `credit_reservation.expired` - a hold passed its expiry unsettled and was released. */\nexport interface CreditReservationExpiredData extends CreditEventBase {\n reservationId: string;\n operationKey: string;\n category: string;\n amount: string;\n expiresAt: string;\n}\n/** What every `credit_top_up.*` event says about the purchase and its payment. */\nexport interface CreditTopUpEventBase extends CreditEventBase {\n topUpId: string;\n packId: string;\n chargeId: string;\n /** What the payment collects, in minor units of `currency`. */\n amount: number;\n currency: string;\n /** The terms bought. */\n credits: string;\n bonusCredits: string;\n}\n/** `credit_top_up.succeeded` - the payment succeeded and its credits (and any bonus) were granted. */\nexport interface CreditTopUpSucceededData extends CreditTopUpEventBase {\n purchasedGrantId: string | null;\n bonusGrantId: string | null;\n}\n/**\n * `credit_top_up.failed` - the payment failed. A later payment on the same checkout can still\n * succeed it: `credit_top_up.succeeded` may follow for the same top-up.\n */\nexport type CreditTopUpFailedData = CreditTopUpEventBase;\n/** `credit_top_up.unfulfilled` - paid after the customer was erased: nothing granted, refund it. */\nexport type CreditTopUpUnfulfilledData = CreditTopUpEventBase;\n/**\n * `credit_top_up.refunded` - a refund or lost chargeback revoked the top-up's credits in\n * proportion to the money returned.\n */\nexport interface CreditTopUpRefundedData extends CreditTopUpEventBase {\n cause: \"refund\" | \"chargeback\";\n /** Money returned so far (refunds plus lost disputes, at most what was charged), minor units. */\n amountReturned: number;\n /** Microcredits this refund or chargeback revoked. */\n revokedNow: string;\n /** Microcredits revoked so far in all. */\n revoked: string;\n /** Of them, what the customer had already spent and nothing has paid back. */\n shortfall: string;\n}\n\n/**\n * The verified webhook envelope billow POSTs to your endpoint — a discriminated union on\n * {@link WebhookEvent.type}. `switch` (or a {@link WebhookHandlers} map) on `type` and `data`\n * narrows to the exact payload for that event.\n *\n * switch (event.type) {\n * case \"invoice.paid\": settle(event.data.invoiceId); break; // InvoiceEventData\n * case \"subscription.canceled\": revoke(event.data.customerExternalId); break;\n * }\n */\nexport type WebhookEventDataMap = {\n [K in \"charge.succeeded\" | \"charge.failed\"]: ChargeEventData;\n} & {\n \"charge.refunded\": ChargeRefundedEventData;\n} & {\n [K in \"charge.disputed\" | \"charge.dispute_resolved\"]: ChargeDisputeEventData;\n} & {\n [K in InvoiceEventType]: InvoiceEventData;\n} & {\n [K in SubscriptionEventType]: SubscriptionEventData;\n} & {\n [K in EntitlementEventType]: EntitlementEventData;\n} & {\n \"usage.threshold_reached\": UsageThresholdReachedData;\n \"usage.alert\": UsageAlertData;\n \"usage.cap_reached\": UsageCapReachedData;\n} & {\n \"credit_balance.threshold_crossed\": CreditThresholdCrossedData;\n \"credit_grant.created\": CreditGrantCreatedData;\n \"credit_grant.expired\": CreditGrantExpiredData;\n \"credit_reservation.expired\": CreditReservationExpiredData;\n \"credit_top_up.succeeded\": CreditTopUpSucceededData;\n \"credit_top_up.failed\": CreditTopUpFailedData;\n \"credit_top_up.refunded\": CreditTopUpRefundedData;\n \"credit_top_up.unfulfilled\": CreditTopUpUnfulfilledData;\n} & {\n \"hosted_domain.activated\": HostedDomainActivatedData;\n \"hosted_domain.dns_failing\": HostedDomainDnsFailingData;\n \"hosted_domain.reassignment_pending\": HostedDomainReassignmentPendingData;\n \"hosted_domain.disabled\": HostedDomainDisabledData;\n};\n\n/** One distributive union member per event literal, derived from the payload map. */\nexport type WebhookEvent = {\n [K in BillowEventType]: WebhookEventEnvelope & { type: K; data: WebhookEventDataMap[K] };\n}[BillowEventType];\n\nexport interface VerifyOptions {\n /**\n * Max age (seconds) of a delivery's signature timestamp before it's rejected as\n * a possible replay. Default 300 (5 minutes).\n */\n toleranceSeconds?: number;\n}\n\n/** Thrown by {@link constructEvent} when a delivery can't be trusted. */\nexport class WebhookVerificationError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"WebhookVerificationError\";\n }\n}\n\nconst DEFAULT_TOLERANCE_SECONDS = 300;\nconst encoder = new TextEncoder();\n\ninterface ParsedHeader {\n timestamp: number;\n signatures: string[];\n}\n\n/** Parse `t=<unix>,v1=<hex>[,v1=<hex>…]` — multiple v1 supports key rotation. */\nfunction parseHeader(header: string): ParsedHeader | null {\n let timestamp = Number.NaN;\n const signatures: string[] = [];\n for (const part of header.split(\",\")) {\n const eq = part.indexOf(\"=\");\n if (eq === -1) continue;\n const key = part.slice(0, eq).trim();\n const value = part.slice(eq + 1).trim();\n if (key === \"t\") timestamp = Number(value);\n else if (key === \"v1\") signatures.push(value);\n }\n if (!Number.isFinite(timestamp) || signatures.length === 0) return null;\n return { timestamp, signatures };\n}\n\nasync function hmacHex(secret: string, payload: string): Promise<string> {\n const key = await crypto.subtle.importKey(\n \"raw\",\n encoder.encode(secret),\n { name: \"HMAC\", hash: \"SHA-256\" },\n false,\n [\"sign\"],\n );\n const sig = await crypto.subtle.sign(\"HMAC\", key, encoder.encode(payload));\n return Array.from(new Uint8Array(sig), (b) => b.toString(16).padStart(2, \"0\")).join(\"\");\n}\n\n/** Constant-time compare of two equal-length hex strings (no early exit). */\nfunction timingSafeEqual(a: string, b: string): boolean {\n if (a.length !== b.length) return false;\n let mismatch = 0;\n for (let i = 0; i < a.length; i++) mismatch |= a.charCodeAt(i) ^ b.charCodeAt(i);\n return mismatch === 0;\n}\n\n/**\n * Return `true` if `header` is a valid signature for `payload` under `secret` and\n * within the freshness window. Never throws — use {@link constructEvent} when you\n * want the parsed event and a thrown error on failure. Pass the RAW request body.\n */\nexport async function verifySignature(\n payload: string,\n header: string | null | undefined,\n secret: string,\n opts: VerifyOptions = {},\n): Promise<boolean> {\n if (!header) return false;\n const parsed = parseHeader(header);\n if (!parsed) return false;\n\n const tolerance = opts.toleranceSeconds ?? DEFAULT_TOLERANCE_SECONDS;\n const now = Math.floor(Date.now() / 1000);\n if (Math.abs(now - parsed.timestamp) > tolerance) return false;\n\n const expected = await hmacHex(secret, `${parsed.timestamp}.${payload}`);\n return parsed.signatures.some((sig) => timingSafeEqual(sig, expected));\n}\n\n/**\n * Produce a valid `billow-signature` header for `payload` under `secret` - the inverse of\n * {@link verifySignature}. Use it to exercise your webhook endpoint in tests without\n * reverse-engineering the signing scheme. Pass the RAW body you will POST. `timestamp` (unix\n * seconds) defaults to now; pass a fixed value for a deterministic - or intentionally stale\n * (replay) - signature.\n *\n * const header = await signWebhook(rawBody, endpointSecret);\n * await fetch(url, { method: \"POST\", headers: { \"billow-signature\": header }, body: rawBody });\n */\nexport async function signWebhook(\n payload: string,\n secret: string,\n opts: { timestamp?: number } = {},\n): Promise<string> {\n const timestamp = opts.timestamp ?? Math.floor(Date.now() / 1000);\n const signature = await hmacHex(secret, `${timestamp}.${payload}`);\n return `t=${timestamp},v1=${signature}`;\n}\n\n/**\n * Verify `payload` against the `billow-signature` header and return the parsed,\n * typed {@link WebhookEvent}. Throws {@link WebhookVerificationError} if the\n * signature is invalid, the timestamp is outside the freshness window, or the body\n * isn't a billow envelope. Always pass the RAW request body — a re-serialized\n * parsed body will not match.\n */\nexport async function constructEvent(\n payload: string,\n header: string | null | undefined,\n secret: string,\n opts: VerifyOptions = {},\n): Promise<WebhookEvent> {\n if (!(await verifySignature(payload, header, secret, opts))) {\n throw new WebhookVerificationError(\"billow webhook signature verification failed\");\n }\n let parsed: unknown;\n try {\n parsed = JSON.parse(payload);\n } catch {\n throw new WebhookVerificationError(\"billow webhook payload is not valid JSON\");\n }\n if (!isWebhookEvent(parsed)) {\n throw new WebhookVerificationError(\"billow webhook payload is not a valid event envelope\");\n }\n return parsed;\n}\n\n/** A handler for one verified webhook event. May be async; a throw propagates to the caller. */\nexport type WebhookHandler = (event: WebhookEvent) => void | Promise<void>;\n\n/**\n * A map of per-event-type handlers plus an optional `onEvent` fallback. Each handler receives\n * the event NARROWED to its type, so `data` is the exact payload for that event\n * (e.g. `\"invoice.paid\": (e) => settle(e.data.invoiceId)`). Keyed by the literal event type so\n * it stays in lock-step with the contract — a new event type is dispatchable with no parallel\n * `onFooBar` name registry to keep in sync.\n */\nexport type WebhookHandlers = {\n [K in BillowEventType]?: (event: Extract<WebhookEvent, { type: K }>) => void | Promise<void>;\n} & {\n /** Called for any event that has no specific handler (receives the full union). */\n onEvent?: WebhookHandler;\n};\n\n/**\n * Build a reusable dispatcher bound to your endpoint secret + handlers: it verifies a\n * delivery (via {@link constructEvent}) then routes the typed event to the matching\n * handler, falling back to `onEvent`. Returns the verified event so the caller can log\n * or ack it. Throws {@link WebhookVerificationError} on an untrusted delivery (return a\n * 4xx) and propagates any error a handler throws (return a 5xx so billow retries).\n * Pass the RAW request body — a re-serialized parsed body won't match the signature.\n *\n * const dispatch = createWebhookDispatcher({\n * secret: process.env.BILLOW_WEBHOOK_SECRET,\n * handlers: {\n * \"invoice.paid\": (e) => fulfil(e.data.invoiceId),\n * \"subscription.canceled\": (e) => revoke(e.data),\n * onEvent: (e) => log(e.type),\n * },\n * });\n * // per request:\n * const event = await dispatch(rawBody, req.headers[\"billow-signature\"]);\n */\nexport function createWebhookDispatcher(config: {\n secret: string;\n handlers: WebhookHandlers;\n toleranceSeconds?: number;\n}): (payload: string, signatureHeader: string | null | undefined) => Promise<WebhookEvent> {\n const { secret, handlers, toleranceSeconds } = config;\n const opts = toleranceSeconds === undefined ? undefined : { toleranceSeconds };\n return async (payload, signatureHeader) => {\n const event = await constructEvent(payload, signatureHeader, secret, opts);\n // Own-property lookup, NOT `handlers[event.type]` directly: `event.type` is only\n // runtime-typed as a string, so a value colliding with an inherited key\n // (\"toString\"/\"constructor\"/\"__proto__\") would otherwise resolve to a prototype\n // method and be invoked instead of routing to `onEvent`. (Not reachable via a\n // trusted delivery — the type is HMAC-verified above and billow only emits fixed\n // event types — but the fallback contract must hold for any signature-valid type.)\n // The looked-up handler expects only its own narrowed variant; cast it to accept the full\n // union so we can invoke it with `event` — safe because the handler registered under key\n // `event.type` only ever receives the matching variant at runtime.\n const own = Object.hasOwn(handlers, event.type)\n ? (handlers[event.type] as WebhookHandler | undefined)\n : undefined;\n const handler = own ?? handlers.onEvent;\n if (handler) await handler(event);\n return event;\n };\n}\n\nfunction isWebhookEvent(value: unknown): value is WebhookEvent {\n if (typeof value !== \"object\" || value === null) return false;\n const e = value as {\n id?: unknown;\n version?: unknown;\n type?: unknown;\n createdAt?: unknown;\n data?: unknown;\n };\n return (\n typeof e.id === \"string\" &&\n typeof e.version === \"number\" &&\n typeof e.type === \"string\" &&\n typeof e.createdAt === \"string\" &&\n typeof e.data === \"object\" &&\n e.data !== null\n );\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/webhook-event-types.ts","../src/webhooks.ts"],"names":[],"mappings":";;;AASO,IAAM,mBAAA,GAAsB;AAAA,EACjC,kBAAA;AAAA,EACA,eAAA;AAAA,EACA,iBAAA;AAAA,EACA,iBAAA;AAAA,EACA,yBAAA;AAAA,EACA,cAAA;AAAA,EACA,wBAAA;AAAA,EACA,4BAAA;AAAA,EACA,wBAAA;AAAA,EACA,gCAAA;AAAA,EACA,sBAAA;AAAA,EACA,uBAAA;AAAA,EACA,6BAAA;AAAA,EACA,sCAAA;AAAA,EACA,qBAAA;AAAA,EACA,qBAAA;AAAA,EACA,sBAAA;AAAA,EACA,sBAAA;AAAA,EACA,+BAAA;AAAA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MAAA,CAAO,MAAA,CAAO,QAAA,EAAU,KAAA,CAAM,IAAI,CAAA,GACzC,QAAA,CAAS,KAAA,CAAM,IAAI,CAAA,GACpB,MAAA;AACJ,IAAA,MAAM,OAAA,GAAU,OAAO,QAAA,CAAS,OAAA;AAChC,IAAA,IAAI,OAAA,EAAS,MAAM,OAAA,CAAQ,KAAK,CAAA;AAChC,IAAA,OAAO,KAAA;AAAA,EACT,CAAA;AACF;AAEA,SAAS,eAAe,KAAA,EAAuC;AAC7D,EAAA,IAAI,OAAO,KAAA,KAAU,QAAA,IAAY,KAAA,KAAU,MAAM,OAAO,KAAA;AACxD,EAAA,MAAM,CAAA,GAAI,KAAA;AAOV,EAAA,OACE,OAAO,EAAE,EAAA,KAAO,QAAA,IAChB,OAAO,CAAA,CAAE,OAAA,KAAY,YACrB,OAAO,CAAA,CAAE,SAAS,QAAA,IAClB,OAAO,EAAE,SAAA,KAAc,QAAA,IACvB,OAAO,CAAA,CAAE,IAAA,KAAS,QAAA,IAClB,CAAA,CAAE,IAAA,KAAS,IAAA;AAEf","file":"webhooks.cjs","sourcesContent":["/**\n * The webhook event catalog: every event type billow emits, and its families as types and runtime\n * arrays (for subscription pickers and exhaustive routing). Re-exported by ./webhooks.ts.\n */\n\n/**\n * Every event type billow emits, in contract order. Mirrors `@billow/core`'s\n * EVENT_TYPES - exported as a runtime array so UIs can render a subscription picker.\n */\nexport const WEBHOOK_EVENT_TYPES = [\n \"charge.succeeded\",\n \"charge.failed\",\n \"charge.refunded\",\n \"charge.disputed\",\n \"charge.dispute_resolved\",\n \"invoice.paid\",\n \"invoice.payment_failed\",\n \"subscription.trial_started\",\n \"subscription.activated\",\n \"subscription.activation_failed\",\n \"subscription.renewed\",\n \"subscription.past_due\",\n \"subscription.payment_failed\",\n \"subscription.requires_payment_method\",\n \"subscription.unpaid\",\n \"subscription.paused\",\n \"subscription.resumed\",\n \"subscription.updated\",\n \"subscription.cancel_scheduled\",\n \"subscription.cancel_resumed\",\n \"subscription.downgrade_scheduled\",\n \"subscription.downgrade_canceled\",\n \"subscription.canceled\",\n \"subscription.ended\",\n \"entitlement.granted\",\n \"entitlement.reset\",\n \"usage.threshold_reached\",\n \"usage.alert\",\n \"usage.cap_reached\",\n \"credit_balance.threshold_crossed\",\n \"credit_grant.created\",\n \"credit_grant.expired\",\n \"credit_reservation.expired\",\n \"credit_top_up.succeeded\",\n \"credit_top_up.failed\",\n \"credit_top_up.refunded\",\n \"credit_top_up.unfulfilled\",\n \"hosted_domain.activated\",\n \"hosted_domain.dns_failing\",\n \"hosted_domain.reassignment_pending\",\n \"hosted_domain.disabled\",\n] as const;\n\n/** A valid billow event type (the compile-time freeze derived from the array above). */\nexport type BillowEventType = (typeof WEBHOOK_EVENT_TYPES)[number];\n\n/** The `charge.*` subset of {@link BillowEventType}. */\nexport type ChargeEventType = Extract<BillowEventType, `charge.${string}`>;\n/** The `invoice.*` subset of {@link BillowEventType}. */\nexport type InvoiceEventType = Extract<BillowEventType, `invoice.${string}`>;\n/** The `subscription.*` subset of {@link BillowEventType} - the events that change a subscription. */\nexport type SubscriptionEventType = Extract<BillowEventType, `subscription.${string}`>;\n/** The `entitlement.*` subset of {@link BillowEventType}. */\nexport type EntitlementEventType = Extract<BillowEventType, `entitlement.${string}`>;\n/** The `usage.*` subset of {@link BillowEventType}. */\nexport type UsageEventType = Extract<BillowEventType, `usage.${string}`>;\n/** The prepaid credits subset of {@link BillowEventType} (`credit_balance.*`, `credit_grant.*`, ...). */\nexport type CreditEventType = Extract<BillowEventType, `credit_${string}`>;\n/** The `hosted_domain.*` subset of {@link BillowEventType}: custom portal domains. */\nexport type HostedDomainEventType = Extract<BillowEventType, `hosted_domain.${string}`>;\n\n/** The subset of {@link WEBHOOK_EVENT_TYPES} sharing `prefix`, as a runtime array (order preserved). */\nfunction eventTypesWithPrefix<P extends string>(\n prefix: P,\n): readonly Extract<BillowEventType, `${P}${string}`>[] {\n return WEBHOOK_EVENT_TYPES.filter((type): type is Extract<BillowEventType, `${P}${string}`> =>\n type.startsWith(prefix),\n );\n}\n\n/** The `charge.*` event types, as a runtime array (for pickers / exhaustive routing). */\nexport const CHARGE_EVENT_TYPES: readonly ChargeEventType[] = eventTypesWithPrefix(\"charge.\");\n/** The `invoice.*` event types, as a runtime array. */\nexport const INVOICE_EVENT_TYPES: readonly InvoiceEventType[] = eventTypesWithPrefix(\"invoice.\");\n/**\n * The subscription lifecycle event types - the `subscription.*` subset of\n * {@link WEBHOOK_EVENT_TYPES}, as a runtime array. Use it (or {@link isSubscriptionEvent})\n * to select the events that affect a subscription mirror without a brittle string match.\n */\nexport const SUBSCRIPTION_EVENT_TYPES: readonly SubscriptionEventType[] =\n eventTypesWithPrefix(\"subscription.\");\n/** The `entitlement.*` event types, as a runtime array. */\nexport const ENTITLEMENT_EVENT_TYPES: readonly EntitlementEventType[] =\n eventTypesWithPrefix(\"entitlement.\");\n/** The `usage.*` event types, as a runtime array. */\nexport const USAGE_EVENT_TYPES: readonly UsageEventType[] = eventTypesWithPrefix(\"usage.\");\n/** The prepaid credits event types, as a runtime array. */\nexport const CREDIT_EVENT_TYPES: readonly CreditEventType[] = eventTypesWithPrefix(\"credit_\");\n/** The `hosted_domain.*` event types, as a runtime array. */\nexport const HOSTED_DOMAIN_EVENT_TYPES: readonly HostedDomainEventType[] =\n eventTypesWithPrefix(\"hosted_domain.\");\n\n/** Whether `type` is a subscription lifecycle event (`subscription.*`); narrows the type. */\nexport function isSubscriptionEvent(type: string): type is SubscriptionEventType {\n return type.startsWith(\"subscription.\");\n}\n","/**\n * Verify and parse billow webhook deliveries.\n *\n * billow signs each delivery with HMAC-SHA256 over `\"<timestamp>.<rawBody>\"` and\n * sends it in the `billow-signature` header as `t=<unix-seconds>,v1=<hex>`. The\n * timestamp lets you reject replays outside a freshness window.\n *\n * Verification is async and uses the Web Crypto API (`globalThis.crypto.subtle`),\n * so the same code runs in Node 20+, edge runtimes, Cloudflare Workers, Deno, and\n * Bun - it never imports `node:crypto`.\n *\n * import { constructEvent } from \"@usebillow/sdk/webhooks\";\n *\n * const event = await constructEvent(rawBody, req.headers[\"billow-signature\"], secret);\n * switch (event.type) {\n * case \"invoice.paid\": // …\n * }\n */\n\nimport type { CreditGrantKind, CreditThresholdLevel } from \"./types/credits\";\nimport type {\n HostedDomainActivatedData,\n HostedDomainDisabledData,\n HostedDomainDnsFailingData,\n HostedDomainReassignmentPendingData,\n} from \"./types/hosted-domains\";\nimport type {\n BillowEventType,\n EntitlementEventType,\n InvoiceEventType,\n SubscriptionEventType,\n} from \"./webhook-event-types\";\n\nexport * from \"./webhook-event-types\";\n\n/**\n * The fields every webhook envelope carries. Each {@link WebhookEvent} variant intersects\n * this with its own `type` + payload-typed `data`.\n */\nexport interface WebhookEventEnvelope {\n /** Stable event id - your idempotency key (delivery is at-least-once). */\n id: string;\n /** Envelope schema version. */\n version: number;\n /** ISO-8601 timestamp of when the event was recorded. */\n createdAt: string;\n}\n\n// --- Per-event-group payloads -------------------------------------------------------------\n// Shapes mirror what the server emits (packages/server/src/services: charges.ts, billing.ts,\n// renewal/*, subscriptions/*, entitlements/*). Grouped where a group's emitters are uniform;\n// `usage.*` is split per event because its emitters diverge. `customerExternalId` is added to\n// every customer-scoped payload by the server's outbox emitter (events.ts).\n\n/** `charge.succeeded` / `charge.failed`. */\nexport interface ChargeEventData {\n chargeId: string;\n /**\n * `false` on a `charge.failed` that closed a checkout its customer abandoned long before: no\n * \"payment failed\" email was sent to the customer. Absent otherwise.\n */\n notifyCustomer?: false;\n}\n/** `charge.refunded`, emitted once for each succeeded refund transition. */\nexport interface ChargeRefundedEventData {\n chargeId: string;\n refundId: string;\n amount: number;\n cumulativeAmount: number;\n currency: string;\n}\n/** Stable dispute facts shared by the opened and resolved events. */\nexport interface ChargeDisputeEventData {\n chargeId: string;\n disputeId: string;\n amount: number;\n currency: string;\n reason: string | null;\n state: \"open\" | \"won\" | \"lost\";\n}\n/** `invoice.paid` / `invoice.payment_failed`. */\nexport interface InvoiceEventData {\n invoiceId: string;\n chargeId: string;\n /**\n * `false` on an `invoice.payment_failed` that closed a checkout its customer abandoned long\n * before: no \"payment failed\" email was sent to the customer. Absent otherwise.\n */\n notifyCustomer?: false;\n}\n/** Any `subscription.*` lifecycle event. */\nexport interface SubscriptionEventData {\n subscriptionId: string;\n customerId: string;\n customerExternalId: string;\n /** The subscription's plan - so a consumer knows which product the event is about. */\n productId: string;\n productSlug: string;\n /** The product's metadata map (Stripe-style); `{}` when the plan carries none. */\n productMetadata: Record<string, string>;\n /** Set on dunning events that reference the unpaid invoice (`unpaid`, `requires_payment_method`). */\n invoiceId?: string;\n /** Set on lifecycle-ending events (`ended`, downgrade-driven `updated`). */\n reason?: string;\n /** Present when a downgrade is scheduled; null when that schedule is cleared. */\n scheduledChange?: {\n productVersionId: string;\n productId: string;\n productSlug: string;\n productName: string;\n effectiveAt: string | null;\n } | null;\n}\n/** `entitlement.granted` / `entitlement.reset`. */\nexport interface EntitlementEventData {\n subscriptionId: string;\n customerId: string;\n customerExternalId: string;\n featureId: string;\n /** Remaining allowance; `null` when the feature is unlimited. */\n balance: number | null;\n /** Whether the feature grants unlimited usage. */\n unlimited: boolean;\n}\n/** Fields shared by every `usage.*` event. */\nexport interface UsageEventBase {\n subscriptionId: string;\n customerId: string;\n customerExternalId: string;\n /** Feature slug. */\n feature: string;\n featureName: string;\n /** Aggregate usage after this step. */\n used: number;\n /** Included allowance; `null` when unlimited. */\n allowance: number | null;\n /** Remaining allowance; `null` when unlimited. */\n balance: number | null;\n}\n/** `usage.threshold_reached` - a built-in usage threshold was crossed. */\nexport interface UsageThresholdReachedData extends UsageEventBase {\n featureId: string;\n /** The threshold crossed (currently only the included allowance being exhausted). */\n level: \"exhausted\";\n}\n/** `usage.alert` - a configured usage alert fired. */\nexport interface UsageAlertData extends UsageEventBase {\n metric: string;\n threshold: number;\n recurring: boolean;\n notifyCustomer: boolean;\n}\n/** `usage.cap_reached` - a configured spend/usage cap was reached. */\nexport interface UsageCapReachedData extends UsageEventBase {\n metric: string;\n cap: number;\n capAt: number;\n}\n\n// Prepaid credits: every credit quantity is a decimal string of microcredits, never a number.\n// Payloads carry ids, codes and quantities, never a grant's, reservation's or top-up's reason or\n// metadata.\n\n/** Fields shared by every prepaid credits event. */\nexport interface CreditEventBase {\n customerId: string;\n customerExternalId: string;\n}\n/**\n * `credit_balance.threshold_crossed` - the balance moved to another level, in either direction\n * (raise a low-balance banner, or clear it). `exhausted` when nothing is spendable; otherwise\n * `critical` / `low` at or below the percentages of `thresholds.reference`, else `normal`.\n */\nexport interface CreditThresholdCrossedData extends CreditEventBase {\n level: CreditThresholdLevel;\n previousLevel: CreditThresholdLevel;\n /** The balance the level was judged on, as of `asOf`; re-read the balance for truth. */\n balance: { spendable: string; held: string; asOf: string };\n thresholds: { lowPercent: number; criticalPercent: number; reference: string | null };\n}\n/** `credit_grant.created` - credits were granted. */\nexport interface CreditGrantCreatedData extends CreditEventBase {\n grantId: string;\n kind: CreditGrantKind;\n amount: string;\n /** For an `included` grant, its window's end. */\n expiresAt: string | null;\n eligibility: string[] | null;\n topUpId: string | null;\n /** An `included` grant's subscription; null for every other kind. */\n subscriptionId: string | null;\n /** The billing period an `included` grant's window belongs to; null for every other kind. */\n periodStart: string | null;\n periodEnd: string | null;\n}\n/**\n * `credit_grant.expired` - one expiry took `expired` credits off a grant: its unheld credits when\n * it expired (or when an early end of its included window brought its expiry forward), or a held\n * part that came back to it afterwards (one more event each).\n */\nexport interface CreditGrantExpiredData extends CreditEventBase {\n grantId: string;\n kind: CreditGrantKind;\n expiresAt: string | null;\n expired: string;\n /**\n * Why it expired: `grant_expired` - the grant reached its expiry; `subscription_canceled` /\n * `subscription_charged_back` - an `included` grant whose subscription was canceled immediately,\n * or whose period's payment was lost to a chargeback, ended early (`expiresAt` is then the end).\n */\n reason: \"grant_expired\" | \"subscription_canceled\" | \"subscription_charged_back\";\n /** The `expire` ledger transaction. */\n transactionId: string;\n}\n/** `credit_reservation.expired` - a hold passed its expiry unsettled and was released. */\nexport interface CreditReservationExpiredData extends CreditEventBase {\n reservationId: string;\n operationKey: string;\n category: string;\n amount: string;\n expiresAt: string;\n}\n/** What every `credit_top_up.*` event says about the purchase and its payment. */\nexport interface CreditTopUpEventBase extends CreditEventBase {\n topUpId: string;\n packId: string;\n chargeId: string;\n /** What the payment collects, in minor units of `currency`. */\n amount: number;\n currency: string;\n /** The terms bought. */\n credits: string;\n bonusCredits: string;\n}\n/** `credit_top_up.succeeded` - the payment succeeded and its credits (and any bonus) were granted. */\nexport interface CreditTopUpSucceededData extends CreditTopUpEventBase {\n purchasedGrantId: string | null;\n bonusGrantId: string | null;\n}\n/**\n * `credit_top_up.failed` - the payment failed. A later payment on the same checkout can still\n * succeed it: `credit_top_up.succeeded` may follow for the same top-up.\n */\nexport type CreditTopUpFailedData = CreditTopUpEventBase;\n/** `credit_top_up.unfulfilled` - paid after the customer was erased: nothing granted, refund it. */\nexport type CreditTopUpUnfulfilledData = CreditTopUpEventBase;\n/**\n * `credit_top_up.refunded` - a refund or lost chargeback revoked the top-up's credits in\n * proportion to the money returned.\n */\nexport interface CreditTopUpRefundedData extends CreditTopUpEventBase {\n cause: \"refund\" | \"chargeback\";\n /** Money returned so far (refunds plus lost disputes, at most what was charged), minor units. */\n amountReturned: number;\n /** Microcredits this refund or chargeback revoked. */\n revokedNow: string;\n /** Microcredits revoked so far in all. */\n revoked: string;\n /** Of them, what the customer had already spent and nothing has paid back. */\n shortfall: string;\n}\n\n/**\n * The verified webhook envelope billow POSTs to your endpoint - a discriminated union on\n * {@link WebhookEvent.type}. `switch` (or a {@link WebhookHandlers} map) on `type` and `data`\n * narrows to the exact payload for that event.\n *\n * switch (event.type) {\n * case \"invoice.paid\": settle(event.data.invoiceId); break; // InvoiceEventData\n * case \"subscription.canceled\": revoke(event.data.customerExternalId); break;\n * }\n */\nexport type WebhookEventDataMap = {\n [K in \"charge.succeeded\" | \"charge.failed\"]: ChargeEventData;\n} & {\n \"charge.refunded\": ChargeRefundedEventData;\n} & {\n [K in \"charge.disputed\" | \"charge.dispute_resolved\"]: ChargeDisputeEventData;\n} & {\n [K in InvoiceEventType]: InvoiceEventData;\n} & {\n [K in SubscriptionEventType]: SubscriptionEventData;\n} & {\n [K in EntitlementEventType]: EntitlementEventData;\n} & {\n \"usage.threshold_reached\": UsageThresholdReachedData;\n \"usage.alert\": UsageAlertData;\n \"usage.cap_reached\": UsageCapReachedData;\n} & {\n \"credit_balance.threshold_crossed\": CreditThresholdCrossedData;\n \"credit_grant.created\": CreditGrantCreatedData;\n \"credit_grant.expired\": CreditGrantExpiredData;\n \"credit_reservation.expired\": CreditReservationExpiredData;\n \"credit_top_up.succeeded\": CreditTopUpSucceededData;\n \"credit_top_up.failed\": CreditTopUpFailedData;\n \"credit_top_up.refunded\": CreditTopUpRefundedData;\n \"credit_top_up.unfulfilled\": CreditTopUpUnfulfilledData;\n} & {\n \"hosted_domain.activated\": HostedDomainActivatedData;\n \"hosted_domain.dns_failing\": HostedDomainDnsFailingData;\n \"hosted_domain.reassignment_pending\": HostedDomainReassignmentPendingData;\n \"hosted_domain.disabled\": HostedDomainDisabledData;\n};\n\n/** One distributive union member per event literal, derived from the payload map. */\nexport type WebhookEvent = {\n [K in BillowEventType]: WebhookEventEnvelope & { type: K; data: WebhookEventDataMap[K] };\n}[BillowEventType];\n\nexport interface VerifyOptions {\n /**\n * Max age (seconds) of a delivery's signature timestamp before it's rejected as\n * a possible replay. Default 300 (5 minutes).\n */\n toleranceSeconds?: number;\n}\n\n/** Thrown by {@link constructEvent} when a delivery can't be trusted. */\nexport class WebhookVerificationError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"WebhookVerificationError\";\n }\n}\n\nconst DEFAULT_TOLERANCE_SECONDS = 300;\nconst encoder = new TextEncoder();\n\ninterface ParsedHeader {\n timestamp: number;\n signatures: string[];\n}\n\n/** Parse `t=<unix>,v1=<hex>[,v1=<hex>…]` - multiple v1 supports key rotation. */\nfunction parseHeader(header: string): ParsedHeader | null {\n let timestamp = Number.NaN;\n const signatures: string[] = [];\n for (const part of header.split(\",\")) {\n const eq = part.indexOf(\"=\");\n if (eq === -1) continue;\n const key = part.slice(0, eq).trim();\n const value = part.slice(eq + 1).trim();\n if (key === \"t\") timestamp = Number(value);\n else if (key === \"v1\") signatures.push(value);\n }\n if (!Number.isFinite(timestamp) || signatures.length === 0) return null;\n return { timestamp, signatures };\n}\n\nasync function hmacHex(secret: string, payload: string): Promise<string> {\n const key = await crypto.subtle.importKey(\n \"raw\",\n encoder.encode(secret),\n { name: \"HMAC\", hash: \"SHA-256\" },\n false,\n [\"sign\"],\n );\n const sig = await crypto.subtle.sign(\"HMAC\", key, encoder.encode(payload));\n return Array.from(new Uint8Array(sig), (b) => b.toString(16).padStart(2, \"0\")).join(\"\");\n}\n\n/** Constant-time compare of two equal-length hex strings (no early exit). */\nfunction timingSafeEqual(a: string, b: string): boolean {\n if (a.length !== b.length) return false;\n let mismatch = 0;\n for (let i = 0; i < a.length; i++) mismatch |= a.charCodeAt(i) ^ b.charCodeAt(i);\n return mismatch === 0;\n}\n\n/**\n * Return `true` if `header` is a valid signature for `payload` under `secret` and\n * within the freshness window. Never throws - use {@link constructEvent} when you\n * want the parsed event and a thrown error on failure. Pass the RAW request body.\n */\nexport async function verifySignature(\n payload: string,\n header: string | null | undefined,\n secret: string,\n opts: VerifyOptions = {},\n): Promise<boolean> {\n if (!header) return false;\n const parsed = parseHeader(header);\n if (!parsed) return false;\n\n const tolerance = opts.toleranceSeconds ?? DEFAULT_TOLERANCE_SECONDS;\n const now = Math.floor(Date.now() / 1000);\n if (Math.abs(now - parsed.timestamp) > tolerance) return false;\n\n const expected = await hmacHex(secret, `${parsed.timestamp}.${payload}`);\n return parsed.signatures.some((sig) => timingSafeEqual(sig, expected));\n}\n\n/**\n * Produce a valid `billow-signature` header for `payload` under `secret` - the inverse of\n * {@link verifySignature}. Use it to exercise your webhook endpoint in tests without\n * reverse-engineering the signing scheme. Pass the RAW body you will POST. `timestamp` (unix\n * seconds) defaults to now; pass a fixed value for a deterministic - or intentionally stale\n * (replay) - signature.\n *\n * const header = await signWebhook(rawBody, endpointSecret);\n * await fetch(url, { method: \"POST\", headers: { \"billow-signature\": header }, body: rawBody });\n */\nexport async function signWebhook(\n payload: string,\n secret: string,\n opts: { timestamp?: number } = {},\n): Promise<string> {\n const timestamp = opts.timestamp ?? Math.floor(Date.now() / 1000);\n const signature = await hmacHex(secret, `${timestamp}.${payload}`);\n return `t=${timestamp},v1=${signature}`;\n}\n\n/**\n * Verify `payload` against the `billow-signature` header and return the parsed,\n * typed {@link WebhookEvent}. Throws {@link WebhookVerificationError} if the\n * signature is invalid, the timestamp is outside the freshness window, or the body\n * isn't a billow envelope. Always pass the RAW request body - a re-serialized\n * parsed body will not match.\n */\nexport async function constructEvent(\n payload: string,\n header: string | null | undefined,\n secret: string,\n opts: VerifyOptions = {},\n): Promise<WebhookEvent> {\n if (!(await verifySignature(payload, header, secret, opts))) {\n throw new WebhookVerificationError(\"billow webhook signature verification failed\");\n }\n let parsed: unknown;\n try {\n parsed = JSON.parse(payload);\n } catch {\n throw new WebhookVerificationError(\"billow webhook payload is not valid JSON\");\n }\n if (!isWebhookEvent(parsed)) {\n throw new WebhookVerificationError(\"billow webhook payload is not a valid event envelope\");\n }\n return parsed;\n}\n\n/** A handler for one verified webhook event. May be async; a throw propagates to the caller. */\nexport type WebhookHandler = (event: WebhookEvent) => void | Promise<void>;\n\n/**\n * A map of per-event-type handlers plus an optional `onEvent` fallback. Each handler receives\n * the event NARROWED to its type, so `data` is the exact payload for that event\n * (e.g. `\"invoice.paid\": (e) => settle(e.data.invoiceId)`). Keyed by the literal event type so\n * it stays in lock-step with the contract - a new event type is dispatchable with no parallel\n * `onFooBar` name registry to keep in sync.\n */\nexport type WebhookHandlers = {\n [K in BillowEventType]?: (event: Extract<WebhookEvent, { type: K }>) => void | Promise<void>;\n} & {\n /** Called for any event that has no specific handler (receives the full union). */\n onEvent?: WebhookHandler;\n};\n\n/**\n * Build a reusable dispatcher bound to your endpoint secret + handlers: it verifies a\n * delivery (via {@link constructEvent}) then routes the typed event to the matching\n * handler, falling back to `onEvent`. Returns the verified event so the caller can log\n * or ack it. Throws {@link WebhookVerificationError} on an untrusted delivery (return a\n * 4xx) and propagates any error a handler throws (return a 5xx so billow retries).\n * Pass the RAW request body - a re-serialized parsed body won't match the signature.\n *\n * const dispatch = createWebhookDispatcher({\n * secret: process.env.BILLOW_WEBHOOK_SECRET,\n * handlers: {\n * \"invoice.paid\": (e) => fulfil(e.data.invoiceId),\n * \"subscription.canceled\": (e) => revoke(e.data),\n * onEvent: (e) => log(e.type),\n * },\n * });\n * // per request:\n * const event = await dispatch(rawBody, req.headers[\"billow-signature\"]);\n */\nexport function createWebhookDispatcher(config: {\n secret: string;\n handlers: WebhookHandlers;\n toleranceSeconds?: number;\n}): (payload: string, signatureHeader: string | null | undefined) => Promise<WebhookEvent> {\n const { secret, handlers, toleranceSeconds } = config;\n const opts = toleranceSeconds === undefined ? undefined : { toleranceSeconds };\n return async (payload, signatureHeader) => {\n const event = await constructEvent(payload, signatureHeader, secret, opts);\n // Own-property lookup, NOT `handlers[event.type]` directly: `event.type` is only\n // runtime-typed as a string, so a value colliding with an inherited key\n // (\"toString\"/\"constructor\"/\"__proto__\") would otherwise resolve to a prototype\n // method and be invoked instead of routing to `onEvent`. (Not reachable via a\n // trusted delivery - the type is HMAC-verified above and billow only emits fixed\n // event types - but the fallback contract must hold for any signature-valid type.)\n // The looked-up handler expects only its own narrowed variant; cast it to accept the full\n // union so we can invoke it with `event` - safe because the handler registered under key\n // `event.type` only ever receives the matching variant at runtime.\n const own = Object.hasOwn(handlers, event.type)\n ? (handlers[event.type] as WebhookHandler | undefined)\n : undefined;\n const handler = own ?? handlers.onEvent;\n if (handler) await handler(event);\n return event;\n };\n}\n\nfunction isWebhookEvent(value: unknown): value is WebhookEvent {\n if (typeof value !== \"object\" || value === null) return false;\n const e = value as {\n id?: unknown;\n version?: unknown;\n type?: unknown;\n createdAt?: unknown;\n data?: unknown;\n };\n return (\n typeof e.id === \"string\" &&\n typeof e.version === \"number\" &&\n typeof e.type === \"string\" &&\n typeof e.createdAt === \"string\" &&\n typeof e.data === \"object\" &&\n e.data !== null\n );\n}\n"]}
|
package/dist/webhooks.d.cts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { C as CreditGrantKind, a as CreditThresholdLevel, H as HostedDomainActivatedData, b as HostedDomainDnsFailingData, c as HostedDomainReassignmentPendingData, d as HostedDomainDisabledData } from './hosted-domains-
|
|
2
|
-
import './index.d-
|
|
1
|
+
import { C as CreditGrantKind, a as CreditThresholdLevel, H as HostedDomainActivatedData, b as HostedDomainDnsFailingData, c as HostedDomainReassignmentPendingData, d as HostedDomainDisabledData } from './hosted-domains-Ci6jeNAe.cjs';
|
|
2
|
+
import './index.d-DSEYhV2c.cjs';
|
|
3
3
|
import 'zod';
|
|
4
4
|
|
|
5
5
|
/**
|
|
@@ -57,7 +57,7 @@ declare function isSubscriptionEvent(type: string): type is SubscriptionEventTyp
|
|
|
57
57
|
*
|
|
58
58
|
* Verification is async and uses the Web Crypto API (`globalThis.crypto.subtle`),
|
|
59
59
|
* so the same code runs in Node 20+, edge runtimes, Cloudflare Workers, Deno, and
|
|
60
|
-
* Bun
|
|
60
|
+
* Bun - it never imports `node:crypto`.
|
|
61
61
|
*
|
|
62
62
|
* import { constructEvent } from "@usebillow/sdk/webhooks";
|
|
63
63
|
*
|
|
@@ -72,7 +72,7 @@ declare function isSubscriptionEvent(type: string): type is SubscriptionEventTyp
|
|
|
72
72
|
* this with its own `type` + payload-typed `data`.
|
|
73
73
|
*/
|
|
74
74
|
interface WebhookEventEnvelope {
|
|
75
|
-
/** Stable event id
|
|
75
|
+
/** Stable event id - your idempotency key (delivery is at-least-once). */
|
|
76
76
|
id: string;
|
|
77
77
|
/** Envelope schema version. */
|
|
78
78
|
version: number;
|
|
@@ -120,7 +120,7 @@ interface SubscriptionEventData {
|
|
|
120
120
|
subscriptionId: string;
|
|
121
121
|
customerId: string;
|
|
122
122
|
customerExternalId: string;
|
|
123
|
-
/** The subscription's plan
|
|
123
|
+
/** The subscription's plan - so a consumer knows which product the event is about. */
|
|
124
124
|
productId: string;
|
|
125
125
|
productSlug: string;
|
|
126
126
|
/** The product's metadata map (Stripe-style); `{}` when the plan carries none. */
|
|
@@ -164,20 +164,20 @@ interface UsageEventBase {
|
|
|
164
164
|
/** Remaining allowance; `null` when unlimited. */
|
|
165
165
|
balance: number | null;
|
|
166
166
|
}
|
|
167
|
-
/** `usage.threshold_reached`
|
|
167
|
+
/** `usage.threshold_reached` - a built-in usage threshold was crossed. */
|
|
168
168
|
interface UsageThresholdReachedData extends UsageEventBase {
|
|
169
169
|
featureId: string;
|
|
170
170
|
/** The threshold crossed (currently only the included allowance being exhausted). */
|
|
171
171
|
level: "exhausted";
|
|
172
172
|
}
|
|
173
|
-
/** `usage.alert`
|
|
173
|
+
/** `usage.alert` - a configured usage alert fired. */
|
|
174
174
|
interface UsageAlertData extends UsageEventBase {
|
|
175
175
|
metric: string;
|
|
176
176
|
threshold: number;
|
|
177
177
|
recurring: boolean;
|
|
178
178
|
notifyCustomer: boolean;
|
|
179
179
|
}
|
|
180
|
-
/** `usage.cap_reached`
|
|
180
|
+
/** `usage.cap_reached` - a configured spend/usage cap was reached. */
|
|
181
181
|
interface UsageCapReachedData extends UsageEventBase {
|
|
182
182
|
metric: string;
|
|
183
183
|
cap: number;
|
|
@@ -213,19 +213,32 @@ interface CreditGrantCreatedData extends CreditEventBase {
|
|
|
213
213
|
grantId: string;
|
|
214
214
|
kind: CreditGrantKind;
|
|
215
215
|
amount: string;
|
|
216
|
+
/** For an `included` grant, its window's end. */
|
|
216
217
|
expiresAt: string | null;
|
|
217
218
|
eligibility: string[] | null;
|
|
218
219
|
topUpId: string | null;
|
|
220
|
+
/** An `included` grant's subscription; null for every other kind. */
|
|
221
|
+
subscriptionId: string | null;
|
|
222
|
+
/** The billing period an `included` grant's window belongs to; null for every other kind. */
|
|
223
|
+
periodStart: string | null;
|
|
224
|
+
periodEnd: string | null;
|
|
219
225
|
}
|
|
220
226
|
/**
|
|
221
227
|
* `credit_grant.expired` - one expiry took `expired` credits off a grant: its unheld credits when
|
|
222
|
-
* it expired
|
|
228
|
+
* it expired (or when an early end of its included window brought its expiry forward), or a held
|
|
229
|
+
* part that came back to it afterwards (one more event each).
|
|
223
230
|
*/
|
|
224
231
|
interface CreditGrantExpiredData extends CreditEventBase {
|
|
225
232
|
grantId: string;
|
|
226
233
|
kind: CreditGrantKind;
|
|
227
234
|
expiresAt: string | null;
|
|
228
235
|
expired: string;
|
|
236
|
+
/**
|
|
237
|
+
* Why it expired: `grant_expired` - the grant reached its expiry; `subscription_canceled` /
|
|
238
|
+
* `subscription_charged_back` - an `included` grant whose subscription was canceled immediately,
|
|
239
|
+
* or whose period's payment was lost to a chargeback, ended early (`expiresAt` is then the end).
|
|
240
|
+
*/
|
|
241
|
+
reason: "grant_expired" | "subscription_canceled" | "subscription_charged_back";
|
|
229
242
|
/** The `expire` ledger transaction. */
|
|
230
243
|
transactionId: string;
|
|
231
244
|
}
|
|
@@ -277,7 +290,7 @@ interface CreditTopUpRefundedData extends CreditTopUpEventBase {
|
|
|
277
290
|
shortfall: string;
|
|
278
291
|
}
|
|
279
292
|
/**
|
|
280
|
-
* The verified webhook envelope billow POSTs to your endpoint
|
|
293
|
+
* The verified webhook envelope billow POSTs to your endpoint - a discriminated union on
|
|
281
294
|
* {@link WebhookEvent.type}. `switch` (or a {@link WebhookHandlers} map) on `type` and `data`
|
|
282
295
|
* narrows to the exact payload for that event.
|
|
283
296
|
*
|
|
@@ -337,7 +350,7 @@ declare class WebhookVerificationError extends Error {
|
|
|
337
350
|
}
|
|
338
351
|
/**
|
|
339
352
|
* Return `true` if `header` is a valid signature for `payload` under `secret` and
|
|
340
|
-
* within the freshness window. Never throws
|
|
353
|
+
* within the freshness window. Never throws - use {@link constructEvent} when you
|
|
341
354
|
* want the parsed event and a thrown error on failure. Pass the RAW request body.
|
|
342
355
|
*/
|
|
343
356
|
declare function verifySignature(payload: string, header: string | null | undefined, secret: string, opts?: VerifyOptions): Promise<boolean>;
|
|
@@ -358,7 +371,7 @@ declare function signWebhook(payload: string, secret: string, opts?: {
|
|
|
358
371
|
* Verify `payload` against the `billow-signature` header and return the parsed,
|
|
359
372
|
* typed {@link WebhookEvent}. Throws {@link WebhookVerificationError} if the
|
|
360
373
|
* signature is invalid, the timestamp is outside the freshness window, or the body
|
|
361
|
-
* isn't a billow envelope. Always pass the RAW request body
|
|
374
|
+
* isn't a billow envelope. Always pass the RAW request body - a re-serialized
|
|
362
375
|
* parsed body will not match.
|
|
363
376
|
*/
|
|
364
377
|
declare function constructEvent(payload: string, header: string | null | undefined, secret: string, opts?: VerifyOptions): Promise<WebhookEvent>;
|
|
@@ -368,7 +381,7 @@ type WebhookHandler = (event: WebhookEvent) => void | Promise<void>;
|
|
|
368
381
|
* A map of per-event-type handlers plus an optional `onEvent` fallback. Each handler receives
|
|
369
382
|
* the event NARROWED to its type, so `data` is the exact payload for that event
|
|
370
383
|
* (e.g. `"invoice.paid": (e) => settle(e.data.invoiceId)`). Keyed by the literal event type so
|
|
371
|
-
* it stays in lock-step with the contract
|
|
384
|
+
* it stays in lock-step with the contract - a new event type is dispatchable with no parallel
|
|
372
385
|
* `onFooBar` name registry to keep in sync.
|
|
373
386
|
*/
|
|
374
387
|
type WebhookHandlers = {
|
|
@@ -385,7 +398,7 @@ type WebhookHandlers = {
|
|
|
385
398
|
* handler, falling back to `onEvent`. Returns the verified event so the caller can log
|
|
386
399
|
* or ack it. Throws {@link WebhookVerificationError} on an untrusted delivery (return a
|
|
387
400
|
* 4xx) and propagates any error a handler throws (return a 5xx so billow retries).
|
|
388
|
-
* Pass the RAW request body
|
|
401
|
+
* Pass the RAW request body - a re-serialized parsed body won't match the signature.
|
|
389
402
|
*
|
|
390
403
|
* const dispatch = createWebhookDispatcher({
|
|
391
404
|
* secret: process.env.BILLOW_WEBHOOK_SECRET,
|