qarpeo 0.1.29 → 0.1.31

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 (51) hide show
  1. package/dist/chunks/wrangler.mjs +1 -1
  2. package/dist/runtime/app/composables/cms.mjs +2 -2
  3. package/dist/runtime/server/routes/auth/magic-link/verify.get.mjs +13 -10
  4. package/dist/runtime/server/routes/auth/sso/login.get.mjs +2 -1
  5. package/dist/runtime/server/routes/auth/sso/oidc/callback.get.mjs +2 -1
  6. package/dist/runtime/server/routes/auth/sso/saml/acs.post.mjs +18 -29
  7. package/dist/runtime/server/routes/cms/[collection]/[id]/preview-token.post.mjs +1 -1
  8. package/dist/runtime/server/routes/cms/[collection]/[id]/publish.post.mjs +1 -1
  9. package/dist/runtime/server/routes/cms/[collection]/[id]/review.post.mjs +1 -1
  10. package/dist/runtime/server/routes/cms/[collection]/[id].delete.mjs +1 -1
  11. package/dist/runtime/server/routes/cms/[collection]/[id].put.mjs +1 -1
  12. package/dist/runtime/server/routes/cms/[collection]/index.get.mjs +13 -3
  13. package/dist/runtime/server/routes/cms/[collection]/index.post.mjs +1 -1
  14. package/dist/runtime/server/routes/cms/[collection]/references.get.mjs +1 -1
  15. package/dist/runtime/server/routes/cms/collections/[id].delete.mjs +1 -1
  16. package/dist/runtime/server/routes/cms/collections/[id].put.mjs +1 -1
  17. package/dist/runtime/server/routes/cms/collections/index.get.mjs +4 -1
  18. package/dist/runtime/server/routes/cms/collections/index.post.mjs +1 -1
  19. package/dist/runtime/server/routes/cms/components/index.get.mjs +2 -0
  20. package/dist/runtime/server/routes/cms/export.post.mjs +13 -5
  21. package/dist/runtime/server/routes/cms/preview/disable.get.mjs +2 -1
  22. package/dist/runtime/server/routes/cms/preview/enable.get.mjs +3 -1
  23. package/dist/runtime/server/routes/cms/search.get.mjs +10 -4
  24. package/dist/runtime/server/routes/cms/sync.post.mjs +1 -1
  25. package/dist/runtime/server/routes/payments/checkout.post.mjs +2 -2
  26. package/dist/runtime/server/routes/payments/pause.post.mjs +6 -5
  27. package/dist/runtime/server/routes/payments/portal.post.mjs +1 -1
  28. package/dist/runtime/server/routes/payments/usage.post.mjs +16 -11
  29. package/dist/runtime/server/routes/payments/webhook.post.d.ts +1 -0
  30. package/dist/runtime/server/utils/analytics-query.mjs +6 -3
  31. package/dist/runtime/server/utils/auth.mjs +3 -2
  32. package/dist/runtime/server/utils/bots.mjs +1 -0
  33. package/dist/runtime/server/utils/cms/common.d.ts +4 -2
  34. package/dist/runtime/server/utils/cms/common.mjs +2 -5
  35. package/dist/runtime/server/utils/cms/git.mjs +6 -2
  36. package/dist/runtime/server/utils/cms-events.mjs +3 -2
  37. package/dist/runtime/server/utils/cms.mjs +6 -4
  38. package/dist/runtime/server/utils/config.mjs +4 -2
  39. package/dist/runtime/server/utils/crypto.d.ts +2 -0
  40. package/dist/runtime/server/utils/crypto.mjs +12 -4
  41. package/dist/runtime/server/utils/domains.mjs +8 -3
  42. package/dist/runtime/server/utils/mail.mjs +2 -0
  43. package/dist/runtime/server/utils/notifications.mjs +1 -3
  44. package/dist/runtime/server/utils/passwordless.mjs +7 -1
  45. package/dist/runtime/server/utils/payments.d.ts +1 -0
  46. package/dist/runtime/server/utils/payments.mjs +40 -13
  47. package/dist/runtime/server/utils/sso.mjs +63 -9
  48. package/dist/runtime/server/utils/string.d.ts +5 -0
  49. package/dist/runtime/server/utils/string.mjs +10 -0
  50. package/dist/runtime/server/utils/turnstile.mjs +8 -3
  51. 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.29";
12
+ const version = "0.1.31";
13
13
 
