@hintergrund/worker 0.1.12 → 0.2.2

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 (52) hide show
  1. package/dist/api/cms/handlers/admin-users.handler.d.ts +0 -1
  2. package/dist/api/cms/handlers/admin-users.handler.d.ts.map +1 -1
  3. package/dist/api/cms/handlers/admin-users.handler.js +2 -27
  4. package/dist/api/cms/handlers/auth.handler.d.ts +0 -4
  5. package/dist/api/cms/handlers/auth.handler.d.ts.map +1 -1
  6. package/dist/api/cms/handlers/auth.handler.js +58 -108
  7. package/dist/api/cms/handlers/github-secrets.handler.d.ts.map +1 -1
  8. package/dist/api/cms/handlers/github-secrets.handler.js +33 -7
  9. package/dist/api/cms/handlers/setup.handler.d.ts +2 -0
  10. package/dist/api/cms/handlers/setup.handler.d.ts.map +1 -1
  11. package/dist/api/cms/handlers/setup.handler.js +109 -16
  12. package/dist/api/cms/handlers/website-repo.handler.d.ts.map +1 -1
  13. package/dist/api/cms/handlers/website-repo.handler.js +11 -4
  14. package/dist/api/cms/handlers/website-templates.handler.d.ts +6 -0
  15. package/dist/api/cms/handlers/website-templates.handler.d.ts.map +1 -0
  16. package/dist/api/cms/handlers/website-templates.handler.js +53 -0
  17. package/dist/api/cms/routes/auth.routes.d.ts.map +1 -1
  18. package/dist/api/cms/routes/auth.routes.js +1 -2
  19. package/dist/api/cms/routes/index.d.ts.map +1 -1
  20. package/dist/api/cms/routes/index.js +7 -3
  21. package/dist/hintergrund-assets.d.ts +4 -4
  22. package/dist/hintergrund-assets.d.ts.map +1 -1
  23. package/dist/hintergrund-assets.js +4 -4
  24. package/dist/index.d.ts +7 -1
  25. package/dist/index.d.ts.map +1 -1
  26. package/dist/index.js +4 -2
  27. package/dist/lib/config.d.ts +6 -0
  28. package/dist/lib/config.d.ts.map +1 -1
  29. package/dist/lib/config.js +17 -5
  30. package/dist/lib/email.d.ts +3 -5
  31. package/dist/lib/email.d.ts.map +1 -1
  32. package/dist/lib/email.js +8 -25
  33. package/dist/lib/github-app.d.ts +1 -0
  34. package/dist/lib/github-app.d.ts.map +1 -1
  35. package/dist/lib/github-app.js +25 -1
  36. package/dist/lib/github.d.ts +9 -3
  37. package/dist/lib/github.d.ts.map +1 -1
  38. package/dist/lib/github.js +35 -12
  39. package/dist/lib/jsonc.d.ts +3 -0
  40. package/dist/lib/jsonc.d.ts.map +1 -0
  41. package/dist/lib/jsonc.js +76 -0
  42. package/dist/lib/project-db.d.ts +2 -2
  43. package/dist/lib/project-db.d.ts.map +1 -1
  44. package/dist/lib/project-db.js +12 -11
  45. package/dist/lib/template.d.ts.map +1 -1
  46. package/dist/lib/template.js +75 -213
  47. package/dist/middleware/auth.d.ts.map +1 -1
  48. package/dist/middleware/auth.js +0 -1
  49. package/package.json +35 -35
  50. package/dist/api/emails/handlers/webhook.handler.d.ts +0 -9
  51. package/dist/api/emails/handlers/webhook.handler.d.ts.map +0 -1
  52. package/dist/api/emails/handlers/webhook.handler.js +0 -161
