@hintergrund/worker 0.1.5 → 0.1.7

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 (186) 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/website-repo.handler.d.ts +8 -0
  11. package/dist/api/cms/handlers/website-repo.handler.d.ts.map +1 -0
  12. package/dist/api/cms/handlers/website-repo.handler.js +148 -0
  13. package/dist/api/cms/routes/index.d.ts.map +1 -1
  14. package/dist/api/cms/routes/index.js +16 -4
  15. package/dist/api/emails/handlers/campaigns.handler.d.ts +10 -23
  16. package/dist/api/emails/handlers/campaigns.handler.d.ts.map +1 -1
  17. package/dist/api/emails/handlers/campaigns.handler.js +164 -92
  18. package/dist/api/emails/handlers/invoice.handler.d.ts +5 -19
  19. package/dist/api/emails/handlers/invoice.handler.d.ts.map +1 -1
  20. package/dist/api/emails/handlers/invoice.handler.js +58 -340
  21. package/dist/api/emails/handlers/public.handler.d.ts +6 -29
  22. package/dist/api/emails/handlers/public.handler.d.ts.map +1 -1
  23. package/dist/api/emails/handlers/public.handler.js +150 -312
  24. package/dist/api/emails/handlers/send.handler.d.ts +5 -17
  25. package/dist/api/emails/handlers/send.handler.d.ts.map +1 -1
  26. package/dist/api/emails/handlers/send.handler.js +107 -92
  27. package/dist/api/emails/handlers/settings.handler.d.ts +28 -33
  28. package/dist/api/emails/handlers/settings.handler.d.ts.map +1 -1
  29. package/dist/api/emails/handlers/settings.handler.js +96 -287
  30. package/dist/api/emails/handlers/subscribers.handler.d.ts +13 -0
  31. package/dist/api/emails/handlers/subscribers.handler.d.ts.map +1 -0
  32. package/dist/api/emails/handlers/subscribers.handler.js +125 -0
  33. package/dist/api/emails/handlers/webhook.handler.d.ts +1 -2
  34. package/dist/api/emails/handlers/webhook.handler.d.ts.map +1 -1
  35. package/dist/api/emails/handlers/webhook.handler.js +66 -166
  36. package/dist/api/emails/routes/admin.routes.d.ts +1 -3
  37. package/dist/api/emails/routes/admin.routes.d.ts.map +1 -1
  38. package/dist/api/emails/routes/admin.routes.js +19 -49
  39. package/dist/api/emails/routes/public.routes.d.ts +1 -3
  40. package/dist/api/emails/routes/public.routes.d.ts.map +1 -1
  41. package/dist/api/emails/routes/public.routes.js +2 -9
  42. package/dist/api/shop/handlers/prices.handler.d.ts +2 -15
  43. package/dist/api/shop/handlers/prices.handler.d.ts.map +1 -1
  44. package/dist/api/shop/handlers/prices.handler.js +2 -83
  45. package/dist/api/shop/handlers/products.handler.d.ts +29 -20
  46. package/dist/api/shop/handlers/products.handler.d.ts.map +1 -1
  47. package/dist/api/shop/handlers/products.handler.js +195 -162
  48. package/dist/api/shop/handlers/public.handler.d.ts +24 -8
  49. package/dist/api/shop/handlers/public.handler.d.ts.map +1 -1
  50. package/dist/api/shop/handlers/public.handler.js +525 -78
  51. package/dist/api/shop/routes.d.ts.map +1 -1
  52. package/dist/api/shop/routes.js +14 -9
  53. package/dist/hintergrund-assets.d.ts +3 -2
  54. package/dist/hintergrund-assets.d.ts.map +1 -1
  55. package/dist/hintergrund-assets.js +4 -2
  56. package/dist/index.d.ts +14 -7
  57. package/dist/index.d.ts.map +1 -1
  58. package/dist/index.js +44 -4
  59. package/dist/lib/auth/crypto.d.ts +2 -15
  60. package/dist/lib/auth/crypto.d.ts.map +1 -1
  61. package/dist/lib/auth/crypto.js +8 -95
  62. package/dist/lib/auth/jwt.d.ts +0 -4
  63. package/dist/lib/auth/jwt.d.ts.map +1 -1
  64. package/dist/lib/auth/jwt.js +0 -6
  65. package/dist/lib/config.d.ts +1 -1
  66. package/dist/lib/config.d.ts.map +1 -1
  67. package/dist/lib/config.js +42 -86
  68. package/dist/lib/email-template.d.ts +15 -0
  69. package/dist/lib/email-template.d.ts.map +1 -0
  70. package/dist/lib/email-template.js +58 -0
  71. package/dist/lib/email.d.ts +18 -8
  72. package/dist/lib/email.d.ts.map +1 -1
  73. package/dist/lib/email.js +59 -70
  74. package/dist/lib/github-config.d.ts +19 -0
  75. package/dist/lib/github-config.d.ts.map +1 -0
  76. package/dist/lib/github-config.js +23 -0
  77. package/dist/lib/github.d.ts +10 -0
  78. package/dist/lib/github.d.ts.map +1 -1
  79. package/dist/lib/github.js +20 -2
  80. package/dist/lib/project-db.d.ts +24 -0
  81. package/dist/lib/project-db.d.ts.map +1 -0
  82. package/dist/lib/project-db.js +172 -0
  83. package/dist/lib/template.js +4 -4
  84. package/dist/middleware/auth.d.ts +0 -2
  85. package/dist/middleware/auth.d.ts.map +1 -1
  86. package/dist/middleware/auth.js +21 -50
  87. package/package.json +2 -1
  88. package/dist/api/builder/handlers/generate.handler.d.ts +0 -12
  89. package/dist/api/builder/handlers/generate.handler.d.ts.map +0 -1
  90. package/dist/api/builder/handlers/generate.handler.js +0 -203
  91. package/dist/api/builder/handlers/template.handler.d.ts +0 -12
  92. package/dist/api/builder/handlers/template.handler.d.ts.map +0 -1
  93. package/dist/api/builder/handlers/template.handler.js +0 -208
  94. package/dist/api/builder/routes.d.ts +0 -7
  95. package/dist/api/builder/routes.d.ts.map +0 -1
  96. package/dist/api/builder/routes.js +0 -15
  97. package/dist/api/cms/handlers/assets.handler.d.ts +0 -31
  98. package/dist/api/cms/handlers/assets.handler.d.ts.map +0 -1
  99. package/dist/api/cms/handlers/assets.handler.js +0 -200
  100. package/dist/api/cms/handlers/config.handler.d.ts +0 -7
  101. package/dist/api/cms/handlers/config.handler.d.ts.map +0 -1
  102. package/dist/api/cms/handlers/config.handler.js +0 -37
  103. package/dist/api/cms/handlers/content.handler.d.ts +0 -21
  104. package/dist/api/cms/handlers/content.handler.d.ts.map +0 -1
  105. package/dist/api/cms/handlers/content.handler.js +0 -117
  106. package/dist/api/cms/routes/assets.routes.d.ts +0 -4
  107. package/dist/api/cms/routes/assets.routes.d.ts.map +0 -1
  108. package/dist/api/cms/routes/assets.routes.js +0 -13
  109. package/dist/api/cms/routes/content.routes.d.ts +0 -4
  110. package/dist/api/cms/routes/content.routes.d.ts.map +0 -1
  111. package/dist/api/cms/routes/content.routes.js +0 -11
  112. package/dist/api/emails/handlers/branding.handler.d.ts +0 -17
  113. package/dist/api/emails/handlers/branding.handler.d.ts.map +0 -1
  114. package/dist/api/emails/handlers/branding.handler.js +0 -120
  115. package/dist/api/emails/handlers/contacts.handler.d.ts +0 -37
  116. package/dist/api/emails/handlers/contacts.handler.d.ts.map +0 -1
  117. package/dist/api/emails/handlers/contacts.handler.js +0 -161
  118. package/dist/api/emails/handlers/templates.handler.d.ts +0 -32
  119. package/dist/api/emails/handlers/templates.handler.d.ts.map +0 -1
  120. package/dist/api/emails/handlers/templates.handler.js +0 -132
  121. package/dist/api/newsletter/handlers/email.handler.d.ts +0 -7
  122. package/dist/api/newsletter/handlers/email.handler.d.ts.map +0 -1
  123. package/dist/api/newsletter/handlers/email.handler.js +0 -102
  124. package/dist/api/newsletter/handlers/emails.handler.d.ts +0 -31
  125. package/dist/api/newsletter/handlers/emails.handler.d.ts.map +0 -1
  126. package/dist/api/newsletter/handlers/emails.handler.js +0 -262
  127. package/dist/api/newsletter/handlers/invoice.handler.d.ts +0 -22
  128. package/dist/api/newsletter/handlers/invoice.handler.d.ts.map +0 -1
  129. package/dist/api/newsletter/handlers/invoice.handler.js +0 -455
  130. package/dist/api/newsletter/handlers/public.handler.d.ts +0 -22
  131. package/dist/api/newsletter/handlers/public.handler.d.ts.map +0 -1
  132. package/dist/api/newsletter/handlers/public.handler.js +0 -300
  133. package/dist/api/newsletter/handlers/send.handler.d.ts +0 -12
  134. package/dist/api/newsletter/handlers/send.handler.d.ts.map +0 -1
  135. package/dist/api/newsletter/handlers/send.handler.js +0 -153
  136. package/dist/api/newsletter/handlers/subscribers.handler.d.ts +0 -22
  137. package/dist/api/newsletter/handlers/subscribers.handler.d.ts.map +0 -1
  138. package/dist/api/newsletter/handlers/subscribers.handler.js +0 -195
  139. package/dist/api/newsletter/routes/admin.routes.d.ts +0 -4
  140. package/dist/api/newsletter/routes/admin.routes.d.ts.map +0 -1
  141. package/dist/api/newsletter/routes/admin.routes.js +0 -28
  142. package/dist/api/newsletter/routes/index.d.ts +0 -4
  143. package/dist/api/newsletter/routes/index.d.ts.map +0 -1
  144. package/dist/api/newsletter/routes/index.js +0 -9
  145. package/dist/api/newsletter/routes/public.routes.d.ts +0 -4
  146. package/dist/api/newsletter/routes/public.routes.d.ts.map +0 -1
  147. package/dist/api/newsletter/routes/public.routes.js +0 -9
  148. package/dist/api/shop/handlers/assets.handler.d.ts +0 -3
  149. package/dist/api/shop/handlers/assets.handler.d.ts.map +0 -1
  150. package/dist/api/shop/handlers/assets.handler.js +0 -62
  151. package/dist/api/shop/handlers/checkout.handler.d.ts +0 -10
  152. package/dist/api/shop/handlers/checkout.handler.d.ts.map +0 -1
  153. package/dist/api/shop/handlers/checkout.handler.js +0 -50
  154. package/dist/api/shop/handlers/customers.handler.d.ts +0 -17
  155. package/dist/api/shop/handlers/customers.handler.d.ts.map +0 -1
  156. package/dist/api/shop/handlers/customers.handler.js +0 -89
  157. package/dist/api/shop/handlers/orders.handler.d.ts +0 -17
  158. package/dist/api/shop/handlers/orders.handler.d.ts.map +0 -1
  159. package/dist/api/shop/handlers/orders.handler.js +0 -84
  160. package/dist/api/shop/handlers/stats.handler.d.ts +0 -10
  161. package/dist/api/shop/handlers/stats.handler.d.ts.map +0 -1
  162. package/dist/api/shop/handlers/stats.handler.js +0 -71
  163. package/dist/api/shop/handlers/webhook.handler.d.ts +0 -10
  164. package/dist/api/shop/handlers/webhook.handler.d.ts.map +0 -1
  165. package/dist/api/shop/handlers/webhook.handler.js +0 -233
  166. package/dist/cms-assets.d.ts +0 -4
  167. package/dist/cms-assets.d.ts.map +0 -1
  168. package/dist/cms-assets.js +0 -5
  169. package/dist/cms-bundle.d.ts +0 -3
  170. package/dist/cms-bundle.d.ts.map +0 -1
  171. package/dist/cms-bundle.js +0 -4
  172. package/dist/config-loader.d.ts +0 -26
  173. package/dist/config-loader.d.ts.map +0 -1
  174. package/dist/config-loader.js +0 -98
  175. package/dist/jwt.d.ts +0 -26
  176. package/dist/jwt.d.ts.map +0 -1
  177. package/dist/jwt.js +0 -102
  178. package/dist/lib/plunk.d.ts +0 -204
  179. package/dist/lib/plunk.d.ts.map +0 -1
  180. package/dist/lib/plunk.js +0 -259
  181. package/dist/template.d.ts +0 -2
  182. package/dist/template.d.ts.map +0 -1
  183. package/dist/template.js +0 -61
  184. package/dist/utils.d.ts +0 -23
  185. package/dist/utils.d.ts.map +0 -1
  186. package/dist/utils.js +0 -110
