qarpeo 0.1.28 → 0.1.29

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 (40) 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/cms/webhooks/[provider].post.mjs +2 -1
  16. package/dist/runtime/server/routes/notifications/push/subscribe.post.mjs +10 -5
  17. package/dist/runtime/server/routes/notifications/push/unsubscribe.post.mjs +6 -5
  18. package/dist/runtime/server/routes/payments/cancel.post.mjs +6 -5
  19. package/dist/runtime/server/routes/payments/change-plan.post.mjs +7 -8
  20. package/dist/runtime/server/routes/payments/checkout.post.mjs +13 -2
  21. package/dist/runtime/server/routes/payments/portal.post.mjs +6 -2
  22. package/dist/runtime/server/utils/analytics-query.mjs +9 -4
  23. package/dist/runtime/server/utils/config.d.ts +1 -1
  24. package/dist/runtime/server/utils/config.mjs +26 -2
  25. package/dist/runtime/server/utils/crypto.d.ts +7 -1
  26. package/dist/runtime/server/utils/crypto.mjs +27 -5
  27. package/dist/runtime/server/utils/domains.mjs +2 -2
  28. package/dist/runtime/server/utils/notifications.mjs +6 -4
  29. package/dist/runtime/server/utils/organization.d.ts +2 -1
  30. package/dist/runtime/server/utils/organization.mjs +18 -11
  31. package/dist/runtime/server/utils/passwordless.mjs +30 -14
  32. package/dist/runtime/server/utils/payments.mjs +7 -7
  33. package/dist/runtime/server/utils/ratelimit.mjs +34 -11
  34. package/dist/runtime/server/utils/string.d.ts +6 -0
  35. package/dist/runtime/server/utils/string.mjs +14 -0
  36. package/dist/runtime/server/utils/tracker.d.ts +4 -4
  37. package/dist/runtime/server/utils/tracker.mjs +13 -11
  38. package/dist/runtime/server.d.ts +4 -2
  39. package/dist/runtime/server.mjs +1 -0
  40. 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.29";
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,
@@ -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,8 +18,9 @@ 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;
19
24
  if (!accountId || !apiToken) {
20
25
  if (process.env.NODE_ENV !== "production") {
21
26
  return [];
@@ -49,7 +54,7 @@ export async function queryAnalytics(sql, options = {}) {
49
54
  }
50
55
  export function useAnalyticsDashboard(options = {}) {
51
56
  const dataset = options.dataset || process.env.QARPEO_ANALYTICS_DATASET || "analytics";
52
- const siteFilter = options.siteId ? `AND index1 = '${options.siteId.replace(/'/g, "''")}'` : "";
57
+ const siteFilter = options.siteId ? `AND index1 = '${escapeAEString(options.siteId)}'` : "";
53
58
  const query = (sql) => queryAnalytics(sql, options);
54
59
  return {
55
60
  /**
@@ -186,7 +191,7 @@ export function useAnalyticsDashboard(options = {}) {
186
191
  */
187
192
  async events(name, limit = 20, range = "7d") {
188
193
  const interval = rangeToInterval(range);
189
- const nameFilter = name ? `AND blob1 = '${name.replace(/'/g, "''")}'` : "AND blob1 != 'pageview'";
194
+ const nameFilter = name ? `AND blob1 = '${escapeAEString(name)}'` : "AND blob1 != 'pageview'";
190
195
  const rows = await query(`
191
196
  SELECT
192
197
  blob1 AS name,
@@ -24,6 +24,6 @@ export declare function getQarpeoConfig(event?: RequestEvent): QarpeoRuntimeConf
24
24
  export declare const useQarpeoConfig: typeof getQarpeoConfig;
25
25
  /**
26
26
  * Returns the application secret (NUXT_APP_SECRET or legacy NUXT_SESSION_PASSWORD) from runtime
27
- * config. Used for HMAC signing where we need a root secret key but not qarpeo-specific config.
27
+ * config or Cloudflare bindings. Used for HMAC signing where we need a root secret key.
28
28
  */
29
29
  export declare function getSessionSecret(event?: RequestEvent, fallback?: string): string;
@@ -27,12 +27,36 @@ export function getQarpeoConfig(event) {
27
27
  };
28
28
  }
29
29
  export const useQarpeoConfig = getQarpeoConfig;
30
- export function getSessionSecret(event, fallback = "qarpeo-storage-secret-key-salt") {
30
+ let _ephemeralDevSecret;
31
+ function getEphemeralDevSecret() {
32
+ if (!_ephemeralDevSecret) {
33
+ _ephemeralDevSecret = "qarpeo_dev_" + Math.random().toString(36).slice(2) + Date.now().toString(36);
34
+ console.warn(
35
+ "[qarpeo] Warning: No NUXT_APP_SECRET or NUXT_SESSION_PASSWORD configured. Using ephemeral in-memory key for token signing."
36
+ );
37
+ }
38
+ return _ephemeralDevSecret;
39
+ }
40
+ export function getSessionSecret(event, fallback) {
31
41
  let rc;
32
42
  try {
33
43
  rc = useRuntimeConfig(event);
34
44
  } catch {
35
45
  rc = void 0;
36
46
  }
37
- return rc?.appSecret || rc?.session?.password || globalThis.__NUXT_RUNTIME_CONFIG__?.appSecret || globalThis.__NUXT_RUNTIME_CONFIG__?.session?.password || globalThis.process?.env?.NUXT_APP_SECRET || globalThis.process?.env?.NUXT_SESSION_PASSWORD || fallback;
47
+ const env = event?.context?.cloudflare?.env || globalThis.__qarpeo_env__ || {};
48
+ const secret = env.NUXT_APP_SECRET || env.APP_SECRET || env.NUXT_SESSION_PASSWORD || rc?.appSecret || rc?.session?.password || globalThis.__NUXT_RUNTIME_CONFIG__?.appSecret || globalThis.__NUXT_RUNTIME_CONFIG__?.session?.password || globalThis.process?.env?.NUXT_APP_SECRET || globalThis.process?.env?.NUXT_SESSION_PASSWORD;
49
+ if (secret) {
50
+ return secret;
51
+ }
52
+ if (fallback && fallback !== "qarpeo-storage-secret-key-salt") {
53
+ return fallback;
54
+ }
55
+ const isProd = globalThis.process?.env?.NODE_ENV === "production";
56
+ if (isProd) {
57
+ throw new Error(
58
+ "[qarpeo] Missing required secret: NUXT_APP_SECRET or NUXT_SESSION_PASSWORD must be configured in production for secure token and signature generation."
59
+ );
60
+ }
61
+ return getEphemeralDevSecret();
38
62
  }
@@ -1,5 +1,11 @@
1
1
  import type { RequestEvent } from "nuxt/server";
2
- /** Constant-time string equality check using byte-level XOR comparison to prevent timing attacks. */
2
+ /**
3
+ * Constant-time string equality check using byte-level XOR comparison to prevent timing attacks.
4
+ *
5
+ * Both strings are UTF-8 encoded into fixed-length buffers of `Math.max(lenA, lenB)` bytes before
6
+ * comparison so that length differences do not leak via early exit — a classic timing side-channel
7
+ * in naive implementations that return early on `a.length !== b.length`.
8
+ */
3
9
  export declare function timingSafeEqualString(a: string, b: string): boolean;
4
10
  /** Alias for timingSafeEqualString */
5
11
  export declare const constantTimeEqual: typeof timingSafeEqualString;
@@ -3,11 +3,16 @@ export function timingSafeEqualString(a, b) {
3
3
  const encoder = new TextEncoder();
4
4
  const bufA = encoder.encode(a);
5
5
  const bufB = encoder.encode(b);
6
- if (bufA.byteLength !== bufB.byteLength) return false;
6
+ const len = Math.max(bufA.byteLength, bufB.byteLength);
7
+ const padA = new Uint8Array(len);
8
+ const padB = new Uint8Array(len);
9
+ padA.set(bufA);
10
+ padB.set(bufB);
7
11
  let diff = 0;
8
- for (let i = 0; i < bufA.byteLength; i++) {
9
- diff |= bufA[i] ^ bufB[i];
12
+ for (let i = 0; i < len; i++) {
13
+ diff |= padA[i] ^ padB[i];
10
14
  }
15
+ diff |= bufA.byteLength ^ bufB.byteLength;
11
16
  return diff === 0;
12
17
  }
13
18
  export const constantTimeEqual = timingSafeEqualString;
@@ -20,8 +25,25 @@ function resolveTokenSecret(event) {
20
25
  }
21
26
  async function deriveAesGcmKey(password, usage) {
22
27
  const encoder = new TextEncoder();
23
- const keyMaterial = await crypto.subtle.digest("SHA-256", encoder.encode(password));
24
- return crypto.subtle.importKey("raw", keyMaterial, { name: "AES-GCM" }, false, usage);
28
+ const keyMaterial = await crypto.subtle.importKey(
29
+ "raw",
30
+ encoder.encode(password),
31
+ { name: "HKDF" },
32
+ false,
33
+ ["deriveKey"]
34
+ );
35
+ return crypto.subtle.deriveKey(
36
+ {
37
+ name: "HKDF",
38
+ hash: "SHA-256",
39
+ salt: encoder.encode("qarpeo-token-encryption-v1"),
40
+ info: encoder.encode("AES-GCM-256")
41
+ },
42
+ keyMaterial,
43
+ { name: "AES-GCM", length: 256 },
44
+ false,
45
+ usage
46
+ );
25
47
  }
26
48
  export async function encryptToken(plaintext, event) {
27
49
  if (!plaintext) return "";
@@ -1,4 +1,5 @@
1
1
  import { getKVBinding } from "../../kv.mjs";
2
+ import { getQarpeoConfig } from "./config.mjs";
2
3
  const devDomainsStore = /* @__PURE__ */ new Map();
3
4
  const devCache = /* @__PURE__ */ new Map();
4
5
  export function normalizeDomain(input) {
@@ -18,8 +19,7 @@ export function isValidDomain(domain) {
18
19
  }
19
20
  export function getMultitenantConfig(event) {
20
21
  try {
21
- const rc = event?.context?.nitro?.runtimeConfig ?? event?.$config;
22
- return rc?.qarpeo?.multitenant || {};
22
+ return getQarpeoConfig(event).multitenant || {};
23
23
  } catch {
24
24
  return {};
25
25
  }
@@ -3,7 +3,8 @@ import { sendMail } from "./mail.mjs";
3
3
  import { signVapidHeader, encryptWebPushPayload } from "./vapid.mjs";
4
4
  function getD1(event) {
5
5
  const env = getCloudflareEnv(event);
6
- const db = env[process.env.QARPEO_DEFAULT_DB_BINDING || "DB"];
6
+ const bindingName = env.QARPEO_DEFAULT_DB_BINDING || process.env.QARPEO_DEFAULT_DB_BINDING || "DB";
7
+ const db = env[bindingName];
7
8
  if (!db) throw new Error("[qarpeo/notifications] D1 database binding not found");
8
9
  return db;
9
10
  }
@@ -170,9 +171,10 @@ export async function sendWebPush(userId, payload, event) {
170
171
  const table = getPushTable();
171
172
  const rows = await db.prepare(`SELECT * FROM ${table} WHERE user_id = ?`).bind(userId).all();
172
173
  if (!rows.results?.length) return;
173
- const vapidPublicKey = process.env.NUXT_VAPID_PUBLIC_KEY || process.env.VAPID_PUBLIC_KEY;
174
- const vapidPrivateKey = process.env.NUXT_VAPID_PRIVATE_KEY || process.env.VAPID_PRIVATE_KEY;
175
- const vapidSubject = process.env.NUXT_VAPID_SUBJECT || process.env.VAPID_SUBJECT || "mailto:push@qarpeo.com";
174
+ const env = getCloudflareEnv(event);
175
+ const vapidPublicKey = env.NUXT_VAPID_PUBLIC_KEY || env.VAPID_PUBLIC_KEY || process.env.NUXT_VAPID_PUBLIC_KEY || process.env.VAPID_PUBLIC_KEY;
176
+ const vapidPrivateKey = env.NUXT_VAPID_PRIVATE_KEY || env.VAPID_PRIVATE_KEY || process.env.NUXT_VAPID_PRIVATE_KEY || process.env.VAPID_PRIVATE_KEY;
177
+ const vapidSubject = env.NUXT_VAPID_SUBJECT || env.VAPID_SUBJECT || process.env.NUXT_VAPID_SUBJECT || process.env.VAPID_SUBJECT || "mailto:push@qarpeo.com";
176
178
  if (!vapidPublicKey || !vapidPrivateKey) {
177
179
  console.warn("[qarpeo/notifications] VAPID keys not configured \u2014 skipping web push");
178
180
  return;
@@ -1,6 +1,7 @@
1
1
  import { type RequestEvent } from "nuxt/server";
2
2
  import type { QarpeoOrganization, QarpeoMember } from "../../types/auth";
3
- export declare function slugify(text: string): string;
3
+ import { slugify } from "./string";
4
+ export { slugify };
4
5
  /** Creates a new organization with the current authenticated user as "owner". */
5
6
  export declare function createOrganization(event: RequestEvent, input: {
6
7
  name: string;
@@ -6,9 +6,8 @@ import { ensureAuthTables } from "./auth.mjs";
6
6
  import { getQarpeoConfig } from "./config.mjs";
7
7
  import { escapeHtml, sanitizeUrl } from "./email-templates.mjs";
8
8
  import { hashSessionToken, getAuthSession, setAuthSession } from "./session.mjs";
9
- export function slugify(text) {
10
- return text.toLowerCase().trim().replace(/[^\w\s-]/g, "").replace(/[\s_-]+/g, "-").replace(/^-+|-+$/g, "");
11
- }
9
+ import { slugify } from "./string.mjs";
10
+ export { slugify };
12
11
  function getD1(event) {
13
12
  const bindingName = globalThis.process?.env?.QARPEO_DEFAULT_DB_BINDING || "DB";
14
13
  return getD1Binding(bindingName, event);
@@ -191,18 +190,26 @@ export async function inviteOrganizationMember(event, input) {
191
190
  expiresAt,
192
191
  createdAt: now
193
192
  };
193
+ const nitroApp = useNitroApp();
194
+ const hasHook = Boolean(
195
+ nitroApp.hooks?.hasHooks?.("qarpeo:auth:organization:invite") || nitroApp.hooks?.hookMap?.["qarpeo:auth:organization:invite"]?.length
196
+ );
194
197
  let hookHandled = false;
195
- try {
196
- const nitroApp = useNitroApp();
197
- await nitroApp.hooks?.callHook("qarpeo:auth:organization:invite", {
198
+ if (hasHook) {
199
+ const payload = {
198
200
  organization: org,
199
201
  invitation,
200
- inviteUrl
201
- });
202
- hookHandled = true;
203
- } catch {
202
+ inviteUrl,
203
+ handled: true
204
+ };
205
+ try {
206
+ await nitroApp.hooks?.callHook("qarpeo:auth:organization:invite", payload);
207
+ hookHandled = payload.handled !== false;
208
+ } catch (err) {
209
+ console.warn("[qarpeo] Custom organization invite hook error:", err?.message || err);
210
+ }
204
211
  }
205
- if (!hookHandled || globalThis.process?.env?.NODE_ENV === "development") {
212
+ if (!hookHandled) {
206
213
  try {
207
214
  await sendEmail(
208
215
  {
@@ -37,17 +37,25 @@ export async function sendOTPCode(event, email, options = {}) {
37
37
  console.warn("[qarpeo] Failed to store OTP in KV:", err.message);
38
38
  }
39
39
  const nitroApp = useNitroApp();
40
+ const hasHook = Boolean(
41
+ nitroApp.hooks?.hasHooks?.("qarpeo:auth:otp:send") || nitroApp.hooks?.hookMap?.["qarpeo:auth:otp:send"]?.length
42
+ );
40
43
  let hookHandled = false;
41
- try {
42
- await nitroApp.hooks?.callHook("qarpeo:auth:otp:send", {
44
+ if (hasHook) {
45
+ const payload = {
43
46
  email: cleanEmail,
44
47
  code,
45
- type: "otp"
46
- });
47
- hookHandled = true;
48
- } catch {
48
+ type: "otp",
49
+ handled: true
50
+ };
51
+ try {
52
+ await nitroApp.hooks?.callHook("qarpeo:auth:otp:send", payload);
53
+ hookHandled = payload.handled !== false;
54
+ } catch (err) {
55
+ console.warn("[qarpeo] Custom OTP hook error:", err?.message || err);
56
+ }
49
57
  }
50
- if (!hookHandled || globalThis.process?.env?.NODE_ENV === "development") {
58
+ if (!hookHandled) {
51
59
  try {
52
60
  await sendEmail(
53
61
  {
@@ -135,16 +143,24 @@ export async function sendMagicLink(event, email, options = {}) {
135
143
  const authPrefix = authConfig.prefix || "/api/auth";
136
144
  const url = `${origin}${authPrefix}/magic-link/verify?token=${token}`;
137
145
  const nitroApp = useNitroApp();
146
+ const hasHook = Boolean(
147
+ nitroApp.hooks?.hasHooks?.("qarpeo:auth:magic-link:send") || nitroApp.hooks?.hookMap?.["qarpeo:auth:magic-link:send"]?.length
148
+ );
138
149
  let hookHandled = false;
139
- try {
140
- await nitroApp.hooks?.callHook("qarpeo:auth:magic-link:send", {
150
+ if (hasHook) {
151
+ const payload = {
141
152
  email: cleanEmail,
142
- url
143
- });
144
- hookHandled = true;
145
- } catch {
153
+ url,
154
+ handled: true
155
+ };
156
+ try {
157
+ await nitroApp.hooks?.callHook("qarpeo:auth:magic-link:send", payload);
158
+ hookHandled = payload.handled !== false;
159
+ } catch (err) {
160
+ console.warn("[qarpeo] Custom magic-link hook error:", err?.message || err);
161
+ }
146
162
  }
147
- if (!hookHandled || globalThis.process?.env?.NODE_ENV === "development") {
163
+ if (!hookHandled) {
148
164
  try {
149
165
  await sendEmail(
150
166
  {
@@ -15,26 +15,26 @@ function nanoid(size = 21) {
15
15
  }
16
16
  export function getPaymentsConfig(event) {
17
17
  const cfg = getQarpeoConfig(event).payments || {};
18
- const cfEnv = event?.context?.cloudflare?.env || {};
18
+ const cfEnv = event?.context?.cloudflare?.env || globalThis.__qarpeo_env__ || {};
19
19
  const provider = cfg.provider || "stripe";
20
20
  let secretKey = cfg.secretKey || "";
21
21
  let webhookSecret = cfg.webhookSecret || "";
22
22
  if (!secretKey) {
23
23
  if (provider === "stripe") {
24
- secretKey = process.env.STRIPE_SECRET_KEY || cfEnv.STRIPE_SECRET_KEY || "";
24
+ secretKey = cfEnv.STRIPE_SECRET_KEY || process.env.STRIPE_SECRET_KEY || "";
25
25
  } else if (provider === "lemonsqueezy") {
26
- secretKey = process.env.LEMONSQUEEZY_API_KEY || cfEnv.LEMONSQUEEZY_API_KEY || "";
26
+ secretKey = cfEnv.LEMONSQUEEZY_API_KEY || process.env.LEMONSQUEEZY_API_KEY || "";
27
27
  } else if (provider === "polar") {
28
- secretKey = process.env.POLAR_ACCESS_TOKEN || cfEnv.POLAR_ACCESS_TOKEN || "";
28
+ secretKey = cfEnv.POLAR_ACCESS_TOKEN || process.env.POLAR_ACCESS_TOKEN || "";
29
29
  }
30
30
  }
31
31
  if (!webhookSecret) {
32
32
  if (provider === "stripe") {
33
- webhookSecret = process.env.STRIPE_WEBHOOK_SECRET || cfEnv.STRIPE_WEBHOOK_SECRET || "";
33
+ webhookSecret = cfEnv.STRIPE_WEBHOOK_SECRET || process.env.STRIPE_WEBHOOK_SECRET || "";
34
34
  } else if (provider === "lemonsqueezy") {
35
- webhookSecret = process.env.LEMONSQUEEZY_WEBHOOK_SECRET || cfEnv.LEMONSQUEEZY_WEBHOOK_SECRET || "";
35
+ webhookSecret = cfEnv.LEMONSQUEEZY_WEBHOOK_SECRET || process.env.LEMONSQUEEZY_WEBHOOK_SECRET || "";
36
36
  } else if (provider === "polar") {
37
- webhookSecret = process.env.POLAR_WEBHOOK_SECRET || cfEnv.POLAR_WEBHOOK_SECRET || "";
37
+ webhookSecret = cfEnv.POLAR_WEBHOOK_SECRET || process.env.POLAR_WEBHOOK_SECRET || "";
38
38
  }
39
39
  }
40
40
  return {
@@ -14,7 +14,24 @@ function setResponseHeaderSafe(event, name, value) {
14
14
  } catch {
15
15
  }
16
16
  }
17
+ const MEMORY_STORE_MAX_KEYS = 5e3;
17
18
  const memoryStore = /* @__PURE__ */ new Map();
19
+ function pruneMemoryStore(now, maxAgeMs) {
20
+ if (memoryStore.size <= MEMORY_STORE_MAX_KEYS) return;
21
+ for (const [key, timestamps] of memoryStore.entries()) {
22
+ if (timestamps.length === 0 || now - (timestamps[timestamps.length - 1] ?? 0) >= maxAgeMs) {
23
+ memoryStore.delete(key);
24
+ }
25
+ }
26
+ if (memoryStore.size > MEMORY_STORE_MAX_KEYS) {
27
+ const toDelete = memoryStore.size - MEMORY_STORE_MAX_KEYS;
28
+ let count = 0;
29
+ for (const key of memoryStore.keys()) {
30
+ if (count++ >= toDelete) break;
31
+ memoryStore.delete(key);
32
+ }
33
+ }
34
+ }
18
35
  export function parseRateLimitWindow(window, defaultSeconds = 60) {
19
36
  if (window === void 0 || window === null) return defaultSeconds;
20
37
  if (typeof window === "number") return Math.max(1, Math.floor(window));
@@ -108,28 +125,30 @@ export async function checkRateLimit(eventOrKey, options) {
108
125
  try {
109
126
  const kv = getKVBinding(options?.binding, event);
110
127
  if (kv && typeof kv.get === "function") {
111
- const nowSec = Math.floor(Date.now() / 1e3);
112
- const bucket = Math.floor(nowSec / windowSecs);
113
- const kvKey = `_rl:${limitKey}:${bucket}`;
128
+ const now2 = Date.now();
129
+ const windowMs2 = windowSecs * 1e3;
130
+ const kvKey = `_rl:${limitKey}`;
114
131
  const raw = await kv.get(kvKey);
115
- const count = raw ? parseInt(raw, 10) : 0;
116
- const reset2 = windowSecs - nowSec % windowSecs;
117
- if (count >= max) {
132
+ let timestamps2 = raw ? JSON.parse(raw) : [];
133
+ timestamps2 = timestamps2.filter((t) => now2 - t < windowMs2);
134
+ const reset2 = timestamps2.length > 0 ? Math.ceil((timestamps2[0] + windowMs2 - now2) / 1e3) : windowSecs;
135
+ if (timestamps2.length >= max) {
118
136
  return {
119
137
  success: false,
120
138
  remaining: 0,
121
139
  limit: max,
122
- reset: reset2
140
+ reset: Math.max(1, reset2)
123
141
  };
124
142
  }
125
- await kv.put(kvKey, String(count + 1), {
126
- expirationTtl: Math.max(60, windowSecs * 2)
143
+ timestamps2.push(now2);
144
+ await kv.put(kvKey, JSON.stringify(timestamps2), {
145
+ expirationTtl: Math.max(60, windowSecs + 10)
127
146
  });
128
147
  return {
129
148
  success: true,
130
- remaining: Math.max(0, max - (count + 1)),
149
+ remaining: Math.max(0, max - timestamps2.length),
131
150
  limit: max,
132
- reset: reset2
151
+ reset: Math.max(1, reset2)
133
152
  };
134
153
  }
135
154
  } catch {
@@ -139,6 +158,9 @@ export async function checkRateLimit(eventOrKey, options) {
139
158
  const windowMs = windowSecs * 1e3;
140
159
  let timestamps = memoryStore.get(limitKey) || [];
141
160
  timestamps = timestamps.filter((t) => now - t < windowMs);
161
+ if (timestamps.length === 0) {
162
+ memoryStore.delete(limitKey);
163
+ }
142
164
  const reset = timestamps.length > 0 ? Math.ceil((timestamps[0] + windowMs - now) / 1e3) : windowSecs;
143
165
  if (timestamps.length >= max) {
144
166
  memoryStore.set(limitKey, timestamps);
@@ -149,6 +171,7 @@ export async function checkRateLimit(eventOrKey, options) {
149
171
  reset: Math.max(1, reset)
150
172
  };
151
173
  }
174
+ pruneMemoryStore(now, windowMs);
152
175
  timestamps.push(now);
153
176
  memoryStore.set(limitKey, timestamps);
154
177
  return {
@@ -0,0 +1,6 @@
1
+ /** Converts a string to a URL-safe lowercase slug. */
2
+ export declare function slugify(text: string): string;
3
+ /** Escapes HTML special characters. */
4
+ export declare function escapeHtml(str: string): string;
5
+ /** Sanitizes a URL to prevent javascript: or data: injection. */
6
+ export declare function sanitizeUrl(url: string): string;
@@ -0,0 +1,14 @@
1
+ export function slugify(text) {
2
+ return text.toLowerCase().trim().replace(/[^\w\s-]/g, "").replace(/[\s_-]+/g, "-").replace(/^-+|-+$/g, "");
3
+ }
4
+ export function escapeHtml(str) {
5
+ return str.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&#039;");
6
+ }
7
+ export function sanitizeUrl(url) {
8
+ if (!url || typeof url !== "string") return "#";
9
+ const trimmed = url.trim();
10
+ if (/^(?:(?:https?|mailto|tel):|\/)/i.test(trimmed)) {
11
+ return trimmed;
12
+ }
13
+ return "#";
14
+ }
@@ -43,7 +43,7 @@ export interface TrackEventOptions {
43
43
  * @param event H3 request event
44
44
  * @param options Optional tracking overrides
45
45
  */
46
- export declare function trackPageview(event: RequestEvent, options?: TrackPageviewOptions): void;
46
+ export declare function trackPageview(event: RequestEvent, options?: TrackPageviewOptions): Promise<void>;
47
47
  /**
48
48
  * Track a named custom business event against the Cloudflare Analytics Engine. Safe to call
49
49
  * fire-and-forget — never throws or blocks response.
@@ -52,7 +52,7 @@ export declare function trackPageview(event: RequestEvent, options?: TrackPagevi
52
52
  * @param name Event name (e.g. "signup", "checkout", "upgrade")
53
53
  * @param options Optional metadata and overrides
54
54
  */
55
- export declare function trackEvent(event: RequestEvent, name: string, options?: TrackEventOptions): void;
55
+ export declare function trackEvent(event: RequestEvent, name: string, options?: TrackEventOptions): Promise<void>;
56
56
  /**
57
57
  * Returns a tracker instance bound to the current H3 event. Useful when you want to call
58
58
  * `trackPageview` / `trackEvent` multiple times without passing the event every time.
@@ -66,7 +66,7 @@ export declare function trackEvent(event: RequestEvent, name: string, options?:
66
66
  */
67
67
  export declare function useTracker(event: RequestEvent): {
68
68
  /** Track a pageview for the current request. */
69
- trackPageview: (options?: TrackPageviewOptions) => void;
69
+ trackPageview: (options?: TrackPageviewOptions) => Promise<void>;
70
70
  /** Track a custom named event. */
71
- trackEvent: (name: string, options?: TrackEventOptions) => void;
71
+ trackEvent: (name: string, options?: TrackEventOptions) => Promise<void>;
72
72
  };
@@ -1,7 +1,11 @@
1
- import { createHash } from "node:crypto";
2
1
  import { getAnalyticsBinding } from "../../analytics.mjs";
3
- function buildSessionId(ip, ua) {
4
- return createHash("sha256").update(`${ip}|${ua}`).digest("base64url").slice(0, 16);
2
+ import { getQarpeoConfig } from "./config.mjs";
3
+ async function buildSessionId(ip, ua) {
4
+ const data = new TextEncoder().encode(`${ip}|${ua}`);
5
+ const hashBuffer = await crypto.subtle.digest("SHA-256", data);
6
+ const hashArray = Array.from(new Uint8Array(hashBuffer));
7
+ const base64url = btoa(String.fromCharCode(...hashArray)).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
8
+ return base64url.slice(0, 16);
5
9
  }
6
10
  function detectDevice(ua) {
7
11
  const lc = ua.toLowerCase();
@@ -20,8 +24,7 @@ function extractPath(url) {
20
24
  function resolveSiteId(event, override) {
21
25
  if (override) return override;
22
26
  try {
23
- const rc = event.context?.nitro?.runtimeConfig ?? event.$config;
24
- const configured = rc?.qarpeo?.analytics?.siteId;
27
+ const configured = getQarpeoConfig(event).analytics?.siteId;
25
28
  if (configured) return configured;
26
29
  } catch {
27
30
  }
@@ -30,13 +33,12 @@ function resolveSiteId(event, override) {
30
33
  function resolveAnalyticsBinding(event, override) {
31
34
  if (override) return override;
32
35
  try {
33
- const rc = event.context?.nitro?.runtimeConfig ?? event.$config;
34
- return rc?.qarpeo?.analytics?.binding || "ANALYTICS";
36
+ return getQarpeoConfig(event).analytics?.binding || "ANALYTICS";
35
37
  } catch {
36
38
  return "ANALYTICS";
37
39
  }
38
40
  }
39
- export function trackPageview(event, options = {}) {
41
+ export async function trackPageview(event, options = {}) {
40
42
  try {
41
43
  const req = event.node?.req;
42
44
  const headers = req?.headers || {};
@@ -47,7 +49,7 @@ export function trackPageview(event, options = {}) {
47
49
  const referrer = options.referrer ?? getHeader("referer");
48
50
  const path = options.path ?? extractPath(req?.url || "/");
49
51
  const device = detectDevice(ua);
50
- const sessionId = buildSessionId(ip, ua);
52
+ const sessionId = await buildSessionId(ip, ua);
51
53
  const siteId = resolveSiteId(event, options.siteId);
52
54
  const bindingName = resolveAnalyticsBinding(event, options.binding);
53
55
  const ae = getAnalyticsBinding(bindingName, event);
@@ -82,7 +84,7 @@ export function trackPageview(event, options = {}) {
82
84
  } catch {
83
85
  }
84
86
  }
85
- export function trackEvent(event, name, options = {}) {
87
+ export async function trackEvent(event, name, options = {}) {
86
88
  try {
87
89
  const req = event.node?.req;
88
90
  const headers = req?.headers || {};
@@ -92,7 +94,7 @@ export function trackEvent(event, name, options = {}) {
92
94
  const country = getHeader("cf-ipcountry") || "XX";
93
95
  const path = extractPath(req?.url || "/");
94
96
  const device = detectDevice(ua);
95
- const sessionId = buildSessionId(ip, ua);
97
+ const sessionId = await buildSessionId(ip, ua);
96
98
  const siteId = resolveSiteId(event, options.siteId);
97
99
  const bindingName = resolveAnalyticsBinding(event, options.binding);
98
100
  const metaJson = options.meta ? JSON.stringify(options.meta).slice(0, 512) : "";
@@ -1,10 +1,11 @@
1
1
  /**
2
2
  * `qarpeo/server` — Standard server-side entrypoint for Qarpeo edge primitives.
3
3
  *
4
- * Provides typed Cloudflare bindings and high-level clients for Nuxt server routes,
5
- * event handlers, middleware, queues, and background tasks.
4
+ * Provides typed Cloudflare bindings and high-level clients for Nuxt server routes, event handlers,
5
+ * middleware, queues, and background tasks.
6
6
  *
7
7
  * Usage:
8
+ *
8
9
  * ```ts
9
10
  * import { defineEventHandler } from "nuxt/server"
10
11
  * import { db, kv, blob, ai } from "qarpeo/server"
@@ -38,3 +39,4 @@ export * from "./payments";
38
39
  export * from "./storage";
39
40
  export * from "./bots";
40
41
  export * from "./rag";
42
+ export * from "./server/utils/string";
@@ -21,3 +21,4 @@ export * from "./payments.mjs";
21
21
  export * from "./storage.mjs";
22
22
  export * from "./bots.mjs";
23
23
  export * from "./rag.mjs";
24
+ export * from "./server/utils/string.mjs";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "qarpeo",
3
- "version": "0.1.28",
3
+ "version": "0.1.29",
4
4
  "description": "Zero-config Cloudflare Edge Platform for Nuxt",
5
5
  "keywords": [
6
6
  "analytics-engine",