@codelitdev/platform 0.2.0 → 0.4.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 (36) hide show
  1. package/README.md +32 -0
  2. package/dist/billing/drizzle.d.ts +21 -0
  3. package/dist/billing/drizzle.d.ts.map +1 -0
  4. package/dist/billing/drizzle.js +41 -0
  5. package/dist/billing/drizzle.js.map +1 -0
  6. package/dist/billing/errors.d.ts +14 -0
  7. package/dist/billing/errors.d.ts.map +1 -0
  8. package/dist/billing/errors.js +29 -0
  9. package/dist/billing/errors.js.map +1 -0
  10. package/dist/billing/grants.d.ts +72 -0
  11. package/dist/billing/grants.d.ts.map +1 -0
  12. package/dist/billing/grants.js +102 -0
  13. package/dist/billing/grants.js.map +1 -0
  14. package/dist/billing/index.d.ts +7 -0
  15. package/dist/billing/index.d.ts.map +1 -0
  16. package/dist/billing/index.js +7 -0
  17. package/dist/billing/index.js.map +1 -0
  18. package/dist/billing/return-url.d.ts +6 -0
  19. package/dist/billing/return-url.d.ts.map +1 -0
  20. package/dist/billing/return-url.js +26 -0
  21. package/dist/billing/return-url.js.map +1 -0
  22. package/dist/billing/sensitive-values.d.ts +19 -0
  23. package/dist/billing/sensitive-values.d.ts.map +1 -0
  24. package/dist/billing/sensitive-values.js +75 -0
  25. package/dist/billing/sensitive-values.js.map +1 -0
  26. package/dist/billing/webhook.d.ts +27 -0
  27. package/dist/billing/webhook.d.ts.map +1 -0
  28. package/dist/billing/webhook.js +64 -0
  29. package/dist/billing/webhook.js.map +1 -0
  30. package/dist/billing/workers.d.ts +26 -0
  31. package/dist/billing/workers.d.ts.map +1 -0
  32. package/dist/billing/workers.js +49 -0
  33. package/dist/billing/workers.js.map +1 -0
  34. package/dist/types.d.ts +5 -0
  35. package/dist/types.d.ts.map +1 -1
  36. package/package.json +26 -1
package/README.md CHANGED
@@ -9,3 +9,35 @@ performs no network I/O. Products implement authentication, tenant, and
9
9
  authorization adapters.
10
10
 
11
11
  See `docs/architecture.md` §6.4 and ADR 0001.
