qarpeo 0.1.28 → 0.1.30

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 (50) hide show
  1. package/dist/chunks/wrangler.mjs +1 -1
  2. package/dist/runtime/bindings.mjs +1 -1
  3. package/dist/runtime/server/plugins/dev-proxy.mjs +0 -1
  4. package/dist/runtime/server/plugins/env.d.ts +2 -2
  5. package/dist/runtime/server/plugins/env.mjs +1 -10
  6. package/dist/runtime/server/routes/__qarpeo/analytics/events.get.mjs +2 -2
  7. package/dist/runtime/server/routes/__qarpeo/analytics/summary.get.mjs +2 -2
  8. package/dist/runtime/server/routes/__qarpeo/blob/files.get.mjs +2 -2
  9. package/dist/runtime/server/routes/__qarpeo/overview/health.get.mjs +2 -2
  10. package/dist/runtime/server/routes/__qarpeo/overview.get.mjs +3 -8
  11. package/dist/runtime/server/routes/__qarpeo/settings.get.mjs +2 -8
  12. package/dist/runtime/server/routes/analytics/events.get.mjs +2 -2
  13. package/dist/runtime/server/routes/analytics/pageviews.get.mjs +2 -2
  14. package/dist/runtime/server/routes/analytics/summary.get.mjs +2 -2
  15. package/dist/runtime/server/routes/auth/magic-link/verify.get.mjs +13 -10
  16. package/dist/runtime/server/routes/auth/sso/login.get.mjs +2 -1
  17. package/dist/runtime/server/routes/auth/sso/oidc/callback.get.mjs +2 -1
  18. package/dist/runtime/server/routes/auth/sso/saml/acs.post.mjs +18 -29
  19. package/dist/runtime/server/routes/cms/preview/disable.get.mjs +2 -1
  20. package/dist/runtime/server/routes/cms/preview/enable.get.mjs +3 -1
  21. package/dist/runtime/server/routes/cms/webhooks/[provider].post.mjs +2 -1
  22. package/dist/runtime/server/routes/notifications/push/subscribe.post.mjs +10 -5
  23. package/dist/runtime/server/routes/notifications/push/unsubscribe.post.mjs +6 -5
  24. package/dist/runtime/server/routes/payments/cancel.post.mjs +6 -5
  25. package/dist/runtime/server/routes/payments/change-plan.post.mjs +7 -8
  26. package/dist/runtime/server/routes/payments/checkout.post.mjs +13 -2
  27. package/dist/runtime/server/routes/payments/portal.post.mjs +6 -2
  28. package/dist/runtime/server/utils/analytics-query.mjs +15 -7
  29. package/dist/runtime/server/utils/auth.mjs +3 -2
  30. package/dist/runtime/server/utils/cms.mjs +3 -3
  31. package/dist/runtime/server/utils/config.d.ts +1 -1
  32. package/dist/runtime/server/utils/config.mjs +28 -2
  33. package/dist/runtime/server/utils/crypto.d.ts +7 -1
  34. package/dist/runtime/server/utils/crypto.mjs +29 -9
  35. package/dist/runtime/server/utils/domains.mjs +8 -4
  36. package/dist/runtime/server/utils/notifications.mjs +6 -4
  37. package/dist/runtime/server/utils/organization.d.ts +2 -1
  38. package/dist/runtime/server/utils/organization.mjs +18 -11
  39. package/dist/runtime/server/utils/passwordless.mjs +37 -15
  40. package/dist/runtime/server/utils/payments.mjs +7 -7
  41. package/dist/runtime/server/utils/ratelimit.mjs +34 -11
  42. package/dist/runtime/server/utils/sso.mjs +59 -7
  43. package/dist/runtime/server/utils/string.d.ts +11 -0
  44. package/dist/runtime/server/utils/string.mjs +24 -0
  45. package/dist/runtime/server/utils/tracker.d.ts +4 -4
  46. package/dist/runtime/server/utils/tracker.mjs +13 -11
  47. package/dist/runtime/server/utils/turnstile.mjs +6 -2
  48. package/dist/runtime/server.d.ts +4 -2
  49. package/dist/runtime/server.mjs +1 -0
  50. package/package.json +1 -1
@@ -9,7 +9,7 @@ import { fileURLToPath } from 'node:url';
9
9
  import { mkdir, writeFile, readFile } from 'node:fs/promises';
10
10
  import { defu } from 'defu';
11
11
 
12
- const version = "0.1.27";
12
+ const version = "0.1.30";
13
13
 
14
14
  function scanSchemaExports(schemaFiles) {
15
15
  const types = [];
@@ -1,5 +1,5 @@
1
1
  export function getCloudflareEnv(event) {
2
- const evt = event || globalThis.__qarpeo_event__;
2
+ const evt = event;
3
3
  if (evt?.context?.cloudflare?.env) {
4
4
  return evt.context.cloudflare.env;
5
5
  }
@@ -15,7 +15,6 @@ export default async function(nitroApp) {
15
15
  event.context = event.context || {};
16
16
  event.context.cloudflare = event.context.cloudflare || {};
17
17
  event.context.cloudflare.env = event.context.cloudflare.env || proxy.env;
18
- globalThis.__qarpeo_event__ = event;
19
18
  });
20
19
  }
