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.
Files changed (260) hide show
  1. package/dist/chunks/tools.mjs +993 -31
  2. package/dist/cli/index.mjs +1071 -31
  3. package/dist/fate/index.d.ts +9 -1
  4. package/dist/fate/index.mjs +20 -3
  5. package/dist/module.mjs +296 -750
  6. package/dist/runtime/browser.mjs +2 -2
  7. package/dist/runtime/comments-server.d.ts +3 -0
  8. package/dist/runtime/comments-server.mjs +2 -0
  9. package/dist/runtime/comments.d.ts +0 -2
  10. package/dist/runtime/comments.mjs +0 -2
  11. package/dist/runtime/db.d.ts +10 -9
  12. package/dist/runtime/db.mjs +79 -8
  13. package/dist/runtime/drizzle.mjs +21 -6
  14. package/dist/runtime/index.d.ts +4 -0
  15. package/dist/runtime/realtime-server.d.ts +4 -0
  16. package/dist/runtime/realtime-server.mjs +13 -0
  17. package/dist/runtime/realtime.d.ts +1 -4
  18. package/dist/runtime/realtime.mjs +0 -13
  19. package/dist/runtime/replica.d.ts +27 -0
  20. package/dist/runtime/replica.mjs +229 -0
  21. package/dist/runtime/server/durable-objects/agent.mjs +14 -2
  22. package/dist/runtime/server/durable-objects/room.d.ts +10 -0
  23. package/dist/runtime/server/durable-objects/room.mjs +119 -28
  24. package/dist/runtime/server/middleware/devtools.mjs +1 -1
  25. package/dist/runtime/server/middleware/tenancy.mjs +7 -4
  26. package/dist/runtime/server/plugins/store.mjs +1 -1
  27. package/dist/runtime/server/routes/__qarpeo/mail/track/click/[id].get.mjs +57 -17
  28. package/dist/runtime/server/routes/agents/[agent]/chat.post.mjs +19 -12
  29. package/dist/runtime/server/routes/agents/[agent]/clear.post.mjs +8 -9
  30. package/dist/runtime/server/routes/agents/[agent]/history.get.mjs +8 -9
  31. package/dist/runtime/server/routes/analytics/events.get.mjs +12 -2
  32. package/dist/runtime/server/routes/analytics/pageviews.get.mjs +10 -1
  33. package/dist/runtime/server/routes/analytics/summary.get.mjs +10 -1
  34. package/dist/runtime/server/routes/auth/2fa/disable.post.mjs +11 -2
  35. package/dist/runtime/server/routes/auth/2fa/setup.post.mjs +7 -0
  36. package/dist/runtime/server/routes/auth/2fa/verify.post.mjs +11 -2
  37. package/dist/runtime/server/routes/auth/account.delete.mjs +7 -0
  38. package/dist/runtime/server/routes/auth/magic-link/verify.get.mjs +5 -3
  39. package/dist/runtime/server/routes/auth/organization/sso/index.post.mjs +10 -0
  40. package/dist/runtime/server/routes/auth/otp/verify.post.mjs +5 -3
  41. package/dist/runtime/server/routes/auth/sso/saml/acs.post.mjs +18 -0
  42. package/dist/runtime/server/routes/auth/webauthn/login/options.post.d.ts +1 -1
  43. package/dist/runtime/server/routes/auth/webauthn/login/options.post.mjs +11 -2
  44. package/dist/runtime/server/routes/auth/webauthn/login/verify.post.mjs +10 -1
  45. package/dist/runtime/server/routes/auth/webauthn/register/options.post.d.ts +1 -1
  46. package/dist/runtime/server/routes/auth/webauthn/register/options.post.mjs +10 -1
  47. package/dist/runtime/server/routes/auth/webauthn/register/verify.post.mjs +10 -1
  48. package/dist/runtime/server/routes/browser/crawl.post.mjs +13 -0
  49. package/dist/runtime/server/routes/browser/invoice.post.mjs +15 -1
  50. package/dist/runtime/server/routes/browser/og-image.post.mjs +13 -0
  51. package/dist/runtime/server/routes/browser/pdf.post.mjs +15 -1
  52. package/dist/runtime/server/routes/browser/screenshot.post.mjs +13 -0
  53. package/dist/runtime/server/routes/cms/[collection]/[id]/preview-token.post.mjs +23 -8
  54. package/dist/runtime/server/routes/cms/[collection]/[id]/publish.post.mjs +2 -1
  55. package/dist/runtime/server/routes/cms/[collection]/[id]/review.post.mjs +2 -1
  56. package/dist/runtime/server/routes/cms/[collection]/[id]/revisions/[revId]/restore.post.mjs +2 -1
  57. package/dist/runtime/server/routes/cms/[collection]/[id].delete.mjs +2 -1
  58. package/dist/runtime/server/routes/cms/[collection]/[id].put.mjs +2 -1
  59. package/dist/runtime/server/routes/cms/[collection]/index.post.mjs +2 -1
  60. package/dist/runtime/server/routes/cms/categories/[id].delete.mjs +2 -1
  61. package/dist/runtime/server/routes/cms/categories/[id].put.mjs +2 -1
  62. package/dist/runtime/server/routes/cms/categories.post.mjs +2 -1
  63. package/dist/runtime/server/routes/cms/collections/[id].delete.mjs +2 -1
  64. package/dist/runtime/server/routes/cms/collections/[id].put.mjs +2 -1
  65. package/dist/runtime/server/routes/cms/collections/index.post.mjs +2 -1
  66. package/dist/runtime/server/routes/cms/export.post.mjs +1 -1
  67. package/dist/runtime/server/routes/cms/subscribers/[id].delete.mjs +2 -1
  68. package/dist/runtime/server/routes/cms/subscribers/[id].patch.mjs +2 -1
  69. package/dist/runtime/server/routes/cms/tags/[id].delete.mjs +2 -1
  70. package/dist/runtime/server/routes/cms/tags.post.mjs +2 -1
  71. package/dist/runtime/server/routes/comments/[id]/react.post.mjs +7 -3
  72. package/dist/runtime/server/routes/comments/[id]/report.post.mjs +3 -0
  73. package/dist/runtime/server/routes/comments/[id].delete.mjs +1 -1
  74. package/dist/runtime/server/routes/comments/[id].get.mjs +13 -0
  75. package/dist/runtime/server/routes/comments/[id].patch.mjs +1 -1
  76. package/dist/runtime/server/routes/fate.d.ts +6 -0
  77. package/dist/runtime/server/routes/fate.mjs +32 -3
  78. package/dist/runtime/server/routes/mail/bounce.post.mjs +14 -2
  79. package/dist/runtime/server/routes/mail/unsubscribe.mjs +2 -1
  80. package/dist/runtime/server/routes/mail/webhooks.post.mjs +18 -4
  81. package/dist/runtime/server/routes/notifications/[id].get.mjs +3 -4
  82. package/dist/runtime/server/routes/notifications/index.get.mjs +4 -2
  83. package/dist/runtime/server/routes/notifications/push/subscribe.post.mjs +3 -1
  84. package/dist/runtime/server/routes/notifications/push/unsubscribe.post.mjs +5 -3
  85. package/dist/runtime/server/routes/notifications/read-all.post.mjs +6 -2
  86. package/dist/runtime/server/routes/notifications/send.post.mjs +13 -2
  87. package/dist/runtime/server/routes/payments/cancel.post.mjs +1 -1
  88. package/dist/runtime/server/routes/payments/change-plan.post.mjs +1 -1
  89. package/dist/runtime/server/routes/payments/checkout.post.mjs +1 -1
  90. package/dist/runtime/server/routes/payments/pause.post.mjs +1 -1
  91. package/dist/runtime/server/routes/payments/portal.post.mjs +1 -1
  92. package/dist/runtime/server/routes/payments/subscription.get.mjs +1 -1
  93. package/dist/runtime/server/routes/payments/usage.get.mjs +1 -1
  94. package/dist/runtime/server/routes/payments/usage.post.mjs +1 -1
  95. package/dist/runtime/server/routes/payments/webhook.post.mjs +8 -1
  96. package/dist/runtime/server/routes/realtime/broadcast.post.mjs +3 -2
  97. package/dist/runtime/server/routes/realtime/history.delete.mjs +2 -2
  98. package/dist/runtime/server/routes/realtime/history.get.mjs +2 -2
  99. package/dist/runtime/server/routes/realtime/presence.get.mjs +3 -3
  100. package/dist/runtime/server/routes/realtime/state.get.mjs +3 -3
  101. package/dist/runtime/server/routes/realtime/state.post.mjs +13 -4
  102. package/dist/runtime/server/routes/realtime/ws.get.mjs +2 -2
  103. package/dist/runtime/server/routes/storage/file/[...key].delete.mjs +1 -1
  104. package/dist/runtime/server/routes/storage/file/[...key].get.mjs +7 -0
  105. package/dist/runtime/server/routes/storage/files.get.d.ts +1 -1
  106. package/dist/runtime/server/routes/storage/files.get.mjs +24 -4
  107. package/dist/runtime/server/routes/storage/multipart/abort.post.mjs +16 -1
  108. package/dist/runtime/server/routes/storage/multipart/complete.post.d.ts +1 -1
  109. package/dist/runtime/server/routes/storage/multipart/complete.post.mjs +15 -1
  110. package/dist/runtime/server/routes/storage/multipart/create.post.mjs +7 -0
  111. package/dist/runtime/server/routes/storage/multipart/part.put.mjs +15 -1
  112. package/dist/runtime/server/routes/storage/presigned-r2.post.mjs +8 -1
  113. package/dist/runtime/server/routes/storage/presigned.post.d.ts +1 -1
  114. package/dist/runtime/server/routes/storage/presigned.post.mjs +8 -1
  115. package/dist/runtime/server/routes/storage/sign.post.mjs +7 -0
  116. package/dist/runtime/server/routes/storage/upload.post.d.ts +2 -2
  117. package/dist/runtime/server/routes/store/cart/index.delete.mjs +3 -4
  118. package/dist/runtime/server/routes/store/cart/index.get.mjs +3 -10
  119. package/dist/runtime/server/routes/store/cart/items/[id].delete.mjs +6 -4
  120. package/dist/runtime/server/routes/store/cart/items/[id].patch.mjs +12 -4
  121. package/dist/runtime/server/routes/store/cart/items.post.mjs +9 -10
  122. package/dist/runtime/server/routes/store/categories/index.get.mjs +4 -2
  123. package/dist/runtime/server/routes/store/checkout.post.mjs +13 -3
  124. package/dist/runtime/server/routes/store/coupons/apply.post.mjs +6 -5
  125. package/dist/runtime/server/routes/store/orders/[id].get.mjs +2 -2
  126. package/dist/runtime/server/routes/store/orders/download/[token].get.mjs +6 -3
  127. package/dist/runtime/server/routes/store/orders/index.get.mjs +1 -1
  128. package/dist/runtime/server/routes/store/products/[slug].get.mjs +2 -2
  129. package/dist/runtime/server/routes/store/products/index.get.mjs +1 -1
  130. package/dist/runtime/server/routes/store/tax/calculate.post.mjs +10 -0
  131. package/dist/runtime/server/routes/tenants/[tenant]/domains/[domain]/index.delete.mjs +26 -25
  132. package/dist/runtime/server/routes/tenants/[tenant]/domains/[domain]/verify.post.mjs +26 -25
  133. package/dist/runtime/server/utils/ai.d.ts +6 -0
  134. package/dist/runtime/server/utils/ai.mjs +12 -2
  135. package/dist/runtime/server/utils/analytics-query.mjs +8 -4
  136. package/dist/runtime/server/utils/browser-utils.d.ts +9 -0
  137. package/dist/runtime/server/utils/browser-utils.mjs +135 -0
  138. package/dist/runtime/server/utils/cms/cache.d.ts +13 -0
  139. package/dist/runtime/server/utils/cms/cache.mjs +95 -0
  140. package/dist/runtime/server/utils/cms/common.mjs +1 -1
  141. package/dist/runtime/server/utils/cms/markdown.mjs +38 -8
  142. package/dist/runtime/server/utils/cms/mutations.d.ts +26 -0
  143. package/dist/runtime/server/utils/cms/mutations.mjs +569 -0
  144. package/dist/runtime/server/utils/cms/path.d.ts +8 -0
  145. package/dist/runtime/server/utils/cms/path.mjs +23 -0
  146. package/dist/runtime/server/utils/cms/queries.d.ts +27 -0
  147. package/dist/runtime/server/utils/cms/queries.mjs +366 -0
  148. package/dist/runtime/server/utils/cms/references.d.ts +48 -0
  149. package/dist/runtime/server/utils/cms/references.mjs +309 -0
  150. package/dist/runtime/server/utils/cms/revisions.d.ts +7 -0
  151. package/dist/runtime/server/utils/cms/revisions.mjs +60 -0
  152. package/dist/runtime/server/utils/cms/sync.mjs +3 -3
  153. package/dist/runtime/server/utils/cms.d.ts +5 -82
  154. package/dist/runtime/server/utils/cms.mjs +28 -1367
  155. package/dist/runtime/server/utils/comments.d.ts +11 -0
  156. package/dist/runtime/server/utils/comments.mjs +65 -17
  157. package/dist/runtime/server/utils/crypto.mjs +1 -1
  158. package/dist/runtime/server/utils/domains.mjs +9 -0
  159. package/dist/runtime/server/utils/drizzle.d.ts +26 -1
  160. package/dist/runtime/server/utils/drizzle.mjs +78 -19
  161. package/dist/runtime/server/utils/email-inbound.mjs +9 -1
  162. package/dist/runtime/server/utils/impersonation.mjs +58 -1
  163. package/dist/runtime/server/utils/lock.d.ts +11 -0
  164. package/dist/runtime/server/utils/lock.mjs +4 -0
  165. package/dist/runtime/server/utils/mail-suppression.mjs +48 -13
  166. package/dist/runtime/server/utils/mail.d.ts +2 -1
  167. package/dist/runtime/server/utils/mail.mjs +17 -11
  168. package/dist/runtime/server/utils/notifications.d.ts +13 -4
  169. package/dist/runtime/server/utils/notifications.mjs +20 -4
  170. package/dist/runtime/server/utils/organization.mjs +36 -1
  171. package/dist/runtime/server/utils/passwordless.mjs +8 -0
  172. package/dist/runtime/server/utils/payments/checkout.d.ts +34 -0
  173. package/dist/runtime/server/utils/payments/checkout.mjs +158 -0
  174. package/dist/runtime/server/utils/payments/common.d.ts +45 -0
  175. package/dist/runtime/server/utils/payments/common.mjs +234 -0
  176. package/dist/runtime/server/utils/payments/index.d.ts +9 -0
  177. package/dist/runtime/server/utils/payments/index.mjs +21 -0
  178. package/dist/runtime/server/utils/payments/lemonsqueezy.d.ts +7 -0
  179. package/dist/runtime/server/utils/payments/lemonsqueezy.mjs +55 -0
  180. package/dist/runtime/server/utils/payments/paddle.d.ts +7 -0
  181. package/dist/runtime/server/utils/payments/paddle.mjs +92 -0
  182. package/dist/runtime/server/utils/payments/polar.d.ts +11 -0
  183. package/dist/runtime/server/utils/payments/polar.mjs +66 -0
  184. package/dist/runtime/server/utils/payments/stripe.d.ts +7 -0
  185. package/dist/runtime/server/utils/payments/stripe.mjs +159 -0
  186. package/dist/runtime/server/utils/payments/subscriptions.d.ts +89 -0
  187. package/dist/runtime/server/utils/payments/subscriptions.mjs +236 -0
  188. package/dist/runtime/server/utils/payments/usage.d.ts +12 -0
  189. package/dist/runtime/server/utils/payments/usage.mjs +143 -0
  190. package/dist/runtime/server/utils/payments/webhooks.d.ts +10 -0
  191. package/dist/runtime/server/utils/payments/webhooks.mjs +200 -0
  192. package/dist/runtime/server/utils/payments.d.ts +1 -158
  193. package/dist/runtime/server/utils/payments.mjs +1 -1289
  194. package/dist/runtime/server/utils/queue.d.ts +2 -0
  195. package/dist/runtime/server/utils/queue.mjs +34 -21
  196. package/dist/runtime/server/utils/rag.mjs +30 -17
  197. package/dist/runtime/server/utils/realtime.d.ts +5 -1
  198. package/dist/runtime/server/utils/realtime.mjs +43 -7
  199. package/dist/runtime/server/utils/session.mjs +16 -3
  200. package/dist/runtime/server/utils/sso.d.ts +3 -0
  201. package/dist/runtime/server/utils/sso.mjs +43 -0
  202. package/dist/runtime/server/utils/storage.mjs +12 -1
  203. package/dist/runtime/server/utils/store/cart.d.ts +63 -0
  204. package/dist/runtime/server/utils/store/cart.mjs +542 -0
  205. package/dist/runtime/server/utils/store/checkout.d.ts +14 -0
  206. package/dist/runtime/server/utils/store/checkout.mjs +118 -0
  207. package/dist/runtime/server/utils/store/common.d.ts +29 -0
  208. package/dist/runtime/server/utils/store/common.mjs +479 -0
  209. package/dist/runtime/server/utils/store/index.d.ts +7 -0
  210. package/dist/runtime/server/utils/store/index.mjs +30 -0
  211. package/dist/runtime/server/utils/store/inventory.d.ts +25 -0
  212. package/dist/runtime/server/utils/store/inventory.mjs +190 -0
  213. package/dist/runtime/server/utils/store/orders.d.ts +60 -0
  214. package/dist/runtime/server/utils/store/orders.mjs +590 -0
  215. package/dist/runtime/server/utils/store/products.d.ts +35 -0
  216. package/dist/runtime/server/utils/store/products.mjs +461 -0
  217. package/dist/runtime/server/utils/store/vendor.d.ts +18 -0
  218. package/dist/runtime/server/utils/store/vendor.mjs +68 -0
  219. package/dist/runtime/server/utils/store.d.ts +1 -207
  220. package/dist/runtime/server/utils/store.mjs +1 -2227
  221. package/dist/runtime/server/utils/string.d.ts +1 -1
  222. package/dist/runtime/server/utils/string.mjs +12 -4
  223. package/dist/runtime/server/utils/tenant.mjs +19 -5
  224. package/dist/runtime/server/utils/tracker.mjs +2 -0
  225. package/dist/runtime/server.d.ts +3 -3
  226. package/dist/runtime/server.mjs +4 -4
  227. package/dist/runtime/storage-server.d.ts +2 -0
  228. package/dist/runtime/storage-server.mjs +1 -0
  229. package/dist/runtime/storage.d.ts +1 -1
  230. package/dist/runtime/storage.mjs +0 -1
  231. package/dist/runtime/store.d.ts +0 -1
  232. package/dist/runtime/store.mjs +0 -1
  233. package/dist/runtime/test-utils.d.ts +4 -0
  234. package/dist/runtime/test-utils.mjs +54 -0
  235. package/dist/runtime/types/d1.d.ts +43 -0
  236. package/dist/runtime/types/drizzle.d.ts +6 -0
  237. package/dist/runtime/types/store.d.ts +1 -1
  238. package/dist/types/analytics.d.ts +80 -0
  239. package/dist/types/auth.d.ts +282 -0
  240. package/dist/types/cache.d.ts +55 -0
  241. package/dist/types/comments.d.ts +130 -0
  242. package/dist/types/db.d.ts +29 -0
  243. package/dist/types/email.d.ts +182 -0
  244. package/dist/types/index.d.ts +22 -0
  245. package/dist/types/jobs.d.ts +58 -0
  246. package/dist/types/notifications.d.ts +77 -0
  247. package/dist/types/options.d.ts +363 -0
  248. package/dist/types/payments.d.ts +145 -0
  249. package/dist/types/ratelimit.d.ts +71 -0
  250. package/dist/types/realtime.d.ts +136 -0
  251. package/dist/types/site.d.ts +121 -0
  252. package/dist/types/storage.d.ts +164 -0
  253. package/dist/types/store-options.d.ts +199 -0
  254. package/dist/types/tenant.d.ts +100 -0
  255. package/dist/types.d.ts +1 -2174
  256. package/dist/utils/migration-lock.d.ts +139 -0
  257. package/dist/utils/pkg.d.ts +14 -1
  258. package/dist/utils/schema-diff.d.ts +39 -0
  259. package/package.json +55 -17
  260. package/dist/chunks/auth-schema.mjs +0 -364
