qarpeo 0.3.5 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (104) hide show
  1. package/dist/chunks/{tools.mjs → manifest.get.mjs} +229 -3
  2. package/dist/cli/index.mjs +74 -5
  3. package/dist/features/console.d.ts +4 -0
  4. package/dist/module.mjs +287 -56
  5. package/dist/runtime/app/components/{BlobImage.vue → QImg.vue} +5 -4
  6. package/dist/runtime/app/composables/console.d.ts +60 -0
  7. package/dist/runtime/app/composables/console.mjs +169 -0
  8. package/dist/runtime/app/composables/pwa.d.ts +34 -0
  9. package/dist/runtime/app/composables/pwa.mjs +86 -0
  10. package/dist/runtime/app/composables/rbac.d.ts +33 -0
  11. package/dist/runtime/app/composables/rbac.mjs +60 -0
  12. package/dist/runtime/app/composables/site.d.ts +73 -0
  13. package/dist/runtime/app/composables/site.mjs +174 -1
  14. package/dist/runtime/app/middleware/console.global.d.ts +2 -0
  15. package/dist/runtime/app/middleware/console.global.mjs +37 -0
  16. package/dist/runtime/app/plugins/pwa.client.d.ts +2 -0
  17. package/dist/runtime/app/plugins/pwa.client.mjs +28 -0
  18. package/dist/runtime/app/plugins/pwa.d.ts +2 -0
  19. package/dist/runtime/app/plugins/pwa.mjs +42 -0
  20. package/dist/runtime/app/plugins/seo.mjs +39 -10
  21. package/dist/runtime/server/routes/__qarpeo/cloud/agents/run.post.d.ts +13 -0
  22. package/dist/runtime/server/routes/__qarpeo/cloud/agents/run.post.mjs +46 -0
  23. package/dist/runtime/server/routes/__qarpeo/cloud/cms/entry.get.d.ts +22 -0
  24. package/dist/runtime/server/routes/__qarpeo/cloud/cms/entry.get.mjs +40 -0
  25. package/dist/runtime/server/routes/__qarpeo/cloud/cms/entry.post.d.ts +20 -0
  26. package/dist/runtime/server/routes/__qarpeo/cloud/cms/entry.post.mjs +52 -0
  27. package/dist/runtime/server/routes/__qarpeo/cloud/cms.get.d.ts +26 -0
  28. package/dist/runtime/server/routes/__qarpeo/cloud/cms.get.mjs +80 -0
  29. package/dist/runtime/server/routes/__qarpeo/cloud/comments/moderate.post.d.ts +16 -0
  30. package/dist/runtime/server/routes/__qarpeo/cloud/comments/moderate.post.mjs +30 -0
  31. package/dist/runtime/server/routes/__qarpeo/cloud/comments.get.d.ts +21 -0
  32. package/dist/runtime/server/routes/__qarpeo/cloud/comments.get.mjs +49 -0
  33. package/dist/runtime/server/routes/__qarpeo/cloud/extras.get.d.ts +22 -0
  34. package/dist/runtime/server/routes/__qarpeo/cloud/extras.get.mjs +65 -0
  35. package/dist/runtime/server/routes/__qarpeo/cloud/mail/unsuppress.post.d.ts +12 -0
  36. package/dist/runtime/server/routes/__qarpeo/cloud/mail/unsuppress.post.mjs +17 -0
  37. package/dist/runtime/server/routes/__qarpeo/cloud/migrate/cms.post.d.ts +22 -0
  38. package/dist/runtime/server/routes/__qarpeo/cloud/migrate/cms.post.mjs +87 -0
  39. package/dist/runtime/server/routes/__qarpeo/cloud/migrate/products.post.d.ts +25 -0
  40. package/dist/runtime/server/routes/__qarpeo/cloud/migrate/products.post.mjs +119 -0
  41. package/dist/runtime/server/routes/__qarpeo/cloud/migrate/users.post.d.ts +19 -0
  42. package/dist/runtime/server/routes/__qarpeo/cloud/migrate/users.post.mjs +86 -0
  43. package/dist/runtime/server/routes/__qarpeo/cloud/migrate.post.d.ts +21 -0
  44. package/dist/runtime/server/routes/__qarpeo/cloud/migrate.post.mjs +91 -0
  45. package/dist/runtime/server/routes/__qarpeo/cloud/notifications/test.post.d.ts +13 -0
  46. package/dist/runtime/server/routes/__qarpeo/cloud/notifications/test.post.mjs +49 -0
  47. package/dist/runtime/server/routes/__qarpeo/cloud/operations.get.d.ts +43 -0
  48. package/dist/runtime/server/routes/__qarpeo/cloud/operations.get.mjs +111 -0
  49. package/dist/runtime/server/routes/__qarpeo/cloud/overview.get.d.ts +22 -0
  50. package/dist/runtime/server/routes/__qarpeo/cloud/overview.get.mjs +44 -0
  51. package/dist/runtime/server/routes/__qarpeo/cloud/store/order-status.post.d.ts +9 -0
  52. package/dist/runtime/server/routes/__qarpeo/cloud/store/order-status.post.mjs +27 -0
  53. package/dist/runtime/server/routes/__qarpeo/cloud/store/orders.get.d.ts +23 -0
  54. package/dist/runtime/server/routes/__qarpeo/cloud/store/orders.get.mjs +56 -0
  55. package/dist/runtime/server/routes/__qarpeo/cloud/store/products.get.d.ts +21 -0
  56. package/dist/runtime/server/routes/__qarpeo/cloud/store/products.get.mjs +50 -0
  57. package/dist/runtime/server/routes/__qarpeo/cloud/tasks/run.post.d.ts +12 -0
  58. package/dist/runtime/server/routes/__qarpeo/cloud/tasks/run.post.mjs +24 -0
  59. package/dist/runtime/server/routes/__qarpeo/cloud/users/action.post.d.ts +26 -0
  60. package/dist/runtime/server/routes/__qarpeo/cloud/users/action.post.mjs +40 -0
  61. package/dist/runtime/server/routes/__qarpeo/cloud/users.get.d.ts +39 -0
  62. package/dist/runtime/server/routes/__qarpeo/cloud/users.get.mjs +69 -0
  63. package/dist/runtime/server/routes/__qarpeo/manifest.get.d.ts +39 -0
  64. package/dist/runtime/server/routes/__qarpeo/manifest.get.mjs +226 -0
  65. package/dist/runtime/server/routes/__qarpeo/og.get.d.ts +15 -0
  66. package/dist/runtime/server/routes/__qarpeo/og.get.mjs +109 -0
  67. package/dist/runtime/server/routes/__qarpeo/rbac/me.get.d.ts +26 -0
  68. package/dist/runtime/server/routes/__qarpeo/rbac/me.get.mjs +23 -0
  69. package/dist/runtime/server/routes/__qarpeo/rbac/roles.delete.d.ts +12 -0
  70. package/dist/runtime/server/routes/__qarpeo/rbac/roles.delete.mjs +12 -0
  71. package/dist/runtime/server/routes/__qarpeo/rbac/roles.get.d.ts +16 -0
  72. package/dist/runtime/server/routes/__qarpeo/rbac/roles.get.mjs +15 -0
  73. package/dist/runtime/server/routes/__qarpeo/rbac/roles.post.d.ts +11 -0
  74. package/dist/runtime/server/routes/__qarpeo/rbac/roles.post.mjs +16 -0
  75. package/dist/runtime/server/routes/__qarpeo/rbac/users.post.d.ts +14 -0
  76. package/dist/runtime/server/routes/__qarpeo/rbac/users.post.mjs +19 -0
  77. package/dist/runtime/server/routes/manifest.webmanifest.get.d.ts +2 -0
  78. package/dist/runtime/server/routes/manifest.webmanifest.get.mjs +31 -0
  79. package/dist/runtime/server/routes/robots.txt.get.mjs +20 -4
  80. package/dist/runtime/server/routes/sitemap.xml.get.mjs +47 -6
  81. package/dist/runtime/server/routes/sw.js.get.d.ts +8 -0
  82. package/dist/runtime/server/routes/sw.js.get.mjs +141 -0
  83. package/dist/runtime/server/utils/auth.d.ts +2 -14
  84. package/dist/runtime/server/utils/auth.mjs +32 -36
  85. package/dist/runtime/server/utils/cloud-auth.d.ts +8 -0
  86. package/dist/runtime/server/utils/cloud-auth.mjs +23 -0
  87. package/dist/runtime/server/utils/console.d.ts +19 -0
  88. package/dist/runtime/server/utils/console.mjs +34 -0
  89. package/dist/runtime/server/utils/legacy-hash.d.ts +76 -0
  90. package/dist/runtime/server/utils/legacy-hash.mjs +96 -0
  91. package/dist/runtime/server/utils/rbac.d.ts +89 -0
  92. package/dist/runtime/server/utils/rbac.mjs +427 -0
  93. package/dist/runtime/server/utils/role-env.d.ts +19 -0
  94. package/dist/runtime/server/utils/role-env.mjs +34 -0
  95. package/dist/runtime/server.d.ts +2 -0
  96. package/dist/runtime/server.mjs +2 -0
  97. package/dist/types/console.d.ts +67 -0
  98. package/dist/types/index.d.ts +1 -0
  99. package/dist/types/options.d.ts +9 -0
  100. package/dist/types/site.d.ts +102 -0
  101. package/dist/types/storage.d.ts +5 -11
  102. package/package.json +1 -1
  103. package/dist/runtime/providers/qarpeo.d.ts +0 -23
  104. package/dist/runtime/providers/qarpeo.mjs +0 -46