@@ -4,232 +4,94 @@ export function getTemplate(element, uiBaseUrl, params = '') {
4
4
  return `
5
5
  <!doctype html>
6
6
  <html>
7
- <head>
8
- <meta charset="utf-8">
9
- <meta name="viewport" content="width=device-width, initial-scale=1">
10
- <title>Login</title>
11
- <link rel="icon" type="image/svg+xml" href="${faviconSvg}">
12
- <style>
13
- * { box-sizing: border-box; margin: 0; padding: 0; }
14
- body { margin: 0; height: 100vh; }
15
- </style>
16
- <link rel="stylesheet" href="${uiBaseUrl}/ui.css">
17
- </head>
18
- <body>
19
- <hintergrund-login ${params}></hintergrund-login>
20
- <script type="module" src="${uiBaseUrl}/login.js"></script>
21
- </body>
22
- </html>
23
- `;
7
+ <head>
8
+ <meta charset="utf-8">
9
+ <meta name="viewport" content="width=device-width, initial-scale=1">
10
+ <title>Login</title>
11
+ <link rel="icon" type="image/svg+xml" href="${faviconSvg}">
12
+ <style>* { box-sizing: border-box; margin: 0; padding: 0; } body { margin: 0; height: 100vh; }</style>
13
+ <link rel="stylesheet" href="${uiBaseUrl}/ui.css">
14
+ </head>
15
+ <body>
16
+ <hintergrund-login ${params}></hintergrund-login>
17
+ <script type="module" src="${uiBaseUrl}/login.js"></script>
18
+ </body>
19
+ </html>`;
24
20
  }
25
21
  if (element === 'setup') {
26
22
  return `
27
23
  <!doctype html>
28
- <html><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><title>Set up your project</title>
29
- <style>body{margin:0;background:#f6f8fa;color:#24292f;font:16px -apple-system,BlinkMacSystemFont,"Segoe UI",sans-serif}.card{max-width:560px;margin:8vh auto;padding:2rem;background:#fff;border:1px solid #d0d7de;border-radius:8px}h1{margin:0 0 .5rem}p{color:#57606a;line-height:1.5}form{display:grid;gap:.8rem;margin-top:1.5rem}label{font-weight:600;font-size:.9rem}input{padding:.7rem;border:1px solid #d0d7de;border-radius:6px;font:inherit}button{padding:.75rem;border:0;border-radius:6px;background:#1f883d;color:#fff;font:inherit;font-weight:600;cursor:pointer}.optional{font-weight:400;color:#57606a}.error{color:#cf222e;min-height:1.3em}</style></head>
30
- <body><main class="card"><h1>Set up your project</h1><p>Create the first administrator. Stripe and Plunk are optional and can be changed later from the project admin.</p>
31
- <form id="setup"><label>Email<input name="email" type="email" required autocomplete="email"></label><label>Name <span class="optional">(optional)</span><input name="name" autocomplete="name"></label><label>Password<input name="password" type="password" required minlength="12" autocomplete="new-password"></label><label>Plunk API key <span class="optional">(optional)</span><input name="plunkApiKey" type="password"></label><label>Sender email <span class="optional">(for magic links)</span><input name="fromEmail" type="email"></label><label>Sender name <span class="optional">(optional)</span><input name="fromName"></label><label>Reply-to email <span class="optional">(optional)</span><input name="replyTo" type="email"></label><label>Stripe secret key <span class="optional">(optional)</span><input name="stripeSecretKey" type="password"></label><label>Stripe webhook secret <span class="optional">(auto-created if blank)</span><input name="stripeWebhookSecret" type="password"></label><p class="error" id="error"></p><button>Finish setup</button></form></main>
32
- <script>document.querySelector('#setup').addEventListener('submit',async(e)=>{e.preventDefault();const form=e.currentTarget,button=form.querySelector('button'),error=document.querySelector('#error');button.disabled=true;error.textContent='';const data=Object.fromEntries(new FormData(form));try{const response=await fetch('/api/admin/setup',{method:'POST',headers:{'content-type':'application/json'},body:JSON.stringify(data)});const result=await response.json();if(!response.ok)throw new Error(result.error||'Setup failed');location.href='/admin'}catch(err){error.textContent=err.message||'Setup failed';button.disabled=false}})</script></body></html>`;
24
+ <html>
25
+ <head>
26
+ <meta charset="utf-8">
27
+ <meta name="viewport" content="width=device-width, initial-scale=1">
28
+ <title>Set up your site</title>
29
+ <link rel="icon" type="image/svg+xml" href="${faviconSvg}">
30
+ <style>body { margin: 0; }</style>
31
+ <link rel="stylesheet" href="${uiBaseUrl}/ui.css">
32
+ </head>
33
+ <body>
34
+ <hintergrund-setup></hintergrund-setup>
35
+ <script type="module" src="${uiBaseUrl}/setup.js"></script>
36
+ </body>
37
+ </html>`;
33
38
  }
34
39
  if (element === 'admin') {
35
40
  return `
36
41
  <!doctype html>
37
42
  <html>
38
- <head>
39
- <meta charset="utf-8">
40
- <meta name="viewport" content="width=device-width, initial-scale=1">
41
- <title>Hintergrund Admin</title>
42
- <meta name="description" content="Admin Panel for Hintergrund">
43
- <link rel="icon" type="image/svg+xml" href="${faviconSvg}">
44
- <style>
45
- * { box-sizing: border-box; margin: 0; padding: 0; }
46
- body { margin: 0; height: 100vh; }
47
- </style>
48
- <link rel="stylesheet" href="${uiBaseUrl}/ui.css">
49
- </head>
50
- <body>
51
- <hintergrund-admin ${params}></hintergrund-admin>
52
- <script type="module" src="${uiBaseUrl}/admin.js"></script>
53
- </body>
54
- </html>
55
- `;
43
+ <head>
44
+ <meta charset="utf-8">
45
+ <meta name="viewport" content="width=device-width, initial-scale=1">
46
+ <title>Hintergrund Admin</title>
47
+ <meta name="description" content="Admin Panel for Hintergrund">
48
+ <link rel="icon" type="image/svg+xml" href="${faviconSvg}">
49
+ <style>* { box-sizing: border-box; margin: 0; padding: 0; } body { margin: 0; height: 100vh; }</style>
50
+ <link rel="stylesheet" href="${uiBaseUrl}/ui.css">
51
+ </head>
52
+ <body>
53
+ <hintergrund-admin ${params}></hintergrund-admin>
54
+ <script type="module" src="${uiBaseUrl}/admin.js"></script>
55
+ </body>
56
+ </html>`;
56
57
  }
57
58
  if (element === 'unsubscribe') {
58
59
  return `
59
60
  <!doctype html>
60
61
  <html>
61
- <head>
62
- <meta charset="utf-8">
63
- <meta name="viewport" content="width=device-width, initial-scale=1">
64
- <title>Unsubscribe</title>
65
- <link rel="icon" type="image/svg+xml" href="${faviconSvg}">
66
- <style>
67
- * { box-sizing: border-box; margin: 0; padding: 0; }
68
- body {
69
- font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, sans-serif;
70
- background: #f6f8fa;
71
- display: flex;
72
- align-items: center;
73
- justify-content: center;
74
- min-height: 100vh;
75
- padding: 1rem;
76
- }
77
- .container {
78
- background: white;
79
- border-radius: 8px;
80
- border: 1px solid #d0d7de;
81
- padding: 2rem;
82
- max-width: 480px;
83
- width: 100%;
84
- box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
85
- }
86
- h1 {
87
- font-size: 1.5rem;
88
- font-weight: 600;
89
- margin-bottom: 1rem;
90
- color: #24292f;
91
- }
92
- p {
93
- color: #57606a;
94
- line-height: 1.5;
95
- margin-bottom: 1.5rem;
96
- }
97
- .buttons {
98
- display: flex;
99
- gap: 0.75rem;
100
- }
101
- button {
102
- flex: 1;
103
- padding: 0.75rem 1rem;
104
- font-size: 0.875rem;
105
- font-weight: 500;
106
- border-radius: 6px;
107
- border: 1px solid;
108
- cursor: pointer;
109
- transition: all 0.15s ease;
110
- }
111
- .btn-primary {
112
- background: #cf222e;
113
- color: white;
114
- border-color: #cf222e;
115
- }
116
- .btn-primary:hover {
117
- background: #a40e26;
118
- border-color: #a40e26;
119
- }
120
- .btn-secondary {
121
- background: #f6f8fa;
122
- color: #24292f;
123
- border-color: #d0d7de;
124
- }
125
- .btn-secondary:hover {
126
- background: #f3f4f6;
127
- border-color: #b1b9c2;
128
- }
129
- .message {
130
- padding: 1rem;
131
- border-radius: 6px;
132
- margin-bottom: 1rem;
133
- display: none;
134
- }
135
- .message.success {
136
- background: #dafbe1;
137
- color: #1a7f37;
138
- border: 1px solid #1a7f37;
139
- }
140
- .message.error {
141
- background: #ffebe9;
142
- color: #cf222e;
143
- border: 1px solid #cf222e;
144
- }
145
- .spinner {
146
- display: none;
147
- border: 2px solid #f3f4f6;
148
- border-top: 2px solid #cf222e;
149
- border-radius: 50%;
150
- width: 16px;
151
- height: 16px;
152
- animation: spin 0.6s linear infinite;
153
- margin: 0 auto;
154
- }
155
- @keyframes spin {
156
- 0% { transform: rotate(0deg); }
157
- 100% { transform: rotate(360deg); }
158
- }
159
- </style>
160
- </head>
161
- <body>
162
- <div class="container">
163
- <h1>Unsubscribe from Emails</h1>
164
- <div id="message" class="message"></div>
165
- <div id="content">
166
- <p>Are you sure you want to unsubscribe from updates?</p>
167
- <div class="buttons">
168
- <button class="btn-secondary" onclick="window.close()">Cancel</button>
169
- <button class="btn-primary" onclick="handleUnsubscribe()">Unsubscribe</button>
170
- </div>
171
- </div>
172
- <div id="spinner" class="spinner"></div>
173
- </div>
174
- <script>
175
- ${params}
176
-
177
- async function handleUnsubscribe() {
178
- const content = document.getElementById('content');
179
- const spinner = document.getElementById('spinner');
180
- const message = document.getElementById('message');
181
-
182
- content.style.display = 'none';
183
- spinner.style.display = 'block';
184
-
185
- try {
186
- const response = await fetch('/api/email/unsubscribe', {
187
- method: 'POST',
188
- headers: { 'Content-Type': 'application/json' },
189
- body: JSON.stringify({ token })
190
- });
191
-
192
- const data = await response.json();
193
- spinner.style.display = 'none';
194
-
195
- if (data.success) {
196
- message.className = 'message success';
197
- message.textContent = data.message || 'You have been unsubscribed successfully.';
198
- message.style.display = 'block';
199
- } else {
200
- message.className = 'message error';
201
- message.textContent = data.message || 'Failed to unsubscribe. Please try again.';
202
- message.style.display = 'block';
203
- content.style.display = 'block';
204
- }
205
- } catch (error) {
206
- spinner.style.display = 'none';
207
- message.className = 'message error';
208
- message.textContent = 'Network error. Please try again.';
209
- message.style.display = 'block';
210
- content.style.display = 'block';
211
- }
212
- }
213
- </script>
214
- </body>
215
- </html>
216
- `;
62
+ <head>
63
+ <meta charset="utf-8">
64
+ <meta name="viewport" content="width=device-width, initial-scale=1">
65
+ <title>Unsubscribe</title>
66
+ <link rel="icon" type="image/svg+xml" href="${faviconSvg}">
67
+ <style>
68
+ * { box-sizing: border-box; margin: 0; padding: 0; }
69
+ body { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif; background: #f6f8fa; display: flex; align-items: center; justify-content: center; min-height: 100vh; padding: 1rem; }
70
+ .container { background: white; border-radius: 8px; border: 1px solid #d0d7de; padding: 2rem; max-width: 480px; width: 100%; }
71
+ h1 { font-size: 1.5rem; margin-bottom: 1rem; } p { color: #57606a; line-height: 1.5; margin-bottom: 1.5rem; }
72
+ .buttons { display: flex; gap: .75rem; } button { flex: 1; padding: .75rem 1rem; border-radius: 6px; border: 1px solid; cursor: pointer; }
73
+ .btn-primary { background: #cf222e; color: white; border-color: #cf222e; } .btn-secondary { background: #f6f8fa; color: #24292f; border-color: #d0d7de; }
74
+ .message { padding: 1rem; border-radius: 6px; margin-bottom: 1rem; display: none; } .message.success { background: #dafbe1; color: #1a7f37; border: 1px solid #1a7f37; } .message.error { background: #ffebe9; color: #cf222e; border: 1px solid #cf222e; }
75
+ .spinner { display: none; border: 2px solid #f3f4f6; border-top-color: #cf222e; border-radius: 50%; width: 16px; height: 16px; animation: spin .6s linear infinite; margin: 0 auto; } @keyframes spin { to { transform: rotate(360deg); } }
76
+ </style>
77
+ </head>
78
+ <body>
79
+ <div class="container"><h1>Unsubscribe from Emails</h1><div id="message" class="message"></div><div id="content"><p>Are you sure you want to unsubscribe from updates?</p><div class="buttons"><button class="btn-secondary" onclick="window.close()">Cancel</button><button class="btn-primary" onclick="handleUnsubscribe()">Unsubscribe</button></div></div><div id="spinner" class="spinner"></div></div>
80
+ <script>
81
+ ${params}
82
+ async function handleUnsubscribe() {
83
+ const content = document.getElementById('content'), spinner = document.getElementById('spinner'), message = document.getElementById('message');
84
+ content.style.display = 'none'; spinner.style.display = 'block';
85
+ try {
86
+ const response = await fetch('/api/email/unsubscribe', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ token }) });
87
+ const data = await response.json(); spinner.style.display = 'none';
88
+ if (data.success) { message.className = 'message success'; message.textContent = data.message || 'You have been unsubscribed successfully.'; message.style.display = 'block'; }
89
+ else { message.className = 'message error'; message.textContent = data.message || 'Failed to unsubscribe. Please try again.'; message.style.display = 'block'; content.style.display = 'block'; }
90
+ } catch (error) { spinner.style.display = 'none'; message.className = 'message error'; message.textContent = 'Network error. Please try again.'; message.style.display = 'block'; content.style.display = 'block'; }
91
+ }
92
+ </script>
93
+ </body>
94
+ </html>`;
217
95
  }
218
- return `
219
- <!doctype html>
220
- <html>
221
- <head>
222
- <meta charset="utf-8">
223
- <meta name="viewport" content="width=device-width, initial-scale=1">
224
- <title>Hintergrund CMS</title>
225
- <meta name="description" content="Admin Panel for Hintergrund CMS">
226
- <link rel="icon" type="image/svg+xml" href="${faviconSvg}">
227
- <style>body{margin:0}</style>
228
- </head>
229
- <body>
230
- <${element} ${params}></${element}>
231
- <script type="module" src="/index.js"></script>
232
- </body>
233
- </html>
234
- `;
96
+ return `<!doctype html><html><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><title>Hintergrund CMS</title><meta name="description" content="Admin Panel for Hintergrund CMS"><link rel="icon" type="image/svg+xml" href="${faviconSvg}"><style>body{margin:0}</style></head><body><${element} ${params}></${element}><script type="module" src="/index.js"></script></body></html>`;
235
97
  }