12
+
13
+ ## Billing adapters
14
+
15
+ `@codelitdev/platform/billing` holds the adapters a product needs around
16
+ `@codelitdev/billing` (architecture §10, ADR 0013). Install
17
+ `@codelitdev/billing` to use it; the root export does not need it.
18
+
19
+ | Export | Use |
20
+ | --- | --- |
21
+ | `createBillingActionGrants` | Single-use action grants: `issue` a token after authenticating a recent session, `grant` to build the workflow input, and `authorization` as `createBilling({ authorization })`. |
22
+ | `createAesGcmSensitiveValues`, `aesGcmSensitiveValuesFromEnv` | AES-256-GCM for `createBilling({ sensitiveValues })`, with previous keys for rotation. |
23
+ | `createReturnUrlValidator` | Origin allowlist for `createBilling({ returnUrlValidator })`. |
24
+ | `startBillingWorkers` | Runs the maintenance batches on timers; `stop()` on shutdown. |
25
+ | `handleBillingWebhook`, `billingWebhookPath` | Verifies, stores, and acknowledges a provider webhook at `POST /webhooks/billing/<provider>`. |
26
+ | `billingErrorResponse` | Maps workflow errors to HTTP status and a stable code. |
27
+
28
+ `@codelitdev/platform/billing/drizzle` provides
29
+ `drizzleVerificationGrantStore(db, verification)`, which keeps grants in
30
+ Better Auth's `verification` table. It needs `drizzle-orm`.
31
+
32
+ ```ts
33
+ const grants = createBillingActionGrants({
34
+ store: drizzleVerificationGrantStore(db, verification),
35
+ });
36
+ const billing = createBilling({
37
+ // ...
38
+ authorization: grants.authorization,
39
+ sensitiveValues: aesGcmSensitiveValuesFromEnv(),
40
+ returnUrlValidator: createReturnUrlValidator([process.env.WEB_ORIGIN!]),
41
+ });
42
+ const workers = startBillingWorkers({ billing, workerId: `billing-${process.pid}` });
43
+ ```
@@ -0,0 +1,21 @@
1
+ import type { ActionGrantStore } from "./grants.js";
2
+ type VerificationTable = {
3
+ id: unknown;
4
+ identifier: unknown;
5
+ value: unknown;
6
+ expiresAt: unknown;
7
+ createdAt: unknown;
8
+ updatedAt: unknown;
9
+ };
10
+ type TransactionalDb = {
11
+ transaction<T>(fn: (tx: any) => Promise<T>): Promise<T>;
12
+ insert(table: any): any;
13
+ delete(table: any): any;
14
+ };
15
+ /**
16
+ * Stores billing action grants in Better Auth's `verification` table, which
17
+ * every Better Auth product already has. Pass the product's Drizzle table.
18
+ */
19
+ export declare function drizzleVerificationGrantStore(db: TransactionalDb, verification: VerificationTable): ActionGrantStore;
20
+ export {};
21
+ //# sourceMappingURL=drizzle.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"drizzle.d.ts","sourceRoot":"","sources":["../../src/billing/drizzle.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,aAAa,CAAC;AAEpD,KAAK,iBAAiB,GAAG;IACvB,EAAE,EAAE,OAAO,CAAC;IACZ,UAAU,EAAE,OAAO,CAAC;IACpB,KAAK,EAAE,OAAO,CAAC;IACf,SAAS,EAAE,OAAO,CAAC;IACnB,SAAS,EAAE,OAAO,CAAC;IACnB,SAAS,EAAE,OAAO,CAAC;CACpB,CAAC;AAEF,KAAK,eAAe,GAAG;IACrB,WAAW,CAAC,CAAC,EAAE,EAAE,EAAE,CAAC,EAAE,EAAE,GAAG,KAAK,OAAO,CAAC,CAAC,CAAC,GAAG,OAAO,CAAC,CAAC,CAAC,CAAC;IACxD,MAAM,CAAC,KAAK,EAAE,GAAG,GAAG,GAAG,CAAC;IACxB,MAAM,CAAC,KAAK,EAAE,GAAG,GAAG,GAAG,CAAC;CACzB,CAAC;AAEF;;;GAGG;AACH,wBAAgB,6BAA6B,CAC3C,EAAE,EAAE,eAAe,EACnB,YAAY,EAAE,iBAAiB,GAC9B,gBAAgB,CAmClB"}
@@ -0,0 +1,41 @@
1
+ import { and, eq, gt, like, lte } from "drizzle-orm";
2
+ /**
3
+ * Stores billing action grants in Better Auth's `verification` table, which
4
+ * every Better Auth product already has. Pass the product's Drizzle table.
5
+ */
6
+ export function drizzleVerificationGrantStore(db, verification) {
7
+ const table = verification;
8
+ return {
9
+ async insert(record) {
10
+ const now = new Date();
11
+ await db.insert(table).values({
12
+ id: crypto.randomUUID(),
13
+ identifier: record.identifier,
14
+ value: record.value,
15
+ expiresAt: record.expiresAt,
16
+ createdAt: now,
17
+ updatedAt: now,
18
+ });
19
+ },
20
+ async take(identifier, now) {
21
+ return db.transaction(async (tx) => {
22
+ const [row] = await tx
23
+ .select()
24
+ .from(table)
25
+ .where(and(eq(table.identifier, identifier), gt(table.expiresAt, now)))
26
+ .limit(1)
27
+ .for("update");
28
+ if (!row)
29
+ return null;
30
+ await tx.delete(table).where(eq(table.id, row.id));
31
+ return row.value;
32
+ });
33
+ },
34
+ async purgeExpired(now) {
35
+ await db
36
+ .delete(table)
37
+ .where(and(like(table.identifier, "billing-action:%"), lte(table.expiresAt, now)));
38
+ },
39
+ };
40
+ }
41
+ //# sourceMappingURL=drizzle.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"drizzle.js","sourceRoot":"","sources":["../../src/billing/drizzle.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,GAAG,EAAE,EAAE,EAAE,EAAE,EAAE,IAAI,EAAE,GAAG,EAAE,MAAM,aAAa,CAAC;AAkBrD;;;GAGG;AACH,MAAM,UAAU,6BAA6B,CAC3C,EAAmB,EACnB,YAA+B;IAE/B,MAAM,KAAK,GAAG,YAAmB,CAAC;IAClC,OAAO;QACL,KAAK,CAAC,MAAM,CAAC,MAAM;YACjB,MAAM,GAAG,GAAG,IAAI,IAAI,EAAE,CAAC;YACvB,MAAM,EAAE,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC,MAAM,CAAC;gBAC5B,EAAE,EAAE,MAAM,CAAC,UAAU,EAAE;gBACvB,UAAU,EAAE,MAAM,CAAC,UAAU;gBAC7B,KAAK,EAAE,MAAM,CAAC,KAAK;gBACnB,SAAS,EAAE,MAAM,CAAC,SAAS;gBAC3B,SAAS,EAAE,GAAG;gBACd,SAAS,EAAE,GAAG;aACf,CAAC,CAAC;QACL,CAAC;QACD,KAAK,CAAC,IAAI,CAAC,UAAU,EAAE,GAAG;YACxB,OAAO,EAAE,CAAC,WAAW,CAAC,KAAK,EAAE,EAAE,EAAE,EAAE;gBACjC,MAAM,CAAC,GAAG,CAAC,GAAG,MAAM,EAAE;qBACnB,MAAM,EAAE;qBACR,IAAI,CAAC,KAAK,CAAC;qBACX,KAAK,CAAC,GAAG,CAAC,EAAE,CAAC,KAAK,CAAC,UAAU,EAAE,UAAU,CAAC,EAAE,EAAE,CAAC,KAAK,CAAC,SAAS,EAAE,GAAG,CAAC,CAAC,CAAC;qBACtE,KAAK,CAAC,CAAC,CAAC;qBACR,GAAG,CAAC,QAAQ,CAAC,CAAC;gBACjB,IAAI,CAAC,GAAG;oBAAE,OAAO,IAAI,CAAC;gBACtB,MAAM,EAAE,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC,KAAK,CAAC,EAAE,CAAC,KAAK,CAAC,EAAE,EAAE,GAAG,CAAC,EAAE,CAAC,CAAC,CAAC;gBACnD,OAAO,GAAG,CAAC,KAAe,CAAC;YAC7B,CAAC,CAAC,CAAC;QACL,CAAC;QACD,KAAK,CAAC,YAAY,CAAC,GAAG;YACpB,MAAM,EAAE;iBACL,MAAM,CAAC,KAAK,CAAC;iBACb,KAAK,CACJ,GAAG,CAAC,IAAI,CAAC,KAAK,CAAC,UAAU,EAAE,kBAAkB,CAAC,EAAE,GAAG,CAAC,KAAK,CAAC,SAAS,EAAE,GAAG,CAAC,CAAC,CAC3E,CAAC;QACN,CAAC;KACF,CAAC;AACJ,CAAC"}
@@ -0,0 +1,14 @@
1
+ export type BillingErrorResponse = {
2
+ status: 403 | 409 | 502 | 503;
3
+ body: {
4
+ error: string;
5
+ retryable?: boolean;
6
+ };
7
+ };
8
+ /**
9
+ * Maps an error thrown by a billing workflow to an HTTP response. Workflow
10
+ * errors expose only their stable code. Anything else becomes a generic
11
+ * failure, so provider and SDK messages never reach the client.
12
+ */
13
+ export declare function billingErrorResponse(error: unknown): BillingErrorResponse;
14
+ //# sourceMappingURL=errors.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"errors.d.ts","sourceRoot":"","sources":["../../src/billing/errors.ts"],"names":[],"mappings":"AAMA,MAAM,MAAM,oBAAoB,GAAG;IACjC,MAAM,EAAE,GAAG,GAAG,GAAG,GAAG,GAAG,GAAG,GAAG,CAAC;IAC9B,IAAI,EAAE;QAAE,KAAK,EAAE,MAAM,CAAC;QAAC,SAAS,CAAC,EAAE,OAAO,CAAA;KAAE,CAAC;CAC9C,CAAC;AAKF;;;;GAIG;AACH,wBAAgB,oBAAoB,CAAC,KAAK,EAAE,OAAO,GAAG,oBAAoB,CAqBzE"}
@@ -0,0 +1,29 @@
1
+ import { BillingCompositionError, BillingConfigurationError, BillingWorkflowError, } from "@codelitdev/billing/core";
2
+ const FORBIDDEN = new Set(["grant_invalid", "grant_consumed", "payer_mismatch"]);
3
+ const UNAVAILABLE = new Set(["provider_unavailable", "catalog_unavailable"]);
4
+ /**
5
+ * Maps an error thrown by a billing workflow to an HTTP response. Workflow
6
+ * errors expose only their stable code. Anything else becomes a generic
7
+ * failure, so provider and SDK messages never reach the client.
8
+ */
9
+ export function billingErrorResponse(error) {
10
+ if (error instanceof BillingWorkflowError) {
11
+ const status = FORBIDDEN.has(error.code)
12
+ ? 403
13
+ : UNAVAILABLE.has(error.code)
14
+ ? 503
15
+ : 409;
16
+ return {
17
+ status,
18
+ body: error.retryable
19
+ ? { error: error.code, retryable: true }
20
+ : { error: error.code },
21
+ };
22
+ }
23
+ if (error instanceof BillingConfigurationError ||
24
+ error instanceof BillingCompositionError) {
25
+ return { status: 503, body: { error: "billing_not_configured" } };
26
+ }
27
+ return { status: 502, body: { error: "billing_request_failed" } };
28
+ }
29
+ //# sourceMappingURL=errors.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"errors.js","sourceRoot":"","sources":["../../src/billing/errors.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,uBAAuB,EACvB,yBAAyB,EACzB,oBAAoB,GACrB,MAAM,0BAA0B,CAAC;AAOlC,MAAM,SAAS,GAAG,IAAI,GAAG,CAAC,CAAC,eAAe,EAAE,gBAAgB,EAAE,gBAAgB,CAAC,CAAC,CAAC;AACjF,MAAM,WAAW,GAAG,IAAI,GAAG,CAAC,CAAC,sBAAsB,EAAE,qBAAqB,CAAC,CAAC,CAAC;AAE7E;;;;GAIG;AACH,MAAM,UAAU,oBAAoB,CAAC,KAAc;IACjD,IAAI,KAAK,YAAY,oBAAoB,EAAE,CAAC;QAC1C,MAAM,MAAM,GAAG,SAAS,CAAC,GAAG,CAAC,KAAK,CAAC,IAAI,CAAC;YACtC,CAAC,CAAC,GAAG;YACL,CAAC,CAAC,WAAW,CAAC,GAAG,CAAC,KAAK,CAAC,IAAI,CAAC;gBAC3B,CAAC,CAAC,GAAG;gBACL,CAAC,CAAC,GAAG,CAAC;QACV,OAAO;YACL,MAAM;YACN,IAAI,EAAE,KAAK,CAAC,SAAS;gBACnB,CAAC,CAAC,EAAE,KAAK,EAAE,KAAK,CAAC,IAAI,EAAE,SAAS,EAAE,IAAI,EAAE;gBACxC,CAAC,CAAC,EAAE,KAAK,EAAE,KAAK,CAAC,IAAI,EAAE;SAC1B,CAAC;IACJ,CAAC;IACD,IACE,KAAK,YAAY,yBAAyB;QAC1C,KAAK,YAAY,uBAAuB,EACxC,CAAC;QACD,OAAO,EAAE,MAAM,EAAE,GAAG,EAAE,IAAI,EAAE,EAAE,KAAK,EAAE,wBAAwB,EAAE,EAAE,CAAC;IACpE,CAAC;IACD,OAAO,EAAE,MAAM,EAAE,GAAG,EAAE,IAAI,EAAE,EAAE,KAAK,EAAE,wBAAwB,EAAE,EAAE,CAAC;AACpE,CAAC"}
@@ -0,0 +1,72 @@
1
+ import type { BillingAction, BillingActionGrant, BillingAuthorizationPort } from "@codelitdev/billing/workflows";
2
+ import { type Clock } from "../clock.js";
3
+ /** Storage for single-use action tokens. */
4
+ export interface ActionGrantStore {
5
+ insert(record: {
6
+ identifier: string;
7
+ value: string;
8
+ expiresAt: Date;
9
+ }): Promise<void>;
10
+ /**
11
+ * Atomically removes the unexpired record with this identifier and returns
12
+ * its value, or returns null when there is none.
13
+ */
14
+ take(identifier: string, now: Date): Promise<string | null>;
15
+ /** Removes expired records. Optional housekeeping. */
16
+ purgeExpired?(now: Date): Promise<void>;
17
+ }
18
+ export type BillingGrantTarget = {
19
+ kind: string;
20
+ id: string;
21
+ };
22
+ export type IssueBillingGrantResult = {
23
+ ok: true;
24
+ token: string;
25
+ expiresAt: Date;
26
+ } | {
27
+ ok: false;
28
+ error: "recent_authentication_required";
29
+ };
30
+ /**
31
+ * Single-use billing action grants. The product issues a token after it has
32
+ * authenticated the person, then passes it back with the billing request. A
33
+ * token is bound to one person, session, action, and target, expires quickly,
34
+ * and works once. `authorization` is the port to pass to `createBilling`.
35
+ */
36
+ export declare function createBillingActionGrants(options: {
37
+ store: ActionGrantStore;
38
+ clock?: Clock;
39
+ /** How long an issued token stays valid. Default five minutes. */
40
+ ttlMs?: number;
41
+ /** How recently the session must have signed in. Default 15 minutes. */
42
+ recentAuthMaxAgeMs?: number;
43
+ }): {
44
+ issue: (input: {
45
+ actorId: string;
46
+ sessionId: string;
47
+ /** When the session signed in. */
48
+ sessionCreatedAt: Date;
49
+ action: BillingAction;
50
+ target: BillingGrantTarget;
51
+ }) => Promise<IssueBillingGrantResult>;
52
+ grant: (input: {
53
+ token: string;
54
+ actorId: string;
55
+ sessionId: string;
56
+ action: BillingAction;
57
+ target: BillingGrantTarget;
58
+ }) => BillingActionGrant;
59
+ authorization: BillingAuthorizationPort;
60
+ };
61
+ /** In-memory grant store for tests and single-process development. */
62
+ export declare class MemoryActionGrantStore implements ActionGrantStore {
63
+ private readonly records;
64
+ insert(record: {
65
+ identifier: string;
66
+ value: string;
67
+ expiresAt: Date;
68
+ }): Promise<void>;
69
+ take(identifier: string, now: Date): Promise<string | null>;
70
+ purgeExpired(now: Date): Promise<void>;
71
+ }
72
+ //# sourceMappingURL=grants.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"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E,MAAM,CAAC;QAClB,kCAAkC;QAClC,gBAAgB,EAAE,IAAI,CAAC;QACvB,MAAM,EAAE,aAAa,CAAC;QACtB,MAAM,EAAE,kBAAkB,CAAC;KAC5B,KAAG,OAAO,CAAC,uBAAuB,CAAC;mBAuBd;QACpB,KAAK,EAAE,MAAM,CAAC;QACd,OAAO,EAAE,MAAM,CAAC;QAChB,SAAS,EAAE,MAAM,CAAC;QAClB,MAAM,EAAE,aAAa,CAAC;QACtB,MAAM,EAAE,kBAAkB,CAAC;KAC5B,KAAG,kBAAkB;;EAuCvB;AAED,sEAAsE;AACtE,qBAAa,sBAAuB,YAAW,gBAAgB;IAC7D,OAAO,CAAC,QAAQ,CAAC,OAAO,CAAyD;IAE3E,MAAM,CAAC,MAAM,EAAE;QAAE,UAAU,EAAE,MAAM,CAAC;QAAC,KAAK,EAAE,MAAM,CAAC;QAAC,SAAS,EAAE,IAAI,CAAA;KAAE;IAOrE,IAAI,CAAC,UAAU,EAAE,MAAM,EAAE,GAAG,EAAE,IAAI;IAOlC,YAAY,CAAC,GAAG,EAAE,IAAI;CAK7B"}
@@ -0,0 +1,102 @@
1
+ import { createHash, randomBytes } from "node:crypto";
2
+ import { BillingWorkflowError } from "@codelitdev/billing/core";
3
+ import { systemClock } from "../clock.js";
4
+ const IDENTIFIER_PREFIX = "billing-action:";
5
+ function identifierFor(token) {
6
+ return `${IDENTIFIER_PREFIX}${createHash("sha256").update(token, "utf8").digest("hex")}`;
7
+ }
8
+ /**
9
+ * Single-use billing action grants. The product issues a token after it has
10
+ * authenticated the person, then passes it back with the billing request. A
11
+ * token is bound to one person, session, action, and target, expires quickly,
12
+ * and works once. `authorization` is the port to pass to `createBilling`.
13
+ */
14
+ export function createBillingActionGrants(options) {
15
+ const clock = options.clock ?? systemClock;
16
+ const ttlMs = options.ttlMs ?? 5 * 60 * 1000;
17
+ const recentAuthMaxAgeMs = options.recentAuthMaxAgeMs ?? 15 * 60 * 1000;
18
+ async function issue(input) {
19
+ const now = clock.now();
20
+ if (now.getTime() - input.sessionCreatedAt.getTime() > recentAuthMaxAgeMs) {
21
+ return { ok: false, error: "recent_authentication_required" };
22
+ }
23
+ await options.store.purgeExpired?.(now);
24
+ const token = randomBytes(32).toString("base64url");
25
+ const expiresAt = new Date(now.getTime() + ttlMs);
26
+ const value = {
27
+ actorId: input.actorId,
28
+ sessionId: input.sessionId,
29
+ action: input.action,
30
+ target: input.target,
31
+ };
32
+ await options.store.insert({
33
+ identifier: identifierFor(token),
34
+ value: JSON.stringify(value),
35
+ expiresAt,
36
+ });
37
+ return { ok: true, token, expiresAt };
38
+ }
39
+ /** Builds the grant to pass to a billing workflow from a token the client sent. */
40
+ function grant(input) {
41
+ const now = clock.now();
42
+ return {
43
+ grantId: `${input.sessionId}:${input.token}`,
44
+ actorId: input.actorId,
45
+ action: input.action,
46
+ target: input.target,
47
+ issuedAt: now,
48
+ expiresAt: new Date(now.getTime() + ttlMs),
49
+ };
50
+ }
51
+ const authorization = {
52
+ async consume(candidate, expectedAction, expectedTarget, now) {
53
+ const separator = candidate.grantId.lastIndexOf(":");
54
+ const sessionId = candidate.grantId.slice(0, separator);
55
+ const token = candidate.grantId.slice(separator + 1);
56
+ if (separator <= 0 || !token)
57
+ throw new BillingWorkflowError("grant_invalid");
58
+ const raw = await options.store.take(identifierFor(token), now);
59
+ if (!raw)
60
+ throw new BillingWorkflowError("grant_invalid");
61
+ let stored;
62
+ try {
63
+ stored = JSON.parse(raw);
64
+ }
65
+ catch {
66
+ throw new BillingWorkflowError("grant_invalid");
67
+ }
68
+ if (stored.actorId !== candidate.actorId ||
69
+ stored.sessionId !== sessionId ||
70
+ stored.action !== expectedAction ||
71
+ stored.target?.kind !== expectedTarget.kind ||
72
+ stored.target?.id !== expectedTarget.id) {
73
+ throw new BillingWorkflowError("grant_invalid");
74
+ }
75
+ },
76
+ };
77
+ return { issue, grant, authorization };
78
+ }
79
+ /** In-memory grant store for tests and single-process development. */
80
+ export class MemoryActionGrantStore {
81
+ records = new Map();
82
+ async insert(record) {
83
+ this.records.set(record.identifier, {
84
+ value: record.value,
85
+ expiresAt: record.expiresAt,
86
+ });
87
+ }
88
+ async take(identifier, now) {
89
+ const record = this.records.get(identifier);
90
+ if (!record)
91
+ return null;
92
+ this.records.delete(identifier);
93
+ return record.expiresAt.getTime() > now.getTime() ? record.value : null;
94
+ }
95
+ async purgeExpired(now) {
96
+ for (const [identifier, record] of this.records) {
97
+ if (record.expiresAt.getTime() <= now.getTime())
98
+ this.records.delete(identifier);
99
+ }
100
+ }
101
+ }
102
+ //# sourceMappingURL=grants.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"grants.js","sourceRoot":"","sources":["../../src/billing/grants.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,WAAW,EAAE,MAAM,aAAa,CAAC;AACtD,OAAO,EAAE,oBAAoB,EAAE,MAAM,0BAA0B,CAAC;AAMhE,OAAO,EAAc,WAAW,EAAE,MAAM,aAAa,CAAC;AA2BtD,MAAM,iBAAiB,GAAG,iBAAiB,CAAC;AAE5C,SAAS,aAAa,CAAC,KAAa;IAClC,OAAO,GAAG,iBAAiB,GAAG,UAAU,CAAC,QAAQ,CAAC,CAAC,MAAM,CAAC,KAAK,EAAE,MAAM,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,EAAE,CAAC;AAC3F,CAAC;AAED;;;;;GAKG;AACH,MAAM,UAAU,yBAAyB,CAAC,OAOzC;IACC,MAAM,KAAK,GAAG,OAAO,CAAC,KAAK,IAAI,WAAW,CAAC;IAC3C,MAAM,KAAK,GAAG,OAAO,CAAC,KAAK,IAAI,CAAC,GAAG,EAAE,GAAG,IAAI,CAAC;IAC7C,MAAM,kBAAkB,GAAG,OAAO,CAAC,kBAAkB,IAAI,EAAE,GAAG,EAAE,GAAG,IAAI,CAAC;IAExE,KAAK,UAAU,KAAK,CAAC,KAOpB;QACC,MAAM,GAAG,GAAG,KAAK,CAAC,GAAG,EAAE,CAAC;QACxB,IA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ACH,CAAC;KACF,CAAC;IAEF,OAAO,EAAE,KAAK,EAAE,KAAK,EAAE,aAAa,EAAE,CAAC;AACzC,CAAC;AAED,sEAAsE;AACtE,MAAM,OAAO,sBAAsB;IAChB,OAAO,GAAG,IAAI,GAAG,EAA8C,CAAC;IAEjF,KAAK,CAAC,MAAM,CAAC,MAA8D;QACzE,IAAI,CAAC,OAAO,CAAC,GAAG,CAAC,MAAM,CAAC,UAAU,EAAE;YAClC,KAAK,EAAE,MAAM,CAAC,KAAK;YACnB,SAAS,EAAE,MAAM,CAAC,SAAS;SAC5B,CAAC,CAAC;IACL,CAAC;IAED,KAAK,CAAC,IAAI,CAAC,UAAkB,EAAE,GAAS;QACtC,MAAM,MAAM,GAAG,IAAI,CAAC,OAAO,CAAC,GAAG,CAAC,UAAU,CAAC,CAAC;QAC5C,IAAI,CAAC,MAAM;YAAE,OAAO,IAAI,CAAC;QACzB,IAAI,CAAC,OAAO,CAAC,MAAM,CAAC,UAAU,CAAC,CAAC;QAChC,OAAO,MAAM,CAAC,SAAS,CAAC,OAAO,EAAE,GAAG,GAAG,CAAC,OAAO,EAAE,CAAC,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC,CAAC,IAAI,CAAC;IAC1E,CAAC;IAED,KAAK,CAAC,YAAY,CAAC,GAAS;QAC1B,KAAK,MAAM,CAAC,UAAU,EAAE,MAAM,CAAC,IAAI,IAAI,CAAC,OAAO,EAAE,CAAC;YAChD,IAAI,MAAM,CAAC,SAAS,CAAC,OAAO,EAAE,IAAI,GAAG,CAAC,OAAO,EAAE;gBAAE,IAAI,CAAC,OAAO,CAAC,MAAM,CAAC,UAAU,CAAC,CAAC;QACnF,CAAC;IACH,CAAC;CACF"}
@@ -0,0 +1,7 @@
1
+ export { type BillingErrorResponse, billingErrorResponse } from "./errors.js";
2
+ export { type ActionGrantStore, type BillingGrantTarget, createBillingActionGrants, type IssueBillingGrantResult, MemoryActionGrantStore, } from "./grants.js";
3
+ export { createReturnUrlValidator } from "./return-url.js";
4
+ export { aesGcmSensitiveValuesFromEnv, createAesGcmSensitiveValues, } from "./sensitive-values.js";
5
+ export { type BillingWebhookResponse, billingWebhookPath, handleBillingWebhook, } from "./webhook.js";
6
+ export { type BillingWorkerTask, startBillingWorkers } from "./workers.js";
7
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/billing/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,oBAAoB,EAAE,oBAAoB,EAAE,MAAM,aAAa,CAAC;AAC9E,OAAO,EACL,KAAK,gBAAgB,EACrB,KAAK,kBAAkB,EACvB,yBAAyB,EACzB,KAAK,uBAAuB,EAC5B,sBAAsB,GACvB,MAAM,aAAa,CAAC;AACrB,OAAO,EAAE,wBAAwB,EAAE,MAAM,iBAAiB,CAAC;AAC3D,OAAO,EACL,4BAA4B,EAC5B,2BAA2B,GAC5B,MAAM,uBAAuB,CAAC;AAC/B,OAAO,EACL,KAAK,sBAAsB,EAC3B,kBAAkB,EAClB,oBAAoB,GACrB,MAAM,cAAc,CAAC;AACtB,OAAO,EAAE,KAAK,iBAAiB,EAAE,mBAAmB,EAAE,MAAM,cAAc,CAAC"}
@@ -0,0 +1,7 @@
1
+ export { billingErrorResponse } from "./errors.js";
2
+ export { createBillingActionGrants, MemoryActionGrantStore, } from "./grants.js";
3
+ export { createReturnUrlValidator } from "./return-url.js";
4
+ export { aesGcmSensitiveValuesFromEnv, createAesGcmSensitiveValues, } from "./sensitive-values.js";
5
+ export { billingWebhookPath, handleBillingWebhook, } from "./webhook.js";
6
+ export { startBillingWorkers } from "./workers.js";
7
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/billing/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAA6B,oBAAoB,EAAE,MAAM,aAAa,CAAC;AAC9E,OAAO,EAGL,yBAAyB,EAEzB,sBAAsB,GACvB,MAAM,aAAa,CAAC;AACrB,OAAO,EAAE,wBAAwB,EAAE,MAAM,iBAAiB,CAAC;AAC3D,OAAO,EACL,4BAA4B,EAC5B,2BAA2B,GAC5B,MAAM,uBAAuB,CAAC;AAC/B,OAAO,EAEL,kBAAkB,EAClB,oBAAoB,GACrB,MAAM,cAAc,CAAC;AACtB,OAAO,EAA0B,mBAAmB,EAAE,MAAM,cAAc,CAAC"}
@@ -0,0 +1,6 @@
1
+ /**
2
+ * Validator for `createBilling({ returnUrlValidator })`: accepts only URLs on
3
+ * one of the given origins, such as the product's dashboard.
4
+ */
5
+ export declare function createReturnUrlValidator(allowedOrigins: readonly string[]): (url: string) => boolean;
6
+ //# sourceMappingURL=return-url.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"return-url.d.ts","sourceRoot":"","sources":["../../src/billing/return-url.ts"],"names":[],"mappings":"AAAA;;;GAGG;AACH,wBAAgB,wBAAwB,CACtC,cAAc,EAAE,SAAS,MAAM,EAAE,GAChC,CAAC,GAAG,EAAE,MAAM,KAAK,OAAO,CAoB1B"}
@@ -0,0 +1,26 @@
1
+ /**
2
+ * Validator for `createBilling({ returnUrlValidator })`: accepts only URLs on
3
+ * one of the given origins, such as the product's dashboard.
4
+ */
5
+ export function createReturnUrlValidator(allowedOrigins) {
6
+ const origins = new Set();
7
+ for (const origin of allowedOrigins) {
8
+ try {
9
+ origins.add(new URL(origin).origin);
10
+ }
11
+ catch {
12
+ // An invalid origin allows nothing.
13
+ }
14
+ }
15
+ return (url) => {
16
+ try {
17
+ const parsed = new URL(url);
18
+ return ((parsed.protocol === "https:" || parsed.protocol === "http:") &&
19
+ origins.has(parsed.origin));
20
+ }
21
+ catch {
22
+ return false;
23
+ }
24
+ };
25
+ }
26
+ //# sourceMappingURL=return-url.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"return-url.js","sourceRoot":"","sources":["../../src/billing/return-url.ts"],"names":[],"mappings":"AAAA;;;GAGG;AACH,MAAM,UAAU,wBAAwB,CACtC,cAAiC;IAEjC,MAAM,OAAO,GAAG,IAAI,GAAG,EAAU,CAAC;IAClC,KAAK,MAAM,MAAM,IAAI,cAAc,EAAE,CAAC;QACpC,IAAI,CAAC;YACH,OAAO,CAAC,GAAG,CAAC,IAAI,GAAG,CAAC,MAAM,CAAC,CAAC,MAAM,CAAC,CAAC;QACtC,CAAC;QAAC,MAAM,CAAC;YACP,oCAAoC;QACtC,CAAC;IACH,CAAC;IACD,OAAO,CAAC,GAAG,EAAE,EAAE;QACb,IAAI,CAAC;YACH,MAAM,MAAM,GAAG,IAAI,GAAG,CAAC,GAAG,CAAC,CAAC;YAC5B,OAAO,CACL,CAAC,MAAM,CAAC,QAAQ,KAAK,QAAQ,IAAI,MAAM,CAAC,QAAQ,KAAK,OAAO,CAAC;gBAC7D,OAAO,CAAC,GAAG,CAAC,MAAM,CAAC,MAAM,CAAC,CAC3B,CAAC;QACJ,CAAC;QAAC,MAAM,CAAC;YACP,OAAO,KAAK,CAAC;QACf,CAAC;IACH,CAAC,CAAC;AACJ,CAAC"}
@@ -0,0 +1,19 @@
1
+ import type { SensitiveValuePort } from "@codelitdev/billing/workflows";
2
+ /**
3
+ * AES-256-GCM encryption for the billing engine's stored secrets, such as
4
+ * checkout URLs and webhook payloads. Ciphertext is `iv.tag.ciphertext` in
5
+ * base64. Decryption also tries `previousKeys`, so a key can be rotated
6
+ * without losing stored values.
7
+ */
8
+ export declare function createAesGcmSensitiveValues(options: {
9
+ /** Base64 of 32 random bytes, for example from `openssl rand -base64 32`. */
10
+ key: string;
11
+ previousKeys?: readonly string[];
12
+ keyVersion?: string;
13
+ }): SensitiveValuePort;
14
+ /**
15
+ * Reads `BILLING_DATA_ENCRYPTION_KEY` and an optional comma-separated
16
+ * `BILLING_DATA_ENCRYPTION_KEY_PREVIOUS`.
17
+ */
18
+ export declare function aesGcmSensitiveValuesFromEnv(env?: Record<string, string | undefined>): SensitiveValuePort;
19
+ //# sourceMappingURL=sensitive-values.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"sensitive-values.d.ts","sourceRoot":"","sources":["../../src/billing/sensitive-values.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,+BAA+B,CAAC;AAYxE;;;;;GAKG;AACH,wBAAgB,2BAA2B,CAAC,OAAO,EAAE;IACnD,6EAA6E;IAC7E,GAAG,EAAE,MAAM,CAAC;IACZ,YAAY,CAAC,EAAE,SAAS,MAAM,EAAE,CAAC;IACjC,UAAU,CAAC,EAAE,MAAM,CAAC;CACrB,GAAG,kBAAkB,CAwCrB;AAED;;;GAGG;AACH,wBAAgB,4BAA4B,CAC1C,GAAG,GAAE,MAAM,CAAC,MAAM,EAAE,MAAM,GAAG,SAAS,CAAe,GACpD,kBAAkB,CAQpB"}
@@ -0,0 +1,75 @@
1
+ import { createCipheriv, createDecipheriv, randomBytes } from "node:crypto";
2
+ const ALGORITHM = "aes-256-gcm";
3
+ const BASE64 = /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/;
4
+ function parseKey(raw, name) {
5
+ if (!BASE64.test(raw))
6
+ throw new Error(`${name}_must_be_base64`);
7
+ const key = Buffer.from(raw, "base64");
8
+ if (key.length !== 32)
9
+ throw new Error(`${name}_must_be_32_bytes`);
10
+ return key;
11
+ }
12
+ /**
13
+ * AES-256-GCM encryption for the billing engine's stored secrets, such as
14
+ * checkout URLs and webhook payloads. Ciphertext is `iv.tag.ciphertext` in
15
+ * base64. Decryption also tries `previousKeys`, so a key can be rotated
16
+ * without losing stored values.
17
+ */
18
+ export function createAesGcmSensitiveValues(options) {
19
+ const current = parseKey(options.key, "billing_encryption_key");
20
+ const keys = [
21
+ current,
22
+ ...(options.previousKeys ?? []).map((key) => parseKey(key, "billing_previous_key")),
23
+ ];
24
+ const keyVersion = options.keyVersion ?? "v1";
25
+ return {
26
+ async encrypt(plaintext) {
27
+ const iv = randomBytes(12);
28
+ const cipher = createCipheriv(ALGORITHM, current, iv);
29
+ const ciphertext = Buffer.concat([
30
+ cipher.update(plaintext, "utf8"),
31
+ cipher.final(),
32
+ ]);
33
+ return {
34
+ ciphertext: [iv, cipher.getAuthTag(), ciphertext]
35
+ .map((part) => part.toString("base64"))
36
+ .join("."),
37
+ keyVersion,
38
+ };
39
+ },
40
+ async decrypt(payload) {
41
+ const [iv, tag, ciphertext] = payload.split(".");
42
+ if (!iv || !tag || !ciphertext)
43
+ throw new Error("billing_ciphertext_invalid");
44
+ for (const key of keys) {
45
+ try {
46
+ const decipher = createDecipheriv(ALGORITHM, key, Buffer.from(iv, "base64"));
47
+ decipher.setAuthTag(Buffer.from(tag, "base64"));
48
+ return Buffer.concat([
49
+ decipher.update(Buffer.from(ciphertext, "base64")),
50
+ decipher.final(),
51
+ ]).toString("utf8");
52
+ }
53
+ catch {
54
+ // try the next key
55
+ }
56
+ }
57
+ throw new Error("billing_ciphertext_authentication_failed");
58
+ },
59
+ };
60
+ }
61
+ /**
62
+ * Reads `BILLING_DATA_ENCRYPTION_KEY` and an optional comma-separated
63
+ * `BILLING_DATA_ENCRYPTION_KEY_PREVIOUS`.
64
+ */
65
+ export function aesGcmSensitiveValuesFromEnv(env = process.env) {
66
+ const key = env.BILLING_DATA_ENCRYPTION_KEY?.trim();
67
+ if (!key)
68
+ throw new Error("BILLING_DATA_ENCRYPTION_KEY_missing");
69
+ const previousKeys = (env.BILLING_DATA_ENCRYPTION_KEY_PREVIOUS ?? "")
70
+ .split(",")
71
+ .map((value) => value.trim())
72
+ .filter(Boolean);
73
+ return createAesGcmSensitiveValues({ key, previousKeys });
74
+ }
75
+ //# sourceMappingURL=sensitive-values.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"sensitive-values.js","sourceRoot":"","sources":["../../src/billing/sensitive-values.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,cAAc,EAAE,gBAAgB,EAAE,WAAW,EAAE,MAAM,aAAa,CAA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E,CAAC;IACpD,IAAI,CAAC,GAAG;QAAE,MAAM,IAAI,KAAK,CAAC,qCAAqC,CAAC,CAAC;IACjE,MAAM,YAAY,GAAG,CAAC,GAAG,CAAC,oCAAoC,IAAI,EAAE,CAAC;SAClE,KAAK,CAAC,GAAG,CAAC;SACV,GAAG,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,KAAK,CAAC,IAAI,EAAE,CAAC;SAC5B,MAAM,CAAC,OAAO,CAAC,CAAC;IACnB,OAAO,2BAA2B,CAAC,EAAE,GAAG,EAAE,YAAY,EAAE,CAAC,CAAC;AAC5D,CAAC"}
@@ -0,0 +1,27 @@
1
+ import type { BillingEngine } from "@codelitdev/billing/workflows";
2
+ /** Products mount provider webhooks at this path, for example `/webhooks/billing/dodo`. */
3
+ export declare function billingWebhookPath(provider: string): string;
4
+ export type BillingWebhookResponse = {
5
+ status: 200 | 202 | 400 | 503;
6
+ body: {
7
+ accepted: boolean;
8
+ duplicate?: boolean;
9
+ error?: string;
10
+ };
11
+ };
12
+ /**
13
+ * Handles a provider webhook: verifies and stores it, answers 202 (200 for a
14
+ * duplicate), then drains the inbox in the background. A rejected request
15
+ * gets 400; a failure to store a verified one gets 503 so the provider
16
+ * retries. Pass the raw request
17
+ * body exactly as received; signature checks fail on re-serialised JSON.
18
+ */
19
+ export declare function handleBillingWebhook(input: {
20
+ billing: Pick<BillingEngine, "ingestWebhook" | "runWebhookInboxBatch"> | null;
21
+ provider: string;
22
+ rawBody: string | Buffer | undefined;
23
+ headers: Record<string, string | string[] | undefined>;
24
+ workerId?: string;
25
+ onError?: (error: unknown) => void;
26
+ }): Promise<BillingWebhookResponse>;
27
+ //# sourceMappingURL=webhook.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"webhook.d.ts","sourceRoot":"","sources":["../../src/billing/webhook.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,+BAA+B,CAAC;AAEnE,2FAA2F;AAC3F,wBAAgB,kBAAkB,CAAC,QAAQ,EAAE,MAAM,GAAG,MAAM,CAE3D;AAED,MAAM,MAAM,sBAAsB,GAAG;IACnC,MAAM,EAAE,GAAG,GAAG,GAAG,GAAG,GAAG,GAAG,GAAG,CAAC;IAC9B,IAAI,EAAE;QAAE,QAAQ,EAAE,OAAO,CAAC;QAAC,SAAS,CAAC,EAAE,OAAO,CAAC;QAAC,KAAK,CAAC,EAAE,MAAM,CAAA;KAAE,CAAC;CAClE,CAAC;AAmBF;;;;;;GAMG;AACH,wBAAsB,oBAAoB,CAAC,KAAK,EAAE;IAChD,OAAO,EAAE,IAAI,CAAC,aAAa,EAAE,eAAe,GAAG,sBAAsB,CAAC,GAAG,IAAI,CAAC;IAC9E,QAAQ,EAAE,MAAM,CAAC;IACjB,OAAO,EAAE,MAAM,GAAG,MAAM,GAAG,SAAS,CAAC;IACrC,OAAO,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,GAAG,MAAM,EAAE,GAAG,SAAS,CAAC,CAAC;IACvD,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,OAAO,CAAC,EAAE,CAAC,KAAK,EAAE,OAAO,KAAK,IAAI,CAAC;CACpC,GAAG,OAAO,CAAC,sBAAsB,CAAC,CAkClC"}
@@ -0,0 +1,64 @@
1
+ import { BillingWorkflowError } from "@codelitdev/billing/core";
2
+ /** Products mount provider webhooks at this path, for example `/webhooks/billing/dodo`. */
3
+ export function billingWebhookPath(provider) {
4
+ return `/webhooks/billing/${provider}`;
5
+ }
6
+ /**
7
+ * A request the provider should not send again: adapters reject a bad
8
+ * signature or body with a `webhook_*` error, and the engine quarantines a
9
+ * malformed envelope. Anything else, such as a database outage, may succeed
10
+ * on redelivery.
11
+ */
12
+ function isRejectedWebhook(error) {
13
+ if (error instanceof BillingWorkflowError) {
14
+ return error.code === "operation_quarantined";
15
+ }
16
+ return (error instanceof Error &&
17
+ error.constructor === Error &&
18
+ error.message.startsWith("webhook_"));
19
+ }
20
+ /**
21
+ * Handles a provider webhook: verifies and stores it, answers 202 (200 for a
22
+ * duplicate), then drains the inbox in the background. A rejected request
23
+ * gets 400; a failure to store a verified one gets 503 so the provider
24
+ * retries. Pass the raw request
25
+ * body exactly as received; signature checks fail on re-serialised JSON.
26
+ */
27
+ export async function handleBillingWebhook(input) {
28
+ if (!input.billing) {
29
+ return { status: 503, body: { accepted: false, error: "billing_not_configured" } };
30
+ }
31
+ if (input.rawBody === undefined) {
32
+ return { status: 400, body: { accepted: false } };
33
+ }
34
+ const headers = {};
35
+ for (const [name, value] of Object.entries(input.headers)) {
36
+ if (typeof value === "string")
37
+ headers[name.toLowerCase()] = value;
38
+ else if (Array.isArray(value) && value[0])
39
+ headers[name.toLowerCase()] = value[0];
40
+ }
41
+ const body = typeof input.rawBody === "string" ? input.rawBody : input.rawBody.toString("utf8");
42
+ try {
43
+ const ingested = await input.billing.ingestWebhook({
44
+ provider: input.provider,
45
+ raw: { body, headers },
46
+ });
47
+ const billing = input.billing;
48
+ void billing
49
+ .runWebhookInboxBatch({
50
+ workerId: input.workerId ?? `billing-webhook-${process.pid}`,
51
+ })
52
+ .catch((error) => input.onError?.(error));
53
+ return ingested.duplicate
54
+ ? { status: 200, body: { accepted: true, duplicate: true } }
55
+ : { status: 202, body: { accepted: true } };
56
+ }
57
+ catch (error) {
58
+ input.onError?.(error);
59
+ return isRejectedWebhook(error)
60
+ ? { status: 400, body: { accepted: false } }
61
+ : { status: 503, body: { accepted: false } };
62
+ }
63
+ }
64
+ //# sourceMappingURL=webhook.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"webhook.js","sourceRoot":"","sources":["../../src/billing/webhook.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,oBAAoB,EAAE,MAAM,0BAA0B,CAAC;AAGhE,2FAA2F;AAC3F,MAAM,UAAU,kBAAkB,CAAC,QAAgB;IACjD,OAAO,qBAAqB,QAAQ,EAAE,CAAC;AACzC,CAAC;AAOD;;;;;GAKG;AACH,SAAS,iBAAiB,CAAC,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| "verifyRequestedCatalog" | "runWebhookInboxBatch" | "runReconciliationBatch" | "runDeadlineBatch" | "purgeExpiredSensitiveValues">;
3
+ export type BillingWorkerTask = "catalog" | "webhooks" | "reconciliation" | "deadlines" | "retention";
4
+ /**
5
+ * Runs the billing engine's maintenance batches on timers: catalog
6
+ * verification, the webhook inbox, reconciliation (including stuck-work
7
+ * discovery), deadlines, and retention of stored secrets. A tick is skipped
8
+ * while the previous one is still running. Call `stop` on shutdown, for
9
+ * example as a graceful-shutdown hook.
10
+ */
11
+ export declare function startBillingWorkers(options: {
12
+ billing: MaintainedBilling;
13
+ /** Unique per process, for example `${product}-billing-${process.pid}`. */
14
+ workerId: string;
15
+ /** Default one minute. */
16
+ intervalMs?: number;
17
+ /** How long stored secrets are kept. Default 30 days. */
18
+ retentionMs?: number;
19
+ /** Default one hour. */
20
+ retentionIntervalMs?: number;
21
+ onError?: (task: BillingWorkerTask, error: unknown) => void;
22
+ }): {
23
+ stop: () => Promise<void>;
24
+ };
25
+ export {};
26
+ //# sourceMappingURL=workers.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"workers.d.ts","sourceRoot":"","sources":["../../src/billing/workers.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,+BAA+B,CAAC;AAEnE,KAAK,iBAAiB,GAAG,IAAI,CAC3B,aAAa,EACX,wBAAwB,GACxB,wBAAwB,GACxB,sBAAsB,GACtB,wBAAwB,GACxB,kBAAkB,GAClB,6BAA6B,CAChC,CAAC;AAEF,MAAM,MAAM,iBAAiB,GACzB,SAAS,GACT,UAAU,GACV,gBAAgB,GAChB,WAAW,GACX,WAAW,CAAC;AAEhB;;;;;;GAMG;AACH,wBAAgB,mBAAmB,CAAC,OAAO,EAAE;IAC3C,OAAO,EAAE,iBAAiB,CAAC;IAC3B,2EAA2E;IAC3E,QAAQ,EAAE,MAAM,CAAC;IACjB,0BAA0B;IAC1B,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,yDAAyD;IACzD,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,wBAAwB;IACxB,mBAAmB,CAAC,EAAE,MAAM,CAAC;IAC7B,OAAO,CAAC,EAAE,CAAC,IAAI,EAAE,iBAAiB,EAAE,KAAK,EAAE,OAAO,KAAK,IAAI,CAAC;CAC7D,GAAG;IAAE,IAAI,EAAE,MAAM,OAAO,CAAC,IAAI,CAAC,CAAA;CAAE,CAmDhC"}
@@ -0,0 +1,49 @@
1
+ /**
2
+ * Runs the billing engine's maintenance batches on timers: catalog
3
+ * verification, the webhook inbox, reconciliation (including stuck-work
4
+ * discovery), deadlines, and retention of stored secrets. A tick is skipped
5
+ * while the previous one is still running. Call `stop` on shutdown, for
6
+ * example as a graceful-shutdown hook.
7
+ */
8
+ export function startBillingWorkers(options) {
9
+ const { billing, workerId } = options;
10
+ const onError = options.onError ?? (() => undefined);
11
+ const retentionMs = options.retentionMs ?? 30 * 24 * 60 * 60 * 1000;
12
+ let running = null;
13
+ async function attempt(task, fn) {
14
+ try {
15
+ await fn();
16
+ }
17
+ catch (error) {
18
+ onError(task, error);
19
+ }
20
+ }
21
+ async function tick() {
22
+ await attempt("catalog", () => billing.verifyRequestedCatalog());
23
+ await attempt("webhooks", () => billing.runWebhookInboxBatch({ workerId }));
24
+ await attempt("reconciliation", () => billing.runReconciliationBatch({ workerId: `${workerId}-reconcile` }));
25
+ await attempt("deadlines", () => billing.runDeadlineBatch());
26
+ }
27
+ function schedule(fn) {
28
+ if (running)
29
+ return;
30
+ running = fn().finally(() => {
31
+ running = null;
32
+ });
33
+ }
34
+ void attempt("catalog", () => billing.recordRequestedCatalog());
35
+ const batches = setInterval(() => schedule(tick), options.intervalMs ?? 60 * 1000);
36
+ const retention = setInterval(() => void attempt("retention", () => billing.purgeExpiredSensitiveValues({
37
+ before: new Date(Date.now() - retentionMs),
38
+ })), options.retentionIntervalMs ?? 60 * 60 * 1000);
39
+ batches.unref?.();
40
+ retention.unref?.();
41
+ return {
42
+ async stop() {
43
+ clearInterval(batches);
44
+ clearInterval(retention);
45
+ await running;
46
+ },
47
+ };
48
+ }
49
+ //# sourceMappingURL=workers.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"workers.js","sourceRoot":"","sources":["../../src/billing/workers.ts"],"names":[],"mappings":"AAmBA;;;;;;GAMG;AACH,MAAM,UAAU,mBAAmB,CAAC,OAWnC;IACC,MAAM,EAAE,OAAO,EAAE,QAAQ,EAAE,GAAG,OAAO,CAAC;IACtC,MAAM,OAAO,GAAG,OAAO,CAAC,OAAO,IAAI,CAAC,GAAG,EAAE,CAAC,SAAS,CAAC,CAAC;IACrD,MAAM,WAAW,GAAG,OAAO,CAAC,WAAW,IAAI,EAAE,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,GAAG,IAAI,CAAC;IACpE,IAAI,OAAO,GAAyB,IAAI,CAAC;IAEzC,KAAK,UAAU,OAAO,CAAC,IAAuB,EAAE,EAA0B;QACxE,IAAI,CAAC;YACH,MAAM,EAAE,EAAE,CAAC;QACb,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACf,OAAO,CAAC,IAAI,EAAE,KAAK,CAAC,CAAC;QACvB,CAAC;IACH,CAAC;IAED,KAAK,UAAU,IAAI;QACjB,MAAM,OAAO,CAAC,SAAS,EAAE,GAAG,EAAE,CAAC,OAAO,CAAC,sBAAsB,EAAE,CAAC,CAAC;QACjE,MAAM,OAAO,CAAC,UAAU,EAAE,GAAG,EAAE,CAAC,OAAO,CAAC,oBAAoB,CAAC,EAAE,QAAQ,EAAE,CAAC,CAAC,CAAC;QAC5E,MAAM,OAAO,CAAC,gBAAgB,EAAE,GAAG,EAAE,CACnC,OAAO,CAAC,sBAAsB,CAAC,EAAE,QAAQ,EAAE,GAAG,QAAQ,YAAY,EAAE,CAAC,CACtE,CAAC;QACF,MAAM,OAAO,CAAC,WAAW,EAAE,GAAG,EAAE,CAAC,OAAO,CAAC,gBAAgB,EAAE,CAAC,CAAC;IAC/D,CAAC;IAED,SAAS,QAAQ,CAAC,EAAuB;QACvC,IAAI,OAAO;YAAE,OAAO;QACpB,OAAO,GAAG,EAAE,EAAE,CAAC,OAAO,CAAC,GAAG,EAAE;YAC1B,OAAO,GAAG,IAAI,CAAC;QACjB,CAAC,CAAC,CAAC;IACL,CAAC;IAED,KAAK,OAAO,CAAC,SAAS,EAAE,GAAG,EAAE,CAAC,OAAO,CAAC,sBAAsB,EAAE,CAAC,CAAC;IAChE,MAAM,OAAO,GAAG,WAAW,CAAC,GAAG,EAAE,CAAC,QAAQ,CAAC,IAAI,CAAC,EAAE,OAAO,CAAC,UAAU,IAAI,EAAE,GAAG,IAAI,CAAC,CAAC;IACnF,MAAM,SAAS,GAAG,WAAW,CAC3B,GAAG,EAAE,CACH,KAAK,OAAO,CAAC,WAAW,EAAE,GAAG,EAAE,CAC7B,OAAO,CAAC,2BAA2B,CAAC;QAClC,MAAM,EAAE,IAAI,IAAI,CAAC,IAAI,CAAC,GAAG,EAAE,GAAG,WAAW,CAAC;KAC3C,CAAC,CACH,EACH,OAAO,CAAC,mBAAmB,IAAI,EAAE,GAAG,EAAE,GAAG,IAAI,CAC9C,CAAC;IACF,OAAO,CAAC,KAAK,EAAE,EAAE,CAAC;IAClB,SAAS,CAAC,KAAK,EAAE,EAAE,CAAC;IAEpB,OAAO;QACL,KAAK,CAAC,IAAI;YACR,aAAa,CAAC,OAAO,CAAC,CAAC;YACvB,aAAa,CAAC,SAAS,CAAC,CAAC;YACzB,MAAM,OAAO,CAAC;QAChB,CAAC;KACF,CAAC;AACJ,CAAC"}
package/dist/types.d.ts CHANGED
@@ -3,6 +3,11 @@ export type CredentialKind = "session" | "oauth" | "api_key" | "system";
3
3
  export interface PlatformCredential {
4
4
  kind: CredentialKind;
5
5
  credentialId?: string;
6
+ /**
7
+ * OAuth scopes granted to the token. Set only for `oauth` credentials;
8
+ * products narrow the principal's permissions to what these scopes allow.
9
+ */
10
+ scopes?: readonly string[];
6
11
  }