21
20
  }
@@ -1,6 +1,6 @@
1
1
  import type { NitroApp } from "nitro/types";
2
2
  /**
3
- * Lightweight Nitro runtime plugin that captures the Cloudflare request context across both
4
- * production and edge environments.
3
+ * Lightweight Nitro runtime plugin that captures the Cloudflare worker environment bindings across
4
+ * both production and edge environments.
5
5
  */
6
6
  export default function (nitroApp: NitroApp): void;
@@ -1,17 +1,8 @@
1
1
  export default function(nitroApp) {
2
2
  nitroApp.hooks?.hook("request", (event) => {
3
- ;
4
- globalThis.__qarpeo_event__ = event;
5
- if (event?.context?.cloudflare?.env) {
3
+ if (event?.context?.cloudflare?.env && !globalThis.__qarpeo_env__) {
6
4
  ;
7
5
  globalThis.__qarpeo_env__ = event.context.cloudflare.env;
8
6
  }
9
7
  });
10
- const cleanup = () => {
11
- if (globalThis.__qarpeo_event__) {
12
- ;
13
- globalThis.__qarpeo_event__ = void 0;
14
- }
15
- };
16
- nitroApp.hooks?.hook?.("response", cleanup);
17
8
  }
@@ -1,12 +1,12 @@
1
1
  import { defineEventHandler, getQuery } from "nuxt/server";
2
2
  import { useAnalyticsDashboard } from "../../../utils/analytics-query.mjs";
3
+ import { getQarpeoConfig } from "../../../utils/config.mjs";
3
4
  export default defineEventHandler(async (event) => {
4
5
  const query = getQuery(event);
5
6
  const range = query.range || "7d";
6
7
  const name = query.name ? String(query.name) : void 0;
7
8
  const limit = query.limit ? parseInt(String(query.limit), 10) : 20;
8
- const rc = event.context?.nitro?.runtimeConfig ?? event.$config ?? {};
9
- const cfg = rc?.qarpeo?.analytics || {};
9
+ const cfg = getQarpeoConfig(event).analytics || {};
10
10
  const hasConfig = Boolean(cfg.dataset || cfg.accountId || cfg.siteId);
11
11
  try {
12
12
  if (hasConfig) {
@@ -1,10 +1,10 @@
1
1
  import { defineEventHandler, getQuery } from "nuxt/server";
2
2
  import { useAnalyticsDashboard } from "../../../utils/analytics-query.mjs";
3
+ import { getQarpeoConfig } from "../../../utils/config.mjs";
3
4
  export default defineEventHandler(async (event) => {
4
5
  const query = getQuery(event);
5
6
  const range = query.range || "7d";
6
- const rc = event.context?.nitro?.runtimeConfig ?? event.$config ?? {};
7
- const cfg = rc?.qarpeo?.analytics || {};
7
+ const cfg = getQarpeoConfig(event).analytics || {};
8
8
  const hasConfig = Boolean(cfg.dataset || cfg.accountId || cfg.siteId);
9
9
  try {
10
10
  if (hasConfig) {
@@ -1,13 +1,13 @@
1
1
  import { defineEventHandler, getQuery } from "nuxt/server";
2
2
  import { getR2Binding } from "../../../../blob.mjs";
3
3
  import { getDevMockBlobStore } from "../../../utils/blob-store.mjs";
4
+ import { getQarpeoConfig } from "../../../utils/config.mjs";
4
5
  export default defineEventHandler(async (event) => {
5
6
  const query = getQuery(event);
6
7
  const prefix = query.prefix ? String(query.prefix) : void 0;
7
8
  const limit = query.limit ? parseInt(String(query.limit), 10) : 50;
8
9
  try {
9
- const rc = event.context?.nitro?.runtimeConfig ?? event.$config ?? {};
10
- const bindingName = rc?.qarpeo?.blob?.binding || "BLOB";
10
+ const bindingName = getQarpeoConfig(event).blob?.binding || "BLOB";
11
11
  const r2 = getR2Binding(bindingName, event);
12
12
  const listRes = await r2.list({ prefix, limit });
13
13
  const files = (listRes.objects || []).map((obj) => ({
@@ -2,6 +2,7 @@ import { defineEventHandler } from "nuxt/server";
2
2
  import { getR2Binding } from "../../../../blob.mjs";
3
3
  import { getD1Binding } from "../../../../db.mjs";
4
4
  import { getKVBinding } from "../../../../kv.mjs";
5
+ import { getQarpeoConfig } from "../../../utils/config.mjs";
5
6
  export default defineEventHandler(async (event) => {
6
7
  const results = {};
7
8
  const t0 = performance.now();
@@ -30,8 +31,7 @@ export default defineEventHandler(async (event) => {
30
31
  }
31
32
  const t2 = performance.now();
32
33
  try {
33
- const rc = event.context?.nitro?.runtimeConfig ?? event.$config ?? {};
34
- const bindingName = rc?.qarpeo?.blob?.binding || "BLOB";
34
+ const bindingName = getQarpeoConfig(event).blob?.binding || "BLOB";
35
35
  const r2 = getR2Binding(bindingName, event);
36
36
  await r2.list({ limit: 1 });
37
37
  results.r2 = { ok: true, latencyMs: +(performance.now() - t2).toFixed(1) };
@@ -1,12 +1,7 @@
1
- import { defineEventHandler, useRuntimeConfig } from "nuxt/server";
1
+ import { defineEventHandler } from "nuxt/server";
2
+ import { getQarpeoConfig } from "../../utils/config.mjs";
2
3
  export default defineEventHandler((event) => {
3
- let rc = {};
4
- try {
5
- rc = useRuntimeConfig(event) || {};
6
- } catch {
7
- rc = event.context?.nitro?.runtimeConfig ?? event.$config ?? {};
8
- }
9
- const qarpeoConfig = rc?.qarpeo || {};
4
+ const qarpeoConfig = getQarpeoConfig(event);
10
5
  const isDev = process.env.NODE_ENV !== "production";
11
6
  return {
12
7
  environment: isDev ? "development" : "production",
@@ -1,16 +1,10 @@
1
1
  import { defineEventHandler } from "nuxt/server";
2
- import { useRuntimeConfig } from "nuxt/server";
3
2
  import { getDevMockBlobStore } from "../../utils/blob-store.mjs";
3
+ import { getQarpeoConfig } from "../../utils/config.mjs";
4
4
  import { getDevMockKvStore } from "../../utils/kv-store.mjs";
5
5
  import { listTenants } from "../../utils/tenant.mjs";
6
6
  export default defineEventHandler(async (event) => {
7
- let rc = {};
8
- try {
9
- rc = useRuntimeConfig(event) || {};
10
- } catch {
11
- rc = event.context?.nitro?.runtimeConfig ?? event.$config ?? {};
12
- }
13
- const qarpeoConfig = rc?.qarpeo || {};
7
+ const qarpeoConfig = getQarpeoConfig(event);
14
8
  const isDev = process.env.NODE_ENV !== "production";
15
9
  const kvStore = getDevMockKvStore();
16
10
  const blobStore = getDevMockBlobStore();
@@ -1,12 +1,12 @@
1
1
  import { defineEventHandler, getQuery } from "nuxt/server";
2
2
  import { useAnalyticsDashboard } from "../../utils/analytics-query.mjs";
3
+ import { getQarpeoConfig } from "../../utils/config.mjs";
3
4
  export default defineEventHandler(async (event) => {
4
5
  const query = getQuery(event);
5
6
  const range = query.range || "7d";
6
7
  const name = query.name ? String(query.name) : void 0;
7
8
  const limit = query.limit ? parseInt(String(query.limit), 10) : 20;
8
- const rc = event.context?.nitro?.runtimeConfig ?? event.$config ?? {};
9
- const cfg = rc?.qarpeo?.analytics || {};
9
+ const cfg = getQarpeoConfig(event).analytics || {};
10
10
  const dash = useAnalyticsDashboard({
11
11
  accountId: cfg.accountId,
12
12
  apiToken: cfg.apiToken,
@@ -1,10 +1,10 @@
1
1
  import { defineEventHandler, getQuery } from "nuxt/server";
2
2
  import { useAnalyticsDashboard } from "../../utils/analytics-query.mjs";
3
+ import { getQarpeoConfig } from "../../utils/config.mjs";
3
4
  export default defineEventHandler(async (event) => {
4
5
  const query = getQuery(event);
5
6
  const range = query.range || "7d";
6
- const rc = event.context?.nitro?.runtimeConfig ?? event.$config ?? {};
7
- const cfg = rc?.qarpeo?.analytics || {};
7
+ const cfg = getQarpeoConfig(event).analytics || {};
8
8
  const dash = useAnalyticsDashboard({
9
9
  accountId: cfg.accountId,
10
10
  apiToken: cfg.apiToken,
@@ -1,10 +1,10 @@
1
1
  import { defineEventHandler, getQuery } from "nuxt/server";
2
2
  import { useAnalyticsDashboard } from "../../utils/analytics-query.mjs";
3
+ import { getQarpeoConfig } from "../../utils/config.mjs";
3
4
  export default defineEventHandler(async (event) => {
4
5
  const query = getQuery(event);
5
6
  const range = query.range || "7d";
6
- const rc = event.context?.nitro?.runtimeConfig ?? event.$config ?? {};
7
- const cfg = rc?.qarpeo?.analytics || {};
7
+ const cfg = getQarpeoConfig(event).analytics || {};
8
8
  const dash = useAnalyticsDashboard({
9
9
  accountId: cfg.accountId,
10
10
  apiToken: cfg.apiToken,
@@ -4,12 +4,16 @@ import { ensureAuthTables } from "../../../utils/auth.mjs";
4
4
  import { getQarpeoConfig } from "../../../utils/config.mjs";
5
5
  import { verifyMagicLinkToken } from "../../../utils/passwordless.mjs";
6
6
  import { createDeviceSession, setAuthSession } from "../../../utils/session.mjs";
7
+ import { safeRedirect } from "../../../utils/string.mjs";
7
8
  export default defineEventHandler(async (event) => {
8
9
  const query = getQuery(event);
9
10
  const token = query?.token;
10
11
  const authConfig = getQarpeoConfig(event).auth;
11
- const loginRedirect = authConfig.redirect?.login || "/login";
12
- const successRedirect = authConfig.redirect?.success || "/dashboard";
12
+ const loginRedirect = safeRedirect(authConfig.redirect?.login, "/login");
13
+ const successRedirect = safeRedirect(
14
+ query?.redirect || authConfig.redirect?.success,
15
+ "/dashboard"
16
+ );
13
17
  if (!token || typeof token !== "string") {
14
18
  return sendRedirect(event, `${loginRedirect}?error=invalid_magic_link`);
15
19
  }
@@ -41,21 +45,20 @@ export default defineEventHandler(async (event) => {
41
45
  } else if (!dbUser.email_verified) {
42
46
  await d1.prepare("UPDATE user SET email_verified = 1, updated_at = ? WHERE id = ?").bind(now, dbUser.id).run();
43
47
  }
44
- } catch {
48
+ } catch (err) {
49
+ console.error("[qarpeo:magic-link] Database error resolving user:", err?.message);
50
+ return sendRedirect(event, `${loginRedirect}?error=database_error`);
51
+ }
52
+ if (!dbUser) {
53
+ return sendRedirect(event, `${loginRedirect}?error=user_creation_failed`);
45
54
  }
46
- const finalUser = dbUser ? {
55
+ const finalUser = {
47
56
  id: dbUser.id,
48
57
  email: dbUser.email,
49
58
  name: dbUser.name,
50
59
  avatarUrl: dbUser.image || dbUser.avatar_url,
51
60
  emailVerified: true,
52
61
  role: dbUser.role || "user"
53
- } : {
54
- id: crypto.randomUUID(),
55
- email: cleanEmail,
56
- name: cleanEmail.split("@")[0],
57
- emailVerified: true,
58
- role: "user"
59
62
  };
60
63
  const sessionConfig = authConfig.session || {};
61
64
  let sessionId;
@@ -8,12 +8,13 @@ import {
8
8
  import { getD1Binding } from "../../../../db.mjs";
9
9
  import { getKVBinding } from "../../../../kv.mjs";
10
10
  import { buildSAMLAuthnRequestUrl, buildOIDCAuthUrl } from "../../../utils/sso.mjs";
11
+ import { safeRedirect } from "../../../utils/string.mjs";
11
12
  export default defineEventHandler(async (event) => {
12
13
  const query = getQuery(event);
13
14
  const domain = query.domain?.toLowerCase()?.trim();
14
15
  const orgSlug = query.org?.toLowerCase()?.trim();
15
16
  const connectionId = query.connectionId;
16
- const redirect = query.redirect || "/dashboard";
17
+ const redirect = safeRedirect(query.redirect, "/dashboard");
17
18
  if (!domain && !orgSlug && !connectionId) {
18
19
  throw createError({
19
20
  statusCode: 400,
@@ -9,6 +9,7 @@ import { getD1Binding } from "../../../../../db.mjs";
9
9
  import { getKVBinding } from "../../../../../kv.mjs";
10
10
  import { setAuthSession, createDeviceSession } from "../../../../utils/session.mjs";
11
11
  import { exchangeOIDCCode } from "../../../../utils/sso.mjs";
12
+ import { safeRedirect } from "../../../../utils/string.mjs";
12
13
  export default defineEventHandler(async (event) => {
13
14
  const query = getQuery(event);
14
15
  const code = query.code;
@@ -28,7 +29,7 @@ export default defineEventHandler(async (event) => {
28
29
  const stateData = await kv.get(`sso:state:${stateId}`, { type: "json" });
29
30
  if (stateData) {
30
31
  connectionId = stateData.connectionId || null;
31
- finalRedirect = stateData.redirect || "/dashboard";
32
+ finalRedirect = safeRedirect(stateData.redirect, "/dashboard");
32
33
  await kv.delete(`sso:state:${stateId}`);
33
34
  }
34
35
  } catch {
@@ -8,6 +8,7 @@ import { getD1Binding } from "../../../../../db.mjs";
8
8
  import { getKVBinding } from "../../../../../kv.mjs";
9
9
  import { setAuthSession, createDeviceSession } from "../../../../utils/session.mjs";
10
10
  import { parseSAMLResponse, verifySAMLSignature } from "../../../../utils/sso.mjs";
11
+ import { safeRedirect } from "../../../../utils/string.mjs";
11
12
  export default defineEventHandler(async (event) => {
12
13
  const body = await readBody(event);
13
14
  const samlResponse = body?.SAMLResponse;
@@ -37,7 +38,7 @@ export default defineEventHandler(async (event) => {
37
38
  const stateData = await kv.get(`sso:state:${relayState}`, { type: "json" });
38
39
  if (stateData) {
39
40
  connectionId = stateData.connectionId || null;
40
- finalRedirect = stateData.redirect || "/dashboard";
41
+ finalRedirect = safeRedirect(stateData.redirect, "/dashboard");
41
42
  await kv.delete(`sso:state:${relayState}`);
42
43
  }
43
44
  } catch {
@@ -50,37 +51,25 @@ export default defineEventHandler(async (event) => {
50
51
  if (connectionId) {
51
52
  connection = await d1.prepare("SELECT * FROM _qarpeo_sso_connections WHERE id = ? LIMIT 1").bind(connectionId).first();
52
53
  }
53
- if (connection?.cert) {
54
- const sigResult = await verifySAMLSignature(rawXml, connection.cert);
55
- if (sigResult === false) {
56
- throw createError({
57
- statusCode: 401,
58
- statusMessage: "Unauthorized",
59
- message: "SAML response signature verification failed. The response may have been tampered with."
60
- });
61
- }
62
- if (sigResult === null) {
63
- console.warn(
64
- "[qarpeo:saml] SAMLResponse from connection %s contains no XML digital signature. Ensure your IdP is configured to sign assertions or the response envelope.",
65
- connectionId
66
- );
67
- }
68
- } else if (!connection) {
69
- }
70
54
  const assertion = parseSAMLResponse(samlResponse);
71
55
  const email = assertion.email;
72
56
  if (!connection && assertion.issuer) {
73
- connection = await d1.prepare("SELECT * FROM _qarpeo_sso_connections WHERE issuer = ? LIMIT 1").bind(assertion.issuer).first();
74
- if (connection?.cert) {
75
- const sigResult = await verifySAMLSignature(rawXml, connection.cert);
76
- if (sigResult === false) {
77
- throw createError({
78
- statusCode: 401,
79
- statusMessage: "Unauthorized",
80
- message: "SAML response signature verification failed."
81
- });
82
- }
83
- }
57
+ connection = await d1.prepare("SELECT * FROM _qarpeo_sso_connections WHERE issuer = ? AND enabled = 1 LIMIT 1").bind(assertion.issuer).first();
58
+ }
59
+ if (!connection || !connection.cert) {
60
+ throw createError({
61
+ statusCode: 401,
62
+ statusMessage: "Unauthorized",
63
+ message: "No active SSO connection or IdP certificate found to verify SAML assertion."
64
+ });
65
+ }
66
+ const sigResult = await verifySAMLSignature(rawXml, connection.cert);
67
+ if (sigResult !== true) {
68
+ throw createError({
69
+ statusCode: 401,
70
+ statusMessage: "Unauthorized",
71
+ message: sigResult === null ? "Unsigned SAML assertions are not permitted. Your IdP must sign assertions or the response." : "SAML response signature verification failed. The response may have been tampered with."
72
+ });
84
73
  }
85
74
  let user = await d1.prepare("SELECT * FROM user WHERE email = ? LIMIT 1").bind(email).first();
86
75
  if (!user) {
@@ -1,7 +1,8 @@
1
1
  import { defineEventHandler, getQuery, deleteCookie, sendRedirect } from "nuxt/server";
2
+ import { safeRedirect } from "../../../utils/string.mjs";
2
3
  export default defineEventHandler((event) => {
3
4
  const query = getQuery(event);
4
- const redirect = String(query.redirect || "/");
5
+ const redirect = safeRedirect(query.redirect, "/");
5
6
  deleteCookie(event, "qarpeo_preview", {
6
7
  path: "/"
7
8
  });
@@ -1,12 +1,14 @@
1
1
  import { defineEventHandler, getQuery, setCookie, sendRedirect, createError } from "nuxt/server";
2
2
  import { verifyPreviewToken } from "../../../utils/cms.mjs";
3
+ import { safeRedirect } from "../../../utils/string.mjs";
3
4
  export default defineEventHandler(async (event) => {
4
5
  const query = getQuery(event);
5
6
  const collection = String(query.collection || "");
6
7
  const slug = String(query.slug || query.id || "");
7
8
  const token = String(query.token || query.preview_token || "");
8
9
  const expires = String(query.expires || "");
9
- const redirect = String(query.redirect || (slug ? `/${collection}/${slug}` : "/"));
10
+ const defaultPath = slug ? `/${collection}/${slug}` : "/";
11
+ const redirect = safeRedirect(query.redirect || defaultPath, defaultPath);
10
12
  if (!collection || !slug || !token || !expires) {
11
13
  throw createError({
12
14
  statusCode: 400,
@@ -43,7 +43,8 @@ export default defineEventHandler(async (event) => {
43
43
  if (provider === "github") {
44
44
  const ghEvent = (getH3Header(event, "x-github-event") || "push").toLowerCase();
45
45
  const ghSignature = getH3Header(event, "x-hub-signature-256") || getH3Header(event, "x-hub-signature");
46
- const webhookSecret2 = config.github?.webhookSecret || config.webhookSecret || (typeof process !== "undefined" ? process.env.GITHUB_WEBHOOK_SECRET || process.env.CMS_WEBHOOK_SECRET : void 0);
46
+ const cfEnv = event?.context?.cloudflare?.env || globalThis.__qarpeo_env__ || {};
47
+ const webhookSecret2 = config.github?.webhookSecret || config.webhookSecret || cfEnv.GITHUB_WEBHOOK_SECRET || cfEnv.CMS_WEBHOOK_SECRET || (typeof process !== "undefined" ? process.env.GITHUB_WEBHOOK_SECRET || process.env.CMS_WEBHOOK_SECRET : void 0);
47
48
  if (webhookSecret2) {
48
49
  const isValid = await verifyGitHubSignature(rawBody, ghSignature, webhookSecret2);
49
50
  if (!isValid) {
@@ -1,15 +1,20 @@
1
- import { createError, defineEventHandler, readBody } from "nuxt/server";
1
+ import { createError, defineEventHandler, readValidatedBody } from "nuxt/server";
2
+ import { z } from "zod";
2
3
  import { savePushSubscription } from "../../../utils/notifications.mjs";
3
4
  import { getAuthSession } from "../../../utils/session.mjs";
5
+ const PushSubscribeSchema = z.object({
6
+ endpoint: z.string().url(),
7
+ keys: z.object({
8
+ p256dh: z.string().min(1),
9
+ auth: z.string().min(1)
10
+ })
11
+ });
4
12
  export default defineEventHandler(async (event) => {
5
13
  const session = await getAuthSession(event);
6
14
  if (!session?.user) {
7
15
  throw createError({ statusCode: 401, message: "Unauthorized" });
8
16
  }
9
- const body = await readBody(event);
10
- if (!body?.endpoint || !body?.keys?.p256dh || !body?.keys?.auth) {
11
- throw createError({ statusCode: 400, message: "Invalid push subscription" });
12
- }
17
+ const body = await readValidatedBody(event, (b) => PushSubscribeSchema.parse(b));
13
18
  await savePushSubscription(
14
19
  session.user.id,
15
20
  { endpoint: body.endpoint, keys: { p256dh: body.keys.p256dh, auth: body.keys.auth } },
@@ -1,15 +1,16 @@
1
- import { createError, defineEventHandler, readBody } from "nuxt/server";
1
+ import { createError, defineEventHandler, readValidatedBody } from "nuxt/server";
2
+ import { z } from "zod";
2
3
  import { removePushSubscription } from "../../../utils/notifications.mjs";
3
4
  import { getAuthSession } from "../../../utils/session.mjs";
5
+ const PushUnsubscribeSchema = z.object({
6
+ endpoint: z.string().url()
7
+ });
4
8
  export default defineEventHandler(async (event) => {
5
9
  const session = await getAuthSession(event);
6
10
  if (!session?.user) {
7
11
  throw createError({ statusCode: 401, message: "Unauthorized" });
8
12
  }
9
- const body = await readBody(event);
10
- if (!body?.endpoint) {
11
- throw createError({ statusCode: 400, message: "Missing endpoint" });
12
- }
13
+ const body = await readValidatedBody(event, (b) => PushUnsubscribeSchema.parse(b));
13
14
  await removePushSubscription(body.endpoint, event);
14
15
  return { ok: true };
15
16
  });
@@ -1,9 +1,10 @@
1
- import { defineEventHandler, readBody, createError } from "nuxt/server";
1
+ import { defineEventHandler, readValidatedBody } from "nuxt/server";
2
+ import { z } from "zod";
2
3
  import { cancelSubscription } from "../../utils/payments.mjs";
4
+ const CancelBodySchema = z.object({
5
+ subscriptionId: z.string().min(1, "subscriptionId is required")
6
+ });
3
7
  export default defineEventHandler(async (event) => {
4
- const body = await readBody(event).catch(() => ({})) || {};
5
- if (!body.subscriptionId) {
6
- throw createError({ statusCode: 400, message: "subscriptionId is required" });
7
- }
8
+ const body = await readValidatedBody(event, (b) => CancelBodySchema.parse(b));
8
9
  return cancelSubscription(event, body.subscriptionId);
9
10
  });
@@ -1,12 +1,11 @@
1
- import { defineEventHandler, readBody, createError } from "nuxt/server";
1
+ import { defineEventHandler, readValidatedBody } from "nuxt/server";
2
+ import { z } from "zod";
2
3
  import { changePlan } from "../../utils/payments.mjs";
4
+ const ChangePlanBodySchema = z.object({
5
+ subscriptionId: z.string().min(1, "subscriptionId is required"),
6
+ newPriceId: z.string().min(1, "newPriceId is required")
7
+ });
3
8
  export default defineEventHandler(async (event) => {
4
- const body = await readBody(event).catch(() => ({})) || {};
5
- if (!body.subscriptionId) {
6
- throw createError({ statusCode: 400, message: "subscriptionId is required" });
7
- }
8
- if (!body.newPriceId) {
9
- throw createError({ statusCode: 400, message: "newPriceId is required" });
10
- }
9
+ const body = await readValidatedBody(event, (b) => ChangePlanBodySchema.parse(b));
11
10
  return changePlan(event, body.subscriptionId, body.newPriceId);
12
11
  });
@@ -1,7 +1,18 @@
1
- import { defineEventHandler, readBody } from "nuxt/server";
1
+ import { defineEventHandler, readValidatedBody } from "nuxt/server";
2
+ import { z } from "zod";
2
3
  import { createCheckoutSession } from "../../utils/payments.mjs";
4
+ const CheckoutBodySchema = z.object({
5
+ planId: z.string().optional(),
6
+ priceId: z.string().optional(),
7
+ mode: z.enum(["subscription", "payment", "setup"]).optional(),
8
+ trialDays: z.number().int().nonnegative().optional(),
9
+ customerEmail: z.string().email().optional(),
10
+ successUrl: z.string().url().optional(),
11
+ cancelUrl: z.string().url().optional(),
12
+ metadata: z.record(z.string(), z.string()).optional()
13
+ });
3
14
  export default defineEventHandler(async (event) => {
4
- const body = await readBody(event) || {};
15
+ const body = await readValidatedBody(event, (b) => CheckoutBodySchema.parse(b));
5
16
  const session = await createCheckoutSession(event, {
6
17
  planId: body.planId,
7
18
  priceId: body.priceId,
@@ -1,7 +1,11 @@
1
- import { defineEventHandler, readBody } from "nuxt/server";
1
+ import { defineEventHandler, readValidatedBody } from "nuxt/server";
2
+ import { z } from "zod";
2
3
  import { createCustomerPortalSession } from "../../utils/payments.mjs";
4
+ const PortalBodySchema = z.object({
5
+ returnUrl: z.string().url().optional()
6
+ });
3
7
  export default defineEventHandler(async (event) => {
4
- const body = await readBody(event).catch(() => ({})) || {};
8
+ const body = await readValidatedBody(event, (b) => PortalBodySchema.parse(b));
5
9
  const session = await createCustomerPortalSession(event, {
6
10
  returnUrl: body.returnUrl
7
11
  });
@@ -1,3 +1,7 @@
1
+ import { getCloudflareEnv } from "../../bindings.mjs";
2
+ function escapeAEString(value) {
3
+ return value.replace(/\0/g, "").replace(/--/g, "").replace(/\/\*/g, "").replace(/'/g, "''");
4
+ }
1
5
  function rangeToInterval(range = "7d") {
2
6
  const map = {
3
7
  "1h": "1 HOUR",
@@ -14,10 +18,14 @@ function rangeToGranularity(range = "7d") {
14
18
  return "toStartOfDay";
15
19
  }
16
20
  export async function queryAnalytics(sql, options = {}) {
17
- const accountId = options.accountId || process.env.CLOUDFLARE_ACCOUNT_ID || process.env.CF_ACCOUNT_ID;
18
- const apiToken = options.apiToken || process.env.CLOUDFLARE_API_TOKEN || process.env.CF_API_TOKEN;
21
+ const env = getCloudflareEnv();
22
+ const accountId = options.accountId || env.CLOUDFLARE_ACCOUNT_ID || env.CF_ACCOUNT_ID || process.env.CLOUDFLARE_ACCOUNT_ID || process.env.CF_ACCOUNT_ID;
23
+ const apiToken = options.apiToken || env.CLOUDFLARE_API_TOKEN || env.CF_API_TOKEN || process.env.CLOUDFLARE_API_TOKEN || process.env.CF_API_TOKEN;
24
+ const isDev = Boolean(
25
+ import.meta.dev || process.env.NODE_ENV === "development" || process.env.NODE_ENV === "test" || env.NODE_ENV === "development"
26
+ );
19
27
  if (!accountId || !apiToken) {
20
- if (process.env.NODE_ENV !== "production") {
28
+ if (isDev) {
21
29
  return [];
22
30
  }
23
31
  throw new Error(
@@ -36,11 +44,11 @@ export async function queryAnalytics(sql, options = {}) {
36
44
  body: sql
37
45
  });
38
46
  } catch (err) {
39
- if (process.env.NODE_ENV !== "production") return [];
47
+ if (isDev) return [];
40
48
  throw new Error(`[qarpeo/analytics] Network error querying AE SQL API: ${err.message}`);
41
49
  }
42
50
  if (!res.ok) {
43
- if (process.env.NODE_ENV !== "production") return [];
51
+ if (isDev) return [];
44
52
  const body = await res.text().catch(() => "");
45
53
  throw new Error(`[qarpeo/analytics] AE SQL API error ${res.status}: ${body}`);
46
54
  }
@@ -49,7 +57,7 @@ export async function queryAnalytics(sql, options = {}) {
49
57
  }
50
58
  export function useAnalyticsDashboard(options = {}) {
51
59
  const dataset = options.dataset || process.env.QARPEO_ANALYTICS_DATASET || "analytics";
52
- const siteFilter = options.siteId ? `AND index1 = '${options.siteId.replace(/'/g, "''")}'` : "";
60
+ const siteFilter = options.siteId ? `AND index1 = '${escapeAEString(options.siteId)}'` : "";
53
61
  const query = (sql) => queryAnalytics(sql, options);
54
62
  return {
55
63
  /**
@@ -186,7 +194,7 @@ export function useAnalyticsDashboard(options = {}) {
186
194
  */
187
195
  async events(name, limit = 20, range = "7d") {
188
196
  const interval = rangeToInterval(range);
189
- const nameFilter = name ? `AND blob1 = '${name.replace(/'/g, "''")}'` : "AND blob1 != 'pageview'";
197
+ const nameFilter = name ? `AND blob1 = '${escapeAEString(name)}'` : "AND blob1 != 'pageview'";
190
198
  const rows = await query(`
191
199
  SELECT
192
200
  blob1 AS name,
@@ -2,13 +2,14 @@ import { drizzleAdapter } from "@better-auth/drizzle-adapter";
2
2
  import { betterAuth } from "better-auth";
3
3
  import { createError } from "nuxt/server";
4
4
  import * as authSchema from "#qarpeo/auth/schema";
5
+ import { getSessionSecret } from "./config.mjs";
5
6
  import { useDrizzle } from "./drizzle.mjs";
6
7
  const _authCache = /* @__PURE__ */ new Map();
7
8
  export function serverAuth(event) {
8
9
  const cfEnv = event?.context?.cloudflare?.env;
9
10
  const secret = cfEnv?.BETTER_AUTH_SECRET || cfEnv?.NUXT_BETTER_AUTH_SECRET || cfEnv?.NUXT_APP_SECRET || process.env.BETTER_AUTH_SECRET || process.env.NUXT_BETTER_AUTH_SECRET || process.env.NUXT_APP_SECRET || null;
10
11
  if (!secret) {
11
- const isDev = globalThis.process?.env?.NODE_ENV === "development" || cfEnv?.NODE_ENV === "development";
12
+ const isDev = Boolean(import.meta.dev) || globalThis.process?.env?.NODE_ENV === "development" || cfEnv?.NODE_ENV === "development";
12
13
  if (!isDev) {
13
14
  throw createError({
14
15
  statusCode: 500,
@@ -17,7 +18,7 @@ export function serverAuth(event) {
17
18
  });
18
19
  }
19
20
  }
20
- const effectiveSecret = secret || "qarpeo-auth-dev-secret-change-before-deploy-32c";
21
+ const effectiveSecret = secret || getSessionSecret(event);
21
22
  const cached = _authCache.get(effectiveSecret);
22
23
  if (cached) return cached;
23
24
  const db = useDrizzle(void 0, event);
@@ -1,4 +1,4 @@
1
- import { createError, getCookie, useRuntimeConfig } from "nuxt/server";
1
+ import { createError, getCookie } from "nuxt/server";
2
2
  import { parse as parseYaml } from "yaml";
3
3
  import { getKVBinding } from "../../kv.mjs";
4
4
  import { fireCMSWebhooks, fireCMSDeployTrigger } from "./cms-events.mjs";
@@ -28,6 +28,7 @@ import {
28
28
  extractTOC
29
29
  } from "./cms/path.mjs";
30
30
  import { registerEnsureCMSSynced } from "./cms/search.mjs";
31
+ import { getSessionSecret } from "./config.mjs";
31
32
  import { getAuthContext } from "./context.mjs";
32
33
  export * from "./cms/common.mjs";
33
34
  export * from "./cms/path.mjs";
@@ -1288,8 +1289,7 @@ export async function pruneRevisions(event, entryId, max) {
1288
1289
  ).bind(entryId, entryId, max).run();
1289
1290
  }
1290
1291
  async function getCMSSecret(event) {
1291
- const rc = useRuntimeConfig(event);
1292
- const secret = rc.appSecret || rc.qarpeo?.sessionPassword || rc.sessionPassword || rc.session?.password || globalThis.process?.env?.NUXT_APP_SECRET || globalThis.process?.env?.NUXT_SESSION_PASSWORD || "qarpeo-cms-preview-secret";
1292
+ const secret = getSessionSecret(event);
1293
1293
  const enc = new TextEncoder();
1294
1294
  return crypto.subtle.importKey(
1295
1295
  "raw",