14
14
  function scanSchemaExports(schemaFiles) {
15
15
  const types = [];
@@ -156,8 +156,8 @@ export function queryCollection(collection) {
156
156
  return builder;
157
157
  },
158
158
  order(field, direction = "ASC") {
159
- _orderField = field;
160
- _orderDirection = direction;
159
+ _orderField = String(field || "").replace(/[^a-zA-Z0-9_]/g, "") || "published_at";
160
+ _orderDirection = String(direction).trim().toUpperCase() === "DESC" ? "DESC" : "ASC";
161
161
  return builder;
162
162
  },
163
163
  select(...fields) {
@@ -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) {
@@ -4,7 +4,7 @@ import { generatePreviewToken, getCMSConfig } from "../../../../utils/cms.mjs";
4
4
  import { requireAuth } from "../../../../utils/context.mjs";
5
5
  export default defineEventHandler(async (event) => {
6
6
  const config = getCMSConfig(event);
7
- await requireAuth(event, { role: config.roles });
7
+ await requireAuth(event, config.roles ? { role: config.roles } : {});
8
8
  const collection = getRouterParam(event, "collection");
9
9
  const id = getRouterParam(event, "id");
10
10
  const db = getD1Binding("DB", event);
@@ -3,7 +3,7 @@ import { publishCMSEntry, getCMSConfig } from "../../../../utils/cms.mjs";
3
3
  import { requireAuth } from "../../../../utils/context.mjs";
4
4
  export default defineEventHandler(async (event) => {
5
5
  const config = getCMSConfig(event);
6
- await requireAuth(event, { role: config.roles });
6
+ await requireAuth(event, config.roles ? { role: config.roles } : {});
7
7
  const collection = getRouterParam(event, "collection");
8
8
  if (config.collections[collection]?.mode === "file") {
9
9
  throw createError({
@@ -3,7 +3,7 @@ import { submitCMSEntryForReview, rejectCMSEntryReview, getCMSConfig } from "../
3
3
  import { requireAuth } from "../../../../utils/context.mjs";
4
4
  export default defineEventHandler(async (event) => {
5
5
  const config = getCMSConfig(event);
6
- await requireAuth(event, { role: config.roles });
6
+ await requireAuth(event, config.roles ? { role: config.roles } : {});
7
7
  const collection = getRouterParam(event, "collection");
8
8
  if (config.collections[collection]?.mode === "file") {
9
9
  throw createError({
@@ -3,7 +3,7 @@ import { deleteCMSEntry, getCMSConfig } from "../../../utils/cms.mjs";
3
3
  import { requireAuth } from "../../../utils/context.mjs";
4
4
  export default defineEventHandler(async (event) => {
5
5
  const config = getCMSConfig(event);
6
- await requireAuth(event, { role: config.roles });
6
+ await requireAuth(event, config.roles ? { role: config.roles } : {});
7
7
  const collection = getRouterParam(event, "collection");
8
8
  if (config.collections[collection]?.mode === "file") {
9
9
  throw createError({
@@ -3,7 +3,7 @@ import { updateCMSEntry, getCMSConfig } from "../../../utils/cms.mjs";
3
3
  import { requireAuth } from "../../../utils/context.mjs";
4
4
  export default defineEventHandler(async (event) => {
5
5
  const config = getCMSConfig(event);
6
- await requireAuth(event, { role: config.roles });
6
+ await requireAuth(event, config.roles ? { role: config.roles } : {});
7
7
  const collection = getRouterParam(event, "collection");
8
8
  if (config.collections[collection]?.mode === "file") {
9
9
  throw createError({
@@ -1,13 +1,23 @@
1
1
  import { defineEventHandler, getRouterParam, getQuery } from "nuxt/server";
2
- import { queryCMSEntries } from "../../../utils/cms.mjs";
2
+ import { getCMSConfig, queryCMSEntries } from "../../../utils/cms.mjs";
3
+ import { getAuthContext } from "../../../utils/context.mjs";
3
4
  export default defineEventHandler(async (event) => {
4
5
  const collection = getRouterParam(event, "collection");
5
6
  const q = getQuery(event);
7
+ const auth = await getAuthContext(event);
8
+ const config = getCMSConfig(event);
9
+ const isEditor = auth?.user && (!config.roles || Array.isArray(config.roles) && config.roles.some((r) => r === auth.role) || auth.isAdmin);
10
+ const VALID_STATUSES = /* @__PURE__ */ new Set(["published", "draft", "archived", "all"]);
11
+ const rawStatus = q.status?.toLowerCase();
12
+ let status = "published";
13
+ if (isEditor && rawStatus && VALID_STATUSES.has(rawStatus)) {
14
+ status = rawStatus;
15
+ }
6
16
  const opts = {
7
17
  page: q.page ? Number(q.page) : 1,
8
- limit: q.limit ? Number(q.limit) : 10,
18
+ limit: Math.min(100, Math.max(1, q.limit ? Number(q.limit) : 10)),
9
19
  sort: q.sort || "published_at:desc",
10
- status: q.status || "published",
20
+ status,
11
21
  tag: q.tag,
12
22
  fields: q.fields
13
23
  };
@@ -3,7 +3,7 @@ import { createCMSEntry, getCMSConfig } from "../../../utils/cms.mjs";
3
3
  import { requireAuth } from "../../../utils/context.mjs";
4
4
  export default defineEventHandler(async (event) => {
5
5
  const config = getCMSConfig(event);
6
- const { user } = await requireAuth(event, { role: config.roles });
6
+ const { user } = await requireAuth(event, config.roles ? { role: config.roles } : {});
7
7
  const collection = getRouterParam(event, "collection");
8
8
  if (config.collections[collection]?.mode === "file") {
9
9
  throw createError({
@@ -3,7 +3,7 @@ import { getCMSConfig, getCollectionFields, queryCMSEntries } from "../../../uti
3
3
  import { requireAuth } from "../../../utils/context.mjs";
4
4
  export default defineEventHandler(async (event) => {
5
5
  const config = getCMSConfig(event);
6
- await requireAuth(event, { role: config.roles });
6
+ await requireAuth(event, config.roles ? { role: config.roles } : {});
7
7
  const collection = getRouterParam(event, "collection");
8
8
  const q = getQuery(event);
9
9
  const fieldName = q.field;
@@ -3,7 +3,7 @@ import { deleteCMSCollection, getCMSConfig } from "../../../utils/cms.mjs";
3
3
  import { requireAuth } from "../../../utils/context.mjs";
4
4
  export default defineEventHandler(async (event) => {
5
5
  const config = getCMSConfig(event);
6
- await requireAuth(event, { role: config.roles });
6
+ await requireAuth(event, config.roles ? { role: config.roles } : {});
7
7
  const id = getRouterParam(event, "id");
8
8
  await deleteCMSCollection(event, id);
9
9
  return { ok: true };
@@ -3,7 +3,7 @@ import { updateCMSCollection, getCMSConfig } from "../../../utils/cms.mjs";
3
3
  import { requireAuth } from "../../../utils/context.mjs";
4
4
  export default defineEventHandler(async (event) => {
5
5
  const config = getCMSConfig(event);
6
- await requireAuth(event, { role: config.roles });
6
+ await requireAuth(event, config.roles ? { role: config.roles } : {});
7
7
  const id = getRouterParam(event, "id");
8
8
  const body = await readBody(event);
9
9
  await updateCMSCollection(event, id, body || {});
@@ -1,6 +1,9 @@
1
1
  import { defineEventHandler } from "nuxt/server";
2
- import { listCMSCollections } from "../../../utils/cms.mjs";
2
+ import { getCMSConfig, listCMSCollections } from "../../../utils/cms.mjs";
3
+ import { requireAuth } from "../../../utils/context.mjs";
3
4
  export default defineEventHandler(async (event) => {
5
+ const config = getCMSConfig(event);
6
+ await requireAuth(event, config.roles ? { role: config.roles } : {});
4
7
  const collections = await listCMSCollections(event);
5
8
  return { collections };
6
9
  });
@@ -3,7 +3,7 @@ import { createCMSCollection, getCMSConfig } from "../../../utils/cms.mjs";
3
3
  import { requireAuth } from "../../../utils/context.mjs";
4
4
  export default defineEventHandler(async (event) => {
5
5
  const config = getCMSConfig(event);
6
- await requireAuth(event, { role: config.roles });
6
+ await requireAuth(event, config.roles ? { role: config.roles } : {});
7
7
  const body = await readBody(event);
8
8
  if (!body?.id || !body?.name) {
9
9
  throw createError({ statusCode: 400, message: "id and name are required" });
@@ -1,7 +1,9 @@
1
1
  import { defineEventHandler } from "nuxt/server";
2
2
  import { getCMSConfig } from "../../../utils/cms.mjs";
3
+ import { requireAuth } from "../../../utils/context.mjs";
3
4
  export default defineEventHandler(async (event) => {
4
5
  const config = getCMSConfig(event);
6
+ await requireAuth(event, config.roles ? { role: config.roles } : {});
5
7
  const components = config.components ?? {};
6
8
  return {
7
9
  components: Object.entries(components).map(([id, def]) => ({
@@ -4,12 +4,15 @@ import { getCMSConfig, formatFrontmatter, computeContentHash } from "../../utils
4
4
  import { requireAuth } from "../../utils/context.mjs";
5
5
  export default defineEventHandler(async (event) => {
6
6
  const config = getCMSConfig(event);
7
- await requireAuth(event, { role: config.roles });
8
- let writeFile, mkdir;
7
+ await requireAuth(event, config.roles ? { role: config.roles } : {});
8
+ let writeFile, mkdir, resolvePath, dirname;
9
9
  try {
10
10
  const fs = await import("node:fs/promises");
11
+ const path = await import("node:path");
11
12
  writeFile = fs.writeFile;
12
13
  mkdir = fs.mkdir;
14
+ resolvePath = path.resolve;
15
+ dirname = path.dirname;
13
16
  } catch {
14
17
  return {
15
18
  ok: false,
@@ -20,15 +23,20 @@ export default defineEventHandler(async (event) => {
20
23
  const rows = await db.prepare("SELECT * FROM _qarpeo_cms_entries ORDER BY collection_id, slug").all();
21
24
  const entries = rows.results || [];
22
25
  let exported = 0;
26
+ const baseContentDir = resolvePath(config.contentDir || "content");
23
27
  for (const entry of entries) {
24
28
  const collectionId = entry.collection_id;
25
29
  const slug = entry.slug;
26
- const dir = `${config.contentDir}/${collectionId}`;
30
+ const safeCollectionId = String(collectionId || "").replace(/[^a-zA-Z0-9_-]/g, "");
31
+ const safeSlug = String(slug || "").split("/").map((part) => part.replace(/[^a-zA-Z0-9_-]/g, "")).filter((part) => Boolean(part) && part !== ".." && part !== ".").join("/");
32
+ if (!safeCollectionId || !safeSlug) continue;
33
+ const dir = resolvePath(baseContentDir, safeCollectionId);
34
+ const filePath = resolvePath(dir, `${safeSlug}.md`);
35
+ if (!filePath.startsWith(baseContentDir)) continue;
27
36
  try {
28
- await mkdir(dir, { recursive: true });
37
+ await mkdir(dirname(filePath), { recursive: true });
29
38
  } catch {
30
39
  }
31
- const filePath = `${dir}/${slug}.md`;
32
40
  let metadata = {};
33
41
  try {
34
42
  metadata = JSON.parse(entry.metadata_json || "{}");
@@ -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,
@@ -17,15 +17,21 @@ export default defineEventHandler(async (event) => {
17
17
  }
18
18
  const auth = await getAuthContext(event);
19
19
  const config = getCMSConfig(event);
20
- const isEditor = auth?.user && (config.roles.some((r) => r === auth.role) || auth.isAdmin);
20
+ const isEditor = auth?.user && (!config.roles || Array.isArray(config.roles) && config.roles.some((r) => r === auth.role) || auth.isAdmin);
21
21
  const db = getD1Binding("DB", event);
22
22
  const conditions = [];
23
23
  const binds = [];
24
+ const VALID_STATUSES = /* @__PURE__ */ new Set(["published", "draft", "archived"]);
24
25
  if (!isEditor) {
25
26
  conditions.push("status = 'published'");
26
- } else if (query.status) {
27
- conditions.push("status = ?");
28
- binds.push(query.status);
27
+ } else if (query.status && query.status !== "all") {
28
+ const rawStatus = String(query.status).toLowerCase();
29
+ if (VALID_STATUSES.has(rawStatus)) {
30
+ conditions.push("status = ?");
31
+ binds.push(rawStatus);
32
+ } else {
33
+ conditions.push("status = 'published'");
34
+ }
29
35
  }
30
36
  if (collection) {
31
37
  conditions.push("collection_id = ?");
@@ -3,7 +3,7 @@ import { getCMSConfig, seedCollectionsFromConfig, syncLocalContentFiles } from "
3
3
  import { requireAuth } from "../../utils/context.mjs";
4
4
  export default defineEventHandler(async (event) => {
5
5
  const config = getCMSConfig(event);
6
- await requireAuth(event, { role: config.roles });
6
+ await requireAuth(event, config.roles ? { role: config.roles } : {});
7
7
  await seedCollectionsFromConfig(event, config.collections);
8
8
  const syncResult = await syncLocalContentFiles(
9
9
  event,
@@ -7,8 +7,8 @@ const CheckoutBodySchema = z.object({
7
7
  mode: z.enum(["subscription", "payment", "setup"]).optional(),
8
8
  trialDays: z.number().int().nonnegative().optional(),
9
9
  customerEmail: z.string().email().optional(),
10
- successUrl: z.string().url().optional(),
11
- cancelUrl: z.string().url().optional(),
10
+ successUrl: z.string().optional(),
11
+ cancelUrl: z.string().optional(),
12
12
  metadata: z.record(z.string(), z.string()).optional()
13
13
  });
14
14
  export default defineEventHandler(async (event) => {
@@ -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 { pauseSubscription } from "../../utils/payments.mjs";
4
+ const PauseBodySchema = 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) => PauseBodySchema.parse(b));
8
9
  return pauseSubscription(event, body.subscriptionId);
9
10
  });
@@ -2,7 +2,7 @@ import { defineEventHandler, readValidatedBody } from "nuxt/server";
2
2
  import { z } from "zod";
3
3
  import { createCustomerPortalSession } from "../../utils/payments.mjs";
4
4
  const PortalBodySchema = z.object({
5
- returnUrl: z.string().url().optional()
5
+ returnUrl: z.string().optional()
6
6
  });
7
7
  export default defineEventHandler(async (event) => {
8
8
  const body = await readValidatedBody(event, (b) => PortalBodySchema.parse(b));
@@ -1,18 +1,23 @@
1
- import { defineEventHandler, readBody, createError } from "nuxt/server";
1
+ import { defineEventHandler, readValidatedBody } from "nuxt/server";
2
+ import { z } from "zod";
2
3
  import { reportUsage } from "../../utils/payments.mjs";
4
+ const UsageBodySchema = z.object({
5
+ eventName: z.string().min(1, "eventName is required"),
6
+ quantity: z.number().int().positive().optional().default(1),
7
+ action: z.enum(["increment", "set"]).optional().default("increment"),
8
+ userId: z.string().optional(),
9
+ orgId: z.string().optional(),
10
+ customerId: z.string().optional(),
11
+ subscriptionId: z.string().optional(),
12
+ metadata: z.record(z.string(), z.string()).optional(),
13
+ timestamp: z.number().int().positive().optional()
14
+ });
3
15
  export default defineEventHandler(async (event) => {
4
- const body = await readBody(event);
5
- if (!body || !body.eventName) {
6
- throw createError({
7
- statusCode: 400,
8
- statusMessage: "Bad Request",
9
- message: "Missing required property: eventName"
10
- });
11
- }
16
+ const body = await readValidatedBody(event, (b) => UsageBodySchema.parse(b));
12
17
  const result = await reportUsage(event, {
13
18
  eventName: body.eventName,
14
- quantity: typeof body.quantity === "number" ? body.quantity : 1,
15
- action: body.action || "increment",
19
+ quantity: body.quantity,
20
+ action: body.action,
16
21
  userId: body.userId,
17
22
  orgId: body.orgId,
18
23
  customerId: body.customerId,
@@ -5,6 +5,7 @@
5
5
  declare const _default: import("nuxt/server").EventHandler<Promise<{
6
6
  success: boolean;
7
7
  eventType?: string;
8
+ error?: string;
8
9
  received: boolean;
9
10
  } | {
10
11
  received: true;
@@ -21,8 +21,11 @@ export async function queryAnalytics(sql, options = {}) {
21
21
  const env = getCloudflareEnv();
22
22
  const accountId = options.accountId || env.CLOUDFLARE_ACCOUNT_ID || env.CF_ACCOUNT_ID || process.env.CLOUDFLARE_ACCOUNT_ID || process.env.CF_ACCOUNT_ID;
23
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
+ );
24
27
  if (!accountId || !apiToken) {
25
- if (process.env.NODE_ENV !== "production") {
28
+ if (isDev) {
26
29
  return [];
27
30
  }
28
31
  throw new Error(
@@ -41,11 +44,11 @@ export async function queryAnalytics(sql, options = {}) {
41
44
  body: sql
42
45
  });
43
46
  } catch (err) {
44
- if (process.env.NODE_ENV !== "production") return [];
47
+ if (isDev) return [];
45
48
  throw new Error(`[qarpeo/analytics] Network error querying AE SQL API: ${err.message}`);
46
49
  }
47
50
  if (!res.ok) {
48
- if (process.env.NODE_ENV !== "production") return [];
51
+ if (isDev) return [];
49
52
  const body = await res.text().catch(() => "");
50
53
  throw new Error(`[qarpeo/analytics] AE SQL API error ${res.status}: ${body}`);
51
54
  }
@@ -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);
@@ -180,6 +180,7 @@ export async function sendWhatsAppMessage(accessToken, phoneNumberId, to, text)
180
180
  "Content-Type": "application/json",
181
181
  Authorization: `Bearer ${accessToken}`
182
182
  },
183
+ signal: AbortSignal.timeout(8e3),
183
184
  body: JSON.stringify({
184
185
  messaging_product: "whatsapp",
185
186
  recipient_type: "individual",
@@ -1,14 +1,16 @@
1
1
  import { type RequestEvent } from "nuxt/server";
2
2
  import type { CMSOptions, CMSCollectionConfig, CMSGitHubConfig, CMSDeployTriggerConfig, CMSApprovalConfig } from "../../../../types";
3
+ import { nanoid } from "../crypto";
4
+ export { nanoid };
3
5
  export declare function getCMSDb(event?: RequestEvent): any;
4
- export declare function nanoid(size?: number): string;
5
- export declare function getCMSConfig(event?: RequestEvent): Omit<Required<CMSOptions>, "github" | "deploy" | "approval" | "exclude" | "webhookSecret"> & {
6
+ export declare function getCMSConfig(event?: RequestEvent): Omit<Required<CMSOptions>, "github" | "deploy" | "approval" | "exclude" | "webhookSecret" | "roles"> & {
6
7
  collections: Record<string, CMSCollectionConfig>;
7
8
  github?: CMSGitHubConfig;
8
9
  deploy?: CMSDeployTriggerConfig;
9
10
  approval?: boolean | CMSApprovalConfig;
10
11
  exclude?: string | string[];
11
12
  webhookSecret?: string;
13
+ roles: string[];
12
14
  };
13
15
  /**
14
16
  * Resolves the effective approval workflow configuration for a collection. Returns null if approval
@@ -1,5 +1,7 @@
1
1
  import { useRuntimeConfig } from "nuxt/server";
2
2
  import { getD1Binding } from "../../../db.mjs";
3
+ import { nanoid } from "../crypto.mjs";
4
+ export { nanoid };
3
5
  export function getCMSDb(event) {
4
6
  try {
5
7
  return getD1Binding("DB", event);
@@ -7,11 +9,6 @@ export function getCMSDb(event) {
7
9
  return null;
8
10
  }
9
11
  }
10
- export function nanoid(size = 21) {
11
- const chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
12
- const bytes = crypto.getRandomValues(new Uint8Array(size));
13
- return Array.from(bytes, (b) => chars[b % chars.length]).join("");
14
- }
15
12
  export function getCMSConfig(event) {
16
13
  const rc = useRuntimeConfig(event);
17
14
  const cfg = rc?.qarpeo?.cms || {};
@@ -93,7 +93,7 @@ export async function syncEntryToGit(event, collectionId, entry, action) {
93
93
  try {
94
94
  const checkRes = await fetch(
95
95
  `https://api.github.com/repos/${owner}/${repoName}/contents/${gitPath}?ref=${baseBranch}`,
96
- { headers }
96
+ { headers, signal: AbortSignal.timeout(1e4) }
97
97
  );
98
98
  if (checkRes.ok) {
99
99
  const checkData = await checkRes.json();
@@ -107,7 +107,7 @@ export async function syncEntryToGit(event, collectionId, entry, action) {
107
107
  try {
108
108
  const refRes = await fetch(
109
109
  `https://api.github.com/repos/${owner}/${repoName}/git/ref/heads/${ghConfig.prBase || baseBranch}`,
110
- { headers }
110
+ { headers, signal: AbortSignal.timeout(1e4) }
111
111
  );
112
112
  if (refRes.ok) {
113
113
  const refData = await refRes.json();
@@ -118,6 +118,7 @@ export async function syncEntryToGit(event, collectionId, entry, action) {
118
118
  {
119
119
  method: "POST",
120
120
  headers,
121
+ signal: AbortSignal.timeout(1e4),
121
122
  body: JSON.stringify({
122
123
  ref: `refs/heads/${newBranch}`,
123
124
  sha: baseSha
@@ -139,6 +140,7 @@ export async function syncEntryToGit(event, collectionId, entry, action) {
139
140
  {
140
141
  method: "DELETE",
141
142
  headers,
143
+ signal: AbortSignal.timeout(1e4),
142
144
  body: JSON.stringify({
143
145
  message: commitMsg,
144
146
  sha: existingSha,
@@ -161,6 +163,7 @@ export async function syncEntryToGit(event, collectionId, entry, action) {
161
163
  {
162
164
  method: "PUT",
163
165
  headers,
166
+ signal: AbortSignal.timeout(1e4),
164
167
  body: JSON.stringify({
165
168
  message: commitMsg,
166
169
  content: base64Content,
@@ -185,6 +188,7 @@ export async function syncEntryToGit(event, collectionId, entry, action) {
185
188
  const prRes = await fetch(`https://api.github.com/repos/${owner}/${repoName}/pulls`, {
186
189
  method: "POST",
187
190
  headers,
191
+ signal: AbortSignal.timeout(1e4),
188
192
  body: JSON.stringify({
189
193
  title: commitMsg,
190
194
  head: targetBranch,
@@ -39,7 +39,7 @@ export async function fireCMSWebhooks(config, collectionId, event, entry) {
39
39
  console.warn("[qarpeo] webhook signature error:", e);
40
40
  }
41
41
  }
42
- fetch(hook.url, { method: "POST", headers, body: bodyStr }).catch((e) => {
42
+ fetch(hook.url, { method: "POST", headers, body: bodyStr, signal: AbortSignal.timeout(8e3) }).catch((e) => {
43
43
  console.warn(`[qarpeo] webhook POST to ${hook.url} failed:`, e);
44
44
  });
45
45
  }
@@ -51,7 +51,7 @@ export async function fireCMSDeployTrigger(config, collectionId, _event) {
51
51
  const trigger = deploy.trigger ?? "on-publish";
52
52
  if (trigger !== "on-publish") return;
53
53
  if (deploy.hookUrl) {
54
- fetch(deploy.hookUrl, { method: "POST" }).catch((e) => {
54
+ fetch(deploy.hookUrl, { method: "POST", signal: AbortSignal.timeout(8e3) }).catch((e) => {
55
55
  console.warn("[qarpeo] deploy hook POST failed:", e);
56
56
  });
57
57
  }
@@ -72,6 +72,7 @@ export async function fireCMSDeployTrigger(config, collectionId, _event) {
72
72
  "Content-Type": "application/json",
73
73
  "User-Agent": "qarpeo-cms"
74
74
  },
75
+ signal: AbortSignal.timeout(8e3),
75
76
  body: JSON.stringify({ ref })
76
77
  }).catch((e) => {
77
78
  console.warn("[qarpeo] GitHub workflow dispatch failed:", e);
@@ -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",
@@ -3002,7 +3002,9 @@ export function queryCollection(event, collection) {
3002
3002
  return builder;
3003
3003
  },
3004
3004
  order(field, direction = "ASC") {
3005
- _sort = `${field}:${direction.toLowerCase()}`;
3005
+ const sanitizedField = String(field || "").replace(/[^a-zA-Z0-9_]/g, "");
3006
+ const dir = String(direction).trim().toUpperCase() === "DESC" ? "desc" : "asc";
3007
+ _sort = `${sanitizedField || "published_at"}:${dir}`;
3006
3008
  return builder;
3007
3009
  },
3008
3010
  where(field, value) {
@@ -52,8 +52,10 @@ export function getSessionSecret(event, fallback) {
52
52
  if (fallback && fallback !== "qarpeo-storage-secret-key-salt") {
53
53
  return fallback;
54
54
  }
55
- const isProd = globalThis.process?.env?.NODE_ENV === "production";
56
- if (isProd) {
55
+ const isDevOrTest = Boolean(
56
+ import.meta.dev || globalThis.process?.env?.NODE_ENV === "development" || globalThis.process?.env?.NODE_ENV === "test" || env.NODE_ENV === "development"
57
+ );
58
+ if (!isDevOrTest) {
57
59
  throw new Error(
58
60
  "[qarpeo] Missing required secret: NUXT_APP_SECRET or NUXT_SESSION_PASSWORD must be configured in production for secure token and signature generation."
59
61
  );
@@ -9,6 +9,8 @@ import type { RequestEvent } from "nuxt/server";
9
9
  export declare function timingSafeEqualString(a: string, b: string): boolean;
10
10
  /** Alias for timingSafeEqualString */
11
11
  export declare const constantTimeEqual: typeof timingSafeEqualString;
12
+ /** Generates a cryptographically secure URL-friendly unique identifier using Web Crypto. */
13
+ export declare function nanoid(size?: number): string;
12
14
  /**
13
15
  * Encrypts a sensitive string (e.g. an OAuth access/refresh token) with AES-256-GCM. The returned
14
16
  * value is prefixed with `enc:` followed by the hex-encoded `iv ‖ ciphertext` so legacy plaintext
@@ -1,3 +1,4 @@
1
+ import { getSessionSecret } from "./config.mjs";
1
2
  export function timingSafeEqualString(a, b) {
2
3
  if (typeof a !== "string" || typeof b !== "string") return false;
3
4
  const encoder = new TextEncoder();
@@ -16,12 +17,19 @@ export function timingSafeEqualString(a, b) {
16
17
  return diff === 0;
17
18
  }
18
19
  export const constantTimeEqual = timingSafeEqualString;
20
+ const NANOID_CHARS = "useandom-26T198340PX75pxJACKVERYMINDBUSHWOLFGQZbfghjklqvwyzrict";
21
+ export function nanoid(size = 21) {
22
+ const bytes = new Uint8Array(size);
23
+ crypto.getRandomValues(bytes);
24
+ let id = "";
25
+ for (let i = 0; i < size; i++) {
26
+ id += NANOID_CHARS[bytes[i] & 63];
27
+ }
28
+ return id;
29
+ }
19
30
  const ENC_PREFIX = "enc:";
20
31
  function resolveTokenSecret(event) {
21
- const ev = event;
22
- return ev?.context?.cloudflare?.env?.NUXT_APP_SECRET || globalThis.process?.env?.NUXT_APP_SECRET || ev?.context?.cloudflare?.env?.NUXT_SESSION_PASSWORD || globalThis.process?.env?.NUXT_SESSION_PASSWORD || // Dev-only fallback — in production NUXT_APP_SECRET must be set
23
- // (enforced by the auth startup guard in serverAuth())
24
- "qarpeo-auth-internal-dev-salt-key-32b";
32
+ return getSessionSecret(event);
25
33
  }
26
34
  async function deriveAesGcmKey(password, usage) {
27
35
  const encoder = new TextEncoder();
@@ -83,7 +83,8 @@ async function callCloudflareHostnamesApi(endpoint, method, body, config) {
83
83
  };
84
84
  const reqInit = {
85
85
  method,
86
- headers
86
+ headers,
87
+ signal: AbortSignal.timeout(1e4)
87
88
  };
88
89
  if (method !== "GET" && body) {
89
90
  reqInit.body = JSON.stringify(body);
@@ -139,15 +140,19 @@ export async function registerCustomDomain(tenantId, rawDomain, options = {}, ev
139
140
  value: cfResult.ownership_verification.value
140
141
  });
141
142
  } else if (!cfResult) {
143
+ const tokenBytes = new Uint8Array(16);
144
+ crypto.getRandomValues(tokenBytes);
145
+ const tokenHex = Array.from(tokenBytes, (b) => b.toString(16).padStart(2, "0")).join("");
142
146
  verificationRecords.push({
143
147
  type: "txt",
144
148
  name: `_cf-custom-hostname.${domain}`,
145
- value: `qarpeo-verify-${Math.random().toString(36).slice(2, 10)}`
149
+ value: `qarpeo-verify-${tokenHex}`
146
150
  });
147
151
  }
148
152
  const now = Date.now();
153
+ const randomSuffix = crypto.randomUUID().slice(0, 8);
149
154
  const record = {
150
- id: cfResult?.id || `dom_${now}_${Math.random().toString(36).slice(2, 8)}`,
155
+ id: cfResult?.id || `dom_${now}_${randomSuffix}`,
151
156
  tenantId,
152
157
  domain,
153
158
  status: cfResult?.status || "pending",
@@ -71,6 +71,7 @@ export async function deliverMailDirect(options, event) {
71
71
  }
72
72
  const res = await fetch("https://api.resend.com/emails", {
73
73
  method: "POST",
74
+ signal: AbortSignal.timeout(8e3),
74
75
  headers: {
75
76
  Authorization: `Bearer ${apiKey}`,
76
77
  "Content-Type": "application/json"
@@ -101,6 +102,7 @@ export async function deliverMailDirect(options, event) {
101
102
  }
102
103
  const res = await fetch("https://api.postmarkapp.com/email", {
103
104
  method: "POST",
105
+ signal: AbortSignal.timeout(8e3),
104
106
  headers: {
105
107
  "X-Postmark-Server-Token": apiKey,
106
108
  "Content-Type": "application/json"
@@ -1,5 +1,6 @@
1
1
  import { getCloudflareEnv } from "../../bindings.mjs";
2
2
  import { sendMail } from "./mail.mjs";
3
+ import { nanoid } from "./crypto.mjs";
3
4
  import { signVapidHeader, encryptWebPushPayload } from "./vapid.mjs";
4
5
  function getD1(event) {
5
6
  const env = getCloudflareEnv(event);
@@ -14,9 +15,6 @@ function getTable() {
14
15
  function getPushTable() {
15
16
  return "_qarpeo_push_subscriptions";
16
17
  }
17
- function nanoid() {
18
- return crypto.randomUUID().replace(/-/g, "");
19
- }
20
18
  function parseChannels(raw) {
21
19
  try {
22
20
  return JSON.parse(raw);
@@ -17,7 +17,13 @@ export async function sendOTPCode(event, email, options = {}) {
17
17
  }).catch((err) => {
18
18
  if (err?.statusCode === 429) throw err;
19
19
  });
20
- const code = Math.floor(1e5 + Math.random() * 9e5).toString();
20
+ const buf = new Uint32Array(1);
21
+ const maxRange = 9e5;
22
+ const limit = Math.floor(4294967295 / maxRange) * maxRange;
23
+ do {
24
+ crypto.getRandomValues(buf);
25
+ } while (buf[0] >= limit);
26
+ const code = (1e5 + buf[0] % maxRange).toString();
21
27
  const codeHash = await hashSessionToken(code);
22
28
  const authConfig = getQarpeoConfig(event).auth;
23
29
  const otpCfg = typeof authConfig.passwordless?.otp === "object" ? authConfig.passwordless.otp : void 0;
@@ -17,6 +17,7 @@ export declare function verifyPaddleSignature(rawBody: string, signatureHeader:
17
17
  export declare function processPaymentWebhook(event: RequestEvent, rawBody: string): Promise<{
18
18
  success: boolean;
19
19
  eventType?: string;
20
+ error?: string;
20
21
  } | {
21
22
  received: true;
22
23
  skipped: true;
@@ -3,16 +3,12 @@ import { createError, useRuntimeConfig, getRequestHeader } from "nuxt/server";
3
3
  import { getD1Binding } from "../../db.mjs";
4
4
  import { getQarpeoConfig } from "./config.mjs";
5
5
  import { getAuthContext } from "./context.mjs";
6
+ import { nanoid } from "./crypto.mjs";
6
7
  const STRIPE_API_VERSION = "2024-06-20";
7
8
  function getPaymentsDb(event) {
8
9
  const bindingName = globalThis.process?.env?.QARPEO_DEFAULT_DB_BINDING || "DB";
9
10
  return getD1Binding(bindingName, event);
10
11
  }
11
- function nanoid(size = 21) {
12
- const chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
13
- const bytes = crypto.getRandomValues(new Uint8Array(size));
14
- return Array.from(bytes, (b) => chars[b % chars.length]).join("");
15
- }
16
12
  export function getPaymentsConfig(event) {
17
13
  const cfg = getQarpeoConfig(event).payments || {};
18
14
  const cfEnv = event?.context?.cloudflare?.env || globalThis.__qarpeo_env__ || {};
@@ -208,11 +204,8 @@ export async function processPaymentWebhook(event, rawBody) {
208
204
  isValid = await verifyPolarSignature(rawBody, sig, config.webhookSecret);
209
205
  }
210
206
  if (!isValid) {
211
- throw createError({
212
- statusCode: 400,
213
- statusMessage: "Bad Request",
214
- message: "Invalid webhook signature"
215
- });
207
+ console.warn(`[qarpeo:payments] Invalid webhook signature from provider: ${provider}`);
208
+ return { success: false, error: "invalid_signature" };
216
209
  }
217
210
  let payload;
218
211
  try {
@@ -585,8 +578,16 @@ export async function createCheckoutSession(event, options) {
585
578
  });
586
579
  }
587
580
  const siteUrl = useRuntimeConfig().public?.siteUrl || "http://localhost:3000";
588
- const successUrl = options.successUrl || config.checkoutUrls?.success || `${siteUrl}/?checkout=success`;
589
- const cancelUrl = options.cancelUrl || config.checkoutUrls?.cancel || `${siteUrl}/?checkout=cancelled`;
581
+ const successUrl = safeReturnUrl(
582
+ options.successUrl || config.checkoutUrls?.success,
583
+ siteUrl,
584
+ "/?checkout=success"
585
+ );
586
+ const cancelUrl = safeReturnUrl(
587
+ options.cancelUrl || config.checkoutUrls?.cancel,
588
+ siteUrl,
589
+ "/?checkout=cancelled"
590
+ );
590
591
  const metadata = {
591
592
  planId,
592
593
  ...options.metadata
@@ -633,6 +634,7 @@ export async function createCheckoutSession(event, options) {
633
634
  }
634
635
  const res = await fetch("https://api.stripe.com/v1/checkout/sessions", {
635
636
  method: "POST",
637
+ signal: AbortSignal.timeout(1e4),
636
638
  headers: {
637
639
  Authorization: `Bearer ${config.secretKey}`,
638
640
  "Content-Type": "application/x-www-form-urlencoded",
@@ -653,6 +655,25 @@ export async function createCheckoutSession(event, options) {
653
655
  message: `Checkout not implemented for provider ${config.provider}`
654
656
  });
655
657
  }
658
+ function safeReturnUrl(url, siteUrl, fallbackPath = "/") {
659
+ const cleanSiteUrl = siteUrl.replace(/\/+$/, "");
660
+ const fallback = `${cleanSiteUrl}${fallbackPath.startsWith("/") ? fallbackPath : "/" + fallbackPath}`;
661
+ if (typeof url !== "string" || !url.trim()) return fallback;
662
+ const trimmed = url.trim();
663
+ if (trimmed.startsWith("/") && !trimmed.startsWith("//") && !trimmed.startsWith("/\\") && !trimmed.startsWith("\\")) {
664
+ if (/[\r\n\0]/.test(trimmed)) return fallback;
665
+ return `${cleanSiteUrl}${trimmed}`;
666
+ }
667
+ try {
668
+ const parsed = new URL(trimmed);
669
+ const site = new URL(cleanSiteUrl);
670
+ if (parsed.origin === site.origin) {
671
+ return parsed.toString();
672
+ }
673
+ } catch {
674
+ }
675
+ return fallback;
676
+ }
656
677
  export async function createCustomerPortalSession(event, options) {
657
678
  await ensurePaymentsTables(event);
658
679
  const db = getPaymentsDb(event);
@@ -670,13 +691,14 @@ export async function createCustomerPortalSession(event, options) {
670
691
  throw createError({ statusCode: 404, message: "No customer account found for this user" });
671
692
  }
672
693
  const siteUrl = useRuntimeConfig().public?.siteUrl || "http://localhost:3000";
673
- const returnUrl = options?.returnUrl || config.portalReturnUrl || siteUrl;
694
+ const returnUrl = safeReturnUrl(options?.returnUrl || config.portalReturnUrl, siteUrl, "/");
674
695
  if (config.provider === "stripe") {
675
696
  const params = new URLSearchParams();
676
697
  params.set("customer", cust.customer_id);
677
698
  params.set("return_url", returnUrl);
678
699
  const res = await fetch("https://api.stripe.com/v1/billing_portal/sessions", {
679
700
  method: "POST",
701
+ signal: AbortSignal.timeout(1e4),
680
702
  headers: {
681
703
  Authorization: `Bearer ${config.secretKey}`,
682
704
  "Content-Type": "application/x-www-form-urlencoded",
@@ -720,6 +742,7 @@ export async function cancelSubscription(event, subscriptionId) {
720
742
  params.set("cancel_at_period_end", "true");
721
743
  const res = await fetch(`https://api.stripe.com/v1/subscriptions/${subscriptionId}`, {
722
744
  method: "POST",
745
+ signal: AbortSignal.timeout(1e4),
723
746
  headers: {
724
747
  Authorization: `Bearer ${config.secretKey}`,
725
748
  "Content-Type": "application/x-www-form-urlencoded",
@@ -762,6 +785,7 @@ export async function pauseSubscription(event, subscriptionId) {
762
785
  params.set("pause_collection[resumes_at]", "");
763
786
  const res = await fetch(`https://api.stripe.com/v1/subscriptions/${subscriptionId}`, {
764
787
  method: "POST",
788
+ signal: AbortSignal.timeout(1e4),
765
789
  headers: {
766
790
  Authorization: `Bearer ${config.secretKey}`,
767
791
  "Content-Type": "application/x-www-form-urlencoded",
@@ -804,6 +828,7 @@ export async function changePlan(event, subscriptionId, newPriceId) {
804
828
  }
805
829
  const getRes = await fetch(`https://api.stripe.com/v1/subscriptions/${subscriptionId}`, {
806
830
  method: "GET",
831
+ signal: AbortSignal.timeout(1e4),
807
832
  headers: {
808
833
  Authorization: `Bearer ${config.secretKey}`,
809
834
  "Stripe-Version": STRIPE_API_VERSION
@@ -827,6 +852,7 @@ export async function changePlan(event, subscriptionId, newPriceId) {
827
852
  params.set("proration_behavior", "create_prorations");
828
853
  const res = await fetch(`https://api.stripe.com/v1/subscriptions/${subscriptionId}`, {
829
854
  method: "POST",
855
+ signal: AbortSignal.timeout(1e4),
830
856
  headers: {
831
857
  Authorization: `Bearer ${config.secretKey}`,
832
858
  "Content-Type": "application/x-www-form-urlencoded",
@@ -989,6 +1015,7 @@ export async function reportUsage(event, options) {
989
1015
  params.set("timestamp", String(Math.floor(timestamp / 1e3)));
990
1016
  const res = await fetch("https://api.stripe.com/v1/billing/meter_events", {
991
1017
  method: "POST",
1018
+ signal: AbortSignal.timeout(1e4),
992
1019
  headers: {
993
1020
  Authorization: `Bearer ${config.secretKey}`,
994
1021
  "Content-Type": "application/x-www-form-urlencoded",
@@ -7,17 +7,69 @@ function pemToDer(pem) {
7
7
  for (let i = 0; i < binary.length; i++) view[i] = binary.charCodeAt(i);
8
8
  return buf;
9
9
  }
10
+ function parseAsn1Length(bytes, offset) {
11
+ const first = bytes[offset];
12
+ if (first === void 0) return { len: 0, headerLen: 0 };
13
+ if ((first & 128) === 0) {
14
+ return { len: first, headerLen: 1 };
15
+ }
16
+ const numOctets = first & 127;
17
+ let len = 0;
18
+ for (let i = 0; i < numOctets; i++) {
19
+ len = len << 8 | (bytes[offset + 1 + i] || 0);
20
+ }
21
+ return { len, headerLen: 1 + numOctets };
22
+ }
23
+ function extractSpkiFromX509Der(derBuf) {
24
+ try {
25
+ const bytes = new Uint8Array(derBuf);
26
+ if (bytes[0] !== 48) return null;
27
+ const outer = parseAsn1Length(bytes, 1);
28
+ let pos = 1 + outer.headerLen;
29
+ if (bytes[pos] !== 48) return null;
30
+ const tbs = parseAsn1Length(bytes, pos + 1);
31
+ pos = pos + 1 + tbs.headerLen;
32
+ if (bytes[pos] === 160) {
33
+ const v = parseAsn1Length(bytes, pos + 1);
34
+ pos += 1 + v.headerLen + v.len;
35
+ }
36
+ if (bytes[pos] === 2) {
37
+ const s = parseAsn1Length(bytes, pos + 1);
38
+ pos += 1 + s.headerLen + s.len;
39
+ }
40
+ if (bytes[pos] === 48) {
41
+ const a = parseAsn1Length(bytes, pos + 1);
42
+ pos += 1 + a.headerLen + a.len;
43
+ }
44
+ if (bytes[pos] === 48) {
45
+ const iss = parseAsn1Length(bytes, pos + 1);
46
+ pos += 1 + iss.headerLen + iss.len;
47
+ }
48
+ if (bytes[pos] === 48) {
49
+ const val = parseAsn1Length(bytes, pos + 1);
50
+ pos += 1 + val.headerLen + val.len;
51
+ }
52
+ if (bytes[pos] === 48) {
53
+ const sub = parseAsn1Length(bytes, pos + 1);
54
+ pos += 1 + sub.headerLen + sub.len;
55
+ }
56
+ if (bytes[pos] === 48) {
57
+ const spki = parseAsn1Length(bytes, pos + 1);
58
+ const spkiTotal = 1 + spki.headerLen + spki.len;
59
+ return bytes.slice(pos, pos + spkiTotal).buffer;
60
+ }
61
+ } catch {
62
+ }
63
+ return null;
64
+ }
10
65
  async function importCertPublicKey(certPem) {
11
66
  try {
12
- const normalized = certPem.includes("BEGIN") ? certPem : `-----BEGIN CERTIFICATE-----
13
- ${certPem}
14
- -----END CERTIFICATE-----`;
15
- const der = pemToDer(normalized);
16
- const cert = await crypto.subtle.importKey("raw", der, { name: "RSASSA-PKCS1-v1_5", hash: "SHA-256" }, false, ["verify"]).catch(() => null);
17
- if (cert) return cert;
67
+ const der = pemToDer(certPem);
68
+ const spki = extractSpkiFromX509Der(der);
69
+ const keyDer = spki || der;
18
70
  return await crypto.subtle.importKey(
19
71
  "spki",
20
- der,
72
+ keyDer,
21
73
  { name: "RSASSA-PKCS1-v1_5", hash: "SHA-256" },
22
74
  false,
23
75
  ["verify"]
@@ -155,7 +207,8 @@ export async function exchangeOIDCCode(options) {
155
207
  const tokenRes = await fetch(options.tokenUrl, {
156
208
  method: "POST",
157
209
  headers: { "Content-Type": "application/x-www-form-urlencoded" },
158
- body: body.toString()
210
+ body: body.toString(),
211
+ signal: AbortSignal.timeout(8e3)
159
212
  });
160
213
  if (!tokenRes.ok) {
161
214
  const errText = await tokenRes.text();
@@ -170,7 +223,8 @@ export async function exchangeOIDCCode(options) {
170
223
  let profileData = {};
171
224
  if (options.userinfoUrl && accessToken) {
172
225
  const userinfoRes = await fetch(options.userinfoUrl, {
173
- headers: { Authorization: `Bearer ${accessToken}` }
226
+ headers: { Authorization: `Bearer ${accessToken}` },
227
+ signal: AbortSignal.timeout(8e3)
174
228
  });
175
229
  if (userinfoRes.ok) {
176
230
  profileData = await userinfoRes.json();
@@ -4,3 +4,8 @@ export declare function slugify(text: string): string;
4
4
  export declare function escapeHtml(str: string): string;
5
5
  /** Sanitizes a URL to prevent javascript: or data: injection. */
6
6
  export declare function sanitizeUrl(url: string): string;
7
+ /**
8
+ * Validates a redirect URL to ensure it is a safe local/relative path, preventing open redirect
9
+ * phishing attacks (e.g. `//evil.com`, `https://evil.com`, `/\evil.com`).
10
+ */
11
+ export declare function safeRedirect(url: unknown, fallback?: string): string;
@@ -12,3 +12,13 @@ export function sanitizeUrl(url) {
12
12
  }
13
13
  return "#";
14
14
  }
15
+ export function safeRedirect(url, fallback = "/") {
16
+ if (typeof url !== "string") return fallback;
17
+ const trimmed = url.trim();
18
+ if (!trimmed) return fallback;
19
+ if (trimmed.startsWith("/") && !trimmed.startsWith("//") && !trimmed.startsWith("/\\") && !trimmed.startsWith("\\")) {
20
+ if (/[\r\n\0]/.test(trimmed)) return fallback;
21
+ return trimmed;
22
+ }
23
+ return fallback;
24
+ }
@@ -13,9 +13,13 @@ export async function verifyTurnstileToken(event, token, remoteIp) {
13
13
  }
14
14
  const authConfig = getQarpeoConfig(event).auth || {};
15
15
  const turnstileConfig = typeof authConfig.turnstile === "object" ? authConfig.turnstile : {};
16
- const secretKey = globalThis.process?.env?.NUXT_TURNSTILE_SECRET_KEY || globalThis.process?.env?.TURNSTILE_SECRET_KEY || turnstileConfig.secretKey;
16
+ const cfEnv = event?.context?.cloudflare?.env;
17
+ const secretKey = cfEnv?.NUXT_TURNSTILE_SECRET_KEY || cfEnv?.TURNSTILE_SECRET_KEY || globalThis.process?.env?.NUXT_TURNSTILE_SECRET_KEY || globalThis.process?.env?.TURNSTILE_SECRET_KEY || turnstileConfig.secretKey;
17
18
  if (!secretKey) {
18
- if (globalThis.process?.env?.NODE_ENV !== "production") {
19
+ const isDev = Boolean(
20
+ import.meta.dev || globalThis.process?.env?.NODE_ENV === "development" || globalThis.process?.env?.NODE_ENV === "test" || cfEnv?.NODE_ENV === "development"
21
+ );
22
+ if (isDev) {
19
23
  console.warn(
20
24
  "[qarpeo:turnstile] NUXT_TURNSTILE_SECRET_KEY is not set. Allowing request in development mode."
21
25
  );
@@ -36,7 +40,8 @@ export async function verifyTurnstileToken(event, token, remoteIp) {
36
40
  try {
37
41
  const res = await fetch("https://challenges.cloudflare.com/turnstile/v0/siteverify", {
38
42
  method: "POST",
39
- body: formData
43
+ body: formData,
44
+ signal: AbortSignal.timeout(8e3)
40
45
  });
41
46
  const outcome = await res.json();
42
47
  return {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "qarpeo",
3
- "version": "0.1.29",
3
+ "version": "0.1.31",
4
4
  "description": "Zero-config Cloudflare Edge Platform for Nuxt",
5
5
  "keywords": [
6
6
  "analytics-engine",