qarpeo 0.2.1 → 0.3.1
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/dist/chunks/tools.mjs +993 -31
- package/dist/cli/index.mjs +1071 -31
- package/dist/fate/index.d.ts +9 -1
- package/dist/fate/index.mjs +20 -3
- package/dist/module.mjs +296 -750
- package/dist/runtime/browser.mjs +2 -2
- package/dist/runtime/comments-server.d.ts +3 -0
- package/dist/runtime/comments-server.mjs +2 -0
- package/dist/runtime/comments.d.ts +0 -2
- package/dist/runtime/comments.mjs +0 -2
- package/dist/runtime/db.d.ts +10 -9
- package/dist/runtime/db.mjs +79 -8
- package/dist/runtime/drizzle.mjs +21 -6
- package/dist/runtime/index.d.ts +4 -0
- package/dist/runtime/realtime-server.d.ts +4 -0
- package/dist/runtime/realtime-server.mjs +13 -0
- package/dist/runtime/realtime.d.ts +1 -4
- package/dist/runtime/realtime.mjs +0 -13
- package/dist/runtime/replica.d.ts +27 -0
- package/dist/runtime/replica.mjs +229 -0
- package/dist/runtime/server/durable-objects/agent.mjs +14 -2
- package/dist/runtime/server/durable-objects/room.d.ts +10 -0
- package/dist/runtime/server/durable-objects/room.mjs +119 -28
- package/dist/runtime/server/middleware/devtools.mjs +1 -1
- package/dist/runtime/server/middleware/tenancy.mjs +7 -4
- package/dist/runtime/server/plugins/store.mjs +1 -1
- package/dist/runtime/server/routes/__qarpeo/mail/track/click/[id].get.mjs +57 -17
- package/dist/runtime/server/routes/agents/[agent]/chat.post.mjs +19 -12
- package/dist/runtime/server/routes/agents/[agent]/clear.post.mjs +8 -9
- package/dist/runtime/server/routes/agents/[agent]/history.get.mjs +8 -9
- package/dist/runtime/server/routes/analytics/events.get.mjs +12 -2
- package/dist/runtime/server/routes/analytics/pageviews.get.mjs +10 -1
- package/dist/runtime/server/routes/analytics/summary.get.mjs +10 -1
- package/dist/runtime/server/routes/auth/2fa/disable.post.mjs +11 -2
- package/dist/runtime/server/routes/auth/2fa/setup.post.mjs +7 -0
- package/dist/runtime/server/routes/auth/2fa/verify.post.mjs +11 -2
- package/dist/runtime/server/routes/auth/account.delete.mjs +7 -0
- package/dist/runtime/server/routes/auth/magic-link/verify.get.mjs +5 -3
- package/dist/runtime/server/routes/auth/organization/sso/index.post.mjs +10 -0
- package/dist/runtime/server/routes/auth/otp/verify.post.mjs +5 -3
- package/dist/runtime/server/routes/auth/sso/saml/acs.post.mjs +18 -0
- package/dist/runtime/server/routes/auth/webauthn/login/options.post.d.ts +1 -1
- package/dist/runtime/server/routes/auth/webauthn/login/options.post.mjs +11 -2
- package/dist/runtime/server/routes/auth/webauthn/login/verify.post.mjs +10 -1
- package/dist/runtime/server/routes/auth/webauthn/register/options.post.d.ts +1 -1
- package/dist/runtime/server/routes/auth/webauthn/register/options.post.mjs +10 -1
- package/dist/runtime/server/routes/auth/webauthn/register/verify.post.mjs +10 -1
- package/dist/runtime/server/routes/browser/crawl.post.mjs +13 -0
- package/dist/runtime/server/routes/browser/invoice.post.mjs +15 -1
- package/dist/runtime/server/routes/browser/og-image.post.mjs +13 -0
- package/dist/runtime/server/routes/browser/pdf.post.mjs +15 -1
- package/dist/runtime/server/routes/browser/screenshot.post.mjs +13 -0
- package/dist/runtime/server/routes/cms/[collection]/[id]/preview-token.post.mjs +23 -8
- package/dist/runtime/server/routes/cms/[collection]/[id]/publish.post.mjs +2 -1
- package/dist/runtime/server/routes/cms/[collection]/[id]/review.post.mjs +2 -1
- package/dist/runtime/server/routes/cms/[collection]/[id]/revisions/[revId]/restore.post.mjs +2 -1
- package/dist/runtime/server/routes/cms/[collection]/[id].delete.mjs +2 -1
- package/dist/runtime/server/routes/cms/[collection]/[id].put.mjs +2 -1
- package/dist/runtime/server/routes/cms/[collection]/index.post.mjs +2 -1
- package/dist/runtime/server/routes/cms/categories/[id].delete.mjs +2 -1
- package/dist/runtime/server/routes/cms/categories/[id].put.mjs +2 -1
- package/dist/runtime/server/routes/cms/categories.post.mjs +2 -1
- package/dist/runtime/server/routes/cms/collections/[id].delete.mjs +2 -1
- package/dist/runtime/server/routes/cms/collections/[id].put.mjs +2 -1
- package/dist/runtime/server/routes/cms/collections/index.post.mjs +2 -1
- package/dist/runtime/server/routes/cms/export.post.mjs +1 -1
- package/dist/runtime/server/routes/cms/subscribers/[id].delete.mjs +2 -1
- package/dist/runtime/server/routes/cms/subscribers/[id].patch.mjs +2 -1
- package/dist/runtime/server/routes/cms/tags/[id].delete.mjs +2 -1
- package/dist/runtime/server/routes/cms/tags.post.mjs +2 -1
- package/dist/runtime/server/routes/comments/[id]/react.post.mjs +7 -3
- package/dist/runtime/server/routes/comments/[id]/report.post.mjs +3 -0
- package/dist/runtime/server/routes/comments/[id].delete.mjs +1 -1
- package/dist/runtime/server/routes/comments/[id].get.mjs +13 -0
- package/dist/runtime/server/routes/comments/[id].patch.mjs +1 -1
- package/dist/runtime/server/routes/fate.d.ts +6 -0
- package/dist/runtime/server/routes/fate.mjs +32 -3
- package/dist/runtime/server/routes/mail/bounce.post.mjs +14 -2
- package/dist/runtime/server/routes/mail/unsubscribe.mjs +2 -1
- package/dist/runtime/server/routes/mail/webhooks.post.mjs +18 -4
- package/dist/runtime/server/routes/notifications/[id].get.mjs +3 -4
- package/dist/runtime/server/routes/notifications/index.get.mjs +4 -2
- package/dist/runtime/server/routes/notifications/push/subscribe.post.mjs +3 -1
- package/dist/runtime/server/routes/notifications/push/unsubscribe.post.mjs +5 -3
- package/dist/runtime/server/routes/notifications/read-all.post.mjs +6 -2
- package/dist/runtime/server/routes/notifications/send.post.mjs +13 -2
- package/dist/runtime/server/routes/payments/cancel.post.mjs +1 -1
- package/dist/runtime/server/routes/payments/change-plan.post.mjs +1 -1
- package/dist/runtime/server/routes/payments/checkout.post.mjs +1 -1
- package/dist/runtime/server/routes/payments/pause.post.mjs +1 -1
- package/dist/runtime/server/routes/payments/portal.post.mjs +1 -1
- package/dist/runtime/server/routes/payments/subscription.get.mjs +1 -1
- package/dist/runtime/server/routes/payments/usage.get.mjs +1 -1
- package/dist/runtime/server/routes/payments/usage.post.mjs +1 -1
- package/dist/runtime/server/routes/payments/webhook.post.mjs +8 -1
- package/dist/runtime/server/routes/realtime/broadcast.post.mjs +3 -2
- package/dist/runtime/server/routes/realtime/history.delete.mjs +2 -2
- package/dist/runtime/server/routes/realtime/history.get.mjs +2 -2
- package/dist/runtime/server/routes/realtime/presence.get.mjs +3 -3
- package/dist/runtime/server/routes/realtime/state.get.mjs +3 -3
- package/dist/runtime/server/routes/realtime/state.post.mjs +13 -4
- package/dist/runtime/server/routes/realtime/ws.get.mjs +2 -2
- package/dist/runtime/server/routes/storage/file/[...key].delete.mjs +1 -1
- package/dist/runtime/server/routes/storage/file/[...key].get.mjs +7 -0
- package/dist/runtime/server/routes/storage/files.get.d.ts +1 -1
- package/dist/runtime/server/routes/storage/files.get.mjs +24 -4
- package/dist/runtime/server/routes/storage/multipart/abort.post.mjs +16 -1
- package/dist/runtime/server/routes/storage/multipart/complete.post.d.ts +1 -1
- package/dist/runtime/server/routes/storage/multipart/complete.post.mjs +15 -1
- package/dist/runtime/server/routes/storage/multipart/create.post.mjs +7 -0
- package/dist/runtime/server/routes/storage/multipart/part.put.mjs +15 -1
- package/dist/runtime/server/routes/storage/presigned-r2.post.mjs +8 -1
- package/dist/runtime/server/routes/storage/presigned.post.d.ts +1 -1
- package/dist/runtime/server/routes/storage/presigned.post.mjs +8 -1
- package/dist/runtime/server/routes/storage/sign.post.mjs +7 -0
- package/dist/runtime/server/routes/storage/upload.post.d.ts +2 -2
- package/dist/runtime/server/routes/store/cart/index.delete.mjs +3 -4
- package/dist/runtime/server/routes/store/cart/index.get.mjs +3 -10
- package/dist/runtime/server/routes/store/cart/items/[id].delete.mjs +6 -4
- package/dist/runtime/server/routes/store/cart/items/[id].patch.mjs +12 -4
- package/dist/runtime/server/routes/store/cart/items.post.mjs +9 -10
- package/dist/runtime/server/routes/store/categories/index.get.mjs +4 -2
- package/dist/runtime/server/routes/store/checkout.post.mjs +13 -3
- package/dist/runtime/server/routes/store/coupons/apply.post.mjs +6 -5
- package/dist/runtime/server/routes/store/orders/[id].get.mjs +2 -2
- package/dist/runtime/server/routes/store/orders/download/[token].get.mjs +6 -3
- package/dist/runtime/server/routes/store/orders/index.get.mjs +1 -1
- package/dist/runtime/server/routes/store/products/[slug].get.mjs +2 -2
- package/dist/runtime/server/routes/store/products/index.get.mjs +1 -1
- package/dist/runtime/server/routes/store/tax/calculate.post.mjs +10 -0
- package/dist/runtime/server/routes/tenants/[tenant]/domains/[domain]/index.delete.mjs +26 -25
- package/dist/runtime/server/routes/tenants/[tenant]/domains/[domain]/verify.post.mjs +26 -25
- package/dist/runtime/server/utils/ai.d.ts +6 -0
- package/dist/runtime/server/utils/ai.mjs +12 -2
- package/dist/runtime/server/utils/analytics-query.mjs +8 -4
- package/dist/runtime/server/utils/browser-utils.d.ts +9 -0
- package/dist/runtime/server/utils/browser-utils.mjs +135 -0
- package/dist/runtime/server/utils/cms/cache.d.ts +13 -0
- package/dist/runtime/server/utils/cms/cache.mjs +95 -0
- package/dist/runtime/server/utils/cms/common.mjs +1 -1
- package/dist/runtime/server/utils/cms/markdown.mjs +38 -8
- package/dist/runtime/server/utils/cms/mutations.d.ts +26 -0
- package/dist/runtime/server/utils/cms/mutations.mjs +569 -0
- package/dist/runtime/server/utils/cms/path.d.ts +8 -0
- package/dist/runtime/server/utils/cms/path.mjs +23 -0
- package/dist/runtime/server/utils/cms/queries.d.ts +27 -0
- package/dist/runtime/server/utils/cms/queries.mjs +366 -0
- package/dist/runtime/server/utils/cms/references.d.ts +48 -0
- package/dist/runtime/server/utils/cms/references.mjs +309 -0
- package/dist/runtime/server/utils/cms/revisions.d.ts +7 -0
- package/dist/runtime/server/utils/cms/revisions.mjs +60 -0
- package/dist/runtime/server/utils/cms/sync.mjs +3 -3
- package/dist/runtime/server/utils/cms.d.ts +5 -82
- package/dist/runtime/server/utils/cms.mjs +28 -1367
- package/dist/runtime/server/utils/comments.d.ts +11 -0
- package/dist/runtime/server/utils/comments.mjs +65 -17
- package/dist/runtime/server/utils/crypto.mjs +1 -1
- package/dist/runtime/server/utils/domains.mjs +9 -0
- package/dist/runtime/server/utils/drizzle.d.ts +26 -1
- package/dist/runtime/server/utils/drizzle.mjs +78 -19
- package/dist/runtime/server/utils/email-inbound.mjs +9 -1
- package/dist/runtime/server/utils/impersonation.mjs +58 -1
- package/dist/runtime/server/utils/lock.d.ts +11 -0
- package/dist/runtime/server/utils/lock.mjs +4 -0
- package/dist/runtime/server/utils/mail-suppression.mjs +48 -13
- package/dist/runtime/server/utils/mail.d.ts +2 -1
- package/dist/runtime/server/utils/mail.mjs +17 -11
- package/dist/runtime/server/utils/notifications.d.ts +13 -4
- package/dist/runtime/server/utils/notifications.mjs +20 -4
- package/dist/runtime/server/utils/organization.mjs +36 -1
- package/dist/runtime/server/utils/passwordless.mjs +8 -0
- package/dist/runtime/server/utils/payments/checkout.d.ts +34 -0
- package/dist/runtime/server/utils/payments/checkout.mjs +158 -0
- package/dist/runtime/server/utils/payments/common.d.ts +45 -0
- package/dist/runtime/server/utils/payments/common.mjs +234 -0
- package/dist/runtime/server/utils/payments/index.d.ts +9 -0
- package/dist/runtime/server/utils/payments/index.mjs +21 -0
- package/dist/runtime/server/utils/payments/lemonsqueezy.d.ts +7 -0
- package/dist/runtime/server/utils/payments/lemonsqueezy.mjs +55 -0
- package/dist/runtime/server/utils/payments/paddle.d.ts +7 -0
- package/dist/runtime/server/utils/payments/paddle.mjs +92 -0
- package/dist/runtime/server/utils/payments/polar.d.ts +11 -0
- package/dist/runtime/server/utils/payments/polar.mjs +66 -0
- package/dist/runtime/server/utils/payments/stripe.d.ts +7 -0
- package/dist/runtime/server/utils/payments/stripe.mjs +159 -0
- package/dist/runtime/server/utils/payments/subscriptions.d.ts +89 -0
- package/dist/runtime/server/utils/payments/subscriptions.mjs +236 -0
- package/dist/runtime/server/utils/payments/usage.d.ts +12 -0
- package/dist/runtime/server/utils/payments/usage.mjs +143 -0
- package/dist/runtime/server/utils/payments/webhooks.d.ts +10 -0
- package/dist/runtime/server/utils/payments/webhooks.mjs +200 -0
- package/dist/runtime/server/utils/payments.d.ts +1 -158
- package/dist/runtime/server/utils/payments.mjs +1 -1289
- package/dist/runtime/server/utils/queue.d.ts +2 -0
- package/dist/runtime/server/utils/queue.mjs +34 -21
- package/dist/runtime/server/utils/rag.mjs +30 -17
- package/dist/runtime/server/utils/realtime.d.ts +5 -1
- package/dist/runtime/server/utils/realtime.mjs +43 -7
- package/dist/runtime/server/utils/session.mjs +16 -3
- package/dist/runtime/server/utils/sso.d.ts +3 -0
- package/dist/runtime/server/utils/sso.mjs +43 -0
- package/dist/runtime/server/utils/storage.mjs +12 -1
- package/dist/runtime/server/utils/store/cart.d.ts +63 -0
- package/dist/runtime/server/utils/store/cart.mjs +542 -0
- package/dist/runtime/server/utils/store/checkout.d.ts +14 -0
- package/dist/runtime/server/utils/store/checkout.mjs +118 -0
- package/dist/runtime/server/utils/store/common.d.ts +29 -0
- package/dist/runtime/server/utils/store/common.mjs +479 -0
- package/dist/runtime/server/utils/store/index.d.ts +7 -0
- package/dist/runtime/server/utils/store/index.mjs +30 -0
- package/dist/runtime/server/utils/store/inventory.d.ts +25 -0
- package/dist/runtime/server/utils/store/inventory.mjs +190 -0
- package/dist/runtime/server/utils/store/orders.d.ts +60 -0
- package/dist/runtime/server/utils/store/orders.mjs +590 -0
- package/dist/runtime/server/utils/store/products.d.ts +35 -0
- package/dist/runtime/server/utils/store/products.mjs +461 -0
- package/dist/runtime/server/utils/store/vendor.d.ts +18 -0
- package/dist/runtime/server/utils/store/vendor.mjs +68 -0
- package/dist/runtime/server/utils/store.d.ts +1 -207
- package/dist/runtime/server/utils/store.mjs +1 -2227
- package/dist/runtime/server/utils/string.d.ts +1 -1
- package/dist/runtime/server/utils/string.mjs +12 -4
- package/dist/runtime/server/utils/tenant.mjs +19 -5
- package/dist/runtime/server/utils/tracker.mjs +2 -0
- package/dist/runtime/server.d.ts +3 -3
- package/dist/runtime/server.mjs +4 -4
- package/dist/runtime/storage-server.d.ts +2 -0
- package/dist/runtime/storage-server.mjs +1 -0
- package/dist/runtime/storage.d.ts +1 -1
- package/dist/runtime/storage.mjs +0 -1
- package/dist/runtime/store.d.ts +0 -1
- package/dist/runtime/store.mjs +0 -1
- package/dist/runtime/test-utils.d.ts +4 -0
- package/dist/runtime/test-utils.mjs +54 -0
- package/dist/runtime/types/d1.d.ts +43 -0
- package/dist/runtime/types/drizzle.d.ts +6 -0
- package/dist/runtime/types/store.d.ts +1 -1
- package/dist/types/analytics.d.ts +80 -0
- package/dist/types/auth.d.ts +282 -0
- package/dist/types/cache.d.ts +55 -0
- package/dist/types/comments.d.ts +130 -0
- package/dist/types/db.d.ts +29 -0
- package/dist/types/email.d.ts +182 -0
- package/dist/types/index.d.ts +22 -0
- package/dist/types/jobs.d.ts +58 -0
- package/dist/types/notifications.d.ts +77 -0
- package/dist/types/options.d.ts +363 -0
- package/dist/types/payments.d.ts +145 -0
- package/dist/types/ratelimit.d.ts +71 -0
- package/dist/types/realtime.d.ts +136 -0
- package/dist/types/site.d.ts +121 -0
- package/dist/types/storage.d.ts +164 -0
- package/dist/types/store-options.d.ts +199 -0
- package/dist/types/tenant.d.ts +100 -0
- package/dist/types.d.ts +1 -2174
- package/dist/utils/migration-lock.d.ts +139 -0
- package/dist/utils/pkg.d.ts +14 -1
- package/dist/utils/schema-diff.d.ts +39 -0
- package/package.json +55 -17
- package/dist/chunks/auth-schema.mjs +0 -364
|
@@ -0,0 +1,234 @@
|
|
|
1
|
+
import { getD1Binding } from "../../../db.mjs";
|
|
2
|
+
import { getQarpeoConfig } from "../config.mjs";
|
|
3
|
+
import { resolveTableName, resolveIndexName } from "../table-names.mjs";
|
|
4
|
+
export function getTbl(base, event) {
|
|
5
|
+
return resolveTableName(base, event);
|
|
6
|
+
}
|
|
7
|
+
export function customerTbl(event) {
|
|
8
|
+
return getTbl("customer", event);
|
|
9
|
+
}
|
|
10
|
+
export function subscriptionTbl(event) {
|
|
11
|
+
return getTbl("subscription", event);
|
|
12
|
+
}
|
|
13
|
+
export function webhookEventTbl(event) {
|
|
14
|
+
return getTbl("webhook_event", event);
|
|
15
|
+
}
|
|
16
|
+
export function usageRecordTbl(event) {
|
|
17
|
+
return getTbl("usage_record", event);
|
|
18
|
+
}
|
|
19
|
+
export const STRIPE_API_VERSION = "2024-06-20";
|
|
20
|
+
export function getPaymentsDb(event) {
|
|
21
|
+
const bindingName = globalThis.process?.env?.QARPEO_DEFAULT_DB_BINDING || "DB";
|
|
22
|
+
return getD1Binding(bindingName, event);
|
|
23
|
+
}
|
|
24
|
+
export function getPaymentsConfig(event) {
|
|
25
|
+
const cfg = getQarpeoConfig(event).payments || {};
|
|
26
|
+
const cfEnv = event?.context?.cloudflare?.env || globalThis.__qarpeo_env__ || {};
|
|
27
|
+
const provider = cfg.provider || "stripe";
|
|
28
|
+
let secretKey = cfg.secretKey || "";
|
|
29
|
+
let webhookSecret = cfg.webhookSecret || "";
|
|
30
|
+
if (!secretKey) {
|
|
31
|
+
if (provider === "stripe") {
|
|
32
|
+
secretKey = cfEnv.STRIPE_SECRET_KEY || process.env.STRIPE_SECRET_KEY || "";
|
|
33
|
+
} else if (provider === "lemonsqueezy") {
|
|
34
|
+
secretKey = cfEnv.LEMONSQUEEZY_API_KEY || process.env.LEMONSQUEEZY_API_KEY || "";
|
|
35
|
+
} else if (provider === "polar") {
|
|
36
|
+
secretKey = cfEnv.POLAR_ACCESS_TOKEN || process.env.POLAR_ACCESS_TOKEN || "";
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
if (!webhookSecret) {
|
|
40
|
+
if (provider === "stripe") {
|
|
41
|
+
webhookSecret = cfEnv.STRIPE_WEBHOOK_SECRET || process.env.STRIPE_WEBHOOK_SECRET || "";
|
|
42
|
+
} else if (provider === "lemonsqueezy") {
|
|
43
|
+
webhookSecret = cfEnv.LEMONSQUEEZY_WEBHOOK_SECRET || process.env.LEMONSQUEEZY_WEBHOOK_SECRET || "";
|
|
44
|
+
} else if (provider === "polar") {
|
|
45
|
+
webhookSecret = cfEnv.POLAR_WEBHOOK_SECRET || process.env.POLAR_WEBHOOK_SECRET || "";
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
return {
|
|
49
|
+
prefix: "/api/payments",
|
|
50
|
+
portalReturnUrl: "/",
|
|
51
|
+
...cfg,
|
|
52
|
+
provider,
|
|
53
|
+
secretKey,
|
|
54
|
+
webhookSecret
|
|
55
|
+
};
|
|
56
|
+
}
|
|
57
|
+
let ensurePaymentsTablesPromise = null;
|
|
58
|
+
export async function ensurePaymentsTables(event) {
|
|
59
|
+
if (!ensurePaymentsTablesPromise) {
|
|
60
|
+
ensurePaymentsTablesPromise = (async () => {
|
|
61
|
+
const db = getPaymentsDb(event);
|
|
62
|
+
const ct = customerTbl(event);
|
|
63
|
+
const st = subscriptionTbl(event);
|
|
64
|
+
const wt = webhookEventTbl(event);
|
|
65
|
+
const ut = usageRecordTbl(event);
|
|
66
|
+
const statements = [
|
|
67
|
+
`CREATE TABLE IF NOT EXISTS ${ct} (
|
|
68
|
+
id TEXT PRIMARY KEY,
|
|
69
|
+
user_id TEXT NOT NULL,
|
|
70
|
+
org_id TEXT,
|
|
71
|
+
provider TEXT NOT NULL DEFAULT 'stripe',
|
|
72
|
+
customer_id TEXT NOT NULL,
|
|
73
|
+
email TEXT NOT NULL,
|
|
74
|
+
name TEXT,
|
|
75
|
+
metadata_json TEXT DEFAULT '{}',
|
|
76
|
+
created_at INTEGER NOT NULL,
|
|
77
|
+
updated_at INTEGER NOT NULL
|
|
78
|
+
);`,
|
|
79
|
+
`CREATE TABLE IF NOT EXISTS ${st} (
|
|
80
|
+
id TEXT PRIMARY KEY,
|
|
81
|
+
customer_id TEXT NOT NULL,
|
|
82
|
+
user_id TEXT NOT NULL,
|
|
83
|
+
org_id TEXT,
|
|
84
|
+
provider TEXT NOT NULL DEFAULT 'stripe',
|
|
85
|
+
subscription_id TEXT NOT NULL UNIQUE,
|
|
86
|
+
plan_id TEXT NOT NULL,
|
|
87
|
+
price_id TEXT NOT NULL,
|
|
88
|
+
status TEXT NOT NULL,
|
|
89
|
+
quantity INTEGER NOT NULL DEFAULT 1,
|
|
90
|
+
cancel_at_period_end INTEGER NOT NULL DEFAULT 0,
|
|
91
|
+
current_period_start INTEGER NOT NULL,
|
|
92
|
+
current_period_end INTEGER NOT NULL,
|
|
93
|
+
trial_end INTEGER,
|
|
94
|
+
canceled_at INTEGER,
|
|
95
|
+
metadata_json TEXT DEFAULT '{}',
|
|
96
|
+
created_at INTEGER NOT NULL,
|
|
97
|
+
updated_at INTEGER NOT NULL
|
|
98
|
+
);`,
|
|
99
|
+
`CREATE TABLE IF NOT EXISTS ${wt} (
|
|
100
|
+
event_id TEXT PRIMARY KEY,
|
|
101
|
+
provider TEXT NOT NULL,
|
|
102
|
+
event_type TEXT,
|
|
103
|
+
processed_at INTEGER NOT NULL
|
|
104
|
+
);`,
|
|
105
|
+
`CREATE INDEX IF NOT EXISTS ${resolveIndexName(ct, "user_idx")} ON ${ct}(user_id);`,
|
|
106
|
+
`CREATE UNIQUE INDEX IF NOT EXISTS ${resolveIndexName(ct, "customer_idx")} ON ${ct}(customer_id);`,
|
|
107
|
+
`CREATE INDEX IF NOT EXISTS ${resolveIndexName(ct, "org_idx")} ON ${ct}(org_id);`,
|
|
108
|
+
`CREATE INDEX IF NOT EXISTS ${resolveIndexName(st, "user_idx")} ON ${st}(user_id);`,
|
|
109
|
+
`CREATE INDEX IF NOT EXISTS ${resolveIndexName(st, "subscription_idx")} ON ${st}(subscription_id);`,
|
|
110
|
+
`CREATE INDEX IF NOT EXISTS ${resolveIndexName(st, "customer_idx")} ON ${st}(customer_id);`,
|
|
111
|
+
`CREATE INDEX IF NOT EXISTS ${resolveIndexName(st, "status_idx")} ON ${st}(status);`,
|
|
112
|
+
`CREATE INDEX IF NOT EXISTS ${resolveIndexName(st, "org_idx")} ON ${st}(org_id);`,
|
|
113
|
+
`CREATE INDEX IF NOT EXISTS ${resolveIndexName(wt, "event_idx")} ON ${wt}(event_id);`,
|
|
114
|
+
`CREATE TABLE IF NOT EXISTS ${ut} (
|
|
115
|
+
id TEXT PRIMARY KEY,
|
|
116
|
+
user_id TEXT,
|
|
117
|
+
org_id TEXT,
|
|
118
|
+
customer_id TEXT,
|
|
119
|
+
subscription_id TEXT,
|
|
120
|
+
event_name TEXT NOT NULL,
|
|
121
|
+
quantity REAL NOT NULL DEFAULT 1,
|
|
122
|
+
action TEXT NOT NULL DEFAULT 'increment',
|
|
123
|
+
metadata_json TEXT DEFAULT '{}',
|
|
124
|
+
timestamp INTEGER NOT NULL,
|
|
125
|
+
created_at INTEGER NOT NULL
|
|
126
|
+
);`,
|
|
127
|
+
`CREATE INDEX IF NOT EXISTS ${resolveIndexName(ut, "user_idx")} ON ${ut}(user_id);`,
|
|
128
|
+
`CREATE INDEX IF NOT EXISTS ${resolveIndexName(ut, "sub_idx")} ON ${ut}(subscription_id);`,
|
|
129
|
+
`CREATE INDEX IF NOT EXISTS ${resolveIndexName(ut, "event_idx")} ON ${ut}(event_name);`,
|
|
130
|
+
`CREATE INDEX IF NOT EXISTS ${resolveIndexName(ut, "timestamp_idx")} ON ${ut}(timestamp);`
|
|
131
|
+
];
|
|
132
|
+
for (const rawSql of statements) {
|
|
133
|
+
const sql = rawSql.replace(/\s+/g, " ").trim();
|
|
134
|
+
try {
|
|
135
|
+
await db.exec(sql);
|
|
136
|
+
} catch (err) {
|
|
137
|
+
console.warn("[qarpeo:payments] ensurePaymentsTables warning:", err);
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
})().catch((err) => {
|
|
141
|
+
ensurePaymentsTablesPromise = null;
|
|
142
|
+
throw err;
|
|
143
|
+
});
|
|
144
|
+
}
|
|
145
|
+
return ensurePaymentsTablesPromise;
|
|
146
|
+
}
|
|
147
|
+
export async function computeHmacSha256(keyStr, dataStr) {
|
|
148
|
+
const encoder = new TextEncoder();
|
|
149
|
+
const key = await crypto.subtle.importKey(
|
|
150
|
+
"raw",
|
|
151
|
+
encoder.encode(keyStr),
|
|
152
|
+
{ name: "HMAC", hash: "SHA-256" },
|
|
153
|
+
false,
|
|
154
|
+
["sign"]
|
|
155
|
+
);
|
|
156
|
+
const sig = await crypto.subtle.sign("HMAC", key, encoder.encode(dataStr));
|
|
157
|
+
return Array.from(new Uint8Array(sig)).map((b) => b.toString(16).padStart(2, "0")).join("");
|
|
158
|
+
}
|
|
159
|
+
export async function computeHmacSha256Base64(keyStr, dataStr) {
|
|
160
|
+
const encoder = new TextEncoder();
|
|
161
|
+
const key = await crypto.subtle.importKey(
|
|
162
|
+
"raw",
|
|
163
|
+
encoder.encode(keyStr),
|
|
164
|
+
{ name: "HMAC", hash: "SHA-256" },
|
|
165
|
+
false,
|
|
166
|
+
["sign"]
|
|
167
|
+
);
|
|
168
|
+
const sig = await crypto.subtle.sign("HMAC", key, encoder.encode(dataStr));
|
|
169
|
+
const binary = String.fromCharCode(...new Uint8Array(sig));
|
|
170
|
+
return btoa(binary);
|
|
171
|
+
}
|
|
172
|
+
export function rowToSubscription(row) {
|
|
173
|
+
let metadata = {};
|
|
174
|
+
try {
|
|
175
|
+
metadata = JSON.parse(row.metadata_json || "{}");
|
|
176
|
+
} catch {
|
|
177
|
+
}
|
|
178
|
+
return {
|
|
179
|
+
id: row.id,
|
|
180
|
+
customerId: row.customer_id,
|
|
181
|
+
userId: row.user_id,
|
|
182
|
+
orgId: row.org_id || null,
|
|
183
|
+
provider: row.provider,
|
|
184
|
+
subscriptionId: row.subscription_id,
|
|
185
|
+
planId: row.plan_id,
|
|
186
|
+
priceId: row.price_id,
|
|
187
|
+
status: row.status,
|
|
188
|
+
quantity: row.quantity || 1,
|
|
189
|
+
cancelAtPeriodEnd: Boolean(row.cancel_at_period_end),
|
|
190
|
+
currentPeriodStart: row.current_period_start,
|
|
191
|
+
currentPeriodEnd: row.current_period_end,
|
|
192
|
+
trialEnd: row.trial_end || null,
|
|
193
|
+
canceledAt: row.canceled_at || null,
|
|
194
|
+
metadata,
|
|
195
|
+
metadataJson: row.metadata_json || "{}",
|
|
196
|
+
createdAt: row.created_at,
|
|
197
|
+
updatedAt: row.updated_at
|
|
198
|
+
};
|
|
199
|
+
}
|
|
200
|
+
export function safeReturnUrl(url, siteUrl, fallbackPath = "/") {
|
|
201
|
+
const cleanSiteUrl = siteUrl.replace(/\/+$/, "");
|
|
202
|
+
const fallback = `${cleanSiteUrl}${fallbackPath.startsWith("/") ? fallbackPath : "/" + fallbackPath}`;
|
|
203
|
+
if (typeof url !== "string" || !url.trim()) return fallback;
|
|
204
|
+
const trimmed = url.trim();
|
|
205
|
+
if (trimmed.startsWith("/") && !trimmed.startsWith("//") && !trimmed.startsWith("/\\") && !trimmed.startsWith("\\")) {
|
|
206
|
+
if (/[\r\n\0]/.test(trimmed)) return fallback;
|
|
207
|
+
return `${cleanSiteUrl}${trimmed}`;
|
|
208
|
+
}
|
|
209
|
+
try {
|
|
210
|
+
const parsed = new URL(trimmed);
|
|
211
|
+
const site = new URL(cleanSiteUrl);
|
|
212
|
+
if (parsed.origin === site.origin) {
|
|
213
|
+
return parsed.toString();
|
|
214
|
+
}
|
|
215
|
+
} catch {
|
|
216
|
+
}
|
|
217
|
+
return fallback;
|
|
218
|
+
}
|
|
219
|
+
const webhookListeners = /* @__PURE__ */ new Set();
|
|
220
|
+
export function registerPaymentWebhookListener(listener) {
|
|
221
|
+
webhookListeners.add(listener);
|
|
222
|
+
return () => {
|
|
223
|
+
webhookListeners.delete(listener);
|
|
224
|
+
};
|
|
225
|
+
}
|
|
226
|
+
export async function notifyPaymentWebhookListeners(info) {
|
|
227
|
+
for (const listener of webhookListeners) {
|
|
228
|
+
try {
|
|
229
|
+
await listener(info);
|
|
230
|
+
} catch (err) {
|
|
231
|
+
console.warn("[qarpeo:payments] Error in payment webhook listener:", err?.message || err);
|
|
232
|
+
}
|
|
233
|
+
}
|
|
234
|
+
}
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
export { getPaymentsConfig, ensurePaymentsTables, registerPaymentWebhookListener, type PaymentWebhookListener, type PaymentWebhookListenerPayload, } from "./common";
|
|
2
|
+
export { verifyStripeSignature } from "./stripe";
|
|
3
|
+
export { verifyLemonSqueezySignature } from "./lemonsqueezy";
|
|
4
|
+
export { verifyPolarSignature } from "./polar";
|
|
5
|
+
export { verifyPaddleSignature } from "./paddle";
|
|
6
|
+
export { processPaymentWebhook } from "./webhooks";
|
|
7
|
+
export { createCheckoutSession, createCustomerPortalSession } from "./checkout";
|
|
8
|
+
export { cancelSubscription, pauseSubscription, changePlan, getSubscription, requireSubscription, hasFeature, checkLimit, type RequireSubscriptionOptions, } from "./subscriptions";
|
|
9
|
+
export { reportUsage, getUsageSummary } from "./usage";
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
export {
|
|
2
|
+
getPaymentsConfig,
|
|
3
|
+
ensurePaymentsTables,
|
|
4
|
+
registerPaymentWebhookListener
|
|
5
|
+
} from "./common.mjs";
|
|
6
|
+
export { verifyStripeSignature } from "./stripe.mjs";
|
|
7
|
+
export { verifyLemonSqueezySignature } from "./lemonsqueezy.mjs";
|
|
8
|
+
export { verifyPolarSignature } from "./polar.mjs";
|
|
9
|
+
export { verifyPaddleSignature } from "./paddle.mjs";
|
|
10
|
+
export { processPaymentWebhook } from "./webhooks.mjs";
|
|
11
|
+
export { createCheckoutSession, createCustomerPortalSession } from "./checkout.mjs";
|
|
12
|
+
export {
|
|
13
|
+
cancelSubscription,
|
|
14
|
+
pauseSubscription,
|
|
15
|
+
changePlan,
|
|
16
|
+
getSubscription,
|
|
17
|
+
requireSubscription,
|
|
18
|
+
hasFeature,
|
|
19
|
+
checkLimit
|
|
20
|
+
} from "./subscriptions.mjs";
|
|
21
|
+
export { reportUsage, getUsageSummary } from "./usage.mjs";
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
/** Verifies Lemon Squeezy webhook signature (X-Signature header) */
|
|
2
|
+
export declare function verifyLemonSqueezySignature(rawBody: string, signatureHeader: string | null | undefined, secret: string): Promise<boolean>;
|
|
3
|
+
export declare function handleLemonSqueezyWebhookEvent(db: any, ct: string, st: string, payload: any, now: number): Promise<{
|
|
4
|
+
eventType: string;
|
|
5
|
+
eventData: any;
|
|
6
|
+
affectedSubId: string | null;
|
|
7
|
+
}>;
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
import { nanoid, timingSafeEqualString } from "../crypto.mjs";
|
|
2
|
+
import { computeHmacSha256 } from "./common.mjs";
|
|
3
|
+
export async function verifyLemonSqueezySignature(rawBody, signatureHeader, secret) {
|
|
4
|
+
if (!signatureHeader || !secret) return false;
|
|
5
|
+
const expected = await computeHmacSha256(secret, rawBody);
|
|
6
|
+
return timingSafeEqualString(signatureHeader.trim().toLowerCase(), expected.toLowerCase());
|
|
7
|
+
}
|
|
8
|
+
export async function handleLemonSqueezyWebhookEvent(db, ct, st, payload, now) {
|
|
9
|
+
const eventType = payload.meta?.event_name;
|
|
10
|
+
const data = payload.data?.attributes || {};
|
|
11
|
+
const eventData = data;
|
|
12
|
+
const subId = String(payload.data?.id || "");
|
|
13
|
+
const affectedSubId = subId;
|
|
14
|
+
const customerId = String(data.customer_id || "");
|
|
15
|
+
const userEmail = data.user_email || "";
|
|
16
|
+
const customData = payload.meta?.custom_data || {};
|
|
17
|
+
const userId = customData.user_id || customData.userId || "";
|
|
18
|
+
const orgId = customData.org_id || customData.orgId || null;
|
|
19
|
+
const planId = String(data.variant_id || "");
|
|
20
|
+
if (eventType === "subscription_created" || eventType === "subscription_updated" || eventType === "subscription_resumed") {
|
|
21
|
+
const status = data.status === "active" ? "active" : data.status === "on_trial" ? "trialing" : data.status === "past_due" ? "past_due" : "canceled";
|
|
22
|
+
const periodStart = data.renews_at ? new Date(data.created_at).getTime() : now;
|
|
23
|
+
const periodEnd = data.renews_at ? new Date(data.renews_at).getTime() : now + 30 * 864e5;
|
|
24
|
+
const cancelAtPeriodEnd = data.cancelled ? 1 : 0;
|
|
25
|
+
if (customerId && userId) {
|
|
26
|
+
await db.prepare(
|
|
27
|
+
`INSERT INTO ${ct} (id, user_id, org_id, provider, customer_id, email, name, metadata_json, created_at, updated_at) VALUES (?, ?, ?, 'lemonsqueezy', ?, ?, ?, '{}', ?, ?) ON CONFLICT(customer_id) DO UPDATE SET email = excluded.email, name = excluded.name, updated_at = excluded.updated_at`
|
|
28
|
+
).bind(nanoid(), userId, orgId, customerId, userEmail, data.user_name || null, now, now).run();
|
|
29
|
+
}
|
|
30
|
+
await db.prepare(
|
|
31
|
+
`INSERT INTO ${st} (id, customer_id, user_id, org_id, provider, subscription_id, plan_id, price_id, status, quantity, cancel_at_period_end, current_period_start, current_period_end, trial_end, canceled_at, metadata_json, created_at, updated_at)
|
|
32
|
+
VALUES (?, ?, ?, ?, 'lemonsqueezy', ?, ?, ?, ?, 1, ?, ?, ?, null, null, '{}', ?, ?)
|
|
33
|
+
ON CONFLICT(subscription_id) DO UPDATE SET status = excluded.status, cancel_at_period_end = excluded.cancel_at_period_end, current_period_start = excluded.current_period_start, current_period_end = excluded.current_period_end, updated_at = excluded.updated_at`
|
|
34
|
+
).bind(
|
|
35
|
+
nanoid(),
|
|
36
|
+
customerId,
|
|
37
|
+
userId,
|
|
38
|
+
orgId,
|
|
39
|
+
subId,
|
|
40
|
+
planId,
|
|
41
|
+
planId,
|
|
42
|
+
status,
|
|
43
|
+
cancelAtPeriodEnd,
|
|
44
|
+
periodStart,
|
|
45
|
+
periodEnd,
|
|
46
|
+
now,
|
|
47
|
+
now
|
|
48
|
+
).run();
|
|
49
|
+
} else if (eventType === "subscription_cancelled" || eventType === "subscription_expired") {
|
|
50
|
+
await db.prepare(
|
|
51
|
+
`UPDATE ${st} SET status = 'canceled', canceled_at = ?, updated_at = ? WHERE subscription_id = ?`
|
|
52
|
+
).bind(now, now, subId).run();
|
|
53
|
+
}
|
|
54
|
+
return { eventType, eventData, affectedSubId };
|
|
55
|
+
}
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
/** Verifies Paddle Billing webhook signature (Paddle-Signature header: `ts=TIMESTAMP;h1=HMAC_HEX`) with replay protection */
|
|
2
|
+
export declare function verifyPaddleSignature(rawBody: string, signatureHeader: string | null | undefined, secret: string, toleranceSec?: number): Promise<boolean>;
|
|
3
|
+
export declare function handlePaddleWebhookEvent(db: any, ct: string, st: string, payload: any, now: number): Promise<{
|
|
4
|
+
eventType: string;
|
|
5
|
+
eventData: any;
|
|
6
|
+
affectedSubId: string | null;
|
|
7
|
+
}>;
|
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
import { nanoid, timingSafeEqualString } from "../crypto.mjs";
|
|
2
|
+
import { computeHmacSha256 } from "./common.mjs";
|
|
3
|
+
export async function verifyPaddleSignature(rawBody, signatureHeader, secret, toleranceSec = 300) {
|
|
4
|
+
if (!signatureHeader || !secret) return false;
|
|
5
|
+
const parts = {};
|
|
6
|
+
for (const item of signatureHeader.split(";")) {
|
|
7
|
+
const idx = item.indexOf("=");
|
|
8
|
+
if (idx !== -1) {
|
|
9
|
+
parts[item.slice(0, idx).trim()] = item.slice(idx + 1).trim();
|
|
10
|
+
}
|
|
11
|
+
}
|
|
12
|
+
const ts = parts.ts;
|
|
13
|
+
const h1 = parts.h1;
|
|
14
|
+
if (!ts || !h1) return false;
|
|
15
|
+
const now = Math.floor(Date.now() / 1e3);
|
|
16
|
+
const tsNum = parseInt(ts, 10);
|
|
17
|
+
if (isNaN(tsNum) || Math.abs(now - tsNum) > toleranceSec) {
|
|
18
|
+
return false;
|
|
19
|
+
}
|
|
20
|
+
const payload = `${ts}:${rawBody}`;
|
|
21
|
+
const expected = await computeHmacSha256(secret, payload);
|
|
22
|
+
return timingSafeEqualString(h1, expected);
|
|
23
|
+
}
|
|
24
|
+
export async function handlePaddleWebhookEvent(db, ct, st, payload, now) {
|
|
25
|
+
const eventType = payload.event_type || payload.type || "";
|
|
26
|
+
const data = payload.data || {};
|
|
27
|
+
const eventData = data;
|
|
28
|
+
const subId = String(data.id || "");
|
|
29
|
+
const affectedSubId = subId;
|
|
30
|
+
const customerId = String(data.customer_id || "");
|
|
31
|
+
const customData = data.custom_data || {};
|
|
32
|
+
const userId = customData.userId || customData.user_id || "";
|
|
33
|
+
const orgId = customData.orgId || customData.org_id || null;
|
|
34
|
+
const priceId = data.items?.[0]?.price?.id || "";
|
|
35
|
+
const planId = customData.planId || priceId;
|
|
36
|
+
if (eventType === "subscription.created" || eventType === "subscription.updated" || eventType === "subscription.activated" || eventType === "subscription.resumed") {
|
|
37
|
+
const status = data.status === "active" ? "active" : data.status === "trialing" ? "trialing" : data.status === "past_due" ? "past_due" : data.status === "paused" ? "paused" : "canceled";
|
|
38
|
+
const periodStart = data.current_billing_period?.starts_at ? new Date(data.current_billing_period.starts_at).getTime() : now;
|
|
39
|
+
const periodEnd = data.current_billing_period?.ends_at ? new Date(data.current_billing_period.ends_at).getTime() : now + 30 * 864e5;
|
|
40
|
+
const cancelAtPeriodEnd = data.scheduled_change?.action === "cancel" ? 1 : 0;
|
|
41
|
+
const quantity = data.items?.[0]?.quantity || 1;
|
|
42
|
+
if (customerId && userId) {
|
|
43
|
+
await db.prepare(
|
|
44
|
+
`INSERT INTO ${ct} (id, user_id, org_id, provider, customer_id, email, name, metadata_json, created_at, updated_at)
|
|
45
|
+
VALUES (?, ?, ?, 'paddle', ?, ?, ?, ?, ?, ?)
|
|
46
|
+
ON CONFLICT(customer_id) DO UPDATE SET org_id = excluded.org_id, metadata_json = excluded.metadata_json, updated_at = excluded.updated_at`
|
|
47
|
+
).bind(
|
|
48
|
+
nanoid(),
|
|
49
|
+
userId,
|
|
50
|
+
orgId,
|
|
51
|
+
customerId,
|
|
52
|
+
customData.email || ``,
|
|
53
|
+
customData.name || null,
|
|
54
|
+
JSON.stringify(customData),
|
|
55
|
+
now,
|
|
56
|
+
now
|
|
57
|
+
).run();
|
|
58
|
+
}
|
|
59
|
+
await db.prepare(
|
|
60
|
+
`INSERT INTO ${st}
|
|
61
|
+
(id, customer_id, user_id, org_id, provider, subscription_id, plan_id, price_id, status, quantity, cancel_at_period_end, current_period_start, current_period_end, trial_end, canceled_at, metadata_json, created_at, updated_at)
|
|
62
|
+
VALUES (?, ?, ?, ?, 'paddle', ?, ?, ?, ?, ?, ?, ?, ?, null, null, ?, ?, ?)
|
|
63
|
+
ON CONFLICT(subscription_id) DO UPDATE SET
|
|
64
|
+
plan_id = excluded.plan_id, price_id = excluded.price_id, status = excluded.status,
|
|
65
|
+
quantity = excluded.quantity, cancel_at_period_end = excluded.cancel_at_period_end,
|
|
66
|
+
current_period_start = excluded.current_period_start, current_period_end = excluded.current_period_end,
|
|
67
|
+
metadata_json = excluded.metadata_json, updated_at = excluded.updated_at`
|
|
68
|
+
).bind(
|
|
69
|
+
nanoid(),
|
|
70
|
+
customerId,
|
|
71
|
+
userId,
|
|
72
|
+
orgId,
|
|
73
|
+
subId,
|
|
74
|
+
planId,
|
|
75
|
+
priceId,
|
|
76
|
+
status,
|
|
77
|
+
quantity,
|
|
78
|
+
cancelAtPeriodEnd,
|
|
79
|
+
periodStart,
|
|
80
|
+
periodEnd,
|
|
81
|
+
JSON.stringify(customData),
|
|
82
|
+
now,
|
|
83
|
+
now
|
|
84
|
+
).run();
|
|
85
|
+
} else if (eventType === "subscription.canceled" || eventType === "subscription.past_due") {
|
|
86
|
+
const newStatus = eventType === "subscription.past_due" ? "past_due" : "canceled";
|
|
87
|
+
await db.prepare(
|
|
88
|
+
`UPDATE ${st} SET status = ?, canceled_at = ?, updated_at = ? WHERE subscription_id = ?`
|
|
89
|
+
).bind(newStatus, newStatus === "canceled" ? now : null, now, subId).run();
|
|
90
|
+
}
|
|
91
|
+
return { eventType, eventData, affectedSubId };
|
|
92
|
+
}
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
/** Verifies Polar webhook signature (webhook-signature header with optional Standard Webhooks headers) */
|
|
2
|
+
export declare function verifyPolarSignature(rawBody: string, signatureHeader: string | null | undefined, secret: string, options?: {
|
|
3
|
+
timestamp?: string | null;
|
|
4
|
+
webhookId?: string | null;
|
|
5
|
+
toleranceSec?: number;
|
|
6
|
+
}): Promise<boolean>;
|
|
7
|
+
export declare function handlePolarWebhookEvent(db: any, st: string, payload: any, now: number): Promise<{
|
|
8
|
+
eventType: string;
|
|
9
|
+
eventData: any;
|
|
10
|
+
affectedSubId: string | null;
|
|
11
|
+
}>;
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
import { nanoid, timingSafeEqualString } from "../crypto.mjs";
|
|
2
|
+
import { computeHmacSha256, computeHmacSha256Base64 } from "./common.mjs";
|
|
3
|
+
export async function verifyPolarSignature(rawBody, signatureHeader, secret, options) {
|
|
4
|
+
if (!signatureHeader || !secret) return false;
|
|
5
|
+
const toleranceSec = options?.toleranceSec ?? 300;
|
|
6
|
+
const ts = options?.timestamp;
|
|
7
|
+
if (ts) {
|
|
8
|
+
const now = Math.floor(Date.now() / 1e3);
|
|
9
|
+
const tsNum = parseInt(ts, 10);
|
|
10
|
+
if (isNaN(tsNum) || Math.abs(now - tsNum) > toleranceSec) {
|
|
11
|
+
return false;
|
|
12
|
+
}
|
|
13
|
+
}
|
|
14
|
+
if (options?.webhookId && ts) {
|
|
15
|
+
const payload = `${options.webhookId}.${ts}.${rawBody}`;
|
|
16
|
+
const rawSecret = secret.startsWith("whsec_") ? secret.slice(6) : secret;
|
|
17
|
+
const expectedHex = await computeHmacSha256(secret, payload);
|
|
18
|
+
const expectedBase64 = await computeHmacSha256Base64(rawSecret, payload);
|
|
19
|
+
const signatures = signatureHeader.split(" ");
|
|
20
|
+
return signatures.some((sig) => {
|
|
21
|
+
const cleanSig = sig.replace(/^v1,/, "");
|
|
22
|
+
return timingSafeEqualString(cleanSig, expectedHex) || timingSafeEqualString(cleanSig, expectedBase64);
|
|
23
|
+
});
|
|
24
|
+
}
|
|
25
|
+
const expected = await computeHmacSha256(secret, rawBody);
|
|
26
|
+
return timingSafeEqualString(signatureHeader, expected);
|
|
27
|
+
}
|
|
28
|
+
export async function handlePolarWebhookEvent(db, st, payload, now) {
|
|
29
|
+
const eventType = payload.type;
|
|
30
|
+
const data = payload.data || {};
|
|
31
|
+
const eventData = data;
|
|
32
|
+
const subId = data.id;
|
|
33
|
+
const affectedSubId = subId;
|
|
34
|
+
const customerId = data.customer_id || data.user_id || "";
|
|
35
|
+
const userId = data.metadata?.userId || data.user?.id || "";
|
|
36
|
+
const orgId = data.metadata?.orgId || null;
|
|
37
|
+
const priceId = data.price_id || data.product_id || "";
|
|
38
|
+
if (eventType === "subscription.created" || eventType === "subscription.updated" || eventType === "subscription.active") {
|
|
39
|
+
const status = data.status === "active" ? "active" : data.status === "canceled" ? "canceled" : "past_due";
|
|
40
|
+
const periodStart = data.current_period_start ? new Date(data.current_period_start).getTime() : now;
|
|
41
|
+
const periodEnd = data.current_period_end ? new Date(data.current_period_end).getTime() : now + 30 * 864e5;
|
|
42
|
+
await db.prepare(
|
|
43
|
+
`INSERT INTO ${st} (id, customer_id, user_id, org_id, provider, subscription_id, plan_id, price_id, status, quantity, cancel_at_period_end, current_period_start, current_period_end, trial_end, canceled_at, metadata_json, created_at, updated_at)
|
|
44
|
+
VALUES (?, ?, ?, ?, 'polar', ?, ?, ?, ?, 1, 0, ?, ?, null, null, '{}', ?, ?)
|
|
45
|
+
ON CONFLICT(subscription_id) DO UPDATE SET status = excluded.status, current_period_start = excluded.current_period_start, current_period_end = excluded.current_period_end, updated_at = excluded.updated_at`
|
|
46
|
+
).bind(
|
|
47
|
+
nanoid(),
|
|
48
|
+
customerId,
|
|
49
|
+
userId,
|
|
50
|
+
orgId,
|
|
51
|
+
subId,
|
|
52
|
+
priceId,
|
|
53
|
+
priceId,
|
|
54
|
+
status,
|
|
55
|
+
periodStart,
|
|
56
|
+
periodEnd,
|
|
57
|
+
now,
|
|
58
|
+
now
|
|
59
|
+
).run();
|
|
60
|
+
} else if (eventType === "subscription.canceled" || eventType === "subscription.revoked") {
|
|
61
|
+
await db.prepare(
|
|
62
|
+
`UPDATE ${st} SET status = 'canceled', canceled_at = ?, updated_at = ? WHERE subscription_id = ?`
|
|
63
|
+
).bind(now, now, subId).run();
|
|
64
|
+
}
|
|
65
|
+
return { eventType, eventData, affectedSubId };
|
|
66
|
+
}
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
/** Verifies Stripe webhook signature: Stripe-Signature header contains: `t=timestamp,v1=signature` */
|
|
2
|
+
export declare function verifyStripeSignature(rawBody: string, signatureHeader: string | null | undefined, secret: string, toleranceSec?: number): Promise<boolean>;
|
|
3
|
+
export declare function handleStripeWebhookEvent(db: any, ct: string, st: string, payload: any, now: number): Promise<{
|
|
4
|
+
eventType: string;
|
|
5
|
+
eventData: any;
|
|
6
|
+
affectedSubId: string | null;
|
|
7
|
+
}>;
|