7
12
  export interface PlatformRequestContext<PrincipalId extends string, TenantId extends string, Permission extends string> {
8
13
  requestId: string;
@@ -1 +1 @@
1
- {"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AAEjD,MAAM,MAAM,cAAc,GAAG,SAAS,GAAG,OAAO,GAAG,SAAS,GAAG,QAAQ,CAAC;AAExE,MAAM,WAAW,kBAAkB;IACjC,IAAI,EAAE,cAAc,CAAC;IACrB,YAAY,CAAC,EAAE,MAAM,CAAC;CACvB;AAED,MAAM,WAAW,sBAAsB,CACrC,WAAW,SAAS,MAAM,EAC1B,QAAQ,SAAS,MAAM,EACvB,UAAU,SAAS,MAAM;IAEzB,SAAS,EAAE,MAAM,CAAC;IAClB,WAAW,EAAE,WAAW,CAAC;IACzB,QAAQ,EAAE,QAAQ,GAAG,IAAI,CAAC;IAC1B,UAAU,EAAE,kBAAkB,CAAC;IAC/B,WAAW,EAAE,WAAW,CAAC,UAAU,CAAC,CAAC;CACtC;AAED,MAAM,MAAM,oBAAoB,CAAC,WAAW,SAAS,MAAM,IACvD;IACE,IAAI,EAAE,eAAe,CAAC;IACtB,WAAW,EAAE,WAAW,CAAC;IACzB,UAAU,EAAE,kBAAkB,CAAC;CAChC,GACD;IAAE,IAAI,EAAE,QAAQ,CAAA;CAAE,GAClB;IAAE,IAAI,EAAE,UAAU,CAAC;IAAC,KAAK,EAAE,aAAa,CAAA;CAAE,CAAC;AAE/C,MAAM,WAAW,qBAAqB,CAAC,OAAO,EAAE,WAAW,SAAS,MAAM;IACxE,YAAY,CAAC,OAAO,EAAE,OAAO,GAAG,OAAO,CAAC,oBAAoB,CAAC,WAAW,CAAC,CAAC,CAAC;CAC5E;AAED,MAAM,WAAW,oBAAoB,CACnC,WAAW,SAAS,MAAM,EAC1B,QAAQ,SAAS,MAAM,EACvB,UAAU,SAAS,MAAM;IAEzB,OAAO,CAAC,KAAK,EAAE;QACb,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B,GAAG,OAAO,CAAC;QAAE,OAAO,EAAE,IAAI,CAAA;KAAE,GAAG;QAAE,OAAO,EAAE,KAAK,CAAC;QAAC,KAAK,EAAE,aAAa,CAAA;KAAE,CAAC,CAAC;CAC3E;AAED,MAAM,WAAW,SAAS,CAAC,OAAO,EAAE,KAAK;IACvC,MAAM,CAAC,OAAO,EAAE,OAAO,EAAE,KAAK,EAAE,KAAK,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;CACvD;AAED,MAAM,MAAM,aAAa,GAAG,MAAM,GAAG,KAAK,CAAC"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@codelitdev/platform",
3
- "version": "0.2.0",
3
+ "version": "0.4.0",
4
4
  "description": "Composition kernel for CodeLit Platform products",
5
5
  "author": "CodeLit",
6
6
  "type": "module",
@@ -19,6 +19,16 @@
19
19
  "types": "./dist/index.d.ts",
20
20
  "import": "./dist/index.js",
21
21
  "default": "./dist/index.js"
22
+ },
23
+ "./billing": {
24
+ "types": "./dist/billing/index.d.ts",
25
+ "import": "./dist/billing/index.js",
26
+ "default": "./dist/billing/index.js"
27
+ },
28
+ "./billing/drizzle": {
29
+ "types": "./dist/billing/drizzle.d.ts",
30
+ "import": "./dist/billing/drizzle.js",
31
+ "default": "./dist/billing/drizzle.js"
22
32
  }
23
33
  },
24
34
  "files": [
@@ -38,8 +48,23 @@
38
48
  "tag": "latest"
39
49
  },
40
50
  "devDependencies": {
51
+ "@codelitdev/billing": "workspace:*",
52
+ "@electric-sql/pglite": "^0.2.17",
41
53
  "@types/bun": "^1.4.1",
42
54
  "@types/node": "^22.14.1",
55
+ "drizzle-orm": "^0.45.2",
43
56
  "typescript": "^5.9.3"
57
+ },
58
+ "peerDependencies": {
59
+ "@codelitdev/billing": "workspace:*",
60
+ "drizzle-orm": "^0.45.2"
61
+ },
62
+ "peerDependenciesMeta": {
63
+ "@codelitdev/billing": {
64
+ "optional": true
65
+ },
66
+ "drizzle-orm": {
67
+ "optional": true
68
+ }
44
69
  }
45
70
  }