qarpeo 0.1.28 → 0.1.30

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (50) hide show
  1. package/dist/chunks/wrangler.mjs +1 -1
  2. package/dist/runtime/bindings.mjs +1 -1
  3. package/dist/runtime/server/plugins/dev-proxy.mjs +0 -1
  4. package/dist/runtime/server/plugins/env.d.ts +2 -2
  5. package/dist/runtime/server/plugins/env.mjs +1 -10
  6. package/dist/runtime/server/routes/__qarpeo/analytics/events.get.mjs +2 -2
  7. package/dist/runtime/server/routes/__qarpeo/analytics/summary.get.mjs +2 -2
  8. package/dist/runtime/server/routes/__qarpeo/blob/files.get.mjs +2 -2
  9. package/dist/runtime/server/routes/__qarpeo/overview/health.get.mjs +2 -2
  10. package/dist/runtime/server/routes/__qarpeo/overview.get.mjs +3 -8
  11. package/dist/runtime/server/routes/__qarpeo/settings.get.mjs +2 -8
  12. package/dist/runtime/server/routes/analytics/events.get.mjs +2 -2
  13. package/dist/runtime/server/routes/analytics/pageviews.get.mjs +2 -2
  14. package/dist/runtime/server/routes/analytics/summary.get.mjs +2 -2
  15. package/dist/runtime/server/routes/auth/magic-link/verify.get.mjs +13 -10
  16. package/dist/runtime/server/routes/auth/sso/login.get.mjs +2 -1
  17. package/dist/runtime/server/routes/auth/sso/oidc/callback.get.mjs +2 -1
  18. package/dist/runtime/server/routes/auth/sso/saml/acs.post.mjs +18 -29
  19. package/dist/runtime/server/routes/cms/preview/disable.get.mjs +2 -1
  20. package/dist/runtime/server/routes/cms/preview/enable.get.mjs +3 -1
  21. package/dist/runtime/server/routes/cms/webhooks/[provider].post.mjs +2 -1
  22. package/dist/runtime/server/routes/notifications/push/subscribe.post.mjs +10 -5
  23. package/dist/runtime/server/routes/notifications/push/unsubscribe.post.mjs +6 -5
  24. package/dist/runtime/server/routes/payments/cancel.post.mjs +6 -5
  25. package/dist/runtime/server/routes/payments/change-plan.post.mjs +7 -8
  26. package/dist/runtime/server/routes/payments/checkout.post.mjs +13 -2
  27. package/dist/runtime/server/routes/payments/portal.post.mjs +6 -2
  28. package/dist/runtime/server/utils/analytics-query.mjs +15 -7
  29. package/dist/runtime/server/utils/auth.mjs +3 -2
  30. package/dist/runtime/server/utils/cms.mjs +3 -3
  31. package/dist/runtime/server/utils/config.d.ts +1 -1
  32. package/dist/runtime/server/utils/config.mjs +28 -2
  33. package/dist/runtime/server/utils/crypto.d.ts +7 -1
  34. package/dist/runtime/server/utils/crypto.mjs +29 -9
  35. package/dist/runtime/server/utils/domains.mjs +8 -4
  36. package/dist/runtime/server/utils/notifications.mjs +6 -4
  37. package/dist/runtime/server/utils/organization.d.ts +2 -1
  38. package/dist/runtime/server/utils/organization.mjs +18 -11
  39. package/dist/runtime/server/utils/passwordless.mjs +37 -15
  40. package/dist/runtime/server/utils/payments.mjs +7 -7
  41. package/dist/runtime/server/utils/ratelimit.mjs +34 -11
  42. package/dist/runtime/server/utils/sso.mjs +59 -7
  43. package/dist/runtime/server/utils/string.d.ts +11 -0
  44. package/dist/runtime/server/utils/string.mjs +24 -0
  45. package/dist/runtime/server/utils/tracker.d.ts +4 -4
  46. package/dist/runtime/server/utils/tracker.mjs +13 -11
  47. package/dist/runtime/server/utils/turnstile.mjs +6 -2
  48. package/dist/runtime/server.d.ts +4 -2
  49. package/dist/runtime/server.mjs +1 -0
  50. package/package.json +1 -1
@@ -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,38 @@ 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 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) {
59
+ throw new Error(
60
+ "[qarpeo] Missing required secret: NUXT_APP_SECRET or NUXT_SESSION_PASSWORD must be configured in production for secure token and signature generation."
61
+ );
62
+ }
63
+ return getEphemeralDevSecret();
38
64
  }
@@ -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;
@@ -1,27 +1,47 @@
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();
4
5
  const bufA = encoder.encode(a);
5
6
  const bufB = encoder.encode(b);
6
- if (bufA.byteLength !== bufB.byteLength) return false;
7
+ const len = Math.max(bufA.byteLength, bufB.byteLength);
8
+ const padA = new Uint8Array(len);
9
+ const padB = new Uint8Array(len);
10
+ padA.set(bufA);
11
+ padB.set(bufB);
7
12
  let diff = 0;
8
- for (let i = 0; i < bufA.byteLength; i++) {
9
- diff |= bufA[i] ^ bufB[i];
13
+ for (let i = 0; i < len; i++) {
14
+ diff |= padA[i] ^ padB[i];
10
15
  }
16
+ diff |= bufA.byteLength ^ bufB.byteLength;
11
17
  return diff === 0;
12
18
  }
13
19
  export const constantTimeEqual = timingSafeEqualString;
