qarpeo 0.2.1 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (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 +292 -748
  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
@@ -1,3 +1,16 @@
1
+ function timingSafeEqual(a, b) {
2
+ const aBytes = new TextEncoder().encode(a);
3
+ const bBytes = new TextEncoder().encode(b);
4
+ if (aBytes.length !== bBytes.length) {
5
+ let _diff = 0;
6
+ for (let i = 0; i < aBytes.length; i++) _diff |= aBytes[i];
7
+ return false;
8
+ }
9
+ let diff = 0;
10
+ for (let i = 0; i < aBytes.length; i++) diff |= aBytes[i] ^ bBytes[i];
11
+ return diff === 0;
12
+ }
13
+ const MAX_PRESENCE_BYTES = 4096;
1
14
  const attachmentFallback = /* @__PURE__ */ new WeakMap();
2
15
  function setAttachment(ws, data) {
3
16
  if (typeof ws.serializeAttachment === "function") {
@@ -95,6 +108,12 @@ export class QarpeoRoomDO {
95
108
  return this.handleWebSocketUpgrade(request, url);
96
109
  }
97
110
  if (url.pathname === "/broadcast" && request.method === "POST") {
111
+ if (!this.isAuthorizedServerRequest(request)) {
112
+ return new Response(JSON.stringify({ error: "Unauthorized" }), {
113
+ status: 401,
114
+ headers: { "Content-Type": "application/json" }
115
+ });
116
+ }
98
117
  try {
99
118
  const body = await request.json();
100
119
  await this.loadHistory();
@@ -132,6 +151,12 @@ export class QarpeoRoomDO {
132
151
  });
133
152
  }
134
153
  if (url.pathname === "/state" && request.method === "POST") {
154
+ if (!this.isAuthorizedServerRequest(request)) {
155
+ return new Response(JSON.stringify({ error: "Unauthorized" }), {
156
+ status: 401,
157
+ headers: { "Content-Type": "application/json" }
158
+ });
159
+ }
135
160
  try {
136
161
  const body = await request.json();
137
162
  await this.loadState();
@@ -184,6 +209,12 @@ export class QarpeoRoomDO {
184
209
  );
185
210
  }
186
211
  if (url.pathname === "/history" && request.method === "DELETE") {
212
+ if (!this.isAuthorizedServerRequest(request)) {
213
+ return new Response(JSON.stringify({ error: "Unauthorized" }), {
214
+ status: 401,
215
+ headers: { "Content-Type": "application/json" }
216
+ });
217
+ }
187
218
  this.history = [];
188
219
  if (this.ctx.storage && typeof this.ctx.storage.delete === "function") {
189
220
  try {
@@ -196,6 +227,12 @@ export class QarpeoRoomDO {
196
227
  });
197
228
  }
198
229
  if (url.pathname === "/disconnect" && request.method === "POST") {
230
+ if (!this.isAuthorizedServerRequest(request)) {
231
+ return new Response(JSON.stringify({ error: "Unauthorized" }), {
232
+ status: 401,
233
+ headers: { "Content-Type": "application/json" }
234
+ });
235
+ }
199
236
  try {
200
237
  const { userId } = await request.json();
201
238
  let disconnected = 0;
@@ -286,33 +323,36 @@ export class QarpeoRoomDO {
286
323
  );
287
324
  const lastMsgId = _url.searchParams.get("lastMessageId") || _url.searchParams.get("lastId") || request.headers.get("x-qarpeo-last-id");
288
325
  const isReconnecting = lastSeq >= 0 || !!lastMsgId || sinceTime > 0;
289
- void this.loadHistory().then((history) => {
290
- if (history.length > 0) {
291
- let replayList = history;
292
- if (lastSeq >= 0) {
293
- replayList = history.filter((m) => (m.seq ?? 0) > lastSeq);
294
- } else if (lastMsgId) {
295
- const idx = history.findIndex((m) => m.id === lastMsgId);
296
- if (idx !== -1) {
297
- replayList = history.slice(idx + 1);
326
+ const allowAnonHistory = this.env?.REALTIME_ALLOW_ANONYMOUS_HISTORY !== "0" && this.env?.REALTIME_ALLOW_ANONYMOUS_HISTORY !== false;
327
+ if (!user.isAnonymous || allowAnonHistory) {
328
+ void this.loadHistory().then((history) => {
329
+ if (history.length > 0) {
330
+ let replayList = history;
331
+ if (lastSeq >= 0) {
332
+ replayList = history.filter((m) => (m.seq ?? 0) > lastSeq);
333
+ } else if (lastMsgId) {
334
+ const idx = history.findIndex((m) => m.id === lastMsgId);
335
+ if (idx !== -1) {
336
+ replayList = history.slice(idx + 1);
337
+ }
338
+ } else if (sinceTime > 0) {
339
+ replayList = history.filter((m) => (m.timestamp ?? 0) > sinceTime);
340
+ }
341
+ try {
342
+ server.send(
343
+ JSON.stringify({
344
+ type: "history:sync",
345
+ history: replayList,
346
+ replay: isReconnecting,
347
+ lastSeq: this.lastSeq,
348
+ timestamp: Date.now()
349
+ })
350
+ );
351
+ } catch {
298
352
  }
299
- } else if (sinceTime > 0) {
300
- replayList = history.filter((m) => (m.timestamp ?? 0) > sinceTime);
301
- }
302
- try {
303
- server.send(
304
- JSON.stringify({
305
- type: "history:sync",
306
- history: replayList,
307
- replay: isReconnecting,
308
- lastSeq: this.lastSeq,
309
- timestamp: Date.now()
310
- })
311
- );
312
- } catch {
313
353
  }
314
- }
315
- });
354
+ });
355
+ }
316
356
  void this.loadState().then((state) => {
317
357
  if (Object.keys(state).length > 0) {
318
358
  try {
@@ -387,10 +427,18 @@ export class QarpeoRoomDO {
387
427
  if (data.type === "presence:update") {
388
428
  const attachment = getAttachment(ws) || {};
389
429
  if (attachment.user) {
390
- attachment.user.presence = {
430
+ const merged = {
391
431
  ...attachment.user.presence,
392
432
  ...data.presence
393
433
  };
434
+ if (JSON.stringify(merged).length > MAX_PRESENCE_BYTES) {
435
+ try {
436
+ ws.close(1009, "Presence payload too large");
437
+ } catch {
438
+ }
439
+ return;
440
+ }
441
+ attachment.user.presence = merged;
394
442
  setAttachment(ws, attachment);
395
443
  this.broadcast(
396
444
  {
@@ -405,6 +453,14 @@ export class QarpeoRoomDO {
405
453
  return;
406
454
  }
407
455
  if (data.type === "state:patch" && data.patch) {
456
+ const att2 = getAttachment(ws);
457
+ if (!this.isStateWriteAuthorized(att2?.user)) {
458
+ try {
459
+ ws.send(JSON.stringify({ type: "error", code: "unauthorized", message: "Not authorized to mutate room state" }));
460
+ } catch {
461
+ }
462
+ return;
463
+ }
408
464
  await this.loadState();
409
465
  this.roomState = { ...this.roomState, ...data.patch };
410
466
  await this.saveState(this.roomState);
@@ -413,7 +469,7 @@ export class QarpeoRoomDO {
413
469
  type: "state:patch",
414
470
  state: this.roomState,
415
471
  payload: data.patch,
416
- sender: getAttachment(ws)?.user?.id,
472
+ sender: att2?.user?.id,
417
473
  timestamp: Date.now()
418
474
  },
419
475
  ws
@@ -421,12 +477,20 @@ export class QarpeoRoomDO {
421
477
  return;
422
478
  }
423
479
  if (data.type === "state:set" && data.state) {
480
+ const att2 = getAttachment(ws);
481
+ if (!this.isStateWriteAuthorized(att2?.user)) {
482
+ try {
483
+ ws.send(JSON.stringify({ type: "error", code: "unauthorized", message: "Not authorized to mutate room state" }));
484
+ } catch {
485
+ }
486
+ return;
487
+ }
424
488
  await this.saveState(data.state);
425
489
  this.broadcast(
426
490
  {
427
491
  type: "state:set",
428
492
  state: this.roomState,
429
- sender: getAttachment(ws)?.user?.id,
493
+ sender: att2?.user?.id,
430
494
  timestamp: Date.now()
431
495
  },
432
496
  ws
@@ -526,4 +590,31 @@ export class QarpeoRoomDO {
526
590
  }
527
591
  return users;
528
592
  }
593
+ /**
594
+ * Validates internal server control requests against REALTIME_ROOM_SECRET (if configured).
595
+ */
596
+ isAuthorizedServerRequest(request) {
597
+ const roomSecret = this.env?.REALTIME_ROOM_SECRET || this.env?.roomSecret;
598
+ if (!roomSecret) return true;
599
+ const provided = request.headers.get("x-qarpeo-room-secret") || "";
600
+ return timingSafeEqual(provided, String(roomSecret));
601
+ }
602
+ /**
603
+ * Authorizes client state mutation (state:patch / state:set).
604
+ * Restricts anonymous users by default unless REALTIME_ALLOW_ANONYMOUS_STATE_WRITE is enabled,
605
+ * or matches against configured REALTIME_STATE_WRITE_ROLES.
606
+ */
607
+ isStateWriteAuthorized(user) {
608
+ if (!user) return false;
609
+ const rawRoles = this.env?.REALTIME_STATE_WRITE_ROLES || this.env?.stateWriteRoles;
610
+ if (rawRoles) {
611
+ const allowed = (Array.isArray(rawRoles) ? rawRoles : String(rawRoles).split(",")).map((r) => r.trim().toLowerCase()).filter(Boolean);
612
+ const userRole = String(user.role || user.metadata?.role || "").toLowerCase();
613
+ return allowed.includes(userRole);
614
+ }
615
+ if (user.isAnonymous) {
616
+ return this.env?.REALTIME_ALLOW_ANONYMOUS_STATE_WRITE === "1" || this.env?.REALTIME_ALLOW_ANONYMOUS_STATE_WRITE === true;
617
+ }
618
+ return true;
619
+ }
529
620
  }
@@ -18,7 +18,7 @@ export default defineEventHandler(async (event) => {
18
18
  ...privateConfig.devtools,
19
19
  ...publicConfig.devtools
20
20
  };
21
- const isDevtoolsPath = pathname.startsWith("/_qarpeo/");
21
+ const isDevtoolsPath = pathname.startsWith("/_qarpeo/") || pathname.startsWith("/__qarpeo/");
22
22
  if (!isDevtoolsPath) return;
23
23
  if (!import.meta.dev) {
24
24
  throw createError({ statusCode: 404, statusMessage: "Not Found" });
@@ -1,15 +1,18 @@
1
1
  import { defineEventHandler } from "nuxt/server";
2
2
  import { resolveTenant } from "../utils/tenant.mjs";
3
3
  export default defineEventHandler(async (event) => {
4
- const url = event.node?.req?.url || "";
4
+ const url = event.path || event.node?.req?.url || "";
5
5
  if (url.startsWith("/_nuxt/") || url.startsWith("/__nuxt")) {
6
6
  return;
7
7
  }
8
8
  const tenant = await resolveTenant(event);
9
9
  if (tenant) {
10
- const res = event.node?.res;
11
- if (res && typeof res.setHeader === "function") {
12
- res.setHeader("x-qarpeo-tenant", tenant.slug);
10
+ try {
11
+ const res = event.node?.res;
12
+ if (res && typeof res.setHeader === "function") {
13
+ res.setHeader("x-qarpeo-tenant", tenant.slug);
14
+ }
15
+ } catch {
13
16
  }
14
17
  }
15
18
  });
@@ -1,4 +1,4 @@
1
- import { ensureStoreTables } from "../utils/store.mjs";
1
+ import { ensureStoreTables } from "../utils/store/index.mjs";
2
2
  export default function(nitroApp) {
3
3
  nitroApp.hooks?.hook("request", async (event) => {
4
4
  await ensureStoreTables(event).catch(() => {
@@ -1,23 +1,63 @@
1
- import { defineEventHandler, getQuery, getRouterParam, sendRedirect } from "nuxt/server";
2
- import { sanitizeUrl } from "../../../../../utils/email-templates.mjs";
3
- import { recordEmailClick } from "../../../../../utils/mail.mjs";
1
+ import {
2
+ defineEventHandler,
3
+ getQuery,
4
+ getRouterParam,
5
+ getRequestHeader,
6
+ sendRedirect
7
+ } from "nuxt/server";
8
+ import { sanitizeUrl } from "../../../../../utils/string.mjs";
9
+ import { getDevEmail, recordEmailClick } from "../../../../../utils/mail.mjs";
10
+ import { verifyHmacSha256 } from "../../../../../utils/crypto.mjs";
4
11
  export default defineEventHandler(async (event) => {
5
12
  const id = getRouterParam(event, "id");
6
13
  const query = getQuery(event);
7
- const targetUrl = sanitizeUrl(query.url);
8
- if (id && targetUrl && targetUrl !== "#") {
9
- recordEmailClick(id, targetUrl);
10
- const ev = event;
11
- const nitroApp = globalThis.useNitroApp?.();
12
- if (nitroApp && typeof nitroApp.hooks?.callHook === "function") {
13
- await nitroApp.hooks.callHook("qarpeo:mail:click", {
14
- id,
15
- url: targetUrl,
16
- timestamp: Date.now(),
17
- ip: ev.node?.req?.headers?.["cf-connecting-ip"] || ev.node?.req?.socket?.remoteAddress,
18
- userAgent: ev.node?.req?.headers?.["user-agent"]
19
- });
14
+ const rawUrl = Array.isArray(query.url) ? query.url[0] : String(query.url || "");
15
+ const targetUrl = sanitizeUrl(rawUrl);
16
+ const sig = typeof query.sig === "string" ? query.sig : "";
17
+ if (!id || !targetUrl || targetUrl === "#") {
18
+ return sendRedirect(event, "/", 302);
19
+ }
20
+ let isAllowed = false;
21
+ let host = "";
22
+ try {
23
+ host = getRequestHeader(event, "host") || event?.headers?.get?.("host") || event?.node?.req?.headers?.host || "";
24
+ } catch {
25
+ host = event?.headers?.get?.("host") || event?.node?.req?.headers?.host || "";
26
+ }
27
+ if (targetUrl.startsWith("/") && !targetUrl.startsWith("//") && !targetUrl.includes("\\")) {
28
+ isAllowed = true;
29
+ } else if (host) {
30
+ try {
31
+ const parsed = new URL(targetUrl);
32
+ if (parsed.host === host) {
33
+ isAllowed = true;
34
+ }
35
+ } catch {
20
36
  }
21
37
  }
22
- return sendRedirect(event, targetUrl && targetUrl !== "#" ? targetUrl : "/", 302);
38
+ if (!isAllowed && sig) {
39
+ isAllowed = await verifyHmacSha256(`${id}:${targetUrl}`, sig, event).catch(() => false);
40
+ }
41
+ if (!isAllowed) {
42
+ const devEmail = getDevEmail(id);
43
+ if (devEmail && (devEmail.html.includes(targetUrl) || devEmail.text.includes(targetUrl))) {
44
+ isAllowed = true;
45
+ }
46
+ }
47
+ if (!isAllowed) {
48
+ return sendRedirect(event, "/", 302);
49
+ }
50
+ recordEmailClick(id, targetUrl);
51
+ const ev = event;
52
+ const nitroApp = globalThis.useNitroApp?.();
53
+ if (nitroApp && typeof nitroApp.hooks?.callHook === "function") {
54
+ await nitroApp.hooks.callHook("qarpeo:mail:click", {
55
+ id,
56
+ url: targetUrl,
57
+ timestamp: Date.now(),
58
+ ip: ev.node?.req?.headers?.["cf-connecting-ip"] || ev.node?.req?.socket?.remoteAddress,
59
+ userAgent: ev.node?.req?.headers?.["user-agent"]
60
+ });
61
+ }
62
+ return sendRedirect(event, targetUrl, 302);
23
63
  });
@@ -2,14 +2,13 @@ import {
2
2
  defineEventHandler,
3
3
  getRouterParam,
4
4
  readBody,
5
- createError,
6
- useRuntimeConfig
5
+ createError
7
6
  } from "nuxt/server";
8
- import { useAgent } from "../../../utils/ai.mjs";
7
+ import { useAgent, resolveAgentInstanceId } from "../../../utils/ai.mjs";
8
+ import { getQarpeoConfig } from "../../../utils/config.mjs";
9
9
  import { getAuthSession } from "../../../utils/session.mjs";
10
10
  export default defineEventHandler(async (event) => {
11
- const config = useRuntimeConfig();
12
- const agentsConfig = config.qarpeo?.agents || {};
11
+ const agentsConfig = getQarpeoConfig(event).agents || {};
13
12
  const requireAuth = agentsConfig.requireAuth || agentsConfig.auth || false;
14
13
  const session = await getAuthSession(event).catch(() => null);
15
14
  const user = session?.user;
@@ -20,21 +19,29 @@ export default defineEventHandler(async (event) => {
20
19
  message: "Agent chat requires an authenticated user session."
21
20
  });
22
21
  }
23
- const agentName = getRouterParam(event, "agent");
22
+ const rawAgentName = getRouterParam(event, "agent");
23
+ const agentName = String(rawAgentName || "").replace(/[^a-zA-Z0-9_-]/g, "");
24
24
  if (!agentName) {
25
- throw createError({ statusCode: 400, message: "Missing agent name" });
25
+ throw createError({ statusCode: 400, message: "Valid agent name is required" });
26
26
  }
27
27
  const body = await readBody(event) || {};
28
- const rawSuffix = body.id ? String(body.id).replace(/[^a-zA-Z0-9_-]/g, "").slice(0, 64) : "default";
29
- const instanceId = user?.id ? `usr_${user.id}__${rawSuffix}` : `anon_${rawSuffix}`;
30
- const message = body.message;
28
+ const instanceId = resolveAgentInstanceId(user?.id, body.id);
29
+ const rawMessage = typeof body.message === "string" ? body.message : typeof body.message?.content === "string" ? body.message.content : "";
30
+ const message = rawMessage.trim();
31
31
  if (!message) {
32
- throw createError({ statusCode: 400, message: "Missing message payload" });
32
+ throw createError({ statusCode: 400, message: "Missing or empty message payload" });
33
33
  }
34
+ if (message.length > 32768) {
35
+ throw createError({
36
+ statusCode: 400,
37
+ message: "Message exceeds maximum length of 32,768 characters"
38
+ });
39
+ }
40
+ const maxSteps = body.maxSteps !== void 0 ? Math.min(Math.max(1, Number(body.maxSteps) || 1), 20) : void 0;
34
41
  const agent = useAgent(agentName, instanceId, event);
35
42
  return await agent.chat(message, {
36
43
  stream: body.stream !== false,
37
- maxSteps: body.maxSteps,
44
+ maxSteps,
38
45
  gateway: agentsConfig.gateway
39
46
  });
40
47
  });
@@ -2,14 +2,13 @@ import {
2
2
  defineEventHandler,
3
3
  getRouterParam,
4
4
  readBody,
5
- createError,
6
- useRuntimeConfig
5
+ createError
7
6
  } from "nuxt/server";
8
- import { useAgent } from "../../../utils/ai.mjs";
7
+ import { useAgent, resolveAgentInstanceId } from "../../../utils/ai.mjs";
8
+ import { getQarpeoConfig } from "../../../utils/config.mjs";
9
9
  import { getAuthSession } from "../../../utils/session.mjs";
10
10
  export default defineEventHandler(async (event) => {
11
- const config = useRuntimeConfig();
12
- const agentsConfig = config.qarpeo?.agents || {};
11
+ const agentsConfig = getQarpeoConfig(event).agents || {};
13
12
  const requireAuth = agentsConfig.requireAuth || agentsConfig.auth || false;
14
13
  const session = await getAuthSession(event).catch(() => null);
15
14
  const user = session?.user;
@@ -20,13 +19,13 @@ export default defineEventHandler(async (event) => {
20
19
  message: "Agent clear requires an authenticated user session."
21
20
  });
22
21
  }
23
- const agentName = getRouterParam(event, "agent");
22
+ const rawAgentName = getRouterParam(event, "agent");
23
+ const agentName = String(rawAgentName || "").replace(/[^a-zA-Z0-9_-]/g, "");
24
24
  if (!agentName) {
25
- throw createError({ statusCode: 400, message: "Missing agent name" });
25
+ throw createError({ statusCode: 400, message: "Valid agent name is required" });
26
26
  }
27
27
  const body = await readBody(event) || {};
28
- const rawId = body.id || (user?.id ? `user_${user.id}` : "default");
29
- const instanceId = user?.id ? rawId.startsWith(`user_${user.id}`) ? rawId : `user_${user.id}_${rawId.replace(/^user_/, "")}` : rawId.startsWith("anon_") ? rawId : `anon_${rawId.replace(/^user_/, "")}`;
28
+ const instanceId = resolveAgentInstanceId(user?.id, body.id);
30
29
  const agent = useAgent(agentName, instanceId, event);
31
30
  await agent.clear();
32
31
  return { success: true };
@@ -2,14 +2,13 @@ import {
2
2
  defineEventHandler,
3
3
  getRouterParam,
4
4
  getQuery,
5
- createError,
6
- useRuntimeConfig
5
+ createError
7
6
  } from "nuxt/server";
8
- import { useAgent } from "../../../utils/ai.mjs";
7
+ import { useAgent, resolveAgentInstanceId } from "../../../utils/ai.mjs";
8
+ import { getQarpeoConfig } from "../../../utils/config.mjs";
9
9
  import { getAuthSession } from "../../../utils/session.mjs";
10
10
  export default defineEventHandler(async (event) => {
11
- const config = useRuntimeConfig();
12
- const agentsConfig = config.qarpeo?.agents || {};
11
+ const agentsConfig = getQarpeoConfig(event).agents || {};
13
12
  const requireAuth = agentsConfig.requireAuth || agentsConfig.auth || false;
14
13
  const session = await getAuthSession(event).catch(() => null);
15
14
  const user = session?.user;
@@ -20,13 +19,13 @@ export default defineEventHandler(async (event) => {
20
19
  message: "Agent history requires an authenticated user session."
21
20
  });
22
21
  }
23
- const agentName = getRouterParam(event, "agent");
22
+ const rawAgentName = getRouterParam(event, "agent");
23
+ const agentName = String(rawAgentName || "").replace(/[^a-zA-Z0-9_-]/g, "");
24
24
  if (!agentName) {
25
- throw createError({ statusCode: 400, message: "Missing agent name" });
25
+ throw createError({ statusCode: 400, message: "Valid agent name is required" });
26
26
  }
27
27
  const q = getQuery(event);
28
- const rawId = q.id || (user?.id ? `user_${user.id}` : "default");
29
- const instanceId = user?.id ? rawId.startsWith(`user_${user.id}`) ? rawId : `user_${user.id}_${rawId.replace(/^user_/, "")}` : rawId.startsWith("anon_") ? rawId : `anon_${rawId.replace(/^user_/, "")}`;
28
+ const instanceId = resolveAgentInstanceId(user?.id, q.id);
30
29
  const agent = useAgent(agentName, instanceId, event);
31
30
  const messages = await agent.history();
32
31
  return { messages };
@@ -11,16 +11,26 @@ export default defineEventHandler(async (event) => {
11
11
  message: "Authentication required to view analytics events."
12
12
  });
13
13
  }
14
+ const isPrivileged = auth.isAdmin || auth.role === "admin" || auth.role === "owner" || auth.user?.role === "admin" || auth.user?.role === "super";
15
+ if (!isPrivileged) {
16
+ throw createError({
17
+ statusCode: 403,
18
+ statusMessage: "Forbidden",
19
+ message: "Insufficient permissions to view analytics events."
20
+ });
21
+ }
14
22
  const query = getQuery(event);
15
23
  const range = query.range || "7d";
16
24
  const name = query.name ? String(query.name) : void 0;
17
- const limit = query.limit ? parseInt(String(query.limit), 10) : 20;
25
+ const rawLimit = Number(query.limit);
26
+ const limit = Math.min(100, Math.max(1, isNaN(rawLimit) ? 20 : Math.trunc(rawLimit)));
18
27
  const cfg = getQarpeoConfig(event).analytics || {};
28
+ const tenantId = event.context?.tenant?.id || event.context?.tenant?.slug;
19
29
  const dash = useAnalyticsDashboard({
20
30
  accountId: cfg.accountId,
21
31
  apiToken: cfg.apiToken,
22
32
  dataset: cfg.dataset,
23
- siteId: cfg.siteId
33
+ siteId: cfg.siteId || (tenantId ? `tenant_${tenantId}` : void 0)
24
34
  });
25
35
  return dash.events(name, limit, range);
26
36
  });
@@ -11,14 +11,23 @@ export default defineEventHandler(async (event) => {
11
11
  message: "Authentication required to view analytics pageviews."
12
12
  });
13
13
  }
14
+ const isPrivileged = auth.isAdmin || auth.role === "admin" || auth.role === "owner" || auth.user?.role === "admin" || auth.user?.role === "super";
15
+ if (!isPrivileged) {
16
+ throw createError({
17
+ statusCode: 403,
18
+ statusMessage: "Forbidden",
19
+ message: "Insufficient permissions to view analytics pageviews."
20
+ });
21
+ }
14
22
  const query = getQuery(event);
15
23
  const range = query.range || "7d";
16
24
  const cfg = getQarpeoConfig(event).analytics || {};
25
+ const tenantId = event.context?.tenant?.id || event.context?.tenant?.slug;
17
26
  const dash = useAnalyticsDashboard({
18
27
  accountId: cfg.accountId,
19
28
  apiToken: cfg.apiToken,
20
29
  dataset: cfg.dataset,
21
- siteId: cfg.siteId
30
+ siteId: cfg.siteId || (tenantId ? `tenant_${tenantId}` : void 0)
22
31
  });
23
32
  return dash.pageviews(range);
24
33
  });
@@ -11,14 +11,23 @@ export default defineEventHandler(async (event) => {
11
11
  message: "Authentication required to view analytics."
12
12
  });
13
13
  }
14
+ const isPrivileged = auth.isAdmin || auth.role === "admin" || auth.role === "owner" || auth.user?.role === "admin" || auth.user?.role === "super";
15
+ if (!isPrivileged) {
16
+ throw createError({
17
+ statusCode: 403,
18
+ statusMessage: "Forbidden",
19
+ message: "Insufficient permissions to view analytics."
20
+ });
21
+ }
14
22
  const query = getQuery(event);
15
23
  const range = query.range || "7d";
16
24
  const cfg = getQarpeoConfig(event).analytics || {};
25
+ const tenantId = event.context?.tenant?.id || event.context?.tenant?.slug;
17
26
  const dash = useAnalyticsDashboard({
18
27
  accountId: cfg.accountId,
19
28
  apiToken: cfg.apiToken,
20
29
  dataset: cfg.dataset,
21
- siteId: cfg.siteId
30
+ siteId: cfg.siteId || (tenantId ? `tenant_${tenantId}` : void 0)
22
31
  });
23
32
  return dash.summary(range);
24
33
  });
@@ -2,6 +2,7 @@ import { defineEventHandler, readBody, createError } from "nuxt/server";
2
2
  import { getD1Binding } from "../../../../db.mjs";
3
3
  import { decryptToken } from "../../../utils/crypto.mjs";
4
4
  import { requireAuthSession, revokeOtherDeviceSessions, setAuthSession } from "../../../utils/session.mjs";
5
+ import { resolveTableName } from "../../../utils/table-names.mjs";
5
6
  import { verifyTOTPCode } from "../../../utils/totp.mjs";
6
7
  export default defineEventHandler(async (event) => {
7
8
  const session = await requireAuthSession(event);
@@ -9,6 +10,13 @@ export default defineEventHandler(async (event) => {
9
10
  if (!user || !user.id) {
10
11
  throw createError({ statusCode: 401, statusMessage: "Unauthorized" });
11
12
  }
13
+ if (session?.impersonator) {
14
+ throw createError({
15
+ statusCode: 403,
16
+ statusMessage: "Forbidden",
17
+ message: "2FA cannot be disabled while impersonating another user"
18
+ });
19
+ }
12
20
  const body = await readBody(event);
13
21
  const code = body?.code;
14
22
  if (!code || typeof code !== "string") {
@@ -20,7 +28,8 @@ export default defineEventHandler(async (event) => {
20
28
  }
21
29
  const bindingName = globalThis.process?.env?.QARPEO_DEFAULT_DB_BINDING || "DB";
22
30
  const d1 = getD1Binding(bindingName, event);
23
- const twoFactorRecord = await d1.prepare("SELECT secret FROM two_factor WHERE user_id = ? LIMIT 1").bind(user.id).first();
31
+ const twoFactorTbl = resolveTableName("two_factor", event);
32
+ const twoFactorRecord = await d1.prepare(`SELECT secret FROM ${twoFactorTbl} WHERE user_id = ? LIMIT 1`).bind(user.id).first();
24
33
  if (!twoFactorRecord?.secret) {
25
34
  throw createError({
26
35
  statusCode: 400,
@@ -37,7 +46,7 @@ export default defineEventHandler(async (event) => {
37
46
  });
38
47
  }
39
48
  try {
40
- await d1.prepare("DELETE FROM two_factor WHERE user_id = ?").bind(user.id).run();
49
+ await d1.prepare(`DELETE FROM ${twoFactorTbl} WHERE user_id = ?`).bind(user.id).run();
41
50
  } catch (err) {
42
51
  console.warn("[qarpeo] Failed to disable 2FA in D1:", err.message);
43
52
  }
@@ -9,6 +9,13 @@ export default defineEventHandler(async (event) => {
9
9
  if (!user || !user.id) {
10
10
  throw createError({ statusCode: 401, statusMessage: "Unauthorized" });
11
11
  }
12
+ if (session?.impersonator) {
13
+ throw createError({
14
+ statusCode: 403,
15
+ statusMessage: "Forbidden",
16
+ message: "2FA setup cannot be initiated while impersonating another user"
17
+ });
18
+ }
12
19
  const runtimeConfig = useRuntimeConfig();
13
20
  const appName = runtimeConfig.public?.qarpeo?.site?.name || process.env.CLOUDFLARE_PROJECT_NAME || "Qarpeo App";
14
21
  const secret = generateBase32Secret(20);
@@ -4,6 +4,7 @@ import { getKVBinding } from "../../../../kv.mjs";
4
4
  import { decryptToken, encryptToken } from "../../../utils/crypto.mjs";
5
5
  import { assertRateLimit } from "../../../utils/ratelimit.mjs";
6
6
  import { requireAuthSession, setAuthSession } from "../../../utils/session.mjs";
7
+ import { resolveTableName } from "../../../utils/table-names.mjs";
7
8
  import { hashBackupCode, verifyTOTPCode } from "../../../utils/totp.mjs";
8
9
  export default defineEventHandler(async (event) => {
9
10
  const session = await requireAuthSession(event);
@@ -11,6 +12,13 @@ export default defineEventHandler(async (event) => {
11
12
  if (!user || !user.id) {
12
13
  throw createError({ statusCode: 401, statusMessage: "Unauthorized" });
13
14
  }
15
+ if (session?.impersonator) {
16
+ throw createError({
17
+ statusCode: 403,
18
+ statusMessage: "Forbidden",
19
+ message: "2FA verification cannot be performed while impersonating another user"
20
+ });
21
+ }
14
22
  await assertRateLimit(event, {
15
23
  key: `2fa:verify:${user.id}`,
16
24
  max: 5,
@@ -42,9 +50,10 @@ export default defineEventHandler(async (event) => {
42
50
  } catch {
43
51
  }
44
52
  }
53
+ const twoFactorTbl = resolveTableName("two_factor", event);
45
54
  if (!secret && d1) {
46
55
  try {
47
- const existing = await d1.prepare("SELECT * FROM two_factor WHERE user_id = ? AND enabled = 1 LIMIT 1").bind(user.id).first();
56
+ const existing = await d1.prepare(`SELECT * FROM ${twoFactorTbl} WHERE user_id = ? AND enabled = 1 LIMIT 1`).bind(user.id).first();
48
57
  if (existing?.secret) {
49
58
  secret = await decryptToken(existing.secret, event);
50
59
  isExisting = true;
@@ -75,7 +84,7 @@ export default defineEventHandler(async (event) => {
75
84
  backupCodes.map(async (c) => c.length === 64 ? c : await hashBackupCode(c))
76
85
  );
77
86
  await d1.prepare(`
78
- INSERT INTO two_factor (id, user_id, secret, backup_codes, enabled, created_at)
87
+ INSERT INTO ${twoFactorTbl} (id, user_id, secret, backup_codes, enabled, created_at)
79
88
  VALUES (?, ?, ?, ?, 1, ?)
80
89
  ON CONFLICT(user_id) DO UPDATE SET secret = excluded.secret, backup_codes = excluded.backup_codes, enabled = 1
81
90
  `).bind(id, user.id, await encryptToken(secret, event), JSON.stringify(hashedBackupCodes), now).run();