@hintergrund/worker 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (122) hide show
  1. package/README.md +45 -0
  2. package/dist/api/builder/handlers/generate.handler.d.ts +12 -0
  3. package/dist/api/builder/handlers/generate.handler.d.ts.map +1 -0
  4. package/dist/api/builder/handlers/generate.handler.js +203 -0
  5. package/dist/api/builder/handlers/template.handler.d.ts +12 -0
  6. package/dist/api/builder/handlers/template.handler.d.ts.map +1 -0
  7. package/dist/api/builder/handlers/template.handler.js +208 -0
  8. package/dist/api/builder/routes.d.ts +7 -0
  9. package/dist/api/builder/routes.d.ts.map +1 -0
  10. package/dist/api/builder/routes.js +15 -0
  11. package/dist/api/cms/handlers/assets.handler.d.ts +8 -0
  12. package/dist/api/cms/handlers/assets.handler.d.ts.map +1 -0
  13. package/dist/api/cms/handlers/assets.handler.js +299 -0
  14. package/dist/api/cms/handlers/auth.handler.d.ts +11 -0
  15. package/dist/api/cms/handlers/auth.handler.d.ts.map +1 -0
  16. package/dist/api/cms/handlers/auth.handler.js +214 -0
  17. package/dist/api/cms/handlers/config.handler.d.ts +3 -0
  18. package/dist/api/cms/handlers/config.handler.d.ts.map +1 -0
  19. package/dist/api/cms/handlers/config.handler.js +88 -0
  20. package/dist/api/cms/handlers/content.handler.d.ts +10 -0
  21. package/dist/api/cms/handlers/content.handler.d.ts.map +1 -0
  22. package/dist/api/cms/handlers/content.handler.js +293 -0
  23. package/dist/api/cms/handlers/dashboard.handler.d.ts +6 -0
  24. package/dist/api/cms/handlers/dashboard.handler.d.ts.map +1 -0
  25. package/dist/api/cms/handlers/dashboard.handler.js +15 -0
  26. package/dist/api/cms/routes/assets.routes.d.ts +4 -0
  27. package/dist/api/cms/routes/assets.routes.d.ts.map +1 -0
  28. package/dist/api/cms/routes/assets.routes.js +13 -0
  29. package/dist/api/cms/routes/auth.routes.d.ts +4 -0
  30. package/dist/api/cms/routes/auth.routes.d.ts.map +1 -0
  31. package/dist/api/cms/routes/auth.routes.js +7 -0
  32. package/dist/api/cms/routes/content.routes.d.ts +4 -0
  33. package/dist/api/cms/routes/content.routes.d.ts.map +1 -0
  34. package/dist/api/cms/routes/content.routes.js +11 -0
  35. package/dist/api/cms/routes/index.d.ts +4 -0
  36. package/dist/api/cms/routes/index.d.ts.map +1 -0
  37. package/dist/api/cms/routes/index.js +16 -0
  38. package/dist/api/newsletter/handlers/email.handler.d.ts +7 -0
  39. package/dist/api/newsletter/handlers/email.handler.d.ts.map +1 -0
  40. package/dist/api/newsletter/handlers/email.handler.js +102 -0
  41. package/dist/api/newsletter/handlers/emails.handler.d.ts +21 -0
  42. package/dist/api/newsletter/handlers/emails.handler.d.ts.map +1 -0
  43. package/dist/api/newsletter/handlers/emails.handler.js +134 -0
  44. package/dist/api/newsletter/handlers/public.handler.d.ts +22 -0
  45. package/dist/api/newsletter/handlers/public.handler.d.ts.map +1 -0
  46. package/dist/api/newsletter/handlers/public.handler.js +242 -0
  47. package/dist/api/newsletter/handlers/send.handler.d.ts +12 -0
  48. package/dist/api/newsletter/handlers/send.handler.d.ts.map +1 -0
  49. package/dist/api/newsletter/handlers/send.handler.js +153 -0
  50. package/dist/api/newsletter/handlers/subscribers.handler.d.ts +22 -0
  51. package/dist/api/newsletter/handlers/subscribers.handler.d.ts.map +1 -0
  52. package/dist/api/newsletter/handlers/subscribers.handler.js +191 -0
  53. package/dist/api/newsletter/routes/admin.routes.d.ts +4 -0
  54. package/dist/api/newsletter/routes/admin.routes.d.ts.map +1 -0
  55. package/dist/api/newsletter/routes/admin.routes.js +21 -0
  56. package/dist/api/newsletter/routes/index.d.ts +4 -0
  57. package/dist/api/newsletter/routes/index.d.ts.map +1 -0
  58. package/dist/api/newsletter/routes/index.js +9 -0
  59. package/dist/api/newsletter/routes/public.routes.d.ts +4 -0
  60. package/dist/api/newsletter/routes/public.routes.d.ts.map +1 -0
  61. package/dist/api/newsletter/routes/public.routes.js +9 -0
  62. package/dist/api/shop/handlers/customers.handler.d.ts +17 -0
  63. package/dist/api/shop/handlers/customers.handler.d.ts.map +1 -0
  64. package/dist/api/shop/handlers/customers.handler.js +89 -0
  65. package/dist/api/shop/handlers/orders.handler.d.ts +17 -0
  66. package/dist/api/shop/handlers/orders.handler.d.ts.map +1 -0
  67. package/dist/api/shop/handlers/orders.handler.js +84 -0
  68. package/dist/api/shop/handlers/prices.handler.d.ts +17 -0
  69. package/dist/api/shop/handlers/prices.handler.d.ts.map +1 -0
  70. package/dist/api/shop/handlers/prices.handler.js +87 -0
  71. package/dist/api/shop/handlers/products.handler.d.ts +45 -0
  72. package/dist/api/shop/handlers/products.handler.d.ts.map +1 -0
  73. package/dist/api/shop/handlers/products.handler.js +243 -0
  74. package/dist/api/shop/handlers/stats.handler.d.ts +10 -0
  75. package/dist/api/shop/handlers/stats.handler.d.ts.map +1 -0
  76. package/dist/api/shop/handlers/stats.handler.js +71 -0
  77. package/dist/api/shop/routes.d.ts +7 -0
  78. package/dist/api/shop/routes.d.ts.map +1 -0
  79. package/dist/api/shop/routes.js +31 -0
  80. package/dist/cms-assets.d.ts +4 -0
  81. package/dist/cms-assets.d.ts.map +1 -0
  82. package/dist/cms-assets.js +5 -0
  83. package/dist/cms-bundle.d.ts +3 -0
  84. package/dist/cms-bundle.d.ts.map +1 -0
  85. package/dist/cms-bundle.js +4 -0
  86. package/dist/config-loader.d.ts +26 -0
  87. package/dist/config-loader.d.ts.map +1 -0
  88. package/dist/config-loader.js +98 -0
  89. package/dist/hintergrund-assets.d.ts +4 -0
  90. package/dist/hintergrund-assets.d.ts.map +1 -0
  91. package/dist/hintergrund-assets.js +9 -0
  92. package/dist/index.d.ts +35 -0
  93. package/dist/index.d.ts.map +1 -0
  94. package/dist/index.js +66 -0
  95. package/dist/jwt.d.ts +26 -0
  96. package/dist/jwt.d.ts.map +1 -0
  97. package/dist/jwt.js +102 -0
  98. package/dist/lib/auth/crypto.d.ts +23 -0
  99. package/dist/lib/auth/crypto.d.ts.map +1 -0
  100. package/dist/lib/auth/crypto.js +110 -0
  101. package/dist/lib/auth/jwt.d.ts +38 -0
  102. package/dist/lib/auth/jwt.d.ts.map +1 -0
  103. package/dist/lib/auth/jwt.js +120 -0
  104. package/dist/lib/config.d.ts +31 -0
  105. package/dist/lib/config.d.ts.map +1 -0
  106. package/dist/lib/config.js +174 -0
  107. package/dist/lib/email.d.ts +16 -0
  108. package/dist/lib/email.d.ts.map +1 -0
  109. package/dist/lib/email.js +83 -0
  110. package/dist/lib/template.d.ts +2 -0
  111. package/dist/lib/template.d.ts.map +1 -0
  112. package/dist/lib/template.js +226 -0
  113. package/dist/middleware/auth.d.ts +9 -0
  114. package/dist/middleware/auth.d.ts.map +1 -0
  115. package/dist/middleware/auth.js +93 -0
  116. package/dist/template.d.ts +2 -0
  117. package/dist/template.d.ts.map +1 -0
  118. package/dist/template.js +61 -0
  119. package/dist/utils.d.ts +23 -0
  120. package/dist/utils.d.ts.map +1 -0
  121. package/dist/utils.js +110 -0
  122. package/package.json +32 -0