@@ -0,0 +1,8 @@
1
+ import type { Context } from 'hono';
2
+ import type { HonoEnv } from '../../../index';
3
+ export declare function listAdminUsers(c: Context<HonoEnv>): Promise<Response>;
4
+ export declare function bootstrapAdminUser(c: Context<HonoEnv>): Promise<Response>;
5
+ export declare function createAdminUser(c: Context<HonoEnv>): Promise<Response>;
6
+ export declare function patchAdminUser(c: Context<HonoEnv>): Promise<Response>;
7
+ export declare function deleteAdminUser(c: Context<HonoEnv>): Promise<Response>;
8
+ //# sourceMappingURL=admin-users.handler.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"admin-users.handler.d.ts","sourceRoot":"","sources":["../../../../src/api/cms/handlers/admin-users.handler.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,MAAM,CAAC;AACpC,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,gBAAgB,CAAC;AAyC9C,wBAAsB,cAAc,CAAC,CAAC,EAAE,OAAO,CAAC,OAAO,CAAC,GAAG,OAAO,CAAC,QAAQ,CAAC,CAU3E;AAED,wBAAsB,kBAAkB,CAAC,CAAC,EAAE,OAAO,CAAC,OAAO,CAAC,GAAG,OAAO,CAAC,QAAQ,CAAC,CAU/E;AAED,wBAAsB,eAAe,CAAC,CAAC,EAAE,OAAO,CAAC,OAAO,CAAC,GAAG,OAAO,CAAC,QAAQ,CAAC,CAE5E;AA8BD,wBAAsB,cAAc,CAAC,CAAC,EAAE,OAAO,CAAC,OAAO,CAAC,GAAG,OAAO,CAAC,QAAQ,CAAC,CAgC3E;AAED,wBAAsB,eAAe,CAAC,CAAC,EAAE,OAAO,CAAC,OAAO,CAAC,GAAG,OAAO,CAAC,QAAQ,CAAC,CAiB5E"}
@@ -0,0 +1,121 @@
1
+ import { hashPw } from '../../../lib/auth/crypto';
2
+ import { createId, ensureProjectAdminSchema, nowSeconds } from '../../../lib/project-db';
3
+ const LOGIN_METHODS = ['password', 'magic-link'];
4
+ function userToResponse(user) {
5
+ return {
6
+ id: user.id,
7
+ email: user.email,
8
+ name: user.name,
9
+ loginMethod: user.login_method,
10
+ disabledAt: user.disabled_at,
11
+ createdAt: user.created_at,
12
+ updatedAt: user.updated_at,
13
+ hasPassword: !!user.password_hash,
14
+ };
15
+ }
16
+ async function hasAdminUsers(c) {
17
+ const db = await ensureProjectAdminSchema(c.env);
18
+ const row = await db.prepare('SELECT COUNT(*) AS count FROM admin_users').first();
19
+ return (row?.count ?? 0) > 0;
20
+ }
21
+ function verifyBootstrapToken(c, provided) {
22
+ const configured = c.env.HG_BOOTSTRAP_TOKEN?.trim();
23
+ if (!configured) {
24
+ return c.json({ error: 'Admin bootstrap is not configured' }, 403);
25
+ }
26
+ if (String(provided ?? '') !== configured) {
27
+ return c.json({ error: 'Invalid bootstrap token' }, 403);
28
+ }
29
+ return null;
30
+ }
31
+ export async function listAdminUsers(c) {
32
+ const db = await ensureProjectAdminSchema(c.env);
33
+ const { results } = await db
34
+ .prepare('SELECT * FROM admin_users ORDER BY created_at ASC, id ASC')
35
+ .all();
36
+ const users = (results ?? []).map((user, index) => ({
37
+ ...userToResponse(user),
38
+ isFirst: index === 0,
39
+ }));
40
+ return c.json({ users });
41
+ }
42
+ export async function bootstrapAdminUser(c) {
43
+ const body = await c.req.json();
44
+ const tokenError = verifyBootstrapToken(c, body.bootstrapToken ?? c.req.header('x-bootstrap-token'));
45
+ if (tokenError)
46
+ return tokenError;
47
+ if (await hasAdminUsers(c)) {
48
+ return c.json({ error: 'Admin users already exist' }, 409);
49
+ }
50
+ return createAdminUserFromBody(c, body, 201);
51
+ }
52
+ export async function createAdminUser(c) {
53
+ return createAdminUserFromBody(c, await c.req.json(), 201);
54
+ }
55
+ async function createAdminUserFromBody(c, body, status) {
56
+ const email = String(body.email ?? '').toLowerCase().trim();
57
+ const name = body.name ? String(body.name).trim() : null;
58
+ const loginMethod = LOGIN_METHODS.includes(body.loginMethod) ? body.loginMethod : 'magic-link';
59
+ if (!email) {
60
+ return c.json({ error: 'Email is required' }, 400);
61
+ }
62
+ if (loginMethod === 'password' && !body.passwordHash && !body.password) {
63
+ return c.json({ error: 'password is required for password users' }, 400);
64
+ }
65
+ const db = await ensureProjectAdminSchema(c.env);
66
+ const now = nowSeconds();
67
+ const id = createId('user');
68
+ const passwordHash = body.password ? await hashPw(String(body.password), c.env.HG_SECRET ?? '') : body.passwordHash ?? null;
69
+ await db
70
+ .prepare(`INSERT INTO admin_users (id, email, name, password_hash, login_method, disabled_at, created_at, updated_at)
71
+ VALUES (?, ?, ?, ?, ?, NULL, ?, ?)`)
72
+ .bind(id, email, name, passwordHash, loginMethod, now, now)
73
+ .run();
74
+ const user = await db.prepare('SELECT * FROM admin_users WHERE id = ?').bind(id).first();
75
+ return c.json({ user: userToResponse(user) }, status);
76
+ }
77
+ export async function patchAdminUser(c) {
78
+ const userId = c.req.param('id');
79
+ if (!userId)
80
+ return c.json({ error: 'Missing user id' }, 400);
81
+ const body = await c.req.json();
82
+ const db = await ensureProjectAdminSchema(c.env);
83
+ const existing = await db.prepare('SELECT * FROM admin_users WHERE id = ?').bind(userId).first();
84
+ if (!existing) {
85
+ return c.json({ error: 'User not found' }, 404);
86
+ }
87
+ const email = body.email === undefined ? existing.email : String(body.email).toLowerCase().trim();
88
+ const name = body.name === undefined ? existing.name : (body.name ? String(body.name).trim() : null);
89
+ const loginMethod = body.loginMethod === undefined || !LOGIN_METHODS.includes(body.loginMethod)
90
+ ? existing.login_method
91
+ : body.loginMethod;
92
+ const disabledAt = body.disabled === undefined ? existing.disabled_at : (body.disabled ? nowSeconds() : null);
93
+ const passwordHash = body.password
94
+ ? await hashPw(String(body.password), c.env.HG_SECRET ?? '')
95
+ : (body.passwordHash === undefined ? existing.password_hash : body.passwordHash);
96
+ const now = nowSeconds();
97
+ await db
98
+ .prepare(`UPDATE admin_users
99
+ SET email = ?, name = ?, password_hash = ?, login_method = ?, disabled_at = ?, updated_at = ?
100
+ WHERE id = ?`)
101
+ .bind(email, name, passwordHash, loginMethod, disabledAt, now, userId)
102
+ .run();
103
+ const user = await db.prepare('SELECT * FROM admin_users WHERE id = ?').bind(userId).first();
104
+ return c.json({ user: userToResponse(user) });
105
+ }
106
+ export async function deleteAdminUser(c) {
107
+ const currentUser = c.get('user');
108
+ const userId = c.req.param('id');
109
+ if (currentUser?.userId === userId) {
110
+ return c.json({ error: 'You cannot delete your own admin user' }, 400);
111
+ }
112
+ const db = await ensureProjectAdminSchema(c.env);
113
+ const firstUser = await db
114
+ .prepare('SELECT id FROM admin_users ORDER BY created_at ASC, id ASC LIMIT 1')
115
+ .first();
116
+ if (firstUser?.id === userId) {
117
+ return c.json({ error: 'The original admin user cannot be deleted' }, 400);
118
+ }
119
+ await db.prepare('DELETE FROM admin_users WHERE id = ?').bind(userId).run();
120
+ return c.json({ success: true });
121
+ }
@@ -0,0 +1,7 @@
1
+ import type { Context } from 'hono';
2
+ import type { HonoEnv } from '../../../index';
3
+ export declare function listConversations(c: Context<HonoEnv>): Promise<Response>;
4
+ export declare function upsertConversation(c: Context<HonoEnv>): Promise<Response>;
5
+ export declare function deleteConversation(c: Context<HonoEnv>): Promise<Response>;
6
+ export declare function getAgentApiKey(c: Context<HonoEnv>): Promise<Response>;
7
+ //# sourceMappingURL=agent-conversations.handler.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"agent-conversations.handler.d.ts","sourceRoot":"","sources":["../../../../src/api/cms/handlers/agent-conversations.handler.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,MAAM,CAAC;AACpC,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,gBAAgB,CAAC;AA4B9C,wBAAsB,iBAAiB,CAAC,CAAC,EAAE,OAAO,CAAC,OAAO,CAAC,GAAG,OAAO,CAAC,QAAQ,CAAC,CAY9E;AAED,wBAAsB,kBAAkB,CAAC,CAAC,EAAE,OAAO,CAAC,OAAO,CAAC,GAAG,OAAO,CAAC,QAAQ,CAAC,CA8C/E;AAED,wBAAsB,kBAAkB,CAAC,CAAC,EAAE,OAAO,CAAC,OAAO,CAAC,GAAG,OAAO,CAAC,QAAQ,CAAC,CAW/E;AAED,wBAAsB,cAAc,CAAC,CAAC,EAAE,OAAO,CAAC,OAAO,CAAC,GAAG,OAAO,CAAC,QAAQ,CAAC,CAO3E"}
@@ -0,0 +1,94 @@
1
+ import { createId, ensureProjectAdminSchema, nowSeconds } from '../../../lib/project-db';
2
+ function getUserId(c) {
3
+ return c.get('user')?.userId ?? null;
4
+ }
5
+ function parseMode(value) {
6
+ return value === 'builder' || value === 'cms' ? value : null;
7
+ }
8
+ function rowToConversation(row) {
9
+ return {
10
+ id: row.id,
11
+ userId: row.user_id,
12
+ mode: row.mode,
13
+ title: row.title,
14
+ messages: JSON.parse(row.messages_json || '[]'),
15
+ modelMetadata: JSON.parse(row.model_metadata_json || '{}'),
16
+ gitDiff: row.git_diff,
17
+ createdAt: row.created_at,
18
+ updatedAt: row.updated_at,
19
+ };
20
+ }
21
+ export async function listConversations(c) {
22
+ const userId = getUserId(c);
23
+ if (!userId)
24
+ return c.json({ error: 'Project admin user required' }, 401);
25
+ const mode = parseMode(c.req.query('mode'));
26
+ if (!mode)
27
+ return c.json({ error: 'mode must be builder or cms' }, 400);
28
+ const db = await ensureProjectAdminSchema(c.env);
29
+ const { results } = await db
30
+ .prepare('SELECT * FROM agent_conversations WHERE user_id = ? AND mode = ? ORDER BY updated_at DESC')
31
+ .bind(userId, mode)
32
+ .all();
33
+ return c.json({ conversations: (results ?? []).map(rowToConversation) });
34
+ }
35
+ export async function upsertConversation(c) {
36
+ const userId = getUserId(c);
37
+ if (!userId)
38
+ return c.json({ error: 'Project admin user required' }, 401);
39
+ const body = await c.req.json();
40
+ const mode = parseMode(body.mode);
41
+ if (!mode)
42
+ return c.json({ error: 'mode must be builder or cms' }, 400);
43
+ const id = body.id ? String(body.id) : createId('conv');
44
+ const now = nowSeconds();
45
+ const title = String(body.title ?? 'Untitled conversation').slice(0, 160);
46
+ const messagesJson = JSON.stringify(body.messages ?? []);
47
+ const modelMetadataJson = JSON.stringify(body.modelMetadata ?? {});
48
+ const gitDiff = body.gitDiff ? String(body.gitDiff) : null;
49
+ const db = await ensureProjectAdminSchema(c.env);
50
+ const existing = await db
51
+ .prepare('SELECT id FROM agent_conversations WHERE id = ? AND user_id = ?')
52
+ .bind(id, userId)
53
+ .first();
54
+ if (existing) {
55
+ await db
56
+ .prepare(`UPDATE agent_conversations
57
+ SET mode = ?, title = ?, messages_json = ?, model_metadata_json = ?, git_diff = ?, updated_at = ?
58
+ WHERE id = ? AND user_id = ?`)
59
+ .bind(mode, title, messagesJson, modelMetadataJson, gitDiff, now, id, userId)
60
+ .run();
61
+ }
62
+ else {
63
+ await db
64
+ .prepare(`INSERT INTO agent_conversations
65
+ (id, user_id, mode, title, messages_json, model_metadata_json, git_diff, created_at, updated_at)
66
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`)
67
+ .bind(id, userId, mode, title, messagesJson, modelMetadataJson, gitDiff, now, now)
68
+ .run();
69
+ }
70
+ const row = await db
71
+ .prepare('SELECT * FROM agent_conversations WHERE id = ? AND user_id = ?')
72
+ .bind(id, userId)
73
+ .first();
74
+ return c.json({ conversation: rowToConversation(row) });
75
+ }
76
+ export async function deleteConversation(c) {
77
+ const userId = getUserId(c);
78
+ if (!userId)
79
+ return c.json({ error: 'Project admin user required' }, 401);
80
+ const id = c.req.param('id');
81
+ const db = await ensureProjectAdminSchema(c.env);
82
+ await db
83
+ .prepare('DELETE FROM agent_conversations WHERE id = ? AND user_id = ?')
84
+ .bind(id, userId)
85
+ .run();
86
+ return c.json({ success: true });
87
+ }
88
+ export async function getAgentApiKey(c) {
89
+ const apiKey = c.env.GEMINI_API_KEY?.trim();
90
+ if (!apiKey) {
91
+ return c.json({ error: 'Builder agent is not configured' }, 500);
92
+ }
93
+ return c.json({ apiKey });
94
+ }
@@ -1,8 +1,5 @@
1
1
  import { Context } from 'hono';