@@ -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;AAMrC,wBAAsB,cAAc,CAAC,CAAC,EAAE,OAAO,EAAE,IAAI,EAAE,IAAI;;;;0FAsE1D"}
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"}
@@ -8,7 +8,6 @@ export async function authMiddleware(c, next) {
8
8
  if (pathname === '/login' ||
9
9
  pathname === '/api/admin/login' ||
10
10
  pathname === '/api/admin/logout' ||
11
- pathname === '/api/admin/verify-magic-link' ||
12
11
  pathname === '/api/admin/setup') {
13
12
  console.log('[AUTH MIDDLEWARE] Skipping auth for:', pathname);
14
13
  return await next();
package/package.json CHANGED
@@ -1,36 +1,36 @@
1
1
  {
2
- "name": "@hintergrund/worker",
3
- "version": "0.1.12",
4
- "type": "module",
5
- "main": "./dist/index.js",
6
- "types": "./dist/index.d.ts",
7
- "exports": {
8
- ".": {
9
- "types": "./dist/index.d.ts",
10
- "import": "./dist/index.js"
11
- }
12
- },
13
- "files": [
14
- "dist"
15
- ],
16
- "devDependencies": {
17
- "@cloudflare/workers-types": "^4.20250111.0",
18
- "concurrently": "^9.2.1",
19
- "typescript": "^5.5.2",
20
- "@hintergrund/runtime-contracts": "^0.1.9"
21
- },
22
- "dependencies": {
23
- "@hintergrund/auth": "^0.1.2",
24
- "@octokit/rest": "^22.0.0",
25
- "blakejs": "^1.2.1",
26
- "cookie": "^1.0.2",
27
- "hono": "^4.10.2",
28
- "pdf-lib": "^1.17.1",
29
- "stripe": "^17.5.0",
30
- "tweetnacl": "^1.0.3"
31
- },
32
- "scripts": {
33
- "build": "tsc",
34
- "dev": "tsc --watch"
35
- }
36
- }
2
+ "name": "@hintergrund/worker",
3
+ "version": "0.2.2",
4
+ "type": "module",
5
+ "main": "./dist/index.js",
6
+ "types": "./dist/index.d.ts",
7
+ "exports": {
8
+ ".": {
9
+ "types": "./dist/index.d.ts",
10
+ "import": "./dist/index.js"
11
+ }
12
+ },
13
+ "scripts": {
14
+ "build": "tsc",
15
+ "dev": "tsc --watch"
16
+ },
17
+ "files": [
18
+ "dist"
19
+ ],
20
+ "devDependencies": {
21
+ "@cloudflare/workers-types": "^4.20250111.0",
22
+ "concurrently": "^9.2.1",
23
+ "typescript": "^5.5.2",
24
+ "@hintergrund/runtime-contracts": "^0.2.2"
25
+ },
26
+ "dependencies": {
27
+ "@hintergrund/auth": "^0.1.2",
28
+ "@octokit/rest": "^22.0.0",
29
+ "blakejs": "^1.2.1",
30
+ "cookie": "^1.0.2",
31
+ "hono": "^4.10.2",
32
+ "pdf-lib": "^1.17.1",
33
+ "stripe": "^17.5.0",
34
+ "tweetnacl": "^1.0.3"
35
+ }
36
+ }
@@ -1,9 +0,0 @@
1
- import type { Context } from 'hono';
2
- import type { Bindings } from '../../../index';
3
- /**
4
- * Legacy Stripe webhook helper. The active route is /api/shop/webhook.
5
- */
6
- export declare function handleStripeWebhook(c: Context<{
7
- Bindings: Bindings;
8
- }>): Promise<Response>;
9
- //# sourceMappingURL=webhook.handler.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"webhook.handler.d.ts","sourceRoot":"","sources":["../../../../src/api/emails/handlers/webhook.handler.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,MAAM,CAAC;AACpC,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,gBAAgB,CAAC;AAyB/C;;GAEG;AACH,wBAAsB,mBAAmB,CAAC,CAAC,EAAE,OAAO,CAAC;IAAE,QAAQ,EAAE,QAAQ,CAAA;CAAE,CAAC,GAAG,OAAO,CAAC,QAAQ,CAAC,CAiC/F"}
@@ -1,161 +0,0 @@
1
- import { getGitHubConfig, getShopConfig } from '../../../lib/config';
2
- import { createGitHubClient } from '../../../lib/github';
3
- import { sendEmail } from '../../../lib/email';
4
- import { renderEmailTemplate } from '../../../lib/email-template';
5
- import Stripe from 'stripe';
6
- import { generateInvoicePdf } from './invoice.handler';
7
- import { readEmailSettings, readEmailTemplateData } from './settings.handler';
8
- function guessLogoMime(path) {
9
- const ext = path.split('.').pop()?.toLowerCase();
10
- if (ext === 'png')
11
- return 'image/png';
12
- if (ext === 'jpg' || ext === 'jpeg')
13
- return 'image/jpeg';
14
- if (ext === 'gif')
15
- return 'image/gif';
16
- if (ext === 'svg')
17
- return 'image/svg+xml';
18
- return 'image/png';
19
- }
20
- function getStripe(env) {
21
- const config = getShopConfig(env);
22
- if (!config.stripeSecretKey)
23
- throw new Error('Stripe secret key is not configured');
24
- return new Stripe(config.stripeSecretKey, { apiVersion: '2025-02-24.acacia' });
25
- }
26
- /**
27
- * Legacy Stripe webhook helper. The active route is /api/shop/webhook.
28
- */
29
- export async function handleStripeWebhook(c) {
30
- const stripe = getStripe(c.env);
31
- const webhookSecret = c.env.STRIPE_WEBHOOK_SECRET;
32
- if (!webhookSecret) {
33
- console.error('Stripe webhook secret not configured');
34
- return c.json({ error: 'Webhook not configured' }, 500);
35
- }
36
- const signature = c.req.header('stripe-signature');
37
- if (!signature)
38
- return c.json({ error: 'Missing stripe-signature header' }, 400);
39
- const rawBody = await c.req.text();
40
- let event;
41
- try {
42
- event = await stripe.webhooks.constructEventAsync(rawBody, signature, webhookSecret);
43
- }
44
- catch (err) {
45
- console.error('Webhook signature verification failed:', err.message);
46
- return c.json({ error: 'Webhook signature verification failed' }, 400);
47
- }
48
- switch (event.type) {
49
- case 'checkout.session.completed': {
50
- const session = event.data.object;
51
- await handleCheckoutSessionCompleted(c, stripe, session);
52
- break;
53
- }
54
- default:
55
- console.log(`Unhandled event type: ${event.type}`);
56
- }
57
- return c.json({ received: true });
58
- }
59
- async function handleCheckoutSessionCompleted(c, stripe, session) {
60
- try {
61
- const customerEmail = session.customer_details?.email;
62
- if (!customerEmail) {
63
- console.error('No customer email in checkout session');
64
- return;
65
- }
66
- const lineItems = await stripe.checkout.sessions.listLineItems(session.id, {
67
- expand: ['data.price.product'],
68
- });
69
- // Load invoice config and generated email template settings.
70
- let invoiceConfig;
71
- let branding;
72
- try {
73
- const { settings } = await readEmailSettings(c.env);
74
- invoiceConfig = settings.invoice;
75
- let logoDataUrl;
76
- if (settings.logoPath) {
77
- try {
78
- const github = createGitHubClient(getGitHubConfig(c.env));
79
- const file = await github.readFileBinary(settings.logoPath);
80
- if (file)
81
- logoDataUrl = `data:${guessLogoMime(settings.logoPath)};base64,${file.content}`;
82
- }
83
- catch (error) {
84
- console.error('Failed to load logo from GitHub:', error);
85
- }
86
- }
87
- branding = {
88
- logo: logoDataUrl,
89
- companyName: settings.invoice.companyName,
90
- primaryColor: settings.invoice.primaryColor,
91
- };
92
- }
93
- catch (error) {
94
- console.error('Failed to fetch email settings from GitHub:', error);
95
- }
96
- const invoiceItems = lineItems.data.map((item) => {
97
- const product = item.price?.product;
98
- return {
99
- description: product?.name || item.description || 'Item',
100
- quantity: item.quantity || 1,
101
- unitPrice: (item.price?.unit_amount || 0) / 100,
102
- total: (item.amount_total || 0) / 100,
103
- };
104
- });
105
- const invoiceData = {
106
- invoiceNumber: `INV-${session.id.slice(-8).toUpperCase()}`,
107
- invoiceDate: new Date().toLocaleDateString('en-US', { year: 'numeric', month: 'long', day: 'numeric' }),
108
- customerName: session.customer_details?.name || 'Customer',
109
- customerEmail,
110
- customerAddress: session.customer_details?.address
111
- ? formatAddress(session.customer_details.address)
112
- : undefined,
113
- items: invoiceItems,
114
- subtotal: (session.amount_subtotal || 0) / 100,
115
- tax: session.total_details?.amount_tax ? session.total_details.amount_tax / 100 : undefined,
116
- total: (session.amount_total || 0) / 100,
117
- currency: session.currency?.toUpperCase() || 'EUR',
118
- paymentMethod: session.payment_method_types?.[0] || 'card',
119
- };
120
- const pdfBytes = await generateInvoicePdf((invoiceConfig ?? {}), invoiceData, branding);
121
- await sendInvoiceEmail(c.env, customerEmail, invoiceData, pdfBytes);
122
- console.log(`Invoice sent to ${customerEmail} for session ${session.id}`);
123
- }
124
- catch (error) {
125
- console.error('Failed to handle checkout session completed:', error);
126
- }
127
- }
128
- function formatAddress(address) {
129
- const parts = [];
130
- if (address.line1)
131
- parts.push(address.line1);
132
- if (address.line2)
133
- parts.push(address.line2);
134
- if (address.city)
135
- parts.push(address.city);
136
- if (address.postal_code)
137
- parts.push(address.postal_code);
138
- if (address.country)
139
- parts.push(address.country);
140
- return parts.join(', ');
141
- }
142
- async function sendInvoiceEmail(env, to, invoiceData, _pdfBytes) {
143
- const html = `
144
- <div style="font-family:sans-serif;max-width:600px;margin:0 auto;padding:20px;">
145
- <h1 style="color:#1f2937;">Thank you for your purchase!</h1>
146
- <p style="color:#4b5563;">Dear ${invoiceData.customerName},</p>
147
- <p style="color:#4b5563;">Thank you for your order.</p>
148
- <div style="background:#f3f4f6;padding:20px;border-radius:8px;margin:20px 0;">
149
- <p style="margin:0;color:#1f2937;"><strong>Invoice Number:</strong> ${invoiceData.invoiceNumber}</p>
150
- <p style="margin:8px 0;color:#1f2937;"><strong>Date:</strong> ${invoiceData.invoiceDate}</p>
151
- <p style="margin:8px 0;color:#1f2937;"><strong>Total:</strong> ${invoiceData.currency} ${invoiceData.total.toFixed(2)}</p>
152
- </div>
153
- <p style="color:#9ca3af;font-size:12px;margin-top:40px;">This is an automated email.</p>
154
- </div>`;
155
- const { settings, logoDataUrl } = await readEmailTemplateData(env);
156
- await sendEmail(env, {
157
- to,
158
- subject: `Your Invoice ${invoiceData.invoiceNumber}`,
159
- html: renderEmailTemplate({ bodyHtml: html, template: settings.emailTemplate, logoDataUrl }),
160
- });
161
- }