@@ -0,0 +1,299 @@
1
+ import { Octokit } from '@octokit/rest';
2
+ import { getCmsConfig } from '../../../lib/config';
3
+ const mimeTypes = {
4
+ '.jpg': 'image/jpeg',
5
+ '.png': 'image/png',
6
+ '.gif': 'image/gif',
7
+ '.svg': 'image/svg+xml',
8
+ '.ico': 'image/x-icon',
9
+ '.webp': 'image/webp',
10
+ '.mp4': 'video/mp4',
11
+ '.webm': 'video/webm',
12
+ '.ogg': 'video/ogg',
13
+ '.ogv': 'video/ogg',
14
+ '.mov': 'video/quicktime',
15
+ '.avi': 'video/x-msvideo',
16
+ '.mkv': 'video/x-matroska',
17
+ '.mp3': 'audio/mpeg',
18
+ '.wav': 'audio/wav',
19
+ '.m4a': 'audio/mp4',
20
+ '.aac': 'audio/aac',
21
+ '.oga': 'audio/ogg'
22
+ };
23
+ function getMimeType(path) {
24
+ const extension = path.slice(((path.lastIndexOf('.') - 1) >>> 0) + 2);
25
+ return mimeTypes['.' + extension] || 'text/plain';
26
+ }
27
+ export async function listAssets(c) {
28
+ try {
29
+ const config = getCmsConfig(c.env);
30
+ const octokit = new Octokit({
31
+ auth: config.gitToken
32
+ });
33
+ // Get all files in the asset directory
34
+ const assetFiles = await octokit.rest.repos.getContent({
35
+ owner: config.gitOwner,
36
+ repo: config.gitRepo,
37
+ path: config.assetDir
38
+ });
39
+ if (assetFiles.status !== 200 || !assetFiles.data || !Array.isArray(assetFiles.data)) {
40
+ return new Response(JSON.stringify(assetFiles), { status: 500 });
41
+ }
42
+ const assetObject = assetFiles.data.map(({ name, path, download_url }) => ({
43
+ name,
44
+ path,
45
+ download_url
46
+ }));
47
+ return new Response(JSON.stringify(assetObject), { status: 200 });
48
+ }
49
+ catch (error) {
50
+ return new Response(JSON.stringify(error), {
51
+ status: 500
52
+ });
53
+ }
54
+ }
55
+ export async function uploadAsset(c) {
56
+ try {
57
+ const config = getCmsConfig(c.env);
58
+ const octokit = new Octokit({
59
+ auth: config.gitToken
60
+ });
61
+ const { file, content } = await c.req.json();
62
+ await octokit.rest.repos.createOrUpdateFileContents({
63
+ owner: config.gitOwner,
64
+ repo: config.gitRepo,
65
+ path: `${config.assetDir}/${file}`,
66
+ message: `Upload asset ${file} [CI SKIP]`,
67
+ content: content,
68
+ branch: config.gitBranch
69
+ });
70
+ const response = { success: true, message: `Uploaded ${file} to ${config.assetDir}` };
71
+ return new Response(JSON.stringify(response), {
72
+ status: 200
73
+ });
74
+ }
75
+ catch (error) {
76
+ return new Response(JSON.stringify(error), {
77
+ status: 500
78
+ });
79
+ }
80
+ }
81
+ export async function deleteAsset(c) {
82
+ try {
83
+ const { file } = await c.req.json();
84
+ const config = getCmsConfig(c.env);
85
+ const octokit = new Octokit({
86
+ auth: config.gitToken
87
+ });
88
+ // Get file sha
89
+ const fileInfo = await octokit.rest.repos.getContent({
90
+ owner: config.gitOwner,
91
+ repo: config.gitRepo,
92
+ path: `${config.assetDir}/${file}`,
93
+ ref: config.gitBranch
94
+ });
95
+ // Type guard to check if data is a file (not array or directory)
96
+ if (Array.isArray(fileInfo.data) || !('sha' in fileInfo.data)) {
97
+ return new Response('File not found or is not a file', { status: 404 });
98
+ }
99
+ if (!fileInfo.data.sha) {
100
+ return new Response('Resource was already deleted', { status: 204 });
101
+ }
102
+ const response = await octokit.rest.repos.deleteFile({
103
+ owner: config.gitOwner,
104
+ repo: config.gitRepo,
105
+ path: `${config.assetDir}/${file}`,
106
+ message: `Delete asset ${file} [CI SKIP]`,
107
+ sha: fileInfo.data.sha
108
+ });
109
+ if (response.status !== 200) {
110
+ return new Response(`Error deleting ${file} from ${config.assetDir}`, {
111
+ status: 500
112
+ });
113
+ }
114
+ return new Response(`Deleted asset ${file}`, { status: 200 });
115
+ }
116
+ catch (error) {
117
+ console.log(error);
118
+ return new Response(error.message, {
119
+ status: 500
120
+ });
121
+ }
122
+ }
123
+ export async function getAssetByPath(c) {
124
+ try {
125
+ const path = c.req.param('path');
126
+ const config = getCmsConfig(c.env);
127
+ const octokit = new Octokit({
128
+ auth: config.gitToken
129
+ });
130
+ // Get file content
131
+ const rawFile = await octokit.rest.repos.getContent({
132
+ owner: config.gitOwner,
133
+ repo: config.gitRepo,
134
+ path: `${config.assetDir}/${path}`
135
+ });
136
+ // Type guard to check if data is a file (not array or directory)
137
+ if (Array.isArray(rawFile.data) || !('content' in rawFile.data)) {
138
+ throw new Error('File not found or is not a file');
139
+ }
140
+ const mimeType = getMimeType(path);
141
+ const response = { image: rawFile.data.content || '', mimeType };
142
+ return new Response(JSON.stringify(response), {
143
+ status: 200,
144
+ headers: {
145
+ 'Content-Type': 'application/json'
146
+ }
147
+ });
148
+ }
149
+ catch (error) {
150
+ return new Response(JSON.stringify(error), {
151
+ status: 500
152
+ });
153
+ }
154
+ }
155
+ export async function syncAssets(c) {
156
+ try {
157
+ const config = getCmsConfig(c.env);
158
+ const octokit = new Octokit({
159
+ auth: config.gitToken
160
+ });
161
+ // Get the latest commit SHA for the branch
162
+ const branchData = await octokit.rest.repos.getBranch({
163
+ owner: config.gitOwner,
164
+ repo: config.gitRepo,
165
+ branch: config.gitBranch
166
+ });
167
+ const commitSha = branchData.data.commit.sha;
168
+ // Get all files in the asset directory
169
+ const assetFiles = await octokit.rest.repos.getContent({
170
+ owner: config.gitOwner,
171
+ repo: config.gitRepo,
172
+ path: config.assetDir,
173
+ ref: config.gitBranch
174
+ });
175
+ if (assetFiles.status !== 200 || !assetFiles.data || !Array.isArray(assetFiles.data)) {
176
+ return new Response(JSON.stringify(assetFiles), { status: 500 });
177
+ }
178
+ // Fetch content for each file
179
+ const filesWithContent = await Promise.all(assetFiles.data.map(async ({ name, path }) => {
180
+ try {
181
+ const rawFile = await octokit.rest.repos.getContent({
182
+ owner: config.gitOwner,
183
+ repo: config.gitRepo,
184
+ path: path,
185
+ ref: config.gitBranch
186
+ });
187
+ // Type guard
188
+ if (Array.isArray(rawFile.data) || !('content' in rawFile.data)) {
189
+ return null;
190
+ }
191
+ const mimeType = getMimeType(name);
192
+ let content = rawFile.data.content?.replace(/\n/g, '') || '';
193
+ // For large files (videos, etc.), GitHub doesn't return content
194
+ // In this case, fetch via download_url
195
+ if (!content && rawFile.data.download_url) {
196
+ try {
197
+ const downloadResponse = await fetch(rawFile.data.download_url);
198
+ if (downloadResponse.ok) {
199
+ const arrayBuffer = await downloadResponse.arrayBuffer();
200
+ // Convert to base64 - process in chunks to avoid stack overflow
201
+ const uint8Array = new Uint8Array(arrayBuffer);
202
+ const chunkSize = 8192;
203
+ let binary = '';
204
+ for (let i = 0; i < uint8Array.length; i += chunkSize) {
205
+ const chunk = uint8Array.subarray(i, Math.min(i + chunkSize, uint8Array.length));
206
+ binary += String.fromCharCode.apply(null, Array.from(chunk));
207
+ }
208
+ content = btoa(binary);
209
+ }
210
+ }
211
+ catch (downloadError) {
212
+ console.error(`Failed to download ${name}:`, downloadError);
213
+ }
214
+ }
215
+ return {
216
+ name,
217
+ path,
218
+ content,
219
+ mimeType,
220
+ lastModified: Date.now()
221
+ };
222
+ }
223
+ catch (error) {
224
+ console.error(`Failed to fetch ${name}:`, error);
225
+ return null;
226
+ }
227
+ }));
228
+ // Filter out failed fetches
229
+ const validFiles = filesWithContent.filter((file) => file !== null);
230
+ const response = {
231
+ assets: validFiles,
232
+ commitSha
233
+ };
234
+ return new Response(JSON.stringify(response), {
235
+ status: 200,
236
+ headers: {
237
+ 'Content-Type': 'application/json'
238
+ }
239
+ });
240
+ }
241
+ catch (error) {
242
+ return new Response(JSON.stringify(error), {
243
+ status: 500
244
+ });
245
+ }
246
+ }
247
+ export async function syncAssetsMock(_c) {
248
+ // Mock data for development - colorful SVG placeholder images
249
+ const mockAssets = [
250
+ {
251
+ name: 'landscape-1.png',
252
+ path: 'static/landscape-1.png',
253
+ content: 'PHN2ZyB3aWR0aD0iMTIwMCIgaGVpZ2h0PSI4MDAiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+CgkJPHJlY3Qgd2lkdGg9IjEyMDAiIGhlaWdodD0iODAwIiBmaWxsPSIjM0I4MkY2Ii8+CgkJPHRleHQgeD0iNTAlIiB5PSI1MCUiCgkJCWZvbnQtZmFtaWx5PSJBcmlhbCwgc2Fucy1zZXJpZiIKCQkJZm9udC1zaXplPSI0OCIKCQkJZm9udC13ZWlnaHQ9ImJvbGQiCgkJCWZpbGw9IndoaXRlIgoJCQl0ZXh0LWFuY2hvcj0ibWlkZGxlIgoJCQlkb21pbmFudC1iYXNlbGluZT0ibWlkZGxlIj5MYW5kc2NhcGUgMTwvdGV4dD4KCQk8dGV4dCB4PSI1MCUiIHk9IjU4JSIKCQkJZm9udC1mYW1pbHk9IkFyaWFsLCBzYW5zLXNlcmlmIgoJCQlmb250LXNpemU9IjI0IgoJCQlmaWxsPSJyZ2JhKDI1NSwyNTUsMjU1LDAuOCkiCgkJCXRleHQtYW5jaG9yPSJtaWRkbGUiCgkJCWRvbWluYW50LWJhc2VsaW5lPSJtaWRkbGUiPjEyMDAgw5cgODAwPC90ZXh0PgoJPC9zdmc+',
254
+ mimeType: 'image/svg+xml',
255
+ lastModified: Date.now()
256
+ },
257
+ {
258
+ name: 'landscape-2.png',
259
+ path: 'static/landscape-2.png',
260
+ content: 'PHN2ZyB3aWR0aD0iMTIwMCIgaGVpZ2h0PSI4MDAiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+CgkJPHJlY3Qgd2lkdGg9IjEyMDAiIGhlaWdodD0iODAwIiBmaWxsPSIjMTBCOTgxIi8+CgkJPHRleHQgeD0iNTAlIiB5PSI1MCUiCgkJCWZvbnQtZmFtaWx5PSJBcmlhbCwgc2Fucy1zZXJpZiIKCQkJZm9udC1zaXplPSI0OCIKCQkJZm9udC13ZWlnaHQ9ImJvbGQiCgkJCWZpbGw9IndoaXRlIgoJCQl0ZXh0LWFuY2hvcj0ibWlkZGxlIgoJCQlkb21pbmFudC1iYXNlbGluZT0ibWlkZGxlIj5MYW5kc2NhcGUgMjwvdGV4dD4KCQk8dGV4dCB4PSI1MCUiIHk9IjU4JSIKCQkJZm9udC1mYW1pbHk9IkFyaWFsLCBzYW5zLXNlcmlmIgoJCQlmb250LXNpemU9IjI0IgoJCQlmaWxsPSJyZ2JhKDI1NSwyNTUsMjU1LDAuOCkiCgkJCXRleHQtYW5jaG9yPSJtaWRkbGUiCgkJCWRvbWluYW50LWJhc2VsaW5lPSJtaWRkbGUiPjEyMDAgw5cgODAwPC90ZXh0PgoJPC9zdmc+',
261
+ mimeType: 'image/svg+xml',
262
+ lastModified: Date.now()
263
+ },
264
+ {
265
+ name: 'portrait-1.png',
266
+ path: 'static/portrait-1.png',
267
+ content: 'PHN2ZyB3aWR0aD0iODAwIiBoZWlnaHQ9IjEyMDAiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+CgkJPHJlY3Qgd2lkdGg9IjgwMCIgaGVpZ2h0PSIxMjAwIiBmaWxsPSIjOEI1Q0Y2Ii8+CgkJPHRleHQgeD0iNTAlIiB5PSI1MCUiCgkJCWZvbnQtZmFtaWx5PSJBcmlhbCwgc2Fucy1zZXJpZiIKCQkJZm9udC1zaXplPSI0OCIKCQkJZm9udC13ZWlnaHQ9ImJvbGQiCgkJCWZpbGw9IndoaXRlIgoJCQl0ZXh0LWFuY2hvcj0ibWlkZGxlIgoJCQlkb21pbmFudC1iYXNlbGluZT0ibWlkZGxlIj5Qb3J0cmFpdCAxPC90ZXh0PgoJCTx0ZXh0IHg9IjUwJSIgeT0iNTglIgoJCQlmb250LWZhbWlseT0iQXJpYWwsIHNhbnMtc2VyaWYiCgkJCWZvbnQtc2l6ZT0iMjQiCgkJCWZpbGw9InJnYmEoMjU1LDI1NSwyNTUsMC44KSIKCQkJdGV4dC1hbmNob3I9Im1pZGRsZSIKCQkJZG9taW5hbnQtYmFzZWxpbmU9Im1pZGRsZSI+ODAwIMOXIDEyMDA8L3RleHQ+Cgk8L3N2Zz4=',
268
+ mimeType: 'image/svg+xml',
269
+ lastModified: Date.now()
270
+ },
271
+ {
272
+ name: 'portrait-2.png',
273
+ path: 'static/portrait-2.png',
274
+ content: 'PHN2ZyB3aWR0aD0iODAwIiBoZWlnaHQ9IjEyMDAiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+CgkJPHJlY3Qgd2lkdGg9IjgwMCIgaGVpZ2h0PSIxMjAwIiBmaWxsPSIjRjU5RTBCIi8+CgkJPHRleHQgeD0iNTAlIiB5PSI1MCUiCgkJCWZvbnQtZmFtaWx5PSJBcmlhbCwgc2Fucy1zZXJpZiIKCQkJZm9udC1zaXplPSI0OCIKCQkJZm9udC13ZWlnaHQ9ImJvbGQiCgkJCWZpbGw9IndoaXRlIgoJCQl0ZXh0LWFuY2hvcj0ibWlkZGxlIgoJCQlkb21pbmFudC1iYXNlbGluZT0ibWlkZGxlIj5Qb3J0cmFpdCAyPC90ZXh0PgoJCTx0ZXh0IHg9IjUwJSIgeT0iNTglIgoJCQlmb250LWZhbWlseT0iQXJpYWwsIHNhbnMtc2VyaWYiCgkJCWZvbnQtc2l6ZT0iMjQiCgkJCWZpbGw9InJnYmEoMjU1LDI1NSwyNTUsMC44KSIKCQkJdGV4dC1hbmNob3I9Im1pZGRsZSIKCQkJZG9taW5hbnQtYmFzZWxpbmU9Im1pZGRsZSI+ODAwIMOXIDEyMDA8L3RleHQ+Cgk8L3N2Zz4=',
275
+ mimeType: 'image/svg+xml',
276
+ lastModified: Date.now()
277
+ },
278
+ {
279
+ name: 'square-1.png',
280
+ path: 'static/square-1.png',
281
+ content: 'PHN2ZyB3aWR0aD0iODAwIiBoZWlnaHQ9IjgwMCIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4KCQk8cmVjdCB3aWR0aD0iODAwIiBoZWlnaHQ9IjgwMCIgZmlsbD0iI0VGNDQ0NCIvPgoJCTx0ZXh0IHg9IjUwJSIgeT0iNTAlIgoJCQlmb250LWZhbWlseT0iQXJpYWwsIHNhbnMtc2VyaWYiCgkJCWZvbnQtc2l6ZT0iNDgiCgkJCWZvbnQtd2VpZ2h0PSJib2xkIgoJCQlmaWxsPSJ3aGl0ZSIKCQkJdGV4dC1hbmNob3I9Im1pZGRsZSIKCQkJZG9taW5hbnQtYmFzZWxpbmU9Im1pZGRsZSI+U3F1YXJlIDE8L3RleHQ+CgkJPHRleHQgeD0iNTAlIiB5PSI1OCUiCgkJCWZvbnQtZmFtaWx5PSJBcmlhbCwgc2Fucy1zZXJpZiIKCQkJZm9udC1zaXplPSIyNCIKCQkJZmlsbD0icmdiYSgyNTUsMjU1LDI1NSwwLjgpIgoJCQl0ZXh0LWFuY2hvcj0ibWlkZGxlIgoJCQlkb21pbmFudC1iYXNlbGluZT0ibWlkZGxlIj44MDAgw5cgODAwPC90ZXh0PgoJPC9zdmc+',
282
+ mimeType: 'image/svg+xml',
283
+ lastModified: Date.now()
284
+ },
285
+ {
286
+ name: 'square-2.png',
287
+ path: 'static/square-2.png',
288
+ content: 'PHN2ZyB3aWR0aD0iODAwIiBoZWlnaHQ9IjgwMCIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4KCQk8cmVjdCB3aWR0aD0iODAwIiBoZWlnaHQ9IjgwMCIgZmlsbD0iI0VDNDg5OSIvPgoJCTx0ZXh0IHg9IjUwJSIgeT0iNTAlIgoJCQlmb250LWZhbWlseT0iQXJpYWwsIHNhbnMtc2VyaWYiCgkJCWZvbnQtc2l6ZT0iNDgiCgkJCWZvbnQtd2VpZ2h0PSJib2xkIgoJCQlmaWxsPSJ3aGl0ZSIKCQkJdGV4dC1hbmNob3I9Im1pZGRsZSIKCQkJZG9taW5hbnQtYmFzZWxpbmU9Im1pZGRsZSI+U3F1YXJlIDI8L3RleHQ+CgkJPHRleHQgeD0iNTAlIiB5PSI1OCUiCgkJCWZvbnQtZmFtaWx5PSJBcmlhbCwgc2Fucy1zZXJpZiIKCQkJZm9udC1zaXplPSIyNCIKCQkJZmlsbD0icmdiYSgyNTUsMjU1LDI1NSwwLjgpIgoJCQl0ZXh0LWFuY2hvcj0ibWlkZGxlIgoJCQlkb21pbmFudC1iYXNlbGluZT0ibWlkZGxlIj44MDAgw5cgODAwPC90ZXh0PgoJPC9zdmc+',
289
+ mimeType: 'image/svg+xml',
290
+ lastModified: Date.now()
291
+ }
292
+ ];
293
+ return new Response(JSON.stringify(mockAssets), {
294
+ status: 200,
295
+ headers: {
296
+ 'Content-Type': 'application/json'
297
+ }
298
+ });
299
+ }
@@ -0,0 +1,11 @@
1
+ import { Context } from 'hono';
2
+ /**
3
+ * Handle login request - supports both password and magic link authentication
4
+ */
5
+ export declare function login(c: Context): Promise<Response>;
6
+ /**
7
+ * Verify magic link token and log user in
8
+ */
9
+ export declare function verifyMagicLink(c: Context): Promise<Response>;
10
+ export declare function logout(c: Context): Promise<Response>;
11
+ //# sourceMappingURL=auth.handler.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"auth.handler.d.ts","sourceRoot":"","sources":["../../../../src/api/cms/handlers/auth.handler.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,MAAM,MAAM,CAAC;AAO/B;;GAEG;AACH,wBAAsB,KAAK,CAAC,CAAC,EAAE,OAAO,GAAG,OAAO,CAAC,QAAQ,CAAC,CAqBzD;AA8LD;;GAEG;AACH,wBAAsB,eAAe,CAAC,CAAC,EAAE,OAAO,GAAG,OAAO,CAAC,QAAQ,CAAC,CAuCnE;AAYD,wBAAsB,MAAM,CAAC,CAAC,EAAE,OAAO,GAAG,OAAO,CAAC,QAAQ,CAAC,CAW1D"}
@@ -0,0 +1,214 @@
1
+ import { readRequestBody, verifyPw } from '../../../lib/auth/crypto';
2
+ import { sign, signWithPayload } from '../../../lib/auth/jwt';
3
+ import { loadConfig } from '../../../lib/config';
4
+ import { sendMagicLinkEmail } from '../../../lib/email';
5
+ /**
6
+ * Handle login request - supports both password and magic link authentication
7
+ */
8
+ export async function login(c) {
9
+ try {
10
+ const appConfig = loadConfig(c.env);
11
+ const body = await readRequestBody(c.req.raw);
12
+ const isSecure = c.req.url.startsWith('https://');
13
+ const secureCookie = isSecure ? '; Secure' : '';
14
+ const authConfig = appConfig.global.auth;
15
+ const loginMethod = authConfig?.loginMethod ?? 'password';
16
+ // Magic link login flow
17
+ if (loginMethod === 'magic-link') {
18
+ return handleMagicLinkLogin(c, body, appConfig, isSecure);
19
+ }
20
+ // Password login flow (legacy or with user groups)
21
+ return handlePasswordLogin(c, body, appConfig, isSecure);
22
+ }
23
+ catch (error) {
24
+ console.error('Login error:', error);
25
+ return new Response(JSON.stringify({ success: false, message: String(error) }), { status: 401 });
26
+ }
27
+ }
28
+ /**
29
+ * Handle password-based login
30
+ */
31
+ async function handlePasswordLogin(c, body, appConfig, isSecure) {
32
+ const secureCookie = isSecure ? '; Secure' : '';
33
+ const password = body.password;
34
+ const userGroupName = body.userGroup;
35
+ if (!password) {
36
+ return new Response(JSON.stringify({ success: false, message: 'Password is required' }), { status: 400 });
37
+ }
38
+ const authConfig = appConfig.global.auth;
39
+ const userGroups = authConfig?.userGroups;
40
+ // If user groups are configured
41
+ if (userGroups && userGroups.length > 0) {
42
+ if (!userGroupName) {
43
+ return new Response(JSON.stringify({ success: false, message: 'Please select a user group' }), { status: 400 });
44
+ }
45
+ const group = userGroups.find(g => g.name === userGroupName);
46
+ if (!group) {
47
+ return new Response(JSON.stringify({ success: false, message: 'Invalid user group' }), { status: 401 });
48
+ }
49
+ if (!group.password) {
50
+ return new Response(JSON.stringify({ success: false, message: 'This group uses email login' }), { status: 400 });
51
+ }
52
+ // Verify password for the specific group
53
+ if (await verifyPw(group.password, password, appConfig.global.hgSecret)) {
54
+ // Sign token with user group info
55
+ const token = await signWithPayload(appConfig.global.hgSecret, {
56
+ userGroup: group.name,
57
+ modules: group.modules,
58
+ });
59
+ const response = { success: true };
60
+ return new Response(JSON.stringify(response), {
61
+ status: 200,
62
+ headers: {
63
+ 'Set-Cookie': `token=${token}; HttpOnly; Path=/; SameSite=Strict${secureCookie}`
64
+ }
65
+ });
66
+ }
67
+ else {
68
+ return new Response(JSON.stringify({ success: false, message: 'Wrong password' }), { status: 401 });
69
+ }
70
+ }
71
+ // Legacy single password mode
72
+ if (!appConfig.global.hgPassword) {
73
+ return new Response(JSON.stringify({ success: false, message: 'No password configured' }), { status: 500 });
74
+ }
75
+ if (await verifyPw(appConfig.global.hgPassword, password, appConfig.global.hgSecret)) {
76
+ const token = await sign(appConfig.global.hgSecret);
77
+ const response = { success: true };
78
+ return new Response(JSON.stringify(response), {
79
+ status: 200,
80
+ headers: {
81
+ 'Set-Cookie': `token=${token}; HttpOnly; Path=/; SameSite=Strict${secureCookie}`
82
+ }
83
+ });
84
+ }
85
+ else {
86
+ return new Response(JSON.stringify({ success: false, message: 'Wrong password' }), { status: 401 });
87
+ }
88
+ }
89
+ /**
90
+ * Handle magic link login - sends email with login link
91
+ */
92
+ async function handleMagicLinkLogin(c, body, appConfig, isSecure) {
93
+ const email = body.email?.toLowerCase().trim();
94
+ const userGroupName = body.userGroup;
95
+ if (!email) {
96
+ return new Response(JSON.stringify({ success: false, message: 'Email is required' }), { status: 400 });
97
+ }
98
+ const authConfig = appConfig.global.auth;
99
+ if (!authConfig?.resendApiKey || !authConfig?.fromEmail) {
100
+ return new Response(JSON.stringify({ success: false, message: 'Email login is not configured' }), { status: 500 });
101
+ }
102
+ const userGroups = authConfig.userGroups;
103
+ // Find which group(s) this email belongs to
104
+ let matchedGroup;
105
+ if (userGroups && userGroups.length > 0) {
106
+ if (userGroupName) {
107
+ // User specified a group - verify email is in that group
108
+ const group = userGroups.find(g => g.name === userGroupName);
109
+ if (!group) {
110
+ return new Response(JSON.stringify({ success: false, message: 'Invalid user group' }), { status: 401 });
111
+ }
112
+ if (!group.emails?.includes(email)) {
113
+ // Don't reveal which emails are valid - just say email sent
114
+ const response = { success: true, emailSent: true, message: 'If your email is registered, you will receive a login link.' };
115
+ return new Response(JSON.stringify(response), { status: 200 });
116
+ }
117
+ matchedGroup = group;
118
+ }
119
+ else {
120
+ // Find any group that contains this email
121
+ matchedGroup = userGroups.find(g => g.emails?.includes(email));
122
+ if (!matchedGroup) {
123
+ // Don't reveal which emails are valid
124
+ const response = { success: true, emailSent: true, message: 'If your email is registered, you will receive a login link.' };
125
+ return new Response(JSON.stringify(response), { status: 200 });
126
+ }
127
+ }
128
+ }
129
+ // Generate magic link token (valid for 15 minutes)
130
+ const magicToken = await signWithPayload(appConfig.global.hgSecret, {
131
+ email,
132
+ userGroup: matchedGroup?.name,
133
+ modules: matchedGroup?.modules,
134
+ type: 'magic-link',
135
+ }, 15 * 60); // 15 minutes
136
+ // Build the magic link URL
137
+ const baseUrl = c.req.url.replace(/\/api\/admin\/login.*$/, '');
138
+ const magicLinkUrl = `${baseUrl}/api/admin/verify-magic-link?token=${encodeURIComponent(magicToken)}`;
139
+ // Send the email
140
+ try {
141
+ await sendMagicLinkEmail({
142
+ to: email,
143
+ fromEmail: authConfig.fromEmail,
144
+ resendApiKey: authConfig.resendApiKey,
145
+ magicLinkUrl,
146
+ userGroup: matchedGroup?.name,
147
+ });
148
+ const response = { success: true, emailSent: true, message: 'Check your email for the login link.' };
149
+ return new Response(JSON.stringify(response), { status: 200 });
150
+ }
151
+ catch (error) {
152
+ console.error('Failed to send magic link email:', error);
153
+ return new Response(JSON.stringify({ success: false, message: 'Failed to send email. Please try again.' }), { status: 500 });
154
+ }
155
+ }
156
+ /**
157
+ * Verify magic link token and log user in
158
+ */
159
+ export async function verifyMagicLink(c) {
160
+ try {
161
+ const appConfig = loadConfig(c.env);
162
+ const token = c.req.query('token');
163
+ const isSecure = c.req.url.startsWith('https://');
164
+ const secureCookie = isSecure ? '; Secure' : '';
165
+ if (!token) {
166
+ return new Response('Missing token', { status: 400 });
167
+ }
168
+ // Verify the magic link token
169
+ const { verify } = await import('../../../lib/auth/jwt');
170
+ const payload = await verify(token, appConfig.global.hgSecret);
171
+ if (!payload || payload.type !== 'magic-link') {
172
+ return redirectToLoginWithError(c, 'Invalid or expired link');
173
+ }
174
+ // Create a new session token (valid for 24 hours)
175
+ const sessionToken = await signWithPayload(appConfig.global.hgSecret, {
176
+ email: payload.email,
177
+ userGroup: payload.userGroup,
178
+ modules: payload.modules,
179
+ });
180
+ // Redirect to admin with cookie set
181
+ const baseUrl = c.req.url.replace(/\/api\/admin\/verify-magic-link.*$/, '');
182
+ return new Response(null, {
183
+ status: 302,
184
+ headers: {
185
+ 'Location': `${baseUrl}/admin`,
186
+ 'Set-Cookie': `token=${sessionToken}; HttpOnly; Path=/; SameSite=Strict${secureCookie}`
187
+ }
188
+ });
189
+ }
190
+ catch (error) {
191
+ console.error('Magic link verification error:', error);
192
+ return redirectToLoginWithError(c, 'Invalid or expired link');
193
+ }
194
+ }
195
+ function redirectToLoginWithError(c, message) {
196
+ const baseUrl = c.req.url.replace(/\/api\/admin\/verify-magic-link.*$/, '');
197
+ return new Response(null, {
198
+ status: 302,
199
+ headers: {
200
+ 'Location': `${baseUrl}/login?error=${encodeURIComponent(message)}`
201
+ }
202
+ });
203
+ }
204
+ export async function logout(c) {
205
+ const isSecure = c.req.url.startsWith('https://');
206
+ const secureCookie = isSecure ? '; Secure' : '';
207
+ return new Response(null, {
208
+ status: 303,
209
+ headers: {
210
+ Location: `/`,
211
+ 'Set-Cookie': `token=; HttpOnly; Path=/; Max-Age=0${secureCookie}`
212
+ }
213
+ });
214
+ }
@@ -0,0 +1,3 @@
1
+ import { Context } from 'hono';
2
+ export declare function updateConfig(c: Context): Promise<Response>;
3
+ //# sourceMappingURL=config.handler.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"config.handler.d.ts","sourceRoot":"","sources":["../../../../src/api/cms/handlers/config.handler.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,MAAM,MAAM,CAAC;AAS/B,wBAAsB,YAAY,CAAC,CAAC,EAAE,OAAO,GAAG,OAAO,CAAC,QAAQ,CAAC,CAiGhE"}
@@ -0,0 +1,88 @@
1
+ import { Octokit } from '@octokit/rest';
2
+ import { getCmsConfig } from '../../../lib/config';
3
+ export async function updateConfig(c) {
4
+ try {
5
+ const request = await c.req.json();
6
+ const config = getCmsConfig(c.env);
7
+ const octokit = new Octokit({
8
+ auth: config.gitToken
9
+ });
10
+ // Get reference from branch
11
+ const ref = await octokit.rest.git.getRef({
12
+ owner: config.gitOwner,
13
+ repo: config.gitRepo,
14
+ ref: `heads/${config.gitBranch}`
15
+ });
16
+ const currentCommitSha = ref.data.object.sha;
17
+ // Check for conflicts - if commit SHA doesn't match, someone else has committed
18
+ if (request.commitSha !== currentCommitSha) {
19
+ // Fetch current config to show in conflict UI
20
+ const configFile = await octokit.rest.repos.getContent({
21
+ owner: config.gitOwner,
22
+ repo: config.gitRepo,
23
+ path: `${config.contentDir}/config.json`
24
+ });
25
+ if (Array.isArray(configFile.data) || !('content' in configFile.data)) {
26
+ throw new Error('Config file not found or is not a file');
27
+ }
28
+ const serverConfig = JSON.parse(atob(configFile.data.content || ''));
29
+ const conflictResponse = {
30
+ conflict: true,
31
+ currentCommitSha,
32
+ serverConfig,
33
+ message: 'Configuration has been modified by another user. Please resolve conflicts.'
34
+ };
35
+ return new Response(JSON.stringify(conflictResponse), { status: 409 });
36
+ }
37
+ // Get latest commit
38
+ const commit = await octokit.rest.git.getCommit({
39
+ owner: config.gitOwner,
40
+ repo: config.gitRepo,
41
+ commit_sha: currentCommitSha
42
+ });
43
+ // Create blob for config.json
44
+ const blob = await octokit.rest.git.createBlob({
45
+ owner: config.gitOwner,
46
+ repo: config.gitRepo,
47
+ content: JSON.stringify(request.config, null, 4),
48
+ encoding: 'utf-8'
49
+ });
50
+ // Create tree with the updated config file
51
+ const newTree = await octokit.rest.git.createTree({
52
+ owner: config.gitOwner,
53
+ repo: config.gitRepo,
54
+ tree: [
55
+ {
56
+ path: `${config.contentDir}/config.json`,
57
+ mode: '100644',
58
+ type: 'blob',
59
+ sha: blob.data.sha
60
+ }
61
+ ],
62
+ base_tree: commit.data.tree.sha
63
+ });
64
+ // Create commit
65
+ const newCommit = await octokit.rest.git.createCommit({
66
+ owner: config.gitOwner,
67
+ repo: config.gitRepo,
68
+ message: 'Update configuration',
69
+ tree: newTree.data.sha,
70
+ parents: [commit.data.sha]
71
+ });
72
+ // Update reference
73
+ await octokit.rest.git.updateRef({
74
+ owner: config.gitOwner,
75
+ repo: config.gitRepo,
76
+ ref: `heads/${config.gitBranch}`,
77
+ sha: newCommit.data.sha
78
+ });
79
+ const response = { success: true };
80
+ return new Response(JSON.stringify(response), { status: 200 });
81
+ }
82
+ catch (error) {
83
+ console.log(error);
84
+ return new Response(JSON.stringify(error), {
85
+ status: 500
86
+ });
87
+ }
88
+ }
@@ -0,0 +1,10 @@
1
+ import { Context } from 'hono';
2
+ export declare function getContents(c: Context): Promise<Response>;
3
+ /**
4
+ * Sync contents from GitHub - optimized for conditional fetching
5
+ * Only fetches content data from GitHub if commitSha has changed
6
+ */
7
+ export declare function syncContents(c: Context): Promise<Response>;
8
+ export declare function updateContents(c: Context): Promise<Response>;
9
+ export declare function deleteContent(c: Context): Promise<Response>;
10
+ //# sourceMappingURL=content.handler.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"content.handler.d.ts","sourceRoot":"","sources":["../../../../src/api/cms/handlers/content.handler.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,MAAM,MAAM,CAAC;AAoC/B,wBAAsB,WAAW,CAAC,CAAC,EAAE,OAAO,GAAG,OAAO,CAAC,QAAQ,CAAC,CAqE/D;AAED;;;GAGG;AACH,wBAAsB,YAAY,CAAC,CAAC,EAAE,OAAO,GAAG,OAAO,CAAC,QAAQ,CAAC,CA2EhE;AAED,wBAAsB,cAAc,CAAC,CAAC,EAAE,OAAO,GAAG,OAAO,CAAC,QAAQ,CAAC,CAwHlE;AAED,wBAAsB,aAAa,CAAC,CAAC,EAAE,OAAO,GAAG,OAAO,CAAC,QAAQ,CAAC,CA6CjE"}