2
2
  import { HonoEnv } from '../../../index';
3
- /**
4
- * Handle login request - supports both password and magic link authentication
5
- */
6
3
  export declare function login(c: Context<HonoEnv>): Promise<Response>;
7
4
  /**
8
5
  * Verify magic link token and log user in
@@ -1 +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;AAC/B,OAAO,EAAE,OAAO,EAAE,MAAM,gBAAgB,CAAC;AAOzC;;GAEG;AACH,wBAAsB,KAAK,CAAC,CAAC,EAAE,OAAO,CAAC,OAAO,CAAC,GAAG,OAAO,CAAC,QAAQ,CAAC,CAqBlE;AAyMD;;GAEG;AACH,wBAAsB,eAAe,CAAC,CAAC,EAAE,OAAO,CAAC,OAAO,CAAC,GAAG,OAAO,CAAC,QAAQ,CAAC,CAuC5E;AAYD,wBAAsB,MAAM,CAAC,CAAC,EAAE,OAAO,CAAC,OAAO,CAAC,GAAG,OAAO,CAAC,QAAQ,CAAC,CAWnE"}
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;AAC/B,OAAO,EAAE,OAAO,EAAE,MAAM,gBAAgB,CAAC;AAgBzC,wBAAsB,KAAK,CAAC,CAAC,EAAE,OAAO,CAAC,OAAO,CAAC,GAAG,OAAO,CAAC,QAAQ,CAAC,CAsClE;AAgFD;;GAEG;AACH,wBAAsB,eAAe,CAAC,CAAC,EAAE,OAAO,CAAC,OAAO,CAAC,GAAG,OAAO,CAAC,QAAQ,CAAC,CAqD5E;AAYD,wBAAsB,MAAM,CAAC,CAAC,EAAE,OAAO,CAAC,OAAO,CAAC,GAAG,OAAO,CAAC,QAAQ,CAAC,CAWnE"}
@@ -1,167 +1,77 @@
1
- import { readRequestBody, verifyPw } from '../../../lib/auth/crypto';
2
- import { sign, signWithPayload } from '../../../lib/auth/jwt';
1
+ import { readRequestBody, verifyPw, generateRandomToken } from '../../../lib/auth/crypto';
2
+ import { signWithPayload } from '../../../lib/auth/jwt';
3
3
  import { loadConfig } from '../../../lib/config';
4
4
  import { sendMagicLinkEmail } from '../../../lib/email';
5
- /**
6
- * Handle login request - supports both password and magic link authentication
7
- */
5
+ import { createId, ensureProjectAdminSchema, getAdminUserByEmail, issueSessionForUser, nowSeconds, sha256Base64Url } from '../../../lib/project-db';
8
6
  export async function login(c) {
9
7
  try {
10
8
  const appConfig = loadConfig(c.env);
11
9
  const body = await readRequestBody(c.req.raw);
12
10
  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);
11
+ const email = body.email?.toLowerCase().trim();
12
+ if (!email) {
13
+ return new Response(JSON.stringify({ success: false, message: 'Email is required' }), { status: 400 });
14
+ }
15
+ const user = await getAdminUserByEmail(c.env, email);
16
+ if (!user) {
17
+ return new Response(JSON.stringify({ success: false, message: 'Invalid credentials' }), { status: 401 });
18
+ }
19
+ if (body.password) {
20
+ return await handleProjectPasswordLogin(c, body.password, appConfig.global.hgSecret, user, isSecure);
21
+ }
22
+ if (user.login_method === 'password') {
23
+ return new Response(JSON.stringify({ success: true, requirePassword: true }), { status: 200 });
19
24
  }
20
- // Password login flow (legacy or with user groups)
21
- return handlePasswordLogin(c, body, appConfig, isSecure);
25
+ return await handleProjectMagicLinkLogin(c, user, appConfig);
22
26
  }
