@hintergrund/worker 0.1.6 → 0.1.8

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 (190) hide show
  1. package/dist/api/cms/handlers/admin-users.handler.d.ts +8 -0
  2. package/dist/api/cms/handlers/admin-users.handler.d.ts.map +1 -0
  3. package/dist/api/cms/handlers/admin-users.handler.js +121 -0
  4. package/dist/api/cms/handlers/agent-conversations.handler.d.ts +7 -0
  5. package/dist/api/cms/handlers/agent-conversations.handler.d.ts.map +1 -0
  6. package/dist/api/cms/handlers/agent-conversations.handler.js +94 -0
  7. package/dist/api/cms/handlers/auth.handler.d.ts +0 -3
  8. package/dist/api/cms/handlers/auth.handler.d.ts.map +1 -1
  9. package/dist/api/cms/handlers/auth.handler.js +74 -153
  10. package/dist/api/cms/handlers/dashboard.handler.js +1 -1
  11. package/dist/api/cms/handlers/website-repo.handler.d.ts +8 -0
  12. package/dist/api/cms/handlers/website-repo.handler.d.ts.map +1 -0
  13. package/dist/api/cms/handlers/website-repo.handler.js +148 -0
  14. package/dist/api/cms/routes/index.d.ts.map +1 -1
  15. package/dist/api/cms/routes/index.js +16 -4
  16. package/dist/api/emails/handlers/campaigns.handler.d.ts +10 -23
  17. package/dist/api/emails/handlers/campaigns.handler.d.ts.map +1 -1
  18. package/dist/api/emails/handlers/campaigns.handler.js +164 -92
  19. package/dist/api/emails/handlers/invoice.handler.d.ts +5 -19
  20. package/dist/api/emails/handlers/invoice.handler.d.ts.map +1 -1
  21. package/dist/api/emails/handlers/invoice.handler.js +58 -340
  22. package/dist/api/emails/handlers/public.handler.d.ts +6 -29
  23. package/dist/api/emails/handlers/public.handler.d.ts.map +1 -1
  24. package/dist/api/emails/handlers/public.handler.js +150 -312
  25. package/dist/api/emails/handlers/send.handler.d.ts +5 -17
  26. package/dist/api/emails/handlers/send.handler.d.ts.map +1 -1
  27. package/dist/api/emails/handlers/send.handler.js +107 -92
  28. package/dist/api/emails/handlers/settings.handler.d.ts +28 -33
  29. package/dist/api/emails/handlers/settings.handler.d.ts.map +1 -1
  30. package/dist/api/emails/handlers/settings.handler.js +96 -287
  31. package/dist/api/emails/handlers/subscribers.handler.d.ts +13 -0
  32. package/dist/api/emails/handlers/subscribers.handler.d.ts.map +1 -0
  33. package/dist/api/emails/handlers/subscribers.handler.js +125 -0
  34. package/dist/api/emails/handlers/webhook.handler.d.ts +1 -2
  35. package/dist/api/emails/handlers/webhook.handler.d.ts.map +1 -1
  36. package/dist/api/emails/handlers/webhook.handler.js +66 -166
  37. package/dist/api/emails/routes/admin.routes.d.ts +1 -3
  38. package/dist/api/emails/routes/admin.routes.d.ts.map +1 -1
  39. package/dist/api/emails/routes/admin.routes.js +19 -49
  40. package/dist/api/emails/routes/public.routes.d.ts +1 -3
  41. package/dist/api/emails/routes/public.routes.d.ts.map +1 -1
  42. package/dist/api/emails/routes/public.routes.js +2 -9
  43. package/dist/api/shop/handlers/prices.handler.d.ts +2 -15
  44. package/dist/api/shop/handlers/prices.handler.d.ts.map +1 -1
  45. package/dist/api/shop/handlers/prices.handler.js +2 -83
  46. package/dist/api/shop/handlers/products.handler.d.ts +29 -20
  47. package/dist/api/shop/handlers/products.handler.d.ts.map +1 -1
  48. package/dist/api/shop/handlers/products.handler.js +195 -162
  49. package/dist/api/shop/handlers/public.handler.d.ts +24 -8
  50. package/dist/api/shop/handlers/public.handler.d.ts.map +1 -1
  51. package/dist/api/shop/handlers/public.handler.js +525 -78
  52. package/dist/api/shop/routes.d.ts.map +1 -1
  53. package/dist/api/shop/routes.js +14 -9
  54. package/dist/hintergrund-assets.d.ts +3 -2
  55. package/dist/hintergrund-assets.d.ts.map +1 -1
  56. package/dist/hintergrund-assets.js +4 -2
  57. package/dist/index.d.ts +15 -8
  58. package/dist/index.d.ts.map +1 -1
  59. package/dist/index.js +44 -4
  60. package/dist/lib/auth/crypto.d.ts +2 -15
  61. package/dist/lib/auth/crypto.d.ts.map +1 -1
  62. package/dist/lib/auth/crypto.js +8 -95
  63. package/dist/lib/auth/jwt.d.ts +0 -4
  64. package/dist/lib/auth/jwt.d.ts.map +1 -1
  65. package/dist/lib/auth/jwt.js +0 -6
  66. package/dist/lib/config.d.ts +8 -10
  67. package/dist/lib/config.d.ts.map +1 -1
  68. package/dist/lib/config.js +30 -106
  69. package/dist/lib/email-template.d.ts +15 -0
  70. package/dist/lib/email-template.d.ts.map +1 -0
  71. package/dist/lib/email-template.js +58 -0
  72. package/dist/lib/email.d.ts +18 -8
  73. package/dist/lib/email.d.ts.map +1 -1
  74. package/dist/lib/email.js +59 -70
  75. package/dist/lib/github-app.d.ts +2 -0
  76. package/dist/lib/github-app.d.ts.map +1 -0
  77. package/dist/lib/github-app.js +49 -0
  78. package/dist/lib/github-config.d.ts +19 -0
  79. package/dist/lib/github-config.d.ts.map +1 -0
  80. package/dist/lib/github-config.js +23 -0
  81. package/dist/lib/github.d.ts +16 -3
  82. package/dist/lib/github.d.ts.map +1 -1
  83. package/dist/lib/github.js +38 -15
  84. package/dist/lib/project-db.d.ts +24 -0
  85. package/dist/lib/project-db.d.ts.map +1 -0
  86. package/dist/lib/project-db.js +172 -0
  87. package/dist/lib/template.js +4 -4
  88. package/dist/middleware/auth.d.ts +0 -2
  89. package/dist/middleware/auth.d.ts.map +1 -1
  90. package/dist/middleware/auth.js +21 -50
  91. package/package.json +3 -2
  92. package/dist/api/builder/handlers/generate.handler.d.ts +0 -12
  93. package/dist/api/builder/handlers/generate.handler.d.ts.map +0 -1
  94. package/dist/api/builder/handlers/generate.handler.js +0 -203
  95. package/dist/api/builder/handlers/template.handler.d.ts +0 -12
  96. package/dist/api/builder/handlers/template.handler.d.ts.map +0 -1
  97. package/dist/api/builder/handlers/template.handler.js +0 -208
  98. package/dist/api/builder/routes.d.ts +0 -7
  99. package/dist/api/builder/routes.d.ts.map +0 -1
  100. package/dist/api/builder/routes.js +0 -15
  101. package/dist/api/cms/handlers/assets.handler.d.ts +0 -31
  102. package/dist/api/cms/handlers/assets.handler.d.ts.map +0 -1
  103. package/dist/api/cms/handlers/assets.handler.js +0 -200
  104. package/dist/api/cms/handlers/config.handler.d.ts +0 -7
  105. package/dist/api/cms/handlers/config.handler.d.ts.map +0 -1
  106. package/dist/api/cms/handlers/config.handler.js +0 -37
  107. package/dist/api/cms/handlers/content.handler.d.ts +0 -21
  108. package/dist/api/cms/handlers/content.handler.d.ts.map +0 -1
  109. package/dist/api/cms/handlers/content.handler.js +0 -117
  110. package/dist/api/cms/routes/assets.routes.d.ts +0 -4
  111. package/dist/api/cms/routes/assets.routes.d.ts.map +0 -1
  112. package/dist/api/cms/routes/assets.routes.js +0 -13
  113. package/dist/api/cms/routes/content.routes.d.ts +0 -4
  114. package/dist/api/cms/routes/content.routes.d.ts.map +0 -1
  115. package/dist/api/cms/routes/content.routes.js +0 -11
  116. package/dist/api/emails/handlers/branding.handler.d.ts +0 -17
  117. package/dist/api/emails/handlers/branding.handler.d.ts.map +0 -1
  118. package/dist/api/emails/handlers/branding.handler.js +0 -120
  119. package/dist/api/emails/handlers/contacts.handler.d.ts +0 -37
  120. package/dist/api/emails/handlers/contacts.handler.d.ts.map +0 -1
  121. package/dist/api/emails/handlers/contacts.handler.js +0 -161
  122. package/dist/api/emails/handlers/templates.handler.d.ts +0 -32
  123. package/dist/api/emails/handlers/templates.handler.d.ts.map +0 -1
  124. package/dist/api/emails/handlers/templates.handler.js +0 -132
  125. package/dist/api/newsletter/handlers/email.handler.d.ts +0 -7
  126. package/dist/api/newsletter/handlers/email.handler.d.ts.map +0 -1
  127. package/dist/api/newsletter/handlers/email.handler.js +0 -102
  128. package/dist/api/newsletter/handlers/emails.handler.d.ts +0 -31
  129. package/dist/api/newsletter/handlers/emails.handler.d.ts.map +0 -1
  130. package/dist/api/newsletter/handlers/emails.handler.js +0 -262
  131. package/dist/api/newsletter/handlers/invoice.handler.d.ts +0 -22
  132. package/dist/api/newsletter/handlers/invoice.handler.d.ts.map +0 -1
  133. package/dist/api/newsletter/handlers/invoice.handler.js +0 -455
  134. package/dist/api/newsletter/handlers/public.handler.d.ts +0 -22
  135. package/dist/api/newsletter/handlers/public.handler.d.ts.map +0 -1
  136. package/dist/api/newsletter/handlers/public.handler.js +0 -300
  137. package/dist/api/newsletter/handlers/send.handler.d.ts +0 -12
  138. package/dist/api/newsletter/handlers/send.handler.d.ts.map +0 -1
  139. package/dist/api/newsletter/handlers/send.handler.js +0 -153
  140. package/dist/api/newsletter/handlers/subscribers.handler.d.ts +0 -22
  141. package/dist/api/newsletter/handlers/subscribers.handler.d.ts.map +0 -1
  142. package/dist/api/newsletter/handlers/subscribers.handler.js +0 -195
  143. package/dist/api/newsletter/routes/admin.routes.d.ts +0 -4
  144. package/dist/api/newsletter/routes/admin.routes.d.ts.map +0 -1
  145. package/dist/api/newsletter/routes/admin.routes.js +0 -28
  146. package/dist/api/newsletter/routes/index.d.ts +0 -4
  147. package/dist/api/newsletter/routes/index.d.ts.map +0 -1
  148. package/dist/api/newsletter/routes/index.js +0 -9
  149. package/dist/api/newsletter/routes/public.routes.d.ts +0 -4
  150. package/dist/api/newsletter/routes/public.routes.d.ts.map +0 -1
  151. package/dist/api/newsletter/routes/public.routes.js +0 -9
  152. package/dist/api/shop/handlers/assets.handler.d.ts +0 -3
  153. package/dist/api/shop/handlers/assets.handler.d.ts.map +0 -1
  154. package/dist/api/shop/handlers/assets.handler.js +0 -62
  155. package/dist/api/shop/handlers/checkout.handler.d.ts +0 -10
  156. package/dist/api/shop/handlers/checkout.handler.d.ts.map +0 -1
  157. package/dist/api/shop/handlers/checkout.handler.js +0 -50
  158. package/dist/api/shop/handlers/customers.handler.d.ts +0 -17
  159. package/dist/api/shop/handlers/customers.handler.d.ts.map +0 -1
  160. package/dist/api/shop/handlers/customers.handler.js +0 -89
  161. package/dist/api/shop/handlers/orders.handler.d.ts +0 -17
  162. package/dist/api/shop/handlers/orders.handler.d.ts.map +0 -1
  163. package/dist/api/shop/handlers/orders.handler.js +0 -84
  164. package/dist/api/shop/handlers/stats.handler.d.ts +0 -10
  165. package/dist/api/shop/handlers/stats.handler.d.ts.map +0 -1
  166. package/dist/api/shop/handlers/stats.handler.js +0 -71
  167. package/dist/api/shop/handlers/webhook.handler.d.ts +0 -10
  168. package/dist/api/shop/handlers/webhook.handler.d.ts.map +0 -1
  169. package/dist/api/shop/handlers/webhook.handler.js +0 -233
  170. package/dist/cms-assets.d.ts +0 -4
  171. package/dist/cms-assets.d.ts.map +0 -1
  172. package/dist/cms-assets.js +0 -5
  173. package/dist/cms-bundle.d.ts +0 -3
  174. package/dist/cms-bundle.d.ts.map +0 -1
  175. package/dist/cms-bundle.js +0 -4
  176. package/dist/config-loader.d.ts +0 -26
  177. package/dist/config-loader.d.ts.map +0 -1
  178. package/dist/config-loader.js +0 -98
  179. package/dist/jwt.d.ts +0 -26
  180. package/dist/jwt.d.ts.map +0 -1
  181. package/dist/jwt.js +0 -102
  182. package/dist/lib/plunk.d.ts +0 -204
  183. package/dist/lib/plunk.d.ts.map +0 -1
  184. package/dist/lib/plunk.js +0 -259
  185. package/dist/template.d.ts +0 -2
  186. package/dist/template.d.ts.map +0 -1
  187. package/dist/template.js +0 -61
  188. package/dist/utils.d.ts +0 -23
  189. package/dist/utils.d.ts.map +0 -1
  190. package/dist/utils.js +0 -110