14
20
  const ENC_PREFIX = "enc:";
15
21
  function resolveTokenSecret(event) {
16
- const ev = event;
17
- 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
18
- // (enforced by the auth startup guard in serverAuth())
19
- "qarpeo-auth-internal-dev-salt-key-32b";
22
+ return getSessionSecret(event);
20
23
  }
21
24
  async function deriveAesGcmKey(password, usage) {
22
25
  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);
26
+ const keyMaterial = await crypto.subtle.importKey(
27
+ "raw",
28
+ encoder.encode(password),
29
+ { name: "HKDF" },
30
+ false,
31
+ ["deriveKey"]
32
+ );
33
+ return crypto.subtle.deriveKey(
34
+ {
35
+ name: "HKDF",
36
+ hash: "SHA-256",
37
+ salt: encoder.encode("qarpeo-token-encryption-v1"),
38
+ info: encoder.encode("AES-GCM-256")
39
+ },
40
+ keyMaterial,
41
+ { name: "AES-GCM", length: 256 },
42
+ false,
43
+ usage
44
+ );
25
45
  }
26
46
  export async function encryptToken(plaintext, event) {
27
47
  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
  }
@@ -139,15 +139,19 @@ export async function registerCustomDomain(tenantId, rawDomain, options = {}, ev
139
139
  value: cfResult.ownership_verification.value
140
140
  });
141
141
  } else if (!cfResult) {
142
+ const tokenBytes = new Uint8Array(16);
143
+ crypto.getRandomValues(tokenBytes);
144
+ const tokenHex = Array.from(tokenBytes, (b) => b.toString(16).padStart(2, "0")).join("");
142
145
  verificationRecords.push({
143
146
  type: "txt",
144
147
  name: `_cf-custom-hostname.${domain}`,
145
- value: `qarpeo-verify-${Math.random().toString(36).slice(2, 10)}`
148
+ value: `qarpeo-verify-${tokenHex}`
146
149
  });
147
150
  }
148
151
  const now = Date.now();
152
+ const randomSuffix = crypto.randomUUID().slice(0, 8);
149
153
  const record = {
150
- id: cfResult?.id || `dom_${now}_${Math.random().toString(36).slice(2, 8)}`,
154
+ id: cfResult?.id || `dom_${now}_${randomSuffix}`,
151
155
  tenantId,
152
156
  domain,
153
157
  status: cfResult?.status || "pending",
@@ -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
  {
@@ -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;
@@ -37,17 +43,25 @@ export async function sendOTPCode(event, email, options = {}) {
37
43
  console.warn("[qarpeo] Failed to store OTP in KV:", err.message);
38
44
  }
39
45
  const nitroApp = useNitroApp();
46
+ const hasHook = Boolean(
47
+ nitroApp.hooks?.hasHooks?.("qarpeo:auth:otp:send") || nitroApp.hooks?.hookMap?.["qarpeo:auth:otp:send"]?.length
48
+ );
40
49
  let hookHandled = false;
41
- try {
42
- await nitroApp.hooks?.callHook("qarpeo:auth:otp:send", {
50
+ if (hasHook) {
51
+ const payload = {
43
52
  email: cleanEmail,
44
53
  code,
45
- type: "otp"
46
- });
47
- hookHandled = true;
48
- } catch {
54
+ type: "otp",
55
+ handled: true
56
+ };
57
+ try {
58
+ await nitroApp.hooks?.callHook("qarpeo:auth:otp:send", payload);
59
+ hookHandled = payload.handled !== false;
60
+ } catch (err) {
61
+ console.warn("[qarpeo] Custom OTP hook error:", err?.message || err);
62
+ }
49
63
  }
50
- if (!hookHandled || globalThis.process?.env?.NODE_ENV === "development") {
64
+ if (!hookHandled) {
51
65
  try {
52
66
  await sendEmail(
53
67
  {
@@ -135,16 +149,24 @@ export async function sendMagicLink(event, email, options = {}) {
135
149
  const authPrefix = authConfig.prefix || "/api/auth";
136
150
  const url = `${origin}${authPrefix}/magic-link/verify?token=${token}`;
137
151
  const nitroApp = useNitroApp();
152
+ const hasHook = Boolean(
153
+ nitroApp.hooks?.hasHooks?.("qarpeo:auth:magic-link:send") || nitroApp.hooks?.hookMap?.["qarpeo:auth:magic-link:send"]?.length
154
+ );
138
155
  let hookHandled = false;
139
- try {
140
- await nitroApp.hooks?.callHook("qarpeo:auth:magic-link:send", {
156
+ if (hasHook) {
157
+ const payload = {
141
158
  email: cleanEmail,
142
- url
143
- });
144
- hookHandled = true;
145
- } catch {
159
+ url,
160
+ handled: true
161
+ };
162
+ try {
163
+ await nitroApp.hooks?.callHook("qarpeo:auth:magic-link:send", payload);
164
+ hookHandled = payload.handled !== false;
165
+ } catch (err) {
166
+ console.warn("[qarpeo] Custom magic-link hook error:", err?.message || err);
167
+ }
146
168
  }
147
- if (!hookHandled || globalThis.process?.env?.NODE_ENV === "development") {
169
+ if (!hookHandled) {
148
170
  try {
149
171
  await sendEmail(
150
172
  {
@@ -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 {
@@ -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"]
@@ -0,0 +1,11 @@
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;
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;
@@ -0,0 +1,24 @@
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
+ }
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
+ }
@@ -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) : "";