23
27
  catch (error) {
24
28
  console.error('Login error:', error);
25
29
  return new Response(JSON.stringify({ success: false, message: String(error) }), { status: 401 });
26
30
  }
27
31
  }
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
- }
32
+ async function handleProjectPasswordLogin(c, password, hgSecret, user, isSecure) {
33
+ if (user.login_method !== 'password' || !user.password_hash) {
34
+ return new Response(JSON.stringify({ success: false, message: 'Password login is not enabled for this user' }), { status: 400 });
70
35
  }
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 });
36
+ if (!(await verifyPw(user.password_hash, password, hgSecret))) {
37
+ return new Response(JSON.stringify({ success: false, message: 'Invalid credentials' }), { status: 401 });
87
38
  }
39
+ const token = await signWithPayload(hgSecret, issueSessionForUser(user));
40
+ const secureCookie = isSecure ? '; Secure' : '';
41
+ return new Response(JSON.stringify({ success: true }), {
42
+ status: 200,
43
+ headers: {
44
+ 'Set-Cookie': `token=${token}; HttpOnly; Path=/; SameSite=Strict${secureCookie}`
45
+ }
46
+ });
88
47
  }
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 });
48
+ async function handleProjectMagicLinkLogin(c, user, appConfig) {
49
+ if (user.login_method !== 'magic-link') {
50
+ return new Response(JSON.stringify({ success: false, message: 'Magic link login is not enabled for this user' }), { status: 400 });
97
51
  }
98
- const authConfig = appConfig.global.auth;
99
52
  const emailsConfig = appConfig.emails;
100
- if (!emailsConfig?.plunkSecretKey || !emailsConfig?.enabled) {
53
+ if (!emailsConfig?.emailApiKey) {
101
54
  return new Response(JSON.stringify({ success: false, message: 'Emails module is not configured' }), { status: 500 });
102
55
  }
103
- const userGroups = authConfig?.userGroups;
104
- const allowedEmails = authConfig?.allowedEmails;
105
- // Find which group(s) this email belongs to
106
- let matchedGroup;
107
- let isAllowed = false;
108
- if (userGroups && userGroups.length > 0) {
109
- if (userGroupName) {
110
- // User specified a group - verify email is in that group
111
- const group = userGroups.find(g => g.name === userGroupName);
112
- if (!group) {
113
- return new Response(JSON.stringify({ success: false, message: 'Invalid user group' }), { status: 401 });
114
- }
115
- if (group.emails?.includes(email)) {
116
- matchedGroup = group;
117
- isAllowed = true;
118
- }
119
- }
120
- else {
121
- // Find any group that contains this email
122
- matchedGroup = userGroups.find(g => g.emails?.includes(email));
123
- if (matchedGroup) {
124
- isAllowed = true;
125
- }
126
- }
127
- }
128
- else {
129
- // No user groups - check whitelist
130
- if (allowedEmails && allowedEmails.includes(email)) {
131
- isAllowed = true;
132
- }
133
- }
134
- if (!isAllowed) {
135
- // Don't reveal which emails are valid - just say email sent
136
- // This applies to both missing from whitelist and missing from user groups
137
- const response = { success: true, emailSent: true, message: 'If your email is registered, you will receive a login link.' };
138
- return new Response(JSON.stringify(response), { status: 200 });
139
- }
140
- // Generate magic link token (valid for 15 minutes)
141
- const magicToken = await signWithPayload(appConfig.global.hgSecret, {
142
- email,
143
- userGroup: matchedGroup?.name,
144
- modules: matchedGroup?.modules,
145
- type: 'magic-link',
146
- }, 15 * 60); // 15 minutes
147
- // Build the magic link URL
56
+ const token = generateRandomToken();
57
+ const tokenHash = await sha256Base64Url(`${token}.${appConfig.global.hgSecret}`);
58
+ const db = await ensureProjectAdminSchema(c.env);
59
+ const now = nowSeconds();
60
+ await db
61
+ .prepare(`INSERT INTO admin_magic_links (id, user_id, token_hash, expires_at, used_at, created_at)
62
+ VALUES (?, ?, ?, ?, NULL, ?)`)
63
+ .bind(createId('magic'), user.id, tokenHash, now + 15 * 60, now)
64
+ .run();
148
65
  const baseUrl = c.req.url.replace(/\/api\/admin\/login.*$/, '');
149
- const magicLinkUrl = `${baseUrl}/api/admin/verify-magic-link?token=${encodeURIComponent(magicToken)}`;
150
- // Send the email
151
- try {
152
- await sendMagicLinkEmail({
153
- to: email,
154
- plunkSecretKey: emailsConfig.plunkSecretKey,
155
- magicLinkUrl,
156
- userGroup: matchedGroup?.name,
157
- });
158
- const response = { success: true, emailSent: true, message: 'Check your email for the login link.' };
159
- return new Response(JSON.stringify(response), { status: 200 });
160
- }
161
- catch (error) {
162
- console.error('Failed to send magic link email:', error);
163
- return new Response(JSON.stringify({ success: false, message: 'Failed to send email. Please try again.' }), { status: 500 });
164
- }
66
+ const magicLinkUrl = `${baseUrl}/api/admin/verify-magic-link?token=${encodeURIComponent(token)}`;
67
+ await sendMagicLinkEmail({
68
+ to: user.email,
69
+ apiKey: emailsConfig.emailApiKey,
70
+ fromEmail: emailsConfig.fromEmail ?? '',
71
+ fromName: emailsConfig.fromName,
72
+ magicLinkUrl,
73
+ });
74
+ return new Response(JSON.stringify({ success: true, emailSent: true, message: 'Check your email for the login link.' }), { status: 200 });
165
75
  }
166
76
  /**
167
77
  * Verify magic link token and log user in
@@ -175,19 +85,30 @@ export async function verifyMagicLink(c) {
175
85
  if (!token) {
176
86
  return new Response('Missing token', { status: 400 });
177
87
  }
178
- // Verify the magic link token
179
- const { verify } = await import('../../../lib/auth/jwt');
180
- const payload = await verify(token, appConfig.global.hgSecret);
181
- if (!payload || payload.type !== 'magic-link') {
88
+ const db = await ensureProjectAdminSchema(c.env);
89
+ const tokenHash = await sha256Base64Url(`${token}.${appConfig.global.hgSecret}`);
90
+ const now = nowSeconds();
91
+ const link = await db
92
+ .prepare(`SELECT * FROM admin_magic_links
93
+ WHERE token_hash = ? AND used_at IS NULL AND expires_at > ?
94
+ LIMIT 1`)
95
+ .bind(tokenHash, now)
96
+ .first();
97
+ if (!link) {
182
98
  return redirectToLoginWithError(c, 'Invalid or expired link');
183
99
  }
184
- // Create a new session token (valid for 24 hours)
185
- const sessionToken = await signWithPayload(appConfig.global.hgSecret, {
186
- email: payload.email,
187
- userGroup: payload.userGroup,
188
- modules: payload.modules,
189
- });
190
- // Redirect to admin with cookie set
100
+ const user = await db
101
+ .prepare('SELECT * FROM admin_users WHERE id = ? AND disabled_at IS NULL LIMIT 1')
102
+ .bind(link.user_id)
103
+ .first();
104
+ if (!user) {
105
+ return redirectToLoginWithError(c, 'Invalid or expired link');
106
+ }
107
+ await db
108
+ .prepare('UPDATE admin_magic_links SET used_at = ? WHERE id = ? AND used_at IS NULL')
109
+ .bind(now, link.id)
110
+ .run();
111
+ const sessionToken = await signWithPayload(appConfig.global.hgSecret, issueSessionForUser(user));
191
112
  const baseUrl = c.req.url.replace(/\/api\/admin\/verify-magic-link.*$/, '');
192
113
  return new Response(null, {
193
114
  status: 302,
@@ -0,0 +1,8 @@
1
+ import type { Context } from 'hono';
2
+ import type { HonoEnv } from '../../../index';
3
+ export declare function isAllowedWebsitePath(path: string): boolean;
4
+ export declare function headWebsiteRepo(c: Context<HonoEnv>): Promise<Response>;
5
+ export declare function syncWebsiteRepo(c: Context<HonoEnv>): Promise<Response>;
6
+ export declare function commitWebsiteRepo(c: Context<HonoEnv>): Promise<Response>;
7
+ export declare function uploadWebsiteAsset(c: Context<HonoEnv>): Promise<Response>;
8
+ //# sourceMappingURL=website-repo.handler.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"website-repo.handler.d.ts","sourceRoot":"","sources":["../../../../src/api/cms/handlers/website-repo.handler.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,MAAM,CAAC;AACpC,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,gBAAgB,CAAC;AAyB9C,wBAAgB,oBAAoB,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO,CAI1D;AA4CD,wBAAsB,eAAe,CAAC,CAAC,EAAE,OAAO,CAAC,OAAO,CAAC,GAAG,OAAO,CAAC,QAAQ,CAAC,CAI5E;AAED,wBAAsB,eAAe,CAAC,CAAC,EAAE,OAAO,CAAC,OAAO,CAAC,GAAG,OAAO,CAAC,QAAQ,CAAC,CAc5E;AAED,wBAAsB,iBAAiB,CAAC,CAAC,EAAE,OAAO,CAAC,OAAO,CAAC,GAAG,OAAO,CAAC,QAAQ,CAAC,CAgC9E;AASD,wBAAsB,kBAAkB,CAAC,CAAC,EAAE,OAAO,CAAC,OAAO,CAAC,GAAG,OAAO,CAAC,QAAQ,CAAC,CA6C/E"}