@@ -2,6 +2,7 @@ import { resolveRuntimeBinding } from "../../bindings.mjs";
2
2
  import { sendEmail } from "../../email.mjs";
3
3
  import { useQueue } from "../../queue.mjs";
4
4
  import { renderEmailTemplate, renderMarkdownEmail } from "./email-templates.mjs";
5
+ import { signHmacSha256 } from "./crypto.mjs";
5
6
  import { buildListUnsubscribeHeaders, isEmailSuppressed } from "./mail-suppression.mjs";
6
7
  function getSharedMailbox() {
7
8
  return globalThis.__qarpeo_dev_mailbox__ ||= [];
@@ -37,20 +38,25 @@ export function recordEmailBounce(id, reason = "Delivery failure") {
37
38
  email.bounceReason = reason;
38
39
  return true;
39
40
  }
40
- export function injectEmailTracking(html, options) {
41
+ export async function injectEmailTracking(html, options) {
41
42
  let result = html;
42
43
  const base = options.baseUrl.replace(/\/$/, "");
43
44
  if (options.clicks !== false) {
44
- result = result.replace(
45
- /<a\b([^>]*)\bhref=["']([^"']+)["']([^>]*)>/gi,
46
- (match, prefix, href, suffix) => {
47
- if (/^(?:mailto:|tel:|#|javascript:)/i.test(href) || href.includes("/__qarpeo/mail/track/")) {
48
- return match;
49
- }
50
- const trackUrl = `${base}/__qarpeo/mail/track/click/${encodeURIComponent(options.messageId)}?url=${encodeURIComponent(href)}`;
51
- return `<a${prefix}href="${trackUrl}"${suffix}>`;
45
+ const matches = [];
46
+ const regex = /<a\b([^>]*)\bhref=["']([^"']+)["']([^>]*)>/gi;
47
+ let m;
48
+ while ((m = regex.exec(html)) !== null) {
49
+ const [full, prefix, href, suffix] = m;
50
+ if (!/^(?:mailto:|tel:|#|javascript:)/i.test(href) && !href.includes("/__qarpeo/mail/track/")) {
51
+ matches.push({ full, prefix, href, suffix });
52
52
  }
53
- );
53
+ }
54
+ for (const match of matches) {
55
+ const sig = await signHmacSha256(`${options.messageId}:${match.href}`, options.secret).catch(() => "");
56
+ const sigParam = sig ? `&sig=${encodeURIComponent(sig)}` : "";
57
+ const trackUrl = `${base}/__qarpeo/mail/track/click/${encodeURIComponent(options.messageId)}?url=${encodeURIComponent(match.href)}${sigParam}`;
58
+ result = result.replace(match.full, `<a${match.prefix}href="${trackUrl}"${match.suffix}>`);
59
+ }
54
60
  }
55
61
  if (options.opens !== false) {
56
62
  const pixelUrl = `${base}/__qarpeo/mail/track/open/${encodeURIComponent(options.messageId)}`;
@@ -223,7 +229,7 @@ export async function sendMail(request, event) {
223
229
  if (baseUrl) {
224
230
  const opens = typeof request.track === "object" ? request.track.opens !== false : trackConfig.opens !== false;
225
231
  const clicks = typeof request.track === "object" ? request.track.clicks !== false : trackConfig.clicks !== false;
226
- html = injectEmailTracking(html, {
232
+ html = await injectEmailTracking(html, {
227
233
  messageId,
228
234
  baseUrl,
229
235
  opens,
@@ -39,6 +39,15 @@ export declare function getNotifications(userId: string, options?: GetNotificati
39
39
  total: number;
40
40
  unread: number;
41
41
  }>;
42
+ /**
43
+ * Get a single notification by ID, scoped to user.
44
+ *
45
+ * @example
46
+ * ```ts
47
+ * const notification = await getNotification(notificationId, user.id, event)
48
+ * ```
49
+ */
50
+ export declare function getNotification(id: string, userId: string, event?: RequestEvent): Promise<NotificationRecord | null>;
42
51
  /**
43
52
  * Mark a single notification as read.
44
53
  *
@@ -56,7 +65,7 @@ export declare function markNotificationRead(id: string, userId: string, event?:
56
65
  * await markAllNotificationsRead(user.id, event)
57
66
  * ```
58
67
  */
59
- export declare function markAllNotificationsRead(userId: string, event?: RequestEvent): Promise<void>;
68
+ export declare function markAllNotificationsRead(userId: string, event?: RequestEvent, tenantId?: string): Promise<void>;
60
69
  /**
61
70
  * Delete a notification.
62
71
  *
@@ -76,14 +85,14 @@ export declare function deleteNotification(id: string, userId: string, event?: R
76
85
  */
77
86
  export declare function savePushSubscription(userId: string, subscription: PushSubscriptionRecord, tenantId?: string, event?: RequestEvent): Promise<void>;
78
87
  /**
79
- * Remove a Web Push subscription by endpoint.
88
+ * Remove a Web Push subscription by endpoint, optionally scoped to user.
80
89
  *
81
90
  * @example
82
91
  * ```ts
83
- * await removePushSubscription(subscription.endpoint, event)
92
+ * await removePushSubscription(subscription.endpoint, event, user.id)
84
93
  * ```
85
94
  */
86
- export declare function removePushSubscription(endpoint: string, event?: RequestEvent): Promise<void>;
95
+ export declare function removePushSubscription(endpoint: string, event?: RequestEvent, userId?: string): Promise<void>;
87
96
  /**
88
97
  * Send a Web Push notification to all subscriptions for a user.
89
98
  *
@@ -136,15 +136,27 @@ export async function getNotifications(userId, options = {}, event) {
136
136
  unread: unreadRow?.cnt ?? 0
137
137
  };
138
138
  }
139
+ export async function getNotification(id, userId, event) {
140
+ const db = getD1(event);
141
+ const table = getTable(event);
142
+ const row = await db.prepare(`SELECT * FROM ${table} WHERE id = ? AND user_id = ?`).bind(id, userId).first();
143
+ return row ? rowToRecord(row) : null;
144
+ }
139
145
  export async function markNotificationRead(id, userId, event) {
140
146
  const db = getD1(event);
141
147
  const table = getTable(event);
142
148
  await db.prepare(`UPDATE ${table} SET read = 1, read_at = ? WHERE id = ? AND user_id = ?`).bind(Date.now(), id, userId).run();
143
149
  }
144
- export async function markAllNotificationsRead(userId, event) {
150
+ export async function markAllNotificationsRead(userId, event, tenantId) {
145
151
  const db = getD1(event);
146
152
  const table = getTable(event);
147
- await db.prepare(`UPDATE ${table} SET read = 1, read_at = ? WHERE user_id = ? AND read = 0`).bind(Date.now(), userId).run();
153
+ let sql = `UPDATE ${table} SET read = 1, read_at = ? WHERE user_id = ? AND read = 0`;
154
+ const binds = [Date.now(), userId];
155
+ if (tenantId) {
156
+ sql += " AND tenant_id = ?";
157
+ binds.push(tenantId);
158
+ }
159
+ await db.prepare(sql).bind(...binds).run();
148
160
  }
149
161
  export async function deleteNotification(id, userId, event) {
150
162
  const db = getD1(event);
@@ -166,10 +178,14 @@ export async function savePushSubscription(userId, subscription, tenantId, event
166
178
  Date.now()
167
179
  ).run();
168
180
  }
169
- export async function removePushSubscription(endpoint, event) {
181
+ export async function removePushSubscription(endpoint, event, userId) {
170
182
  const db = getD1(event);
171
183
  const table = getPushTable(event);
172
- await db.prepare(`DELETE FROM ${table} WHERE endpoint = ?`).bind(endpoint).run();
184
+ if (userId) {
185
+ await db.prepare(`DELETE FROM ${table} WHERE endpoint = ? AND user_id = ?`).bind(endpoint, userId).run();
186
+ } else {
187
+ await db.prepare(`DELETE FROM ${table} WHERE endpoint = ?`).bind(endpoint).run();
188
+ }
173
189
  }
174
190
  export async function sendWebPush(userId, payload, event) {
175
191
  const db = getD1(event);
@@ -171,7 +171,28 @@ export async function inviteOrganizationMember(event, input) {
171
171
  message: "Organization not found"
172
172
  });
173
173
  }
174
- const role = input.role && ["owner", "admin", "member"].includes(input.role) ? input.role : "member";
174
+ if (input.role && !["owner", "admin", "member"].includes(input.role)) {
175
+ throw createError({
176
+ statusCode: 400,
177
+ statusMessage: "Bad Request",
178
+ message: `Invalid role "${input.role}". Allowed roles are: owner, admin, member`
179
+ });
180
+ }
181
+ const role = input.role || "member";
182
+ if (role === "owner" && callerMember.role !== "owner") {
183
+ throw createError({
184
+ statusCode: 403,
185
+ statusMessage: "Forbidden",
186
+ message: "Only organization owners can invite new owners"
187
+ });
188
+ }
189
+ if (role === "admin" && callerMember.role !== "owner") {
190
+ throw createError({
191
+ statusCode: 403,
192
+ statusMessage: "Forbidden",
193
+ message: "Only organization owners can invite new admins"
194
+ });
195
+ }
175
196
  const rawToken = crypto.randomUUID().replace(/-/g, "") + crypto.randomUUID().replace(/-/g, "");
176
197
  const tokenHash = await hashSessionToken(rawToken);
177
198
  const invitationId = crypto.randomUUID();
@@ -270,6 +291,20 @@ export async function removeOrganizationMember(event, input) {
270
291
  if (!isSelf && !isOwnerOrAdmin) {
271
292
  throw createError({ statusCode: 403, statusMessage: "Forbidden", message: "Permission denied" });
272
293
  }
294
+ if (!isSelf && targetMember.role === "owner" && callerMember.role !== "owner") {
295
+ throw createError({
296
+ statusCode: 403,
297
+ statusMessage: "Forbidden",
298
+ message: "Admins cannot remove organization owners"
299
+ });
300
+ }
301
+ if (!isSelf && targetMember.role === "admin" && callerMember.role !== "owner") {
302
+ throw createError({
303
+ statusCode: 403,
304
+ statusMessage: "Forbidden",
305
+ message: "Admins cannot remove other organization admins"
306
+ });
307
+ }
273
308
  if (targetMember.role === "owner") {
274
309
  const ownerCount = await d1.prepare(`SELECT count(*) as count FROM ${memberTbl(event)} WHERE organization_id = ? AND role = 'owner'`).bind(input.organizationId).first();
275
310
  if ((ownerCount?.count || 0) <= 1) {
@@ -105,6 +105,10 @@ export async function verifyOTPCode(event, email, code) {
105
105
  return { valid: false, reason: "expired" };
106
106
  }
107
107
  const record = raw;
108
+ if (record.expiresAt && Date.now() > record.expiresAt) {
109
+ await kv.delete(`otp:${cleanEmail}`);
110
+ return { valid: false, reason: "expired" };
111
+ }
108
112
  if (record.attempts >= 5) {
109
113
  await kv.delete(`otp:${cleanEmail}`);
110
114
  return { valid: false, reason: "too_many_attempts" };
@@ -195,6 +199,10 @@ export async function verifyMagicLinkToken(event, token) {
195
199
  if (!data || !data.email) {
196
200
  return { valid: false };
197
201
  }
202
+ if (data.expiresAt && Date.now() > data.expiresAt) {
203
+ await kv.delete(`magic:${token}`);
204
+ return { valid: false };
205
+ }
198
206
  await kv.delete(`magic:${token}`);
199
207
  return { valid: true, email: data.email };
200
208
  }
@@ -0,0 +1,34 @@
1
+ import { type RequestEvent } from "nuxt/server";
2
+ import type { CreateCheckoutOptions } from "../../../../types";
3
+ /**
4
+ * Creates a Stripe checkout session via Stripe REST API. Runs 100% edge-native on Cloudflare
5
+ * Workers using standard `fetch`.
6
+ *
7
+ * @example
8
+ * ```ts
9
+ * const { url } = await createCheckoutSession(event, {
10
+ * planId: "pro_monthly",
11
+ * successUrl: "https://example.com/billing?success=true",
12
+ * cancelUrl: "https://example.com/pricing",
13
+ * })
14
+ * ```
15
+ */
16
+ export declare function createCheckoutSession(event: RequestEvent, options: CreateCheckoutOptions): Promise<{
17
+ id: string;
18
+ url: string;
19
+ }>;
20
+ /**
21
+ * Creates a Customer Billing Portal session for the current user.
22
+ *
23
+ * @example
24
+ * ```ts
25
+ * const { url } = await createCustomerPortalSession(event, {
26
+ * returnUrl: "https://example.com/settings/billing",
27
+ * })
28
+ * ```
29
+ */
30
+ export declare function createCustomerPortalSession(event: RequestEvent, options?: {
31
+ returnUrl?: string;
32
+ }): Promise<{
33
+ url: string;
34
+ }>;
@@ -0,0 +1,158 @@
1
+ import { createError, useRuntimeConfig } from "nuxt/server";
2
+ import { getAuthContext } from "../context.mjs";
3
+ import {
4
+ STRIPE_API_VERSION,
5
+ customerTbl,
6
+ getPaymentsDb,
7
+ getPaymentsConfig,
8
+ ensurePaymentsTables,
9
+ safeReturnUrl
10
+ } from "./common.mjs";
11
+ export async function createCheckoutSession(event, options) {
12
+ await ensurePaymentsTables(event);
13
+ const ct = customerTbl(event);
14
+ const db = getPaymentsDb(event);
15
+ const config = getPaymentsConfig(event);
16
+ const auth = await getAuthContext(event);
17
+ const user = auth?.user;
18
+ if (!config.secretKey) {
19
+ throw createError({
20
+ statusCode: 500,
21
+ statusMessage: "Internal Server Error",
22
+ message: "Payment provider secret key is not configured (STRIPE_SECRET_KEY)"
23
+ });
24
+ }
25
+ let priceId = options.priceId;
26
+ const planId = options.planId || "default";
27
+ if (!priceId && config.plans && config.plans[planId]) {
28
+ priceId = config.plans[planId].priceId;
29
+ }
30
+ if (!priceId) {
31
+ throw createError({
32
+ statusCode: 400,
33
+ message: `Could not resolve price ID for plan "${planId}"`
34
+ });
35
+ }
36
+ const siteUrl = useRuntimeConfig().public?.siteUrl || "http://localhost:3000";
37
+ const successUrl = safeReturnUrl(
38
+ options.successUrl || config.checkoutUrls?.success,
39
+ siteUrl,
40
+ "/?checkout=success"
41
+ );
42
+ const cancelUrl = safeReturnUrl(
43
+ options.cancelUrl || config.checkoutUrls?.cancel,
44
+ siteUrl,
45
+ "/?checkout=cancelled"
46
+ );
47
+ const metadata = {
48
+ planId,
49
+ ...options.metadata
50
+ };
51
+ if (user?.id) metadata.userId = user.id;
52
+ if (auth?.organization?.id) metadata.orgId = auth.organization.id;
53
+ if (config.provider === "stripe") {
54
+ let customerId = null;
55
+ if (user?.id) {
56
+ const cust = await db.prepare(
57
+ `SELECT customer_id FROM ${ct} WHERE user_id = ? AND provider = 'stripe' LIMIT 1`
58
+ ).bind(user.id).first();
59
+ if (cust) customerId = cust.customer_id;
60
+ }
61
+ const mode = options.mode || "subscription";
62
+ const params = new URLSearchParams();
63
+ params.set("mode", mode);
64
+ params.set("line_items[0][price]", priceId);
65
+ params.set("line_items[0][quantity]", "1");
66
+ params.set("success_url", successUrl);
67
+ params.set("cancel_url", cancelUrl);
68
+ if (customerId) {
69
+ params.set("customer", customerId);
70
+ } else {
71
+ const email = options.customerEmail || user?.email;
72
+ if (email) params.set("customer_email", email);
73
+ }
74
+ if (user?.id) params.set("client_reference_id", user.id);
75
+ for (const [k, v] of Object.entries(metadata)) {
76
+ params.set(`metadata[${k}]`, String(v));
77
+ if (mode === "subscription") {
78
+ params.set(`subscription_data[metadata][${k}]`, String(v));
79
+ } else if (mode === "payment") {
80
+ params.set(`payment_intent_data[metadata][${k}]`, String(v));
81
+ } else if (mode === "setup") {
82
+ params.set(`setup_intent_data[metadata][${k}]`, String(v));
83
+ }
84
+ }
85
+ if (mode === "subscription") {
86
+ const trialDays = options.trialDays || config.trialDays;
87
+ if (trialDays && trialDays > 0) {
88
+ params.set("subscription_data[trial_period_days]", String(trialDays));
89
+ }
90
+ }
91
+ const res = await fetch("https://api.stripe.com/v1/checkout/sessions", {
92
+ method: "POST",
93
+ signal: AbortSignal.timeout(1e4),
94
+ headers: {
95
+ Authorization: `Bearer ${config.secretKey}`,
96
+ "Content-Type": "application/x-www-form-urlencoded",
97
+ "Stripe-Version": STRIPE_API_VERSION
98
+ },
99
+ body: params.toString()
100
+ });
101
+ if (!res.ok) {
102
+ const errText = await res.text();
103
+ console.error("[qarpeo:payments] Stripe Checkout error:", errText);
104
+ throw createError({ statusCode: res.status, message: `Stripe checkout failed: ${errText}` });
105
+ }
106
+ const session = await res.json();
107
+ return { id: session.id, url: session.url };
108
+ }
109
+ throw createError({
110
+ statusCode: 501,
111
+ message: `Checkout not implemented for provider ${config.provider}`
112
+ });
113
+ }
114
+ export async function createCustomerPortalSession(event, options) {
115
+ await ensurePaymentsTables(event);
116
+ const ct = customerTbl(event);
117
+ const db = getPaymentsDb(event);
118
+ const config = getPaymentsConfig(event);
119
+ const auth = await getAuthContext(event);
120
+ const user = auth?.user;
121
+ if (!user?.id) {
122
+ throw createError({
123
+ statusCode: 401,
124
+ message: "Authentication required to access billing portal"
125
+ });
126
+ }
127
+ const cust = await db.prepare(`SELECT customer_id FROM ${ct} WHERE user_id = ? AND provider = ? LIMIT 1`).bind(user.id, config.provider).first();
128
+ if (!cust?.customer_id) {
129
+ throw createError({ statusCode: 404, message: "No customer account found for this user" });
130
+ }
131
+ const siteUrl = useRuntimeConfig().public?.siteUrl || "http://localhost:3000";
132
+ const returnUrl = safeReturnUrl(options?.returnUrl || config.portalReturnUrl, siteUrl, "/");
133
+ if (config.provider === "stripe") {
134
+ const params = new URLSearchParams();
135
+ params.set("customer", cust.customer_id);
136
+ params.set("return_url", returnUrl);
137
+ const res = await fetch("https://api.stripe.com/v1/billing_portal/sessions", {
138
+ method: "POST",
139
+ signal: AbortSignal.timeout(1e4),
140
+ headers: {
141
+ Authorization: `Bearer ${config.secretKey}`,
142
+ "Content-Type": "application/x-www-form-urlencoded",
143
+ "Stripe-Version": STRIPE_API_VERSION
144
+ },
145
+ body: params.toString()
146
+ });
147
+ if (!res.ok) {
148
+ const errText = await res.text();
149
+ throw createError({ statusCode: res.status, message: `Billing portal failed: ${errText}` });
150
+ }
151
+ const session = await res.json();
152
+ return { url: session.url };
153
+ }
154
+ throw createError({
155
+ statusCode: 501,
156
+ message: `Billing portal not supported for provider ${config.provider}`
157
+ });
158
+ }
@@ -0,0 +1,45 @@
1
+ import { type RequestEvent } from "nuxt/server";
2
+ import type { PaymentsOptions, PaymentProvider, QarpeoSubscription } from "../../../../types";
3
+ export declare function getTbl(base: string, event?: RequestEvent): string;
4
+ export declare function customerTbl(event?: RequestEvent): string;
5
+ export declare function subscriptionTbl(event?: RequestEvent): string;
6
+ export declare function webhookEventTbl(event?: RequestEvent): string;
7
+ export declare function usageRecordTbl(event?: RequestEvent): string;
8
+ /**
9
+ * Pinned Stripe API version. Sent on every Stripe REST call so an account upgrade can't silently
10
+ * change the response shape and break webhook payload parsing.
11
+ */
12
+ export declare const STRIPE_API_VERSION = "2024-06-20";
13
+ export declare function getPaymentsDb(event?: RequestEvent): import("../../..").D1Database;
14
+ export declare function getPaymentsConfig(event?: RequestEvent): PaymentsOptions & {
15
+ provider: PaymentProvider;
16
+ secretKey: string;
17
+ webhookSecret: string;
18
+ };
19
+ export declare function ensurePaymentsTables(event?: RequestEvent): Promise<void>;
20
+ /** Computes an HMAC-SHA256 hex signature using native Web Crypto. */
21
+ export declare function computeHmacSha256(keyStr: string, dataStr: string): Promise<string>;
22
+ /** Computes an HMAC-SHA256 Base64 signature using native Web Crypto (for Standard Webhooks). */
23
+ export declare function computeHmacSha256Base64(keyStr: string, dataStr: string): Promise<string>;
24
+ export declare function rowToSubscription(row: Record<string, unknown>): QarpeoSubscription;
25
+ /**
26
+ * Validates a return or redirect URL to ensure it is either a relative path or an absolute URL
27
+ * matching the application's origin, preventing open redirect / phishing vulnerabilities.
28
+ */
29
+ export declare function safeReturnUrl(url: unknown, siteUrl: string, fallbackPath?: string): string;
30
+ export interface PaymentWebhookListenerPayload {
31
+ event: RequestEvent;
32
+ provider: PaymentProvider;
33
+ type: string;
34
+ data: any;
35
+ payload: any;
36
+ subscription: QarpeoSubscription | null;
37
+ }
38
+ export type PaymentWebhookListener = (payload: PaymentWebhookListenerPayload) => void | Promise<void>;
39
+ /**
40
+ * Registers a server-side listener for verified payment webhook events.
41
+ * Used by higher-level modules (such as Store) to reconcile orders without
42
+ * creating a compile-time dependency from Payments to App modules.
43
+ */
44
+ export declare function registerPaymentWebhookListener(listener: PaymentWebhookListener): () => void;
45
+ export declare function notifyPaymentWebhookListeners(info: PaymentWebhookListenerPayload): Promise<void>;