@@ -0,0 +1,172 @@
1
+ // Full project schema — all modules in one place.
2
+ // Mirrors db/schema.sql exactly; kept in sync manually.
3
+ // All statements use IF NOT EXISTS so this is safe to re-run on an existing DB.
4
+ export const PROJECT_SCHEMA_SQL = `
5
+ CREATE TABLE IF NOT EXISTS admin_users (
6
+ id TEXT NOT NULL PRIMARY KEY,
7
+ email TEXT NOT NULL UNIQUE,
8
+ name TEXT,
9
+ password_hash TEXT,
10
+ login_method TEXT NOT NULL CHECK(login_method IN ('password', 'magic-link')),
11
+ disabled_at INTEGER,
12
+ created_at INTEGER NOT NULL,
13
+ updated_at INTEGER NOT NULL
14
+ );
15
+
16
+ CREATE TABLE IF NOT EXISTS admin_magic_links (
17
+ id TEXT NOT NULL PRIMARY KEY,
18
+ user_id TEXT NOT NULL REFERENCES admin_users(id) ON DELETE CASCADE,
19
+ token_hash TEXT NOT NULL UNIQUE,
20
+ expires_at INTEGER NOT NULL,
21
+ used_at INTEGER,
22
+ created_at INTEGER NOT NULL
23
+ );
24
+
25
+ CREATE TABLE IF NOT EXISTS agent_conversations (
26
+ id TEXT NOT NULL PRIMARY KEY,
27
+ user_id TEXT NOT NULL REFERENCES admin_users(id) ON DELETE CASCADE,
28
+ mode TEXT NOT NULL CHECK(mode IN ('builder', 'cms')),
29
+ title TEXT NOT NULL,
30
+ messages_json TEXT NOT NULL,
31
+ model_metadata_json TEXT NOT NULL DEFAULT '{}',
32
+ git_diff TEXT,
33
+ created_at INTEGER NOT NULL,
34
+ updated_at INTEGER NOT NULL
35
+ );
36
+
37
+ CREATE INDEX IF NOT EXISTS idx_admin_magic_links_token ON admin_magic_links(token_hash);
38
+ CREATE INDEX IF NOT EXISTS idx_agent_conversations_user_mode ON agent_conversations(user_id, mode, updated_at);
39
+
40
+ CREATE TABLE IF NOT EXISTS subscribers (
41
+ id TEXT NOT NULL PRIMARY KEY,
42
+ email TEXT NOT NULL UNIQUE,
43
+ name TEXT,
44
+ status TEXT NOT NULL DEFAULT 'pending' CHECK(status IN ('pending', 'subscribed', 'unsubscribed', 'bounced', 'complained')),
45
+ source TEXT NOT NULL DEFAULT 'website' CHECK(source IN ('manual', 'import', 'website')),
46
+ data_json TEXT NOT NULL DEFAULT '{}',
47
+ confirmation_token TEXT,
48
+ confirmation_sent_at INTEGER,
49
+ confirmed_at INTEGER,
50
+ subscribed_at INTEGER,
51
+ unsubscribed_at INTEGER,
52
+ unsubscribe_token TEXT,
53
+ created_at INTEGER NOT NULL,
54
+ updated_at INTEGER NOT NULL
55
+ );
56
+
57
+ CREATE UNIQUE INDEX IF NOT EXISTS idx_subscribers_email ON subscribers(email);
58
+ CREATE INDEX IF NOT EXISTS idx_subscribers_status ON subscribers(status);
59
+ CREATE INDEX IF NOT EXISTS idx_subscribers_created_at ON subscribers(created_at DESC);
60
+ CREATE INDEX IF NOT EXISTS idx_subscribers_source ON subscribers(source);
61
+
62
+ CREATE TABLE IF NOT EXISTS campaigns (
63
+ id TEXT NOT NULL PRIMARY KEY,
64
+ name TEXT NOT NULL,
65
+ subject TEXT NOT NULL,
66
+ body_html TEXT NOT NULL,
67
+ status TEXT NOT NULL DEFAULT 'draft' CHECK(status IN ('draft', 'scheduled', 'sent')),
68
+ recipient_count INTEGER,
69
+ scheduled_at INTEGER,
70
+ sent_at INTEGER,
71
+ created_at INTEGER NOT NULL,
72
+ updated_at INTEGER NOT NULL
73
+ );
74
+
75
+ CREATE INDEX IF NOT EXISTS idx_campaigns_status ON campaigns(status);
76
+ CREATE INDEX IF NOT EXISTS idx_campaigns_created_at ON campaigns(created_at DESC);
77
+
78
+ CREATE TABLE IF NOT EXISTS email_sends (
79
+ id TEXT NOT NULL PRIMARY KEY,
80
+ type TEXT NOT NULL CHECK(type IN ('campaign', 'transactional', 'auto')),
81
+ campaign_id TEXT REFERENCES campaigns(id) ON DELETE SET NULL,
82
+ subject TEXT NOT NULL,
83
+ recipient_count INTEGER NOT NULL DEFAULT 0,
84
+ status TEXT NOT NULL DEFAULT 'queued' CHECK(status IN ('queued', 'sent', 'failed')),
85
+ error TEXT,
86
+ sent_at INTEGER,
87
+ created_at INTEGER NOT NULL
88
+ );
89
+
90
+ CREATE INDEX IF NOT EXISTS idx_email_sends_type ON email_sends(type);
91
+ CREATE INDEX IF NOT EXISTS idx_email_sends_created_at ON email_sends(created_at DESC);
92
+ CREATE INDEX IF NOT EXISTS idx_email_sends_campaign_id ON email_sends(campaign_id);
93
+
94
+ CREATE TABLE IF NOT EXISTS shop_orders (
95
+ id TEXT NOT NULL PRIMARY KEY,
96
+ order_number TEXT NOT NULL UNIQUE,
97
+ status TEXT NOT NULL DEFAULT 'pending' CHECK(status IN ('pending', 'approved', 'successful', 'aborted', 'failed')),
98
+ payment_method TEXT NOT NULL DEFAULT 'bank_transfer' CHECK(payment_method IN ('bank_transfer', 'stripe')),
99
+ customer_json TEXT NOT NULL DEFAULT '{}',
100
+ items_json TEXT NOT NULL DEFAULT '[]',
101
+ totals_json TEXT NOT NULL DEFAULT '{"subtotal":0,"shipping":0,"tax":0,"total":0,"currency":"eur"}',
102
+ stripe_session_id TEXT,
103
+ stripe_payment_intent_id TEXT,
104
+ invoice_number TEXT,
105
+ invoice_sent_at INTEGER,
106
+ metadata_json TEXT NOT NULL DEFAULT '{}',
107
+ created_at INTEGER NOT NULL,
108
+ updated_at INTEGER NOT NULL
109
+ );
110
+
111
+ CREATE INDEX IF NOT EXISTS idx_shop_orders_status ON shop_orders(status);
112
+ CREATE INDEX IF NOT EXISTS idx_shop_orders_payment_method ON shop_orders(payment_method);
113
+ CREATE INDEX IF NOT EXISTS idx_shop_orders_stripe_session ON shop_orders(stripe_session_id);
114
+ CREATE UNIQUE INDEX IF NOT EXISTS idx_shop_orders_order_number ON shop_orders(order_number);
115
+ `;
116
+ // Keep the old export name as an alias so existing call-sites don't break.
117
+ export const PROJECT_ADMIN_SCHEMA_SQL = PROJECT_SCHEMA_SQL;
118
+ export function getProjectDb(env) {
119
+ const db = env.PROJECT_DB ?? env.SHOP_DB;
120
+ if (!db) {
121
+ throw new Error('PROJECT_DB binding is not configured');
122
+ }
123
+ return db;
124
+ }
125
+ export async function ensureSchema(env) {
126
+ const db = getProjectDb(env);
127
+ const statements = PROJECT_SCHEMA_SQL
128
+ .split(';')
129
+ .map((s) => s.trim())
130
+ .filter((s) => s.length > 0);
131
+ for (const stmt of statements) {
132
+ await db.prepare(stmt).run();
133
+ }
134
+ return db;
135
+ }
136
+ // Backward-compatible alias
137
+ export const ensureProjectAdminSchema = ensureSchema;
138
+ export function nowSeconds() {
139
+ return Math.floor(Date.now() / 1000);
140
+ }
141
+ export function createId(prefix) {
142
+ return `${prefix}_${Date.now().toString(36)}_${crypto.randomUUID().replace(/-/g, '').slice(0, 12)}`;
143
+ }
144
+ export async function sha256Base64Url(value) {
145
+ const bytes = new TextEncoder().encode(value);
146
+ const hash = await crypto.subtle.digest('SHA-256', bytes);
147
+ return btoa(String.fromCharCode(...new Uint8Array(hash)))
148
+ .replace(/=/g, '')
149
+ .replace(/\+/g, '-')
150
+ .replace(/\//g, '_');
151
+ }
152
+ export async function getAdminUserByEmail(env, email) {
153
+ const db = await ensureProjectAdminSchema(env);
154
+ return await db
155
+ .prepare('SELECT * FROM admin_users WHERE email = ? AND disabled_at IS NULL LIMIT 1')
156
+ .bind(email.toLowerCase().trim())
157
+ .first();
158
+ }
159
+ export async function getAdminUserById(env, userId) {
160
+ const db = await ensureProjectAdminSchema(env);
161
+ return await db
162
+ .prepare('SELECT * FROM admin_users WHERE id = ? AND disabled_at IS NULL LIMIT 1')
163
+ .bind(userId)
164
+ .first();
165
+ }
166
+ export function issueSessionForUser(user) {
167
+ return {
168
+ userId: user.id,
169
+ email: user.email,
170
+ name: user.name,
171
+ };
172
+ }
@@ -16,7 +16,7 @@ export function getTemplate(element, uiBaseUrl, params = '') {
16
16
  <link rel="stylesheet" href="${uiBaseUrl}/ui.css">
17
17
  </head>
18
18
  <body>
19
- <hintergrund-login></hintergrund-login>
19
+ <hintergrund-login ${params}></hintergrund-login>
20
20
  <script type="module" src="${uiBaseUrl}/login.js"></script>
21
21
  </body>
22
22
  </html>
@@ -151,10 +151,10 @@ export function getTemplate(element, uiBaseUrl, params = '') {
151
151
  </head>
152
152
  <body>
153
153
  <div class="container">
154
- <h1>Unsubscribe from Newsletter</h1>
154
+ <h1>Unsubscribe from Emails</h1>
155
155
  <div id="message" class="message"></div>
156
156
  <div id="content">
157
- <p>Are you sure you want to unsubscribe from our newsletter?</p>
157
+ <p>Are you sure you want to unsubscribe from updates?</p>
158
158
  <div class="buttons">
159
159
  <button class="btn-secondary" onclick="window.close()">Cancel</button>
160
160
  <button class="btn-primary" onclick="handleUnsubscribe()">Unsubscribe</button>
@@ -174,7 +174,7 @@ export function getTemplate(element, uiBaseUrl, params = '') {
174
174
  spinner.style.display = 'block';
175
175
 
176
176
  try {
177
- const response = await fetch('/api/newsletter/unsubscribe', {
177
+ const response = await fetch('/api/email/unsubscribe', {
178
178
  method: 'POST',
179
179
  headers: { 'Content-Type': 'application/json' },
180
180
  body: JSON.stringify({ token })
@@ -3,7 +3,5 @@ export declare function authMiddleware(c: Context, next: Next): Promise<void | (
3
3
  error: string;
4
4
  }, 500, "json">) | (Response & import("hono").TypedResponse<"Server configuration error: No configuration found", 500, "text">) | (Response & import("hono").TypedResponse<{
5
5
  error: string;
6
- }, 403, "json">) | (Response & import("hono").TypedResponse<"Access denied to this module", 403, "text">) | (Response & import("hono").TypedResponse<{
7
- error: string;
8
6
  }, 401, "json">) | (Response & import("hono").TypedResponse<undefined, 302, "redirect">)>;
9
7
  //# sourceMappingURL=auth.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"auth.d.ts","sourceRoot":"","sources":["../../src/middleware/auth.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,MAAM,MAAM,CAAC;AAsCrC,wBAAsB,cAAc,CAAC,CAAC,EAAE,OAAO,EAAE,IAAI,EAAE,IAAI;;;;;;0FAuE1D"}
1
+ {"version":3,"file":"auth.d.ts","sourceRoot":"","sources":["../../src/middleware/auth.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,MAAM,MAAM,CAAC;AAMrC,wBAAsB,cAAc,CAAC,CAAC,EAAE,OAAO,EAAE,IAAI,EAAE,IAAI;;;;0FAqE1D"}
@@ -1,38 +1,10 @@
1
1
  import { parse } from 'cookie';
2
2
  import { verify } from '../lib/auth/jwt';
3
3
  import { loadConfig } from '../lib/config';
4
- /**
5
- * Determines which module is being accessed based on the pathname
6
- */
7
- function getModuleFromPath(pathname) {
8
- if (pathname.includes('/api/admin/cms') || pathname.includes('/api/admin/collections') || pathname.includes('/api/admin/assets')) {
9
- return 'cms';
10
- }
11
- if (pathname.includes('/api/email/admin')) {
12
- return 'emails';
13
- }
14
- if (pathname.includes('/api/admin/shop')) {
15
- return 'shop';
16
- }
17
- return null;
18
- }
19
- /**
20
- * Check if user has access to a specific module based on their group
21
- */
22
- function hasModuleAccess(userModules, targetModule) {
23
- // If no target module, allow access (general admin routes)
24
- if (!targetModule)
25
- return true;
26
- // If user has no module restrictions, allow all
27
- if (!userModules || userModules.length === 0)
28
- return true;
29
- // Check if the target module is in the allowed list
30
- return userModules.includes(targetModule);
31
- }
4
+ import { getAdminUserById } from '../lib/project-db';
32
5
  export async function authMiddleware(c, next) {
33
6
  const { pathname } = new URL(c.req.url);
34
7
  console.log('[AUTH MIDDLEWARE] Checking:', pathname);
35
- // Skip authentication for login, logout, and magic link verification routes
36
8
  if (pathname === '/login' ||
37
9
  pathname === '/api/admin/login' ||
38
10
  pathname === '/api/admin/logout' ||
@@ -40,9 +12,8 @@ export async function authMiddleware(c, next) {
40
12
  console.log('[AUTH MIDDLEWARE] Skipping auth for:', pathname);
41
13
  return await next();
42
14
  }
43
- // Check if configuration exists
44
- if (!c.env.HG_CONFIG && !c.env.HG_SECRET) {
45
- console.error('No configuration found. Set HG_SECRET/HG_PASSWORD or HG_CONFIG');
15
+ if (!c.env.HG_SECRET) {
16
+ console.error('No configuration found. Set HG_SECRET or HG_CONFIG');
46
17
  if (pathname.startsWith('/api/')) {
47
18
  return c.json({ error: 'Server configuration error' }, 500);
48
19
  }
@@ -55,36 +26,36 @@ export async function authMiddleware(c, next) {
55
26
  const appConfig = loadConfig(c.env);
56
27
  const payload = await verify(token, appConfig.global.hgSecret);
57
28
  if (payload) {
58
- // Token is valid - check module access
59
- const targetModule = getModuleFromPath(pathname);
60
- const userModules = payload.modules;
61
- if (!hasModuleAccess(userModules, targetModule)) {
62
- console.log('[AUTH MIDDLEWARE] User does not have access to module:', targetModule);
63
- if (pathname.startsWith('/api/')) {
64
- return c.json({ error: 'Access denied to this module' }, 403);
29
+ let user = {
30
+ userId: payload.userId,
31
+ email: payload.email,
32
+ name: payload.name,
33
+ };
34
+ if (payload.userId && (c.env.PROJECT_DB || c.env.SHOP_DB)) {
35
+ const dbUser = await getAdminUserById(c.env, String(payload.userId));
36
+ if (!dbUser) {
37
+ if (pathname.startsWith('/api/')) {
38
+ return c.json({ error: 'Unauthorized' }, 401);
39
+ }
40
+ return c.redirect('/login');
65
41
  }
66
- return c.text('Access denied to this module', 403);
42
+ user = {
43
+ userId: dbUser.id,
44
+ email: dbUser.email,
45
+ name: dbUser.name,
46
+ };
67
47
  }
68
- // Store user info in context for downstream handlers
69
- c.set('user', {
70
- email: payload.email,
71
- userGroup: payload.userGroup,
72
- modules: userModules,
73
- });
48
+ c.set('user', user);
74
49
  return await next();
75
50
  }
76
51
  }
77
52
  catch (error) {
78
53
  console.error('Token verification error:', error);
79
- // Continue to unauthorized handling
80
54
  }
81
55
  }
82
- // No cookie or incorrect hash in cookie
83
56
  console.log('[AUTH MIDDLEWARE] No valid token, redirecting to login');
84
- // Check if this is an API request
85
57
  if (pathname.startsWith('/api/')) {
86
58
  return c.json({ error: 'Unauthorized' }, 401);
87
59
  }
88
- // For non-API requests, redirect to login
89
60
  return c.redirect('/login');
90
61
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@hintergrund/worker",
3
- "version": "0.1.6",
3
+ "version": "0.1.8",
4
4
  "type": "module",
5
5
  "main": "./dist/index.js",
6
6
  "types": "./dist/index.d.ts",
@@ -23,7 +23,8 @@
23
23
  "typescript": "^5.5.2"
24
24
  },
25
25
  "dependencies": {
26
- "@hintergrund/shared": "^0.1.5",
26
+ "@hintergrund/auth": "^0.1.2",
27
+ "@hintergrund/runtime-contracts": "workspace:*",
27
28
  "@octokit/rest": "^22.0.0",
28
29
  "cookie": "^1.0.2",
29
30
  "hono": "^4.10.2",
@@ -1,12 +0,0 @@
1
- import { Context } from 'hono';
2
- /**
3
- * POST /api/builder/admin/chat
4
- * Analyze user request, return implementation plan + questions
5
- */
6
- export declare function chat(c: Context): Promise<Response>;
7
- /**
8
- * POST /api/builder/admin/implement
9
- * Generate final code based on conversation
10
- */
11
- export declare function implement(c: Context): Promise<Response>;
12
- //# sourceMappingURL=generate.handler.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"generate.handler.d.ts","sourceRoot":"","sources":["../../../../src/api/builder/handlers/generate.handler.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,MAAM,MAAM,CAAC;AA8K/B;;;GAGG;AACH,wBAAsB,IAAI,CAAC,CAAC,EAAE,OAAO,GAAG,OAAO,CAAC,QAAQ,CAAC,CAgDxD;AAED;;;GAGG;AACH,wBAAsB,SAAS,CAAC,CAAC,EAAE,OAAO,GAAG,OAAO,CAAC,QAAQ,CAAC,CA6C7D"}
@@ -1,203 +0,0 @@
1
- import { getBuilderConfig } from '../../../lib/config';
2
- const SYSTEM_PROMPT = `You are an AI assistant helping to build and modify a SvelteKit website. You are working with a template that includes CMS integration, newsletter signup, and shop functionality.
3
-
4
- ## Template Structure
5
- - src/routes/ - SvelteKit page components (+page.svelte, +layout.svelte)
6
- - src/lib/components/ - Reusable Svelte 5 components
7
- - src/lib/content/globals.json - Site content (name, tagline, about text, social links, newsletter text)
8
- - src/lib/content/config.json - CMS schema definitions
9
- - src/lib/api/newsletter.ts - Newsletter API client (subscribe, unsubscribe, confirm)
10
- - src/lib/api/shop.ts - Shop API client (getProducts, createCheckoutSession)
11
- - src/lib/assets/ - Static images
12
- - static/ - Public static files
13
-
14
- ## Svelte 5 Patterns
15
- - Use $state() for reactive state: let count = $state(0);
16
- - Use $derived() for computed values: const doubled = $derived(count * 2);
17
- - Use $effect() for side effects: $effect(() => { console.log(count); });
18
- - Use $props() for component props: let { name, value = '' } = $props();
19
-
20
- ## Content Management
21
- - Site content is in src/lib/content/globals.json
22
- - Components import content: import { globals } from '$lib';
23
- - Access content: globals.siteName, globals.siteTagline, etc.
24
-
25
- ## API Integration
26
- - Newsletter: import { subscribeToNewsletter } from '$lib/api/newsletter';
27
- - Shop: import { getProducts, createCheckoutSession } from '$lib/api/shop';
28
-
29
- ## CSS Styling
30
- - Use scoped <style> blocks in Svelte components
31
- - CSS custom properties are available (--color-gray-900, etc.)
32
- - Follow existing design patterns in the codebase
33
-
34
- ## Guidelines
35
- 1. Follow existing code patterns and naming conventions
36
- 2. Keep components small and focused
37
- 3. Use semantic HTML elements
38
- 4. Ensure responsive design
39
- 5. Maintain accessibility (aria labels, keyboard navigation)`;
40
- const CHAT_PROMPT = `Based on the user's request, analyze what changes need to be made to the website.
41
-
42
- Your response must be valid JSON with this structure:
43
- {
44
- "plan": "A detailed implementation plan describing what will be changed and how",
45
- "questions": ["List of clarifying questions if you need more information to implement properly"],
46
- "affectedFiles": ["List of file paths that will be modified"]
47
- }
48
-
49
- Rules:
50
- 1. If the request is clear and you have all the information needed, return an empty questions array
51
- 2. If you need more details to implement properly, ask specific clarifying questions
52
- 3. If there are no questions, end your plan with: "Do you have any additional changes you'd like to make, or should I implement this now?"
53
- 4. The plan should be specific about what code changes will be made
54
- 5. List ALL files that will need to be modified
55
-
56
- Respond ONLY with valid JSON, no markdown code blocks.`;
57
- const IMPLEMENT_PROMPT = `Based on the conversation history, implement all the requested changes.
58
-
59
- Your response must be valid JSON with this structure:
60
- {
61
- "files": {
62
- "path/to/file.svelte": "complete file content",
63
- "path/to/another/file.ts": "complete file content"
64
- },
65
- "summary": "Brief summary of all changes made"
66
- }
67
-
68
- Rules:
69
- 1. Return the COMPLETE file content for each modified file, not partial snippets
70
- 2. Include ALL files that need to be changed based on the entire conversation
71
- 3. Follow the existing code style and patterns
72
- 4. Ensure the code is production-ready and error-free
73
- 5. The summary should list what was changed in each file
74
-
75
- Respond ONLY with valid JSON, no markdown code blocks.`;
76
- /**
77
- * Call Gemini API
78
- */
79
- async function callGemini(apiKey, systemPrompt, userPrompt, conversationHistory = []) {
80
- // Build conversation context
81
- const historyContext = conversationHistory
82
- .map(msg => `${msg.role === 'user' ? 'User' : 'Assistant'}: ${msg.content}`)
83
- .join('\n\n');
84
- const fullPrompt = historyContext
85
- ? `${historyContext}\n\nUser: ${userPrompt}`
86
- : userPrompt;
87
- const response = await fetch(`https://generativelanguage.googleapis.com/v1beta/models/gemini-1.5-pro:generateContent?key=${apiKey}`, {
88
- method: 'POST',
89
- headers: {
90
- 'Content-Type': 'application/json'
91
- },
92
- body: JSON.stringify({
93
- contents: [
94
- {
95
- role: 'user',
96
- parts: [{ text: `${systemPrompt}\n\n${fullPrompt}` }]
97
- }
98
- ],
99
- generationConfig: {
100
- temperature: 0.7,
101
- maxOutputTokens: 8192
102
- }
103
- })
104
- });
105
- if (!response.ok) {
106
- const error = await response.text();
107
- throw new Error(`Gemini API error: ${error}`);
108
- }
109
- const data = await response.json();
110
- const text = data.candidates?.[0]?.content?.parts?.[0]?.text;
111
- if (!text) {
112
- throw new Error('No response from Gemini');
113
- }
114
- return text;
115
- }
116
- /**
117
- * Parse JSON from AI response, handling potential markdown code blocks
118
- */
119
- function parseAIResponse(text) {
120
- // Remove markdown code blocks if present
121
- let cleaned = text.trim();
122
- if (cleaned.startsWith('```json')) {
123
- cleaned = cleaned.slice(7);
124
- }
125
- else if (cleaned.startsWith('```')) {
126
- cleaned = cleaned.slice(3);
127
- }
128
- if (cleaned.endsWith('```')) {
129
- cleaned = cleaned.slice(0, -3);
130
- }
131
- cleaned = cleaned.trim();
132
- return JSON.parse(cleaned);
133
- }
134
- /**
135
- * POST /api/builder/admin/chat
136
- * Analyze user request, return implementation plan + questions
137
- */
138
- export async function chat(c) {
139
- try {
140
- const request = await c.req.json();
141
- const config = getBuilderConfig(c.env);
142
- // Build file context
143
- const fileContext = Object.entries(request.currentFiles)
144
- .map(([path, content]) => `### ${path}\n\`\`\`\n${content}\n\`\`\``)
145
- .join('\n\n');
146
- const userPrompt = `${CHAT_PROMPT}
147
-
148
- ## Current Files
149
- ${fileContext}
150
-
151
- ## User Request
152
- ${request.message}`;
153
- const aiResponse = await callGemini(config.geminiApiKey, SYSTEM_PROMPT, userPrompt, request.conversationHistory);
154
- const parsed = parseAIResponse(aiResponse);
155
- const response = {
156
- success: true,
157
- response: {
158
- plan: parsed.plan,
159
- questions: parsed.questions || [],
160
- affectedFiles: parsed.affectedFiles || []
161
- }
162
- };
163
- return c.json(response);
164
- }
165
- catch (error) {
166
- console.error('Chat error:', error);
167
- return c.json({ success: false, error: error.message || 'Failed to process chat' }, 500);
168
- }
169
- }
170
- /**
171
- * POST /api/builder/admin/implement
172
- * Generate final code based on conversation
173
- */
174
- export async function implement(c) {
175
- try {
176
- const request = await c.req.json();
177
- const config = getBuilderConfig(c.env);
178
- // Build file context
179
- const fileContext = Object.entries(request.currentFiles)
180
- .map(([path, content]) => `### ${path}\n\`\`\`\n${content}\n\`\`\``)
181
- .join('\n\n');
182
- const userPrompt = `${IMPLEMENT_PROMPT}
183
-
184
- ## Current Files
185
- ${fileContext}
186
-
187
- Please implement all the changes discussed in the conversation.`;
188
- const aiResponse = await callGemini(config.geminiApiKey, SYSTEM_PROMPT, userPrompt, request.conversationHistory);
189
- const parsed = parseAIResponse(aiResponse);
190
- const response = {
191
- success: true,
192
- result: {
193
- files: parsed.files || {},
194
- summary: parsed.summary || 'Changes implemented'
195
- }
196
- };
197
- return c.json(response);
198
- }
199
- catch (error) {
200
- console.error('Implement error:', error);
201
- return c.json({ success: false, error: error.message || 'Failed to implement changes' }, 500);
202
- }
203
- }
@@ -1,12 +0,0 @@
1
- import { Context } from 'hono';
2
- /**
3
- * GET /api/builder/admin/template
4
- * Fetch all template files from the GitHub repository
5
- */
6
- export declare function getTemplate(c: Context): Promise<Response>;
7
- /**
8
- * PUT /api/builder/admin/template
9
- * Save modified files to GitHub (commit)
10
- */
11
- export declare function updateTemplate(c: Context): Promise<Response>;
12
- //# sourceMappingURL=template.handler.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"template.handler.d.ts","sourceRoot":"","sources":["../../../../src/api/builder/handlers/template.handler.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,MAAM,MAAM,CAAC;AA+G/B;;;GAGG;AACH,wBAAsB,WAAW,CAAC,CAAC,EAAE,OAAO,GAAG,OAAO,CAAC,QAAQ,CAAC,CAwC/D;AAED;;;GAGG;AACH,wBAAsB,cAAc,CAAC,CAAC,EAAE,OAAO,GAAG,OAAO,CAAC,QAAQ,CAAC,CA4FlE"}