qarpeo 0.3.5 → 0.4.1

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 (106) 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 +299 -57
  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/schema.d.ts +32 -12
  22. package/dist/runtime/schema.mjs +47 -125
  23. package/dist/runtime/server/routes/__qarpeo/cloud/agents/run.post.d.ts +13 -0
  24. package/dist/runtime/server/routes/__qarpeo/cloud/agents/run.post.mjs +46 -0
  25. package/dist/runtime/server/routes/__qarpeo/cloud/cms/entry.get.d.ts +22 -0
  26. package/dist/runtime/server/routes/__qarpeo/cloud/cms/entry.get.mjs +40 -0
  27. package/dist/runtime/server/routes/__qarpeo/cloud/cms/entry.post.d.ts +20 -0
  28. package/dist/runtime/server/routes/__qarpeo/cloud/cms/entry.post.mjs +52 -0
  29. package/dist/runtime/server/routes/__qarpeo/cloud/cms.get.d.ts +26 -0
  30. package/dist/runtime/server/routes/__qarpeo/cloud/cms.get.mjs +80 -0
  31. package/dist/runtime/server/routes/__qarpeo/cloud/comments/moderate.post.d.ts +16 -0
  32. package/dist/runtime/server/routes/__qarpeo/cloud/comments/moderate.post.mjs +30 -0
  33. package/dist/runtime/server/routes/__qarpeo/cloud/comments.get.d.ts +21 -0
  34. package/dist/runtime/server/routes/__qarpeo/cloud/comments.get.mjs +49 -0
  35. package/dist/runtime/server/routes/__qarpeo/cloud/extras.get.d.ts +22 -0
  36. package/dist/runtime/server/routes/__qarpeo/cloud/extras.get.mjs +65 -0
  37. package/dist/runtime/server/routes/__qarpeo/cloud/mail/unsuppress.post.d.ts +12 -0
  38. package/dist/runtime/server/routes/__qarpeo/cloud/mail/unsuppress.post.mjs +17 -0
  39. package/dist/runtime/server/routes/__qarpeo/cloud/migrate/cms.post.d.ts +22 -0
  40. package/dist/runtime/server/routes/__qarpeo/cloud/migrate/cms.post.mjs +87 -0
  41. package/dist/runtime/server/routes/__qarpeo/cloud/migrate/products.post.d.ts +25 -0
  42. package/dist/runtime/server/routes/__qarpeo/cloud/migrate/products.post.mjs +119 -0
  43. package/dist/runtime/server/routes/__qarpeo/cloud/migrate/users.post.d.ts +19 -0
  44. package/dist/runtime/server/routes/__qarpeo/cloud/migrate/users.post.mjs +86 -0
  45. package/dist/runtime/server/routes/__qarpeo/cloud/migrate.post.d.ts +21 -0
  46. package/dist/runtime/server/routes/__qarpeo/cloud/migrate.post.mjs +91 -0
  47. package/dist/runtime/server/routes/__qarpeo/cloud/notifications/test.post.d.ts +13 -0
  48. package/dist/runtime/server/routes/__qarpeo/cloud/notifications/test.post.mjs +49 -0
  49. package/dist/runtime/server/routes/__qarpeo/cloud/operations.get.d.ts +43 -0
  50. package/dist/runtime/server/routes/__qarpeo/cloud/operations.get.mjs +111 -0
  51. package/dist/runtime/server/routes/__qarpeo/cloud/overview.get.d.ts +22 -0
  52. package/dist/runtime/server/routes/__qarpeo/cloud/overview.get.mjs +44 -0
  53. package/dist/runtime/server/routes/__qarpeo/cloud/store/order-status.post.d.ts +9 -0
  54. package/dist/runtime/server/routes/__qarpeo/cloud/store/order-status.post.mjs +27 -0
  55. package/dist/runtime/server/routes/__qarpeo/cloud/store/orders.get.d.ts +23 -0
  56. package/dist/runtime/server/routes/__qarpeo/cloud/store/orders.get.mjs +56 -0
  57. package/dist/runtime/server/routes/__qarpeo/cloud/store/products.get.d.ts +21 -0
  58. package/dist/runtime/server/routes/__qarpeo/cloud/store/products.get.mjs +50 -0
  59. package/dist/runtime/server/routes/__qarpeo/cloud/tasks/run.post.d.ts +12 -0
  60. package/dist/runtime/server/routes/__qarpeo/cloud/tasks/run.post.mjs +24 -0
  61. package/dist/runtime/server/routes/__qarpeo/cloud/users/action.post.d.ts +26 -0
  62. package/dist/runtime/server/routes/__qarpeo/cloud/users/action.post.mjs +40 -0
  63. package/dist/runtime/server/routes/__qarpeo/cloud/users.get.d.ts +39 -0
  64. package/dist/runtime/server/routes/__qarpeo/cloud/users.get.mjs +69 -0
  65. package/dist/runtime/server/routes/__qarpeo/manifest.get.d.ts +39 -0
  66. package/dist/runtime/server/routes/__qarpeo/manifest.get.mjs +226 -0
  67. package/dist/runtime/server/routes/__qarpeo/og.get.d.ts +15 -0
  68. package/dist/runtime/server/routes/__qarpeo/og.get.mjs +109 -0
  69. package/dist/runtime/server/routes/__qarpeo/rbac/me.get.d.ts +26 -0
  70. package/dist/runtime/server/routes/__qarpeo/rbac/me.get.mjs +23 -0
  71. package/dist/runtime/server/routes/__qarpeo/rbac/roles.delete.d.ts +12 -0
  72. package/dist/runtime/server/routes/__qarpeo/rbac/roles.delete.mjs +12 -0
  73. package/dist/runtime/server/routes/__qarpeo/rbac/roles.get.d.ts +16 -0
  74. package/dist/runtime/server/routes/__qarpeo/rbac/roles.get.mjs +15 -0
  75. package/dist/runtime/server/routes/__qarpeo/rbac/roles.post.d.ts +11 -0
  76. package/dist/runtime/server/routes/__qarpeo/rbac/roles.post.mjs +16 -0
  77. package/dist/runtime/server/routes/__qarpeo/rbac/users.post.d.ts +14 -0
  78. package/dist/runtime/server/routes/__qarpeo/rbac/users.post.mjs +19 -0
  79. package/dist/runtime/server/routes/manifest.webmanifest.get.d.ts +2 -0
  80. package/dist/runtime/server/routes/manifest.webmanifest.get.mjs +31 -0
  81. package/dist/runtime/server/routes/robots.txt.get.mjs +20 -4
  82. package/dist/runtime/server/routes/sitemap.xml.get.mjs +47 -6
  83. package/dist/runtime/server/routes/sw.js.get.d.ts +8 -0
  84. package/dist/runtime/server/routes/sw.js.get.mjs +141 -0
  85. package/dist/runtime/server/utils/auth.d.ts +2 -14
  86. package/dist/runtime/server/utils/auth.mjs +32 -36
  87. package/dist/runtime/server/utils/cloud-auth.d.ts +8 -0
  88. package/dist/runtime/server/utils/cloud-auth.mjs +23 -0
  89. package/dist/runtime/server/utils/console.d.ts +19 -0
  90. package/dist/runtime/server/utils/console.mjs +34 -0
  91. package/dist/runtime/server/utils/legacy-hash.d.ts +76 -0
  92. package/dist/runtime/server/utils/legacy-hash.mjs +96 -0
  93. package/dist/runtime/server/utils/rbac.d.ts +89 -0
  94. package/dist/runtime/server/utils/rbac.mjs +427 -0
  95. package/dist/runtime/server/utils/role-env.d.ts +19 -0
  96. package/dist/runtime/server/utils/role-env.mjs +34 -0
  97. package/dist/runtime/server.d.ts +2 -0
  98. package/dist/runtime/server.mjs +2 -0
  99. package/dist/types/console.d.ts +67 -0
  100. package/dist/types/index.d.ts +1 -0
  101. package/dist/types/options.d.ts +9 -0
  102. package/dist/types/site.d.ts +102 -0
  103. package/dist/types/storage.d.ts +5 -11
  104. package/package.json +1 -1
  105. package/dist/runtime/providers/qarpeo.d.ts +0 -23
  106. package/dist/runtime/providers/qarpeo.mjs +0 -46
