@pithy-sh/payments 0.6.0 → 0.7.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/README.md +6 -1
- package/dist/admin/coverage.d.ts.map +1 -1
- package/dist/admin/coverage.js +13 -7
- package/dist/admin/read.d.ts +60 -0
- package/dist/admin/read.d.ts.map +1 -1
- package/dist/admin/read.js +86 -2
- package/dist/audit/actions.d.ts +5 -0
- package/dist/audit/actions.d.ts.map +1 -1
- package/dist/audit/actions.js +6 -1
- package/dist/capability.d.ts +3 -3
- package/dist/capability.d.ts.map +1 -1
- package/dist/capability.js +14 -7
- package/dist/client/api.d.ts +25 -9
- package/dist/client/api.d.ts.map +1 -1
- package/dist/client/api.js +68 -12
- package/dist/client/hooks.d.ts +27 -39
- package/dist/client/hooks.d.ts.map +1 -1
- package/dist/client/hooks.js +166 -315
- package/dist/client/projection.d.ts +25 -18
- package/dist/client/projection.d.ts.map +1 -1
- package/dist/client/railChoice.d.ts +46 -0
- package/dist/client/railChoice.d.ts.map +1 -0
- package/dist/client/railChoice.js +48 -0
- package/dist/data/webhookEvent.d.ts +67 -0
- package/dist/data/webhookEvent.d.ts.map +1 -1
- package/dist/data/webhookEvent.js +76 -1
- package/dist/http/responses.d.ts +64 -0
- package/dist/http/responses.d.ts.map +1 -1
- package/dist/http/responses.js +34 -1
- package/dist/http/routes.d.ts +1 -0
- package/dist/http/routes.d.ts.map +1 -1
- package/dist/http/routes.js +64 -11
- package/dist/http/schemas.d.ts +19 -0
- package/dist/http/schemas.d.ts.map +1 -1
- package/dist/http/schemas.js +18 -1
- package/dist/http/scopes.d.ts +15 -6
- package/dist/http/scopes.d.ts.map +1 -1
- package/dist/http/scopes.js +55 -5
- package/dist/http/view.d.ts +9 -2
- package/dist/http/view.d.ts.map +1 -1
- package/dist/http/view.js +29 -1
- package/dist/http/webhookGuard.d.ts +7 -1
- package/dist/http/webhookGuard.d.ts.map +1 -1
- package/dist/http/webhookGuard.js +3 -2
- package/dist/migrations/0003_webhook_targets.d.ts +19 -0
- package/dist/migrations/0003_webhook_targets.d.ts.map +1 -0
- package/dist/migrations/0003_webhook_targets.js +29 -0
- package/dist/processing/activities.d.ts +9 -0
- package/dist/processing/activities.d.ts.map +1 -0
- package/dist/processing/activities.js +30 -0
- package/dist/projection/orphans.d.ts.map +1 -1
- package/dist/projection/orphans.js +15 -6
- package/dist/projection/targets.d.ts +50 -0
- package/dist/projection/targets.d.ts.map +1 -0
- package/dist/projection/targets.js +50 -0
- package/dist/purge/contribution.d.ts +32 -0
- package/dist/purge/contribution.d.ts.map +1 -0
- package/dist/purge/contribution.js +120 -0
- package/dist/version.generated.d.ts +1 -1
- package/dist/version.generated.js +1 -1
- package/dist/workflows/paddleSweep.d.ts.map +1 -1
- package/dist/workflows/paddleSweep.js +20 -9
- package/docs/lemon-squeezy.md +1 -1
- package/docs/paddle.md +2 -0
- package/package.json +6 -4
- package/src/admin/coverage.ts +13 -9
- package/src/admin/read.ts +135 -0
- package/src/audit/actions.ts +5 -0
- package/src/capability.ts +25 -15
- package/src/client/api.ts +74 -11
- package/src/client/hooks.ts +206 -301
- package/src/client/projection.ts +25 -18
- package/src/client/railChoice.ts +72 -0
- package/src/data/webhookEvent.ts +115 -0
- package/src/http/responses.ts +66 -0
- package/src/http/routes.ts +73 -11
- package/src/http/schemas.ts +26 -0
- package/src/http/scopes.ts +58 -6
- package/src/http/view.ts +31 -1
- package/src/http/webhookGuard.ts +23 -3
- package/src/migrations/0003_webhook_targets.ts +34 -0
- package/src/processing/activities.ts +34 -0
- package/src/projection/orphans.ts +28 -11
- package/src/projection/targets.ts +66 -0
- package/src/purge/contribution.ts +135 -0
- package/src/version.generated.ts +1 -1
- package/src/workflows/paddleSweep.ts +39 -14
package/src/admin/coverage.ts
CHANGED
|
@@ -9,6 +9,7 @@ import {
|
|
|
9
9
|
PAYMENTS_RECONCILE_READ_SCOPE,
|
|
10
10
|
PAYMENTS_SUBSCRIPTIONS_READ_SCOPE,
|
|
11
11
|
PAYMENTS_USAGE_READ_SCOPE,
|
|
12
|
+
PAYMENTS_WEBHOOKS_READ_SCOPE,
|
|
12
13
|
} from "../http/scopes";
|
|
13
14
|
|
|
14
15
|
/**
|
|
@@ -74,16 +75,19 @@ export const PAYMENTS_TABLE_DISCLOSURE: Record<keyof PaymentsTables, PaymentsDis
|
|
|
74
75
|
"Every row pairs a provider-side account identifier with a subject — a Pithy user, or an organization from the adopter's own membership model. In bulk that is a cross-reference from a store's id space into the adopter's, and nothing on this surface needs it: a purchase already names its subject and its rail.",
|
|
75
76
|
},
|
|
76
77
|
/**
|
|
77
|
-
*
|
|
78
|
-
*
|
|
79
|
-
*
|
|
80
|
-
*
|
|
81
|
-
*
|
|
78
|
+
* The webhook-event log, on its own scope (#830).
|
|
79
|
+
*
|
|
80
|
+
* It was withheld, on the argument that every row is a raw provider payload and that the purchase's status
|
|
81
|
+
* and the audit trail answer what a delivery log is read for. The second half did not survive contact with
|
|
82
|
+
* the first adopter: a notification that arrived and **never** projected leaves no purchase status to read
|
|
83
|
+
* and no `payments/webhook_received` success to find — it is precisely the row nothing else explains, and
|
|
84
|
+
* the one `pithy-sh/dashboard#167` needs to say why a purchase is paid and not entitled.
|
|
85
|
+
*
|
|
86
|
+
* The first half still holds, so the read is a projection rather than a table dump: the payload is never
|
|
87
|
+
* selected (the event's type is read out of it by the database), and the stored `error` crosses as its code
|
|
88
|
+
* alone. See `read.ts`'s `listWebhookEvents` and `http/view.ts`'s `adminWebhookEventView`.
|
|
82
89
|
*/
|
|
83
|
-
pithyPaymentsWebhookEvents: {
|
|
84
|
-
withheld:
|
|
85
|
-
"Each row is a raw verified provider payload — a bearer artifact. The question a delivery log is read for is answered by the purchase's status and the audit trail, without handing anyone a receipt.",
|
|
86
|
-
},
|
|
90
|
+
pithyPaymentsWebhookEvents: { reads: [PAYMENTS_WEBHOOKS_READ_SCOPE] },
|
|
87
91
|
/**
|
|
88
92
|
* The reconciliation run log — operational state, on its own scope.
|
|
89
93
|
*
|
package/src/admin/read.ts
CHANGED
|
@@ -4,6 +4,7 @@
|
|
|
4
4
|
import type { D1Database } from "@cloudflare/workers-types";
|
|
5
5
|
import { chunkByBoundParameters } from "@pithy-sh/core/src/data/boundParameters";
|
|
6
6
|
import { decodeCursor, type PageCursor, pageLimit, toPage } from "@pithy-sh/core/src/data/cursor";
|
|
7
|
+
import { sql } from "kysely";
|
|
7
8
|
import type { z } from "zod";
|
|
8
9
|
import { PaymentsEntitlement } from "../data/entitlement";
|
|
9
10
|
import { PaymentsOverride } from "../data/override";
|
|
@@ -19,10 +20,12 @@ import {
|
|
|
19
20
|
PAYMENTS_RECONCILE_RUNS_TABLE,
|
|
20
21
|
PAYMENTS_USAGE_REPORTS_TABLE,
|
|
21
22
|
PAYMENTS_USAGE_RUNS_TABLE,
|
|
23
|
+
PAYMENTS_WEBHOOK_EVENTS_TABLE,
|
|
22
24
|
paymentsDatabase,
|
|
23
25
|
} from "../data/tables";
|
|
24
26
|
import { PaymentsUsageReport } from "../data/usageReport";
|
|
25
27
|
import { PaymentsUsageRun } from "../data/usageRun";
|
|
28
|
+
import { PaymentsWebhookEvent, type PaymentsWebhookEventReadState } from "../data/webhookEvent";
|
|
26
29
|
|
|
27
30
|
/**
|
|
28
31
|
* The management read model — the queries behind the control-plane reads, and nothing else.
|
|
@@ -530,3 +533,135 @@ export async function listReconcileRuns(
|
|
|
530
533
|
(run) => ({ sort: run.startedAt.getTime(), id: run.id }),
|
|
531
534
|
);
|
|
532
535
|
}
|
|
536
|
+
|
|
537
|
+
/**
|
|
538
|
+
* A recorded delivery as the management read selects it — every column but the payload, and the one fact read
|
|
539
|
+
* out of the payload by the database: the store's own name for the event.
|
|
540
|
+
*
|
|
541
|
+
* Derived from {@link PaymentsWebhookEvent} with `.pick`, so the row schema stays the one definition of the
|
|
542
|
+
* table and the codecs still decode the timestamps and the targets on the way out of D1.
|
|
543
|
+
*/
|
|
544
|
+
export const PaymentsWebhookEventRecord = PaymentsWebhookEvent.pick({
|
|
545
|
+
id: true,
|
|
546
|
+
rail: true,
|
|
547
|
+
providerEventId: true,
|
|
548
|
+
receivedAt: true,
|
|
549
|
+
processedAt: true,
|
|
550
|
+
abandonedAt: true,
|
|
551
|
+
error: true,
|
|
552
|
+
attempts: true,
|
|
553
|
+
projectedTargets: true,
|
|
554
|
+
}).describe("One recorded delivery as a management read selects it — never the stored provider payload.");
|
|
555
|
+
|
|
556
|
+
/** {@link PaymentsWebhookEventRecord}, with the event type the database read out of the payload. */
|
|
557
|
+
export type PaymentsWebhookEventListing = z.output<typeof PaymentsWebhookEventRecord> & {
|
|
558
|
+
/** The store's own name for the event, or null when the payload names none in the shape of one. */
|
|
559
|
+
eventType: string | null;
|
|
560
|
+
};
|
|
561
|
+
|
|
562
|
+
/** The columns {@link PaymentsWebhookEventRecord} covers, as Kysely needs them. */
|
|
563
|
+
const WEBHOOK_EVENT_COLUMNS = Object.keys(PaymentsWebhookEventRecord.shape) as (keyof z.output<
|
|
564
|
+
typeof PaymentsWebhookEventRecord
|
|
565
|
+
>)[];
|
|
566
|
+
|
|
567
|
+
/**
|
|
568
|
+
* The shape an event name takes in every store's vocabulary — `customer.subscription.updated`,
|
|
569
|
+
* `DID_FAIL_TO_RENEW.GRACE_PERIOD`, `subscription_payment_refunded`, `subscription.4`. Anything else the
|
|
570
|
+
* payload holds at that path is withheld rather than echoed: it is the one string this read lifts out of a
|
|
571
|
+
* document it otherwise never touches.
|
|
572
|
+
*/
|
|
573
|
+
const EVENT_TYPE = /^[A-Za-z0-9_.]{1,128}$/;
|
|
574
|
+
|
|
575
|
+
/**
|
|
576
|
+
* Each store's event name, read **by the database** out of the stored payload, so the payload itself never
|
|
577
|
+
* reaches the Worker's memory on a management read.
|
|
578
|
+
*
|
|
579
|
+
* One path per rail, because each store names the field differently: Stripe's `type`, Paddle's `event_type`,
|
|
580
|
+
* Lemon Squeezy's `meta.event_name`, Apple's `notificationType` qualified by its `subtype`, and Google's
|
|
581
|
+
* notification block with its numeric type. `json_valid` first, so a payload that is somehow not JSON reads as
|
|
582
|
+
* no type rather than failing the page.
|
|
583
|
+
*/
|
|
584
|
+
const EVENT_TYPE_SQL = sql<unknown>`case when json_valid(${sql.ref("payload")}) then case ${sql.ref("rail")}
|
|
585
|
+
when 'stripe' then json_extract(${sql.ref("payload")}, '$.type')
|
|
586
|
+
when 'paddle' then json_extract(${sql.ref("payload")}, '$.event_type')
|
|
587
|
+
when 'lemonSqueezy' then json_extract(${sql.ref("payload")}, '$.meta.event_name')
|
|
588
|
+
when 'apple' then json_extract(${sql.ref("payload")}, '$.notificationType') || coalesce('.' || json_extract(${sql.ref("payload")}, '$.subtype'), '')
|
|
589
|
+
when 'google' then coalesce(
|
|
590
|
+
'subscription.' || json_extract(${sql.ref("payload")}, '$.notification.subscriptionNotification.notificationType'),
|
|
591
|
+
'oneTimeProduct.' || json_extract(${sql.ref("payload")}, '$.notification.oneTimeProductNotification.notificationType'),
|
|
592
|
+
case when json_type(${sql.ref("payload")}, '$.notification.voidedPurchaseNotification') is not null then 'voidedPurchase' end,
|
|
593
|
+
case when json_type(${sql.ref("payload")}, '$.notification.testNotification') is not null then 'test' end
|
|
594
|
+
)
|
|
595
|
+
end end`;
|
|
596
|
+
|
|
597
|
+
/** What {@link listWebhookEvents} accepts. Every filter is optional; together they are an AND. */
|
|
598
|
+
export interface WebhookEventsQuery {
|
|
599
|
+
/** Restrict to one store. */
|
|
600
|
+
rail?: PaymentsRail;
|
|
601
|
+
/** Restrict to one state, as a management read names them. */
|
|
602
|
+
state?: PaymentsWebhookEventReadState;
|
|
603
|
+
/** Received at or after this instant. */
|
|
604
|
+
since?: Date;
|
|
605
|
+
/** Received before this instant. */
|
|
606
|
+
until?: Date;
|
|
607
|
+
/** Where to resume, from a previous page's `nextCursor`. A malformed one is a first page. */
|
|
608
|
+
cursor?: string;
|
|
609
|
+
/** How many rows to return, clamped by `pageLimit`. */
|
|
610
|
+
limit?: number;
|
|
611
|
+
}
|
|
612
|
+
|
|
613
|
+
/**
|
|
614
|
+
* Every notification a store sent, newest received first (#830).
|
|
615
|
+
*
|
|
616
|
+
* Ordered on `receivedAt` — when the delivery reached us — with the id as the tiebreak, on the index
|
|
617
|
+
* `payments_0003_webhook_targets` creates for exactly this. Named columns and never `payload`: the provider's
|
|
618
|
+
* document carries the customer's details, so it is not selected, and the one thing read out of it — the
|
|
619
|
+
* event's type — is read by the database.
|
|
620
|
+
*
|
|
621
|
+
* The state filter is the SQL spelling of `webhookEventReadState`, and `read.workers.test.ts` holds the two to
|
|
622
|
+
* each other over every shape a row takes.
|
|
623
|
+
*/
|
|
624
|
+
export async function listWebhookEvents(
|
|
625
|
+
d1: D1Database,
|
|
626
|
+
query: WebhookEventsQuery = {},
|
|
627
|
+
): Promise<PaymentsPage<PaymentsWebhookEventListing>> {
|
|
628
|
+
const limit = pageLimit(query.limit);
|
|
629
|
+
const after = resume(query.cursor);
|
|
630
|
+
|
|
631
|
+
let selection = paymentsDatabase(d1)
|
|
632
|
+
.selectFrom(PAYMENTS_WEBHOOK_EVENTS_TABLE)
|
|
633
|
+
.select(WEBHOOK_EVENT_COLUMNS)
|
|
634
|
+
.select(EVENT_TYPE_SQL.as("eventType"))
|
|
635
|
+
.orderBy("receivedAt", "desc")
|
|
636
|
+
.orderBy("id", "desc")
|
|
637
|
+
.limit(limit + 1);
|
|
638
|
+
|
|
639
|
+
if (query.rail !== undefined) selection = selection.where("rail", "=", query.rail);
|
|
640
|
+
if (query.state === "projected") selection = selection.where("processedAt", "is not", null);
|
|
641
|
+
if (query.state === "pending") {
|
|
642
|
+
selection = selection.where("processedAt", "is", null).where("abandonedAt", "is", null);
|
|
643
|
+
}
|
|
644
|
+
if (query.state === "abandoned") {
|
|
645
|
+
selection = selection.where("processedAt", "is", null).where("abandonedAt", "is not", null);
|
|
646
|
+
}
|
|
647
|
+
if (query.since !== undefined) selection = selection.where("receivedAt", ">=", query.since.getTime());
|
|
648
|
+
if (query.until !== undefined) selection = selection.where("receivedAt", "<", query.until.getTime());
|
|
649
|
+
if (after) {
|
|
650
|
+
selection = selection.where((eb) =>
|
|
651
|
+
eb.or([eb("receivedAt", "<", after.sort), eb.and([eb("receivedAt", "=", after.sort), eb("id", "<", after.id)])]),
|
|
652
|
+
);
|
|
653
|
+
}
|
|
654
|
+
|
|
655
|
+
const rows = await selection.execute();
|
|
656
|
+
return toPage(
|
|
657
|
+
rows.map((row) => {
|
|
658
|
+
const { eventType, ...columns } = row as typeof row & { eventType: unknown };
|
|
659
|
+
return {
|
|
660
|
+
...PaymentsWebhookEventRecord.parse(columns),
|
|
661
|
+
eventType: typeof eventType === "string" && EVENT_TYPE.test(eventType) ? eventType : null,
|
|
662
|
+
};
|
|
663
|
+
}),
|
|
664
|
+
limit,
|
|
665
|
+
(event) => ({ sort: event.receivedAt.getTime(), id: event.id }),
|
|
666
|
+
);
|
|
667
|
+
}
|
package/src/audit/actions.ts
CHANGED
|
@@ -221,6 +221,11 @@ export const PaymentsAuditActions = {
|
|
|
221
221
|
* A management client read the usage-reporting run log. Counts and filters only, as every management read.
|
|
222
222
|
*/
|
|
223
223
|
usageRunsRead: "payments/usage_runs_read",
|
|
224
|
+
/**
|
|
225
|
+
* A management client read the webhook-event log (#830). Counts and filters only, as every management read:
|
|
226
|
+
* the events are already a queryable table, and copying them into the trail would make a second one.
|
|
227
|
+
*/
|
|
228
|
+
webhookEventsRead: "payments/webhook_events_read",
|
|
224
229
|
} as const;
|
|
225
230
|
|
|
226
231
|
/** One of the payments audit action codes. */
|
package/src/capability.ts
CHANGED
|
@@ -26,7 +26,10 @@ import { registerPaymentsRoutes } from "./http/routes";
|
|
|
26
26
|
import { paymentsAdminRoutes } from "./http/scopes";
|
|
27
27
|
import { payments_0001_purchases } from "./migrations/0001_purchases";
|
|
28
28
|
import { payments_0002_allowances } from "./migrations/0002_allowances";
|
|
29
|
+
import { payments_0003_webhook_targets } from "./migrations/0003_webhook_targets";
|
|
29
30
|
import { type PaymentsPeer, paymentsPeer } from "./peer";
|
|
31
|
+
import { paymentsProcessing } from "./processing/activities";
|
|
32
|
+
import { paymentsUserPurge } from "./purge/contribution";
|
|
30
33
|
import { paymentsInapplicableSecrets, paymentsSecretBranches } from "./secret/branches";
|
|
31
34
|
import { paymentsSecretsRegistry } from "./secret/registry";
|
|
32
35
|
import { paymentsExampleSeed } from "./seeds/example";
|
|
@@ -87,11 +90,11 @@ export type PaymentsOptions = PaymentsConfigInput & {
|
|
|
87
90
|
* Structural, and recognized by a copied three-line predicate rather than by importing the ledger's own
|
|
88
91
|
* `isLedgerCapability`. The ledger is an **optional** peer, and a specifier naming it — static, or a dynamic
|
|
89
92
|
* `import()` behind a `try` — is one a bundler resolves whether or not the branch holding it ever runs, so a
|
|
90
|
-
* project that never installed it could not bundle payments at all
|
|
93
|
+
* project that never installed it could not bundle payments at all. So payments names the package
|
|
91
94
|
* nowhere, not even for a type, and the ledger reaches it through the composition: this hook finds it, and
|
|
92
95
|
* {@link payments} keeps its `ledgerPeer` for the routes.
|
|
93
96
|
*
|
|
94
|
-
* `ledgerPeer` is optional here because
|
|
97
|
+
* `ledgerPeer` is optional here because an older ledger does not carry one, and that is a
|
|
95
98
|
* composition {@link checkLedgerGrants} refuses by name rather than a purchase that fails later.
|
|
96
99
|
*/
|
|
97
100
|
interface LedgerPeerCapability extends Capability {
|
|
@@ -159,7 +162,7 @@ function checkLedgerGrants({ capabilities }: CapabilityComposeContext, config: P
|
|
|
159
162
|
detail: `Products with a \`grants.ledger\` clause: ${granting.map((entry) => entry.id).join(", ")}. Crediting needs @pithy-sh/ledger composed in the same Worker.`,
|
|
160
163
|
});
|
|
161
164
|
}
|
|
162
|
-
//
|
|
165
|
+
// An older ledger is composed and cannot be called: it carries no peer surface, and payments no
|
|
163
166
|
// longer imports the package to reach around it. Refused here, by name, rather than as the first purchase.
|
|
164
167
|
if (typeof peer.ledgerPeer?.openLedger !== "function") {
|
|
165
168
|
throw new ValidationError({
|
|
@@ -207,7 +210,7 @@ function checkLedgerGrants({ capabilities }: CapabilityComposeContext, config: P
|
|
|
207
210
|
* `pithy.config.ts` is evaluated and the CLI evaluates it on nearly every command. Refusing the
|
|
208
211
|
* placeholder here would leave the adopter with no `pithy` at all in the project the scaffold just landed
|
|
209
212
|
* in. `requireImplementedSubject`, on the capability's `boot` hook, is where the placeholder is refused —
|
|
210
|
-
* `createEntrypoint` runs it and nothing else does, so the Worker still will not serve
|
|
213
|
+
* `createEntrypoint` runs it and nothing else does, so the Worker still will not serve.
|
|
211
214
|
*/
|
|
212
215
|
function requireResolvableSubject(config: PaymentsConfig, resolveSubject: PaymentsSubjectResolver | undefined): void {
|
|
213
216
|
if (config.billingSubject !== "organization" || resolveSubject !== undefined) return;
|
|
@@ -253,8 +256,7 @@ function requireQuantityResolver(config: PaymentsConfig, resolveQuantity: Paymen
|
|
|
253
256
|
* **Nothing else can cross, and not merely by discipline.** Apple's issuer id and key, Google's
|
|
254
257
|
* service-account credentials, and Stripe's secret and webhook signing keys live in the secrets store
|
|
255
258
|
* behind `paymentsSecretsRegistry` — they are not in the config this closure can see, so there is no
|
|
256
|
-
* expression here that would reach them. What discipline does cover is the rest of the catalog:
|
|
257
|
-
* product's Apple and Google SKUs stay server-side because a browser has no use for them, and the
|
|
259
|
+
* expression here that would reach them. What discipline does cover is the rest of the catalog: the
|
|
258
260
|
* `grants` block stays server-side because a currency code and an amount describe the economy.
|
|
259
261
|
* `capability.test.ts` locks the key set and sweeps the serialized result for every credential shape.
|
|
260
262
|
*
|
|
@@ -284,9 +286,11 @@ function clientProjection(config: PaymentsConfig, environment: string): Payments
|
|
|
284
286
|
// **Keyed by rail, not one field per rail.** Two flat fields were already one too many, and a third
|
|
285
287
|
// would have made `purchasable()` a growing chain of `&&`s that a fourth rail silently falls out of.
|
|
286
288
|
// A screen now asks `skus[rail]`, which is the same question it was already asking and cannot go
|
|
287
|
-
// stale when a rail is added. Every id here is publishable by design: each is what a checkout
|
|
288
|
-
// so each may reach a
|
|
289
|
+
// stale when a rail is added. Every id here is publishable by design: each is what a checkout or a
|
|
290
|
+
// store purchase names, so each may reach a client. The API keys and the signing secrets never do.
|
|
289
291
|
skus: {
|
|
292
|
+
apple: product.apple?.productId ?? null,
|
|
293
|
+
google: product.google?.productId ?? null,
|
|
290
294
|
stripe: product.stripe?.priceId ?? null,
|
|
291
295
|
lemonSqueezy: product.lemonSqueezy?.variantId ?? null,
|
|
292
296
|
paddle: product.paddle?.priceId ?? null,
|
|
@@ -349,7 +353,7 @@ export interface PaymentsCapability
|
|
|
349
353
|
/**
|
|
350
354
|
* What a capability composed beside this one reads purchases through — `support`, showing an operator what a
|
|
351
355
|
* sender bought. Found in its `compose` hook, so it never imports this package and a project without
|
|
352
|
-
* payments bundles it
|
|
356
|
+
* payments bundles it. See `peer.ts`.
|
|
353
357
|
*/
|
|
354
358
|
paymentsPeer: PaymentsPeer;
|
|
355
359
|
/**
|
|
@@ -384,8 +388,8 @@ export interface PaymentsCapability
|
|
|
384
388
|
* than at the first receipt. Auth is *not* listed — it is a seam: under `billingSubject: "user"` a purchase
|
|
385
389
|
* scopes to the authenticated caller, so with no auth capability composed every route denies, which is the
|
|
386
390
|
* right failure and needs no dependency edge. `@pithy-sh/ledger` is likewise a seam: `compose` finds it among
|
|
387
|
-
* the composed capabilities and hands its `ledgerPeer` to the routes, and nothing in this package imports it
|
|
388
|
-
*
|
|
391
|
+
* the composed capabilities and hands its `ledgerPeer` to the routes, and nothing in this package imports it.
|
|
392
|
+
* Only a product whose catalog entry declares `grants` ever calls it. Both belong in the manifest's
|
|
389
393
|
* `optionalCapabilities`.
|
|
390
394
|
*
|
|
391
395
|
* Under `billingSubject: "organization"` the holder is not the caller and cannot be derived from them, so
|
|
@@ -432,6 +436,7 @@ export function payments(options: PaymentsOptions): PaymentsCapability {
|
|
|
432
436
|
const migrations: Record<string, Migration> = {
|
|
433
437
|
"0001_purchases": payments_0001_purchases,
|
|
434
438
|
"0002_allowances": payments_0002_allowances,
|
|
439
|
+
"0003_webhook_targets": payments_0003_webhook_targets,
|
|
435
440
|
};
|
|
436
441
|
// Usage reporting only where something is billed by a reported quantity: a project that sells none binds
|
|
437
442
|
// nothing for it, and its `pithy doctor` has nothing to report about a Workflow it does not have.
|
|
@@ -452,7 +457,7 @@ export function payments(options: PaymentsOptions): PaymentsCapability {
|
|
|
452
457
|
// The package this capability ships in and the version it ships at, both stamped by
|
|
453
458
|
// `scripts/stampVersions.ts` — a Worker cannot read its own package.json. Reported per capability by
|
|
454
459
|
// the control-plane manifest, and reported together: a release feed is keyed by package name, so the
|
|
455
|
-
// version alone leaves a client guessing the key
|
|
460
|
+
// version alone leaves a client guessing the key.
|
|
456
461
|
version: PACKAGE_VERSION,
|
|
457
462
|
package: PACKAGE_NAME,
|
|
458
463
|
dependsOn: ["secrets"],
|
|
@@ -464,14 +469,14 @@ export function payments(options: PaymentsOptions): PaymentsCapability {
|
|
|
464
469
|
// schema knows five are possible; only this catalog knows which are on. See `secret/branches.ts`.
|
|
465
470
|
secretBranches: paymentsSecretBranches(resolved.rails),
|
|
466
471
|
// And whether the bundle is reachable at all. With every rail off, every read of it is behind a
|
|
467
|
-
// refusal — so it is not outstanding work, and `pithy doctor` asked for it anyway
|
|
472
|
+
// refusal — so it is not outstanding work, and `pithy doctor` asked for it anyway.
|
|
468
473
|
inapplicableSecrets: paymentsInapplicableSecrets(resolved.rails),
|
|
469
474
|
// The one durable job: the nightly reconciliation pass. Declared here so `createBackend` derives its
|
|
470
475
|
// binding and types `c.var.workflows.trigger("payments/reconcile", …)` precisely.
|
|
471
476
|
workflows,
|
|
472
477
|
// The one thing this capability cannot check on its own: whether the ledger it credits agrees the
|
|
473
478
|
// currency exists. See `checkLedgerGrants` for why the failure is otherwise invisible. And the one place
|
|
474
|
-
// the ledger reaches payments at all: found among the composed capabilities, never imported
|
|
479
|
+
// the ledger reaches payments at all: found among the composed capabilities, never imported.
|
|
475
480
|
compose: (context) => {
|
|
476
481
|
checkLedgerGrants(context, resolved);
|
|
477
482
|
peers.ledger = composedLedger(context.capabilities);
|
|
@@ -501,7 +506,7 @@ export function payments(options: PaymentsOptions): PaymentsCapability {
|
|
|
501
506
|
// manifest naming `/billing/entitlements/grant` — the whole point of describing rather than
|
|
502
507
|
// assuming. `routeContract.test.ts` checks these against the routes actually registered.
|
|
503
508
|
adminRoutes: paymentsAdminRoutes(resolved.basePath),
|
|
504
|
-
// The one decision a management client cannot infer: what this project bills
|
|
509
|
+
// The one decision a management client cannot infer: what this project bills. Built from the
|
|
505
510
|
// resolved config for the same reason the routes are, and it is the only check there is — nothing
|
|
506
511
|
// downstream compares a stated fact against the seam that acts on it.
|
|
507
512
|
manifestConfig: paymentsManifestConfig(resolved.billingSubject),
|
|
@@ -509,6 +514,11 @@ export function payments(options: PaymentsOptions): PaymentsCapability {
|
|
|
509
514
|
// to key a row to — so they are handed the same seam rather than building one from the config alone.
|
|
510
515
|
routes: registerPaymentsRoutes({ config: resolved, subject, ledger: () => peers.ledger }),
|
|
511
516
|
seeds: [paymentsExampleSeed],
|
|
517
|
+
// A person's purchases and what they granted are kept through their purge, for tax law, and exported on an access
|
|
518
|
+
// request with the basis that keeps them.
|
|
519
|
+
purge: [paymentsUserPurge()],
|
|
520
|
+
// Each rail the config turns on is named as a recipient of the purchases made on it.
|
|
521
|
+
processing: paymentsProcessing(resolved.rails),
|
|
512
522
|
});
|
|
513
523
|
|
|
514
524
|
return Object.assign(capability, {
|
package/src/client/api.ts
CHANGED
|
@@ -11,11 +11,12 @@
|
|
|
11
11
|
* after the file was written. So the calls, the error mapping, and the redirect-and-return dance ship
|
|
12
12
|
* here and upgrade with a minor release; the scaffolded stub renders and styles, and calls these.
|
|
13
13
|
*
|
|
14
|
-
* **
|
|
15
|
-
*
|
|
16
|
-
*
|
|
17
|
-
*
|
|
18
|
-
*
|
|
14
|
+
* **Two transports, chosen by one option.** With no `origin`, every request is relative and carries
|
|
15
|
+
* `credentials: "include"` and nothing else: the SPA and its Worker share an origin, so the session rides
|
|
16
|
+
* an httpOnly cookie that JavaScript cannot read and the server's same-origin check covers CSRF. With an
|
|
17
|
+
* `origin` — a native app, which has no page origin to be relative to — the request goes to that origin
|
|
18
|
+
* with `credentials: "omit"`, and the caller hands in the bearer session's `fetch`, which adds the
|
|
19
|
+
* `Authorization` header. This module holds no credential either way.
|
|
19
20
|
*
|
|
20
21
|
* **Nothing here throws, and nothing here hides a failure either.** An unreachable Worker, an HTML error
|
|
21
22
|
* page from a proxy, a 500 — each becomes a renderable {@link PaymentsFailure} on a `PaymentsResult`, and
|
|
@@ -27,8 +28,8 @@
|
|
|
27
28
|
* The server's `requireEntitlement()` is still the security boundary. Nothing on this side of the wire
|
|
28
29
|
* protects a feature; it only decides what a screen shows.
|
|
29
30
|
*
|
|
30
|
-
* **No absolute URL literals, and no schema library.** Paths are relative
|
|
31
|
-
* origin
|
|
31
|
+
* **No absolute URL literals, and no schema library.** Paths are relative unless a caller names an
|
|
32
|
+
* origin, so a web bundle's calls follow whatever origin it is served from. Answers are narrowed by hand-written `is…(value: unknown): value is T`
|
|
32
33
|
* guards rather than Zod: this file is compiled into a browser bundle, and it must not drag the server's
|
|
33
34
|
* schema graph in behind it.
|
|
34
35
|
*/
|
|
@@ -264,7 +265,7 @@ export interface PaymentsRequestInit {
|
|
|
264
265
|
headers?: Record<string, string>;
|
|
265
266
|
/** The JSON body, already serialized. */
|
|
266
267
|
body?: string;
|
|
267
|
-
/** Cookie policy
|
|
268
|
+
/** Cookie policy: `include` for the same-origin cookie session, `omit` for a bearer call to an origin. */
|
|
268
269
|
credentials?: "include" | "same-origin" | "omit";
|
|
269
270
|
}
|
|
270
271
|
|
|
@@ -300,6 +301,13 @@ export interface PaymentsGlobal {
|
|
|
300
301
|
|
|
301
302
|
/** What every call takes: where the routes are, and the seams a test replaces. */
|
|
302
303
|
export interface PaymentsClientOptions {
|
|
304
|
+
/**
|
|
305
|
+
* The Worker's absolute origin, such as `https://api.example.com`: an http(s) scheme and a host, with no
|
|
306
|
+
* path, query, fragment or trailing slash. Set it where there is no page origin to be relative to — a
|
|
307
|
+
* native app — and pass the bearer session's `fetch` beside it. The request then sends no cookie. Unset,
|
|
308
|
+
* every request is relative and carries the session cookie.
|
|
309
|
+
*/
|
|
310
|
+
origin?: string;
|
|
303
311
|
/** Where the payments routes mount. Defaults to {@link PAYMENTS_BASE_PATH}. */
|
|
304
312
|
basePath?: string;
|
|
305
313
|
/** The fetch to use. Defaults to the one on {@link PaymentsClientOptions.global}. */
|
|
@@ -317,6 +325,20 @@ export const PAYMENTS_UNREACHABLE: PaymentsFailure = {
|
|
|
317
325
|
action: "Check your connection, then try again.",
|
|
318
326
|
};
|
|
319
327
|
|
|
328
|
+
/**
|
|
329
|
+
* The request would have left this app's backend, so it was never sent.
|
|
330
|
+
*
|
|
331
|
+
* Reached through a `basePath` that is not a rooted path, or an `origin` that is not a bare http(s) origin.
|
|
332
|
+
* Appended to an origin, `evil.example` or `//evil.example` names a different host, and the bearer session's
|
|
333
|
+
* `fetch` would hand it the credential.
|
|
334
|
+
*/
|
|
335
|
+
export const PAYMENTS_CROSS_ORIGIN: PaymentsFailure = {
|
|
336
|
+
code: "client/cross_origin",
|
|
337
|
+
message: "That request would have left this app's backend, so it wasn't sent.",
|
|
338
|
+
action:
|
|
339
|
+
"Check the payments `basePath` in pithy.config.ts, which is a path on the worker and not a URL, and the client's `origin`, which is a scheme and host with no path.",
|
|
340
|
+
};
|
|
341
|
+
|
|
320
342
|
/** The worker answered with something this client cannot read. A proxy's HTML page, or a shape change. */
|
|
321
343
|
export const PAYMENTS_UNREADABLE: PaymentsFailure = {
|
|
322
344
|
code: "client/unreadable",
|
|
@@ -486,7 +508,46 @@ function readFailure(body: unknown): PaymentsFailure {
|
|
|
486
508
|
}
|
|
487
509
|
|
|
488
510
|
/**
|
|
489
|
-
*
|
|
511
|
+
* Whether a configured origin is a bare http(s) origin: a scheme, a host, an optional port, nothing else.
|
|
512
|
+
*
|
|
513
|
+
* A regular expression rather than `new URL`, because React Native's `URL` does not implement the getters a
|
|
514
|
+
* parsed check would read. Userinfo, a path, a query, a fragment, a backslash and whitespace are all refused, so
|
|
515
|
+
* the composed URL can only ever name this host. `@pithy-sh/auth` and `@pithy-sh/organization` apply the same
|
|
516
|
+
* rule.
|
|
517
|
+
*/
|
|
518
|
+
function isBareOrigin(origin: string): boolean {
|
|
519
|
+
return /^https?:\/\/[A-Za-z0-9.-]+(?::[0-9]{1,5})?$|^https?:\/\/\[[0-9A-Fa-f:.]+\](?::[0-9]{1,5})?$/.test(origin);
|
|
520
|
+
}
|
|
521
|
+
|
|
522
|
+
/**
|
|
523
|
+
* Whether a composed path stays on the origin it is appended to.
|
|
524
|
+
*
|
|
525
|
+
* A rooted path, and not `//host` or `/\host`: a URL parser reads either as an authority rather than a path.
|
|
526
|
+
*/
|
|
527
|
+
function isRootedPath(path: string): boolean {
|
|
528
|
+
if (!path.startsWith("/")) return false;
|
|
529
|
+
const second = path.charAt(1);
|
|
530
|
+
return second !== "/" && second !== "\\";
|
|
531
|
+
}
|
|
532
|
+
|
|
533
|
+
/**
|
|
534
|
+
* Where a request goes and which cookie policy it carries, or why it may not be sent.
|
|
535
|
+
*
|
|
536
|
+
* No origin is the cookie transport, unchanged: a relative URL and `include`. An origin is the bearer
|
|
537
|
+
* transport: an absolute URL, checked to stay on that origin, and `omit`.
|
|
538
|
+
*/
|
|
539
|
+
function requestTarget(
|
|
540
|
+
path: string,
|
|
541
|
+
origin: string | undefined,
|
|
542
|
+
): { url: string; credentials: "include" | "omit" } | { failure: PaymentsFailure } {
|
|
543
|
+
if (origin === undefined) return { url: path, credentials: "include" };
|
|
544
|
+
if (!isBareOrigin(origin)) return { failure: PAYMENTS_CROSS_ORIGIN };
|
|
545
|
+
if (!isRootedPath(path)) return { failure: PAYMENTS_CROSS_ORIGIN };
|
|
546
|
+
return { url: `${origin}${path}`, credentials: "omit" };
|
|
547
|
+
}
|
|
548
|
+
|
|
549
|
+
/**
|
|
550
|
+
* One call to this Worker, never throwing. **The only producer of that request.**
|
|
490
551
|
*
|
|
491
552
|
* The body is read before the status is judged, because a refusal's body is the failure a screen renders.
|
|
492
553
|
* A body that will not parse is the generic failure rather than a crash — a corporate proxy's HTML page
|
|
@@ -509,13 +570,15 @@ export async function callPayments<T>(
|
|
|
509
570
|
options: PaymentsClientOptions | undefined,
|
|
510
571
|
guard: (value: unknown) => value is T,
|
|
511
572
|
): Promise<PaymentsResult<T>> {
|
|
573
|
+
const target = requestTarget(`${options?.basePath ?? PAYMENTS_BASE_PATH}${path}`, options?.origin);
|
|
574
|
+
if ("failure" in target) return { ok: false, failure: target.failure };
|
|
575
|
+
|
|
512
576
|
const fetcher = options?.fetch ?? globals(options).fetch;
|
|
513
577
|
if (!fetcher) return { ok: false, failure: PAYMENTS_UNREACHABLE };
|
|
514
578
|
|
|
515
|
-
const base = options?.basePath ?? PAYMENTS_BASE_PATH;
|
|
516
579
|
let response: PaymentsResponse;
|
|
517
580
|
try {
|
|
518
|
-
response = await fetcher(
|
|
581
|
+
response = await fetcher(target.url, { ...init, credentials: target.credentials });
|
|
519
582
|
} catch {
|
|
520
583
|
return { ok: false, failure: PAYMENTS_UNREACHABLE };
|
|
521
584
|
}
|