@@ -1,12 +1,15 @@
1
- import { defineEventHandler } from "nuxt/server";
1
+ import { defineEventHandler, useRuntimeConfig } from "nuxt/server";
2
2
  import { getCloudflareEnv } from "../../bindings.mjs";
3
3
  import { resolveTableName } from "../utils/table-names.mjs";
4
4
  function matchesPattern(path, pattern) {
5
5
  const regexPattern = pattern.replace(/\*\*/g, ".*").replace(/\*/g, "[^/]*").replace(/\//g, "\\/");
6
6
  return new RegExp(`^${regexPattern}$`).test(path);
7
7
  }
8
+ function escapeXml(value) {
9
+ return value.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&apos;");
10
+ }
8
11
  export default defineEventHandler(async (event) => {
9
- const runtimeConfig = globalThis.__NUXT_RUNTIME_CONFIG__ || {};
12
+ const runtimeConfig = useRuntimeConfig(event) || globalThis.__NUXT_RUNTIME_CONFIG__ || {};
10
13
  const site = runtimeConfig.public?.qarpeo?.site || {};
11
14
  const sitemapConfig = typeof site.sitemap === "object" ? site.sitemap : {};
12
15
  const baseUrl = (site.url || "").replace(/\/$/, "");
@@ -21,6 +24,20 @@ export default defineEventHandler(async (event) => {
21
24
  },
22
25
  ...sitemapConfig.urls || []
23
26
  ];
27
+ if (sitemapConfig.pages !== false && Array.isArray(sitemapConfig.discoveredPages)) {
28
+ for (const pagePath of sitemapConfig.discoveredPages) {
29
+ const cleanPath = pagePath.startsWith("/") ? pagePath : `/${pagePath}`;
30
+ if (cleanPath === "/") continue;
31
+ const isExcluded = excludes.some((pattern) => matchesPattern(cleanPath, pattern));
32
+ if (!isExcluded) {
33
+ urls.push({
34
+ loc: `${baseUrl}${cleanPath}`,
35
+ changefreq: "weekly",
36
+ priority: 0.7
37
+ });
38
+ }
39
+ }
40
+ }
24
41
  if (sitemapConfig.cms !== false && baseUrl) {
25
42
  try {
26
43
  const env = getCloudflareEnv(event);
@@ -59,22 +76,46 @@ export default defineEventHandler(async (event) => {
59
76
  dedupedUrls.push(u);
60
77
  }
61
78
  }
79
+ const hasAlternates = dedupedUrls.some((u) => u.alternates && u.alternates.length > 0);
80
+ const hasImages = dedupedUrls.some((u) => u.images && u.images.length > 0);
81
+ const namespaces = ['xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"'];
82
+ if (hasAlternates) namespaces.push('xmlns:xhtml="http://www.w3.org/1999/xhtml"');
83
+ if (hasImages) namespaces.push('xmlns:image="http://www.google.com/schemas/sitemap-image/1.1"');
62
84
  const xmlEntries = dedupedUrls.map((u) => {
63
85
  let entry = ` <url>
64
- <loc>${u.loc}</loc>
86
+ <loc>${escapeXml(u.loc)}</loc>
65
87
  `;
66
- if (u.lastmod) entry += ` <lastmod>${u.lastmod}</lastmod>
88
+ if (u.lastmod) entry += ` <lastmod>${escapeXml(u.lastmod)}</lastmod>
67
89
  `;
68
- if (u.changefreq) entry += ` <changefreq>${u.changefreq}</changefreq>
90
+ if (u.changefreq) entry += ` <changefreq>${escapeXml(u.changefreq)}</changefreq>
69
91
  `;
70
92
  if (typeof u.priority === "number")
71
93
  entry += ` <priority>${u.priority.toFixed(1)}</priority>
72
94
  `;
95
+ if (u.alternates?.length) {
96
+ for (const alt of u.alternates) {
97
+ entry += ` <xhtml:link rel="alternate" hreflang="${escapeXml(alt.hreflang)}" href="${escapeXml(alt.href)}" />
98
+ `;
99
+ }
100
+ }
101
+ if (u.images?.length) {
102
+ for (const img of u.images) {
103
+ entry += ` <image:image>
104
+ <image:loc>${escapeXml(img.loc)}</image:loc>
105
+ `;
106
+ if (img.title) entry += ` <image:title>${escapeXml(img.title)}</image:title>
107
+ `;
108
+ if (img.caption) entry += ` <image:caption>${escapeXml(img.caption)}</image:caption>
109
+ `;
110
+ entry += ` </image:image>
111
+ `;
112
+ }
113
+ }
73
114
  entry += ` </url>`;
74
115
  return entry;
75
116
  }).join("\n");
76
117
  const sitemapXml = `<?xml version="1.0" encoding="UTF-8"?>
77
- <urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
118
+ <urlset ${namespaces.join(" ")}>
78
119
  ${xmlEntries}
79
120
  </urlset>
80
121
  `;
@@ -0,0 +1,8 @@
1
+ import type { QarpeoPwaConfig } from "../../../types";
2
+ /**
3
+ * Generates a zero-dependency Cloudflare-compatible Service Worker script for offline asset
4
+ * caching, stale-while-revalidate API routes, and optional Web Push notifications.
5
+ */
6
+ export declare function buildServiceWorkerScript(pwa: QarpeoPwaConfig): string;
7
+ declare const _default: import("nuxt/server").EventHandler<Response>;
8
+ export default _default;
@@ -0,0 +1,141 @@
1
+ import { defineEventHandler, useRuntimeConfig } from "nuxt/server";
2
+ export function buildServiceWorkerScript(pwa) {
3
+ const cacheVersion = pwa.cacheVersion || "v1";
4
+ const cacheName = `qarpeo-pwa-${cacheVersion}`;
5
+ const precacheUrls = Array.from(
6
+ /* @__PURE__ */ new Set([...pwa.precacheUrls || [], ...pwa.offlinePage ? [pwa.offlinePage] : []])
7
+ );
8
+ const cacheRoutes = pwa.cacheRoutes || [];
9
+ const offlinePage = pwa.offlinePage || "";
10
+ const pushBlock = pwa.push ? `
11
+ self.addEventListener("push", (event) => {
12
+ if (!event.data) return
13
+ let payload = {}
14
+ try { payload = event.data.json() } catch { payload = { title: "Notification", body: event.data.text() } }
15
+ const title = payload.title || "Notification"
16
+ event.waitUntil(
17
+ self.registration.showNotification(title, {
18
+ body: payload.body || "",
19
+ icon: payload.icon || undefined,
20
+ badge: payload.badge || undefined,
21
+ data: payload.data || { url: payload.url || "/" },
22
+ })
23
+ )
24
+ })
25
+
26
+ self.addEventListener("notificationclick", (event) => {
27
+ event.notification.close()
28
+ const targetUrl = (event.notification.data && event.notification.data.url) || "/"
29
+ event.waitUntil(
30
+ self.clients.matchAll({ type: "window", includeUncontrolled: true }).then((clients) => {
31
+ for (const client of clients) {
32
+ if (client.url.includes(targetUrl) && "focus" in client) return client.focus()
33
+ }
34
+ if (self.clients.openWindow) return self.clients.openWindow(targetUrl)
35
+ })
36
+ )
37
+ })
38
+ ` : "";
39
+ return `// Qarpeo Edge Service Worker (${cacheVersion})
40
+ const CACHE_NAME = ${JSON.stringify(cacheName)}
41
+ const PRECACHE_URLS = ${JSON.stringify(precacheUrls)}
42
+ const CACHE_ROUTES = ${JSON.stringify(cacheRoutes)}
43
+ const OFFLINE_PAGE = ${JSON.stringify(offlinePage)}
44
+
45
+ self.addEventListener("install", (event) => {
46
+ event.waitUntil(
47
+ caches.open(CACHE_NAME).then((cache) => {
48
+ if (!PRECACHE_URLS.length) return Promise.resolve()
49
+ return cache.addAll(PRECACHE_URLS).catch(() => {})
50
+ }).then(() => self.skipWaiting())
51
+ )
52
+ })
53
+
54
+ self.addEventListener("activate", (event) => {
55
+ event.waitUntil(
56
+ caches.keys().then((keys) =>
57
+ Promise.all(
58
+ keys
59
+ .filter((key) => key.startsWith("qarpeo-pwa-") && key !== CACHE_NAME)
60
+ .map((key) => caches.delete(key))
61
+ )
62
+ ).then(() => self.clients.claim())
63
+ )
64
+ })
65
+
66
+ self.addEventListener("message", (event) => {
67
+ if (event.data && event.data.type === "SKIP_WAITING") {
68
+ self.skipWaiting()
69
+ }
70
+ })
71
+
72
+ self.addEventListener("fetch", (event) => {
73
+ const req = event.request
74
+ if (req.method !== "GET") return
75
+
76
+ const url = new URL(req.url)
77
+ if (url.origin !== self.location.origin) return
78
+
79
+ // Hashed Nuxt build assets & static fonts/icons: Cache-First
80
+ if (
81
+ url.pathname.startsWith("/_nuxt/") ||
82
+ /\\.(?:woff2?|ttf|eot|png|jpe?g|webp|avif|svg|ico)$/i.test(url.pathname)
83
+ ) {
84
+ event.respondWith(
85
+ caches.match(req).then((cached) => {
86
+ if (cached) return cached
87
+ return fetch(req).then((res) => {
88
+ if (res && res.status === 200) {
89
+ const clone = res.clone()
90
+ caches.open(CACHE_NAME).then((cache) => cache.put(req, clone))
91
+ }
92
+ return res
93
+ })
94
+ })
95
+ )
96
+ return
97
+ }
98
+
99
+ // Configured API/CMS routes: Stale-While-Revalidate
100
+ if (CACHE_ROUTES.some((prefix) => url.pathname.startsWith(prefix))) {
101
+ event.respondWith(
102
+ caches.open(CACHE_NAME).then((cache) =>
103
+ cache.match(req).then((cached) => {
104
+ const networkFetch = fetch(req).then((res) => {
105
+ if (res && res.status === 200) cache.put(req, res.clone())
106
+ return res
107
+ })
108
+ return cached || networkFetch
109
+ })
110
+ )
111
+ )
112
+ return
113
+ }
114
+
115
+ // HTML navigation requests: Network-First with optional offline fallback
116
+ if (req.mode === "navigate") {
117
+ event.respondWith(
118
+ fetch(req).catch(() =>
119
+ caches.match(req).then((cached) => {
120
+ if (cached) return cached
121
+ if (OFFLINE_PAGE) return caches.match(OFFLINE_PAGE)
122
+ return new Response("Offline", { status: 503, headers: { "Content-Type": "text/plain" } })
123
+ })
124
+ )
125
+ )
126
+ }
127
+ })
128
+ ${pushBlock}`;
129
+ }
130
+ export default defineEventHandler((event) => {
131
+ const rc = useRuntimeConfig(event) || globalThis.__NUXT_RUNTIME_CONFIG__ || {};
132
+ const pwa = rc.public?.qarpeo?.pwa || {};
133
+ const script = buildServiceWorkerScript(pwa);
134
+ return new Response(script, {
135
+ headers: {
136
+ "Content-Type": "application/javascript; charset=UTF-8",
137
+ "Service-Worker-Allowed": "/",
138
+ "Cache-Control": "no-cache, no-store, must-revalidate"
139
+ }
140
+ });
141
+ });
@@ -1,4 +1,6 @@
1
1
  import { type RequestEvent } from "nuxt/server";
2
+ export { type QarpeoRole, getRoleFromEnv } from "./role-env";
3
+ import { type QarpeoRole } from "./role-env";
2
4
  import type { QarpeoSession } from "../../types/auth";
3
5
  /**
4
6
  * Returns a memoized Better Auth instance connected to Cloudflare D1 via Drizzle. The instance is
@@ -98,7 +100,6 @@ export declare function resolveMfaStatus(d1: any, user: {
98
100
  * - 'developer': Technical observer (analytics, logs, error monitoring, read-only diagnostic)
99
101
  * - 'user': Standard user / member
100
102
  */
101
- export type QarpeoRole = "super" | "admin" | "moderator" | "developer" | "user";
102
103
  export interface ResolveUserRoleResult {
103
104
  /** Whether the user already exists in the database */
104
105
  exists: boolean;
@@ -109,19 +110,6 @@ export interface ResolveUserRoleResult {
109
110
  /** The user record from the database, if found */
110
111
  user?: any | null;
111
112
  }
112
- /**
113
- * Resolves the configured role for an email address from environment variables:
114
- * - `QARPEO_SUPER_EMAILS` -> 'super'
115
- * - `QARPEO_ADMIN_EMAILS` -> 'admin'
116
- * - `QARPEO_MODERATOR_EMAILS` -> 'moderator'
117
- * - `QARPEO_DEVELOPER_EMAILS` -> 'developer'
118
- * - Default -> 'user'
119
- *
120
- * Checks both Cloudflare Worker env (via event context or globalThis) and process.env.
121
- * Supports both `(event, email)` (standard Nuxt/Nitro convention) and `(email, event?)`.
122
- */
123
- export declare function getRoleFromEnv(event: RequestEvent, email: string): QarpeoRole;
124
- export declare function getRoleFromEnv(email: string, event?: RequestEvent): QarpeoRole;
125
113
  /**
126
114
  * Preflight utility to inspect user registration status and suggested role before creating an account.
127
115
  *
@@ -1,9 +1,13 @@
1
1
  import { drizzleAdapter } from "@better-auth/drizzle-adapter";
2
2
  import { betterAuth } from "better-auth";
3
+ import { hashPassword, verifyPassword } from "better-auth/crypto";
3
4
  import { createError } from "nuxt/server";
4
5
  import * as authSchema from "#qarpeo/auth/schema";
6
+ export { getRoleFromEnv } from "./role-env.mjs";
7
+ import { getRoleFromEnv as getRoleFromEnv2 } from "./role-env.mjs";
5
8
  import { getSessionSecret } from "./config.mjs";
6
9
  import { useDrizzle } from "./drizzle.mjs";
10
+ import { detectHashType, verifyLegacyPassword } from "./legacy-hash.mjs";
7
11
  import { resolveTableName, resolveIndexName } from "./table-names.mjs";
8
12
  const _authCache = /* @__PURE__ */ new Map();
9
13
  export function serverAuth(event) {
@@ -44,7 +48,30 @@ export function serverAuth(event) {
44
48
  secret: effectiveSecret,
45
49
  baseURL,
46
50
  emailAndPassword: {
47
- enabled: true
51
+ enabled: true,
52
+ password: {
53
+ verify: async ({ hash, password }) => {
54
+ const legacyType = detectHashType(hash);
55
+ if (legacyType !== "unknown") {
56
+ const { valid } = await verifyLegacyPassword(password, hash);
57
+ if (valid) {
58
+ try {
59
+ const newHash = await hashPassword(password);
60
+ const d1 = db?.$client || getD1Binding();
61
+ if (d1) {
62
+ const accountTable = resolveTableName("account").replace(/"/g, "");
63
+ await d1.prepare(
64
+ `UPDATE "${accountTable}" SET password = ?1, updated_at = ?2 WHERE password = ?3 AND provider_id = 'credential'`
65
+ ).bind(newHash, Math.floor(Date.now() / 1e3), hash).run();
66
+ }
67
+ } catch {
68
+ }
69
+ }
70
+ return valid;
71
+ }
72
+ return verifyPassword({ hash, password });
73
+ }
74
+ }
48
75
  },
49
76
  advanced: {
50
77
  database: {
@@ -82,6 +109,7 @@ export async function requireServerSession(event) {
82
109
  import { getD1Binding } from "../../db.mjs";
83
110
  import { getQarpeoConfig } from "./config.mjs";
84
111
  import { encryptToken } from "./crypto.mjs";
112
+ import { ensureRbacTables } from "./rbac.mjs";
85
113
  import { createDeviceSession, setAuthSession, revokeAllDeviceSessions } from "./session.mjs";
86
114
  let ensureAuthTablesPromise = null;
87
115
  export async function ensureAuthTables(d1, event) {
@@ -295,6 +323,8 @@ export async function ensureAuthTables(d1, event) {
295
323
  } catch {
296
324
  }
297
325
  }
326
+ await ensureRbacTables(d1, event).catch(() => {
327
+ });
298
328
  })().catch((err) => {
299
329
  ensureAuthTablesPromise = null;
300
330
  throw err;
@@ -546,40 +576,6 @@ export async function resolveMfaStatus(d1, user, authConfig = {}) {
546
576
  mfaVerified: !required
547
577
  };
548
578
  }
549
- function parseEmailList(raw) {
550
- if (!raw || typeof raw !== "string") return [];
551
- return raw.split(",").map((e) => e.trim().toLowerCase()).filter(Boolean);
552
- }
553
- export function getRoleFromEnv(arg1, arg2) {
554
- let event;
555
- let email;
556
- if (typeof arg1 === "string") {
557
- email = arg1;
558
- event = arg2;
559
- } else {
560
- event = arg1;
561
- email = typeof arg2 === "string" ? arg2 : "";
562
- }
563
- const normalizedEmail = (email || "").trim().toLowerCase();
564
- if (!normalizedEmail) return "user";
565
- const cfEnv = event?.context?.cloudflare?.env || globalThis.__qarpeo_env__ || {};
566
- const getVal = (key) => {
567
- if (cfEnv[key] !== void 0 && cfEnv[key] !== null) return String(cfEnv[key]);
568
- if (typeof process !== "undefined" && process?.env && process.env[key] !== void 0) {
569
- return String(process.env[key]);
570
- }
571
- return "";
572
- };
573
- const superEmails = parseEmailList(getVal("QARPEO_SUPER_EMAILS"));
574
- if (superEmails.includes(normalizedEmail)) return "super";
575
- const adminEmails = parseEmailList(getVal("QARPEO_ADMIN_EMAILS"));
576
- if (adminEmails.includes(normalizedEmail)) return "admin";
577
- const moderatorEmails = parseEmailList(getVal("QARPEO_MODERATOR_EMAILS"));
578
- if (moderatorEmails.includes(normalizedEmail)) return "moderator";
579
- const developerEmails = parseEmailList(getVal("QARPEO_DEVELOPER_EMAILS"));
580
- if (developerEmails.includes(normalizedEmail)) return "developer";
581
- return "user";
582
- }
583
579
  export async function resolveUserRole(arg1, arg2) {
584
580
  let event;
585
581
  let email;
@@ -591,7 +587,7 @@ export async function resolveUserRole(arg1, arg2) {
591
587
  email = typeof arg2 === "string" ? arg2 : "";
592
588
  }
593
589
  const normalizedEmail = (email || "").trim().toLowerCase();
594
- const suggestedRole = getRoleFromEnv(normalizedEmail, event);
590
+ const suggestedRole = getRoleFromEnv2(normalizedEmail, event);
595
591
  if (!normalizedEmail) {
596
592
  return {
597
593
  exists: false,
@@ -0,0 +1,8 @@
1
+ import { type RequestEvent } from "nuxt/server";
2
+ /**
3
+ * Verifies that an incoming request carries a valid `Authorization: Bearer <QARPEO_CLOUD_SECRET>`
4
+ * header matching the Worker's configured `QARPEO_CLOUD_SECRET` environment secret.
5
+ *
6
+ * Always fails closed (throws 401) if `QARPEO_CLOUD_SECRET` is not configured.
7
+ */
8
+ export declare function verifyCloudSecret(event: RequestEvent): void;
@@ -0,0 +1,23 @@
1
+ import { createError } from "nuxt/server";
2
+ import { timingSafeEqualString } from "./crypto.mjs";
3
+ export function verifyCloudSecret(event) {
4
+ const cfEnv = event.context?.cloudflare?.env;
5
+ const expected = typeof cfEnv?.QARPEO_CLOUD_SECRET === "string" && cfEnv.QARPEO_CLOUD_SECRET || typeof process !== "undefined" && process.env?.QARPEO_CLOUD_SECRET || "";
6
+ if (!expected) {
7
+ throw createError({
8
+ statusCode: 401,
9
+ statusMessage: "Unauthorized",
10
+ message: "[qarpeo] QARPEO_CLOUD_SECRET is not configured on this Worker."
11
+ });
12
+ }
13
+ const ev = event;
14
+ const authHeader = ev.req?.headers?.get?.("authorization") || ev.headers?.get?.("authorization") || ev.node?.req?.headers?.authorization || "";
15
+ const token = typeof authHeader === "string" && authHeader.startsWith("Bearer ") ? authHeader.slice(7).trim() : "";
16
+ if (!token || !timingSafeEqualString(token, expected)) {
17
+ throw createError({
18
+ statusCode: 401,
19
+ statusMessage: "Unauthorized",
20
+ message: "[qarpeo] Invalid QARPEO_CLOUD_SECRET token."
21
+ });
22
+ }
23
+ }
@@ -0,0 +1,19 @@
1
+ import { type RequestEvent } from "nuxt/server";
2
+ import { type ResolvedPermissions } from "./rbac";
3
+ /**
4
+ * Enforces that the current request has `console:access`.
5
+ * Throws 401 if unauthenticated, 403 if denied.
6
+ */
7
+ export declare function requireConsoleAccess(event: RequestEvent): Promise<ResolvedPermissions>;
8
+ /**
9
+ * Checks whether the current request has `console:access` without throwing.
10
+ */
11
+ export declare function hasConsoleAccess(event: RequestEvent): Promise<boolean>;
12
+ /**
13
+ * Enforces `console:access` AND the specified module/action permission(s).
14
+ *
15
+ * @param event - Nitro/H3 request event
16
+ * @param permission - Required permission key or list of keys
17
+ * @param match - `"all"` (default) requires every permission; `"any"` requires at least one
18
+ */
19
+ export declare function requireConsolePermission(event: RequestEvent, permission: string | string[], match?: "all" | "any"): Promise<ResolvedPermissions>;
@@ -0,0 +1,34 @@
1
+ import { createError } from "nuxt/server";
2
+ import { getAuthContext } from "./context.mjs";
3
+ import {
4
+ evaluatePermission,
5
+ hasPermission,
6
+ requirePermission
7
+ } from "./rbac.mjs";
8
+ export async function requireConsoleAccess(event) {
9
+ return requirePermission(event, "console:access");
10
+ }
11
+ export async function hasConsoleAccess(event) {
12
+ return hasPermission(event, "console:access");
13
+ }
14
+ export async function requireConsolePermission(event, permission, match = "all") {
15
+ const resolved = await requireConsoleAccess(event);
16
+ const requiredList = (Array.isArray(permission) ? permission : [permission]).filter(Boolean);
17
+ if (requiredList.length === 0) {
18
+ return resolved;
19
+ }
20
+ const auth = await getAuthContext(event);
21
+ const checkOne = (perm) => {
22
+ if (auth && !auth.hasScope(perm)) return false;
23
+ return evaluatePermission(resolved, perm);
24
+ };
25
+ const allowed = match === "any" ? requiredList.some(checkOne) : requiredList.every(checkOne);
26
+ if (!allowed) {
27
+ throw createError({
28
+ statusCode: 403,
29
+ statusMessage: "Forbidden",
30
+ message: `Missing console permission: ${requiredList.join(match === "any" ? " | " : ", ")}`
31
+ });
32
+ }
33
+ return resolved;
34
+ }
@@ -0,0 +1,76 @@
1
+ /**
2
+ * Legacy password hash verification helpers for migrating users from other auth systems.
3
+ *
4
+ * Better Auth uses `scrypt` (via `@noble/hashes/scrypt`) for all new hashes. This module
5
+ * provides pure-Web-Crypto / pure-JS fallbacks to verify passwords stored in older formats so
6
+ * that users can log in with their existing password, which is then transparently re-hashed to
7
+ * scrypt on successful verification.
8
+ *
9
+ * Supported legacy formats:
10
+ * - bcrypt — `$2a$`, `$2b$`, `$2x$`, `$2y$` prefix (requires `bcryptjs` dev dep)
11
+ * - Django PBKDF2-SHA256 — `pbkdf2_sha256$<iterations>$<salt>$<hash>` format (pure Web Crypto)
12
+ * - SHA-1 — 40-char hex (plain SHA-1, common in very old Rails / PHP apps)
13
+ * - MD5 — 32-char hex (plain MD5 — not supported, Web Crypto lacks MD5)
14
+ *
15
+ * Usage in `defineQarpeoAuth`:
16
+ * ```ts
17
+ * emailAndPassword: {
18
+ * verifyLegacyPassword: async (password, hash) => {
19
+ * return verifyLegacyPassword(password, hash)
20
+ * }
21
+ * }
22
+ * ```
23
+ */
24
+ /**
25
+ * Returns true if `hash` looks like a bcrypt hash (`$2a$`, `$2b$`, `$2x$`, `$2y$`).
26
+ */
27
+ export declare function isBcryptHash(hash: string): boolean;
28
+ /**
29
+ * Verifies a password against a bcrypt hash using `bcryptjs` (pure JS, works on CF Workers).
30
+ * Returns `false` if `bcryptjs` is not installed — install it as a dev dependency and add it
31
+ * to `optimizeDeps.include` / `noExternal` if needed.
32
+ */
33
+ export declare function verifyBcrypt(password: string, hash: string): Promise<boolean>;
34
+ /**
35
+ * Returns true if `hash` is a Django-style PBKDF2-SHA256 hash.
36
+ * Format: `pbkdf2_sha256$<iterations>$<salt>$<hash_base64>`
37
+ */
38
+ export declare function isDjangoPbkdf2Hash(hash: string): boolean;
39
+ /**
40
+ * Verifies a password against a Django PBKDF2-SHA256 hash using the Web Crypto API.
41
+ * This works without any external library on Cloudflare Workers.
42
+ */
43
+ export declare function verifyDjangoPbkdf2(password: string, hash: string): Promise<boolean>;
44
+ /**
45
+ * Returns true if `hash` looks like a plain 40-char hex SHA-1 digest.
46
+ */
47
+ export declare function isSha1Hash(hash: string): boolean;
48
+ /**
49
+ * Verifies a password against a plain SHA-1 hex hash using Web Crypto.
50
+ * Note: SHA-1 is cryptographically broken — this is provided only for migration.
51
+ */
52
+ export declare function verifySha1(password: string, hash: string): Promise<boolean>;
53
+ export type LegacyHashType = "bcrypt" | "pbkdf2_sha256" | "sha1" | "unknown";
54
+ /**
55
+ * Detects the hash type from the hash string.
56
+ */
57
+ export declare function detectHashType(hash: string): LegacyHashType;
58
+ /**
59
+ * Verifies a password against any supported legacy hash format.
60
+ * Returns `{ valid: boolean; type: LegacyHashType }`.
61
+ *
62
+ * Use this inside `verifyLegacyPassword` callback in `defineQarpeoAuth` options:
63
+ *
64
+ * ```ts
65
+ * emailAndPassword: {
66
+ * verifyLegacyPassword: async (password, hash) => {
67
+ * const { valid } = await verifyLegacyPassword(password, hash)
68
+ * return valid
69
+ * }
70
+ * }
71
+ * ```
72
+ */
73
+ export declare function verifyLegacyPassword(password: string, hash: string): Promise<{
74
+ valid: boolean;
75
+ type: LegacyHashType;
76
+ }>;
@@ -0,0 +1,96 @@
1
+ export function isBcryptHash(hash) {
2
+ return /^\$2[abxy]\$\d{2}\$/.test(hash);
3
+ }
4
+ export async function verifyBcrypt(password, hash) {
5
+ if (!isBcryptHash(hash)) return false;
6
+ try {
7
+ const bcrypt = await import("bcryptjs").catch(() => null);
8
+ if (!bcrypt) return false;
9
+ return bcrypt.compare(password, hash);
10
+ } catch {
11
+ return false;
12
+ }
13
+ }
14
+ export function isDjangoPbkdf2Hash(hash) {
15
+ return hash.startsWith("pbkdf2_sha256$");
16
+ }
17
+ export async function verifyDjangoPbkdf2(password, hash) {
18
+ if (!isDjangoPbkdf2Hash(hash)) return false;
19
+ try {
20
+ const parts = hash.split("$");
21
+ if (parts.length < 4) return false;
22
+ const iterations = parseInt(parts[1], 10);
23
+ const salt = parts[2];
24
+ const expectedBase64 = parts.slice(3).join("$");
25
+ const encoder = new TextEncoder();
26
+ const keyMaterial = await crypto.subtle.importKey(
27
+ "raw",
28
+ encoder.encode(password),
29
+ { name: "PBKDF2" },
30
+ false,
31
+ ["deriveBits"]
32
+ );
33
+ const derivedBits = await crypto.subtle.deriveBits(
34
+ {
35
+ name: "PBKDF2",
36
+ hash: "SHA-256",
37
+ salt: encoder.encode(salt),
38
+ iterations
39
+ },
40
+ keyMaterial,
41
+ 256
42
+ );
43
+ const derivedBase64 = btoa(String.fromCharCode(...new Uint8Array(derivedBits)));
44
+ const a = encoder.encode(derivedBase64);
45
+ const b = encoder.encode(expectedBase64);
46
+ if (a.byteLength !== b.byteLength) return false;
47
+ let diff = 0;
48
+ for (let i = 0; i < a.byteLength; i++) diff |= a[i] ^ b[i];
49
+ return diff === 0;
50
+ } catch {
51
+ return false;
52
+ }
53
+ }
54
+ export function isSha1Hash(hash) {
55
+ return /^[0-9a-f]{40}$/i.test(hash);
56
+ }
57
+ export async function verifySha1(password, hash) {
58
+ if (!isSha1Hash(hash)) return false;
59
+ try {
60
+ const encoder = new TextEncoder();
61
+ const digest = await crypto.subtle.digest("SHA-1", encoder.encode(password));
62
+ const hex = Array.from(new Uint8Array(digest)).map((b2) => b2.toString(16).padStart(2, "0")).join("");
63
+ const a = encoder.encode(hex.toLowerCase());
64
+ const b = encoder.encode(hash.toLowerCase());
65
+ if (a.byteLength !== b.byteLength) return false;
66
+ let diff = 0;
67
+ for (let i = 0; i < a.byteLength; i++) diff |= a[i] ^ b[i];
68
+ return diff === 0;
69
+ } catch {
70
+ return false;
71
+ }
72
+ }
73
+ export function detectHashType(hash) {
74
+ if (isBcryptHash(hash)) return "bcrypt";
75
+ if (isDjangoPbkdf2Hash(hash)) return "pbkdf2_sha256";
76
+ if (isSha1Hash(hash)) return "sha1";
77
+ return "unknown";
78
+ }
79
+ export async function verifyLegacyPassword(password, hash) {
80
+ const type = detectHashType(hash);
81
+ let valid = false;
82
+ switch (type) {
83
+ case "bcrypt":
84
+ valid = await verifyBcrypt(password, hash);
85
+ break;
86
+ case "pbkdf2_sha256":
87
+ valid = await verifyDjangoPbkdf2(password, hash);
88
+ break;
89
+ case "sha1":
90
+ valid = await verifySha1(password, hash);
91
+ break;
92
+ default:
93
+ valid = false;
94
+ }
95
+ return { valid, type };
96
+ }