@@ -0,0 +1,26 @@
1
+ /**
2
+ * GET /__qarpeo/rbac/me
3
+ *
4
+ * Returns the current authenticated user's resolved roles, effective role
5
+ * permissions, and per-user `allow` / `deny` overrides for client UI checks (`useCan`).
6
+ */
7
+ declare const _default: import("nuxt/server").EventHandler<Promise<{
8
+ authenticated: boolean;
9
+ userId: null;
10
+ primaryRole: null;
11
+ roles: string[];
12
+ isSuper: boolean;
13
+ rolePermissions: string[];
14
+ allow: string[];
15
+ deny: string[];
16
+ } | {
17
+ userId: string;
18
+ primaryRole: string;
19
+ roles: string[];
20
+ isSuper: boolean;
21
+ rolePermissions: string[];
22
+ allow: string[];
23
+ deny: string[];
24
+ authenticated: boolean;
25
+ }>>;
26
+ export default _default;
@@ -0,0 +1,23 @@
1
+ import { defineEventHandler } from "nuxt/server";
2
+ import { getAuthContext } from "../../../utils/context.mjs";
3
+ import { resolveUserPermissions } from "../../../utils/rbac.mjs";
4
+ export default defineEventHandler(async (event) => {
5
+ const auth = await getAuthContext(event);
6
+ if (!auth?.user?.id) {
7
+ return {
8
+ authenticated: false,
9
+ userId: null,
10
+ primaryRole: null,
11
+ roles: [],
12
+ isSuper: false,
13
+ rolePermissions: [],
14
+ allow: [],
15
+ deny: []
16
+ };
17
+ }
18
+ const resolved = await resolveUserPermissions(auth.user, event);
19
+ return {
20
+ authenticated: true,
21
+ ...resolved
22
+ };
23
+ });
@@ -0,0 +1,12 @@
1
+ /**
2
+ * DELETE /__qarpeo/rbac/roles?id=<roleId>
3
+ *
4
+ * Deletes a custom role or resets an overridden built-in role back to code defaults.
5
+ * Requires `roles:manage` (or `super`).
6
+ */
7
+ declare const _default: import("nuxt/server").EventHandler<Promise<{
8
+ reset: boolean;
9
+ ok: boolean;
10
+ id: string;
11
+ }>>;
12
+ export default _default;
@@ -0,0 +1,12 @@
1
+ import { createError, defineEventHandler, getQuery, readBody } from "nuxt/server";
2
+ import { deleteRole } from "../../../utils/rbac.mjs";
3
+ export default defineEventHandler(async (event) => {
4
+ const qs = getQuery(event);
5
+ const body = await readBody(event).catch(() => ({}));
6
+ const roleId = typeof qs?.id === "string" && qs.id.trim() || typeof body?.id === "string" && body.id.trim() || "";
7
+ if (!roleId) {
8
+ throw createError({ statusCode: 400, statusMessage: "Bad Request", message: "role id is required." });
9
+ }
10
+ const result = await deleteRole(event, roleId);
11
+ return { ok: true, id: roleId, ...result };
12
+ });
@@ -0,0 +1,16 @@
1
+ /**
2
+ * GET /__qarpeo/rbac/roles
3
+ *
4
+ * Lists all built-in + D1-overridden + custom roles and the standard permission catalog.
5
+ * Requires `roles:manage` (or `super`).
6
+ */
7
+ declare const _default: import("nuxt/server").EventHandler<Promise<{
8
+ ok: boolean;
9
+ roles: import("../../../..").RoleDefinition[];
10
+ catalog: readonly {
11
+ key: string;
12
+ module: "console" | "cms" | "store" | "comments" | "media" | "users" | "roles";
13
+ description: string;
14
+ }[];
15
+ }>>;
16
+ export default _default;
@@ -0,0 +1,15 @@
1
+ import { defineEventHandler } from "nuxt/server";
2
+ import {
3
+ listRoles,
4
+ PERMISSION_CATALOG,
5
+ requirePermission
6
+ } from "../../../utils/rbac.mjs";
7
+ export default defineEventHandler(async (event) => {
8
+ await requirePermission(event, "roles:manage");
9
+ const roles = await listRoles(event);
10
+ return {
11
+ ok: true,
12
+ roles,
13
+ catalog: PERMISSION_CATALOG
14
+ };
15
+ });
@@ -0,0 +1,11 @@
1
+ /**
2
+ * POST /__qarpeo/rbac/roles
3
+ *
4
+ * Creates or updates a role's permissions in D1.
5
+ * Requires `roles:manage` (or `super`). `super` itself is immutable.
6
+ */
7
+ declare const _default: import("nuxt/server").EventHandler<Promise<{
8
+ ok: boolean;
9
+ role: import("../../../..").RoleDefinition;
10
+ }>>;
11
+ export default _default;
@@ -0,0 +1,16 @@
1
+ import { createError, defineEventHandler, readBody } from "nuxt/server";
2
+ import { upsertRole } from "../../../utils/rbac.mjs";
3
+ export default defineEventHandler(async (event) => {
4
+ const body = await readBody(event).catch(() => ({}));
5
+ const id = typeof body?.id === "string" ? body.id.trim() : "";
6
+ if (!id) {
7
+ throw createError({ statusCode: 400, statusMessage: "Bad Request", message: "role id is required." });
8
+ }
9
+ const role = await upsertRole(event, {
10
+ id,
11
+ name: typeof body?.name === "string" ? body.name : id,
12
+ description: typeof body?.description === "string" ? body.description : void 0,
13
+ permissions: Array.isArray(body?.permissions) ? body.permissions : []
14
+ });
15
+ return { ok: true, role };
16
+ });
@@ -0,0 +1,14 @@
1
+ /**
2
+ * POST /__qarpeo/rbac/users
3
+ *
4
+ * Updates per-user `extraRoles`, `allow`, and `deny` permission overrides in D1.
5
+ * Requires `roles:manage` (or `super`).
6
+ */
7
+ declare const _default: import("nuxt/server").EventHandler<Promise<{
8
+ userId: string;
9
+ extraRoles: string[];
10
+ allow: string[];
11
+ deny: string[];
12
+ ok: boolean;
13
+ }>>;
14
+ export default _default;
@@ -0,0 +1,19 @@
1
+ import { createError, defineEventHandler, readBody } from "nuxt/server";
2
+ import { setUserPermissions } from "../../../utils/rbac.mjs";
3
+ export default defineEventHandler(async (event) => {
4
+ const body = await readBody(event).catch(() => ({}));
5
+ const userId = typeof body?.userId === "string" ? body.userId.trim() : "";
6
+ if (!userId) {
7
+ throw createError({
8
+ statusCode: 400,
9
+ statusMessage: "Bad Request",
10
+ message: "userId is required."
11
+ });
12
+ }
13
+ const overrides = await setUserPermissions(event, userId, {
14
+ extraRoles: Array.isArray(body?.extraRoles) ? body.extraRoles : [],
15
+ allow: Array.isArray(body?.allow) ? body.allow : [],
16
+ deny: Array.isArray(body?.deny) ? body.deny : []
17
+ });
18
+ return { ok: true, ...overrides };
19
+ });
@@ -0,0 +1,2 @@
1
+ declare const _default: import("nuxt/server").EventHandler<Response>;
2
+ export default _default;
@@ -0,0 +1,31 @@
1
+ import { defineEventHandler, useRuntimeConfig } from "nuxt/server";
2
+ export default defineEventHandler((event) => {
3
+ const rc = useRuntimeConfig(event) || globalThis.__NUXT_RUNTIME_CONFIG__ || {};
4
+ const qarpeoPublic = rc.public?.qarpeo || {};
5
+ const site = qarpeoPublic.site || {};
6
+ const pwa = qarpeoPublic.pwa || {};
7
+ const name = pwa.name || site.name || "Qarpeo App";
8
+ const shortName = pwa.shortName || (name.length > 16 ? name.slice(0, 16).trim() : name);
9
+ const manifest = {
10
+ name,
11
+ short_name: shortName,
12
+ description: pwa.description || site.description || void 0,
13
+ start_url: pwa.startUrl || "/",
14
+ scope: pwa.scope || "/",
15
+ display: pwa.display || "standalone",
16
+ theme_color: pwa.themeColor || "#0f172a",
17
+ background_color: pwa.backgroundColor || "#ffffff",
18
+ lang: pwa.lang || site.defaultLocale || "en"
19
+ };
20
+ if (pwa.orientation) manifest.orientation = pwa.orientation;
21
+ if (pwa.dir) manifest.dir = pwa.dir;
22
+ if (pwa.icons?.length) manifest.icons = pwa.icons;
23
+ if (pwa.shortcuts?.length) manifest.shortcuts = pwa.shortcuts;
24
+ if (pwa.categories?.length) manifest.categories = pwa.categories;
25
+ return new Response(JSON.stringify(manifest, null, 2), {
26
+ headers: {
27
+ "Content-Type": "application/manifest+json; charset=UTF-8",
28
+ "Cache-Control": "public, max-age=3600, s-maxage=86400"
29
+ }
30
+ });
31
+ });
@@ -1,6 +1,16 @@
1
- import { defineEventHandler } from "nuxt/server";
2
- export default defineEventHandler((_event) => {
3
- const runtimeConfig = globalThis.__NUXT_RUNTIME_CONFIG__ || {};
1
+ import { defineEventHandler, useRuntimeConfig } from "nuxt/server";
2
+ const AI_CRAWLER_AGENTS = [
3
+ "GPTBot",
4
+ "ChatGPT-User",
5
+ "CCBot",
6
+ "ClaudeBot",
7
+ "anthropic-ai",
8
+ "Google-Extended",
9
+ "Bytespider",
10
+ "PerplexityBot"
11
+ ];
12
+ export default defineEventHandler((event) => {
13
+ const runtimeConfig = useRuntimeConfig(event) || globalThis.__NUXT_RUNTIME_CONFIG__ || {};
4
14
  const site = runtimeConfig.public?.qarpeo?.site || {};
5
15
  const procEnv = globalThis.process?.env || {};
6
16
  const isDev = procEnv.NODE_ENV !== "production";
@@ -25,11 +35,17 @@ Disallow: /
25
35
  for (const rule of disallowRules) {
26
36
  lines.push(`Disallow: ${rule}`);
27
37
  }
38
+ if (robotsConfig.blockAiBots) {
39
+ lines.push("", "# AI Crawler Restrictions");
40
+ for (const agent of AI_CRAWLER_AGENTS) {
41
+ lines.push(`User-agent: ${agent}`, "Disallow: /", "");
42
+ }
43
+ }
28
44
  if (site.url && site.sitemap !== false) {
29
45
  const sitemapUrl = `${site.url.replace(/\/$/, "")}/sitemap.xml`;
30
46
  lines.push("", `Sitemap: ${sitemapUrl}`);
31
47
  }
32
- content = `${lines.join("\n")}
48
+ content = `${lines.join("\n").replace(/\n{3,}/g, "\n\n")}
33
49
  `;
34
50
  }
35
51
  return new Response(content, {
@@ -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;