@rebasepro/server-core 0.0.1-canary.ca2cb6e → 0.0.1-canary.cbdd980

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 (55) hide show
  1. package/dist/index.es.js +1179 -2626
  2. package/dist/index.es.js.map +1 -1
  3. package/dist/index.umd.js +1178 -2625
  4. package/dist/index.umd.js.map +1 -1
  5. package/dist/server-core/src/api/rest/api-generator.d.ts +15 -3
  6. package/dist/server-core/src/auth/admin-routes.d.ts +5 -0
  7. package/dist/server-core/src/auth/google-oauth.d.ts +36 -3
  8. package/dist/server-core/src/auth/index.d.ts +1 -0
  9. package/dist/server-core/src/cron/cron-scheduler.d.ts +45 -0
  10. package/dist/server-core/src/cron/index.d.ts +1 -1
  11. package/dist/server-core/src/init.d.ts +11 -1
  12. package/dist/types/src/controllers/auth.d.ts +8 -2
  13. package/dist/types/src/controllers/client.d.ts +13 -0
  14. package/dist/types/src/controllers/collection_registry.d.ts +2 -1
  15. package/dist/types/src/controllers/data_driver.d.ts +36 -1
  16. package/dist/types/src/controllers/navigation.d.ts +18 -6
  17. package/dist/types/src/controllers/registry.d.ts +9 -1
  18. package/dist/types/src/controllers/side_entity_controller.d.ts +7 -0
  19. package/dist/types/src/rebase_context.d.ts +17 -0
  20. package/dist/types/src/types/backend_hooks.d.ts +187 -0
  21. package/dist/types/src/types/collections.d.ts +31 -11
  22. package/dist/types/src/types/component_ref.d.ts +47 -0
  23. package/dist/types/src/types/cron.d.ts +1 -1
  24. package/dist/types/src/types/entity_views.d.ts +6 -7
  25. package/dist/types/src/types/formex.d.ts +40 -0
  26. package/dist/types/src/types/index.d.ts +3 -0
  27. package/dist/types/src/types/plugins.d.ts +6 -3
  28. package/dist/types/src/types/properties.d.ts +72 -88
  29. package/dist/types/src/types/slots.d.ts +20 -10
  30. package/dist/types/src/types/translations.d.ts +6 -0
  31. package/package.json +9 -9
  32. package/src/api/errors.ts +3 -2
  33. package/src/api/rest/api-generator-count.test.ts +113 -0
  34. package/src/api/rest/api-generator.ts +123 -22
  35. package/src/api/server.ts +8 -4
  36. package/src/auth/admin-routes.ts +133 -57
  37. package/src/auth/apple-oauth.ts +8 -18
  38. package/src/auth/google-oauth.ts +192 -22
  39. package/src/auth/index.ts +1 -0
  40. package/src/auth/rate-limiter.ts +9 -5
  41. package/src/auth/routes.ts +25 -5
  42. package/src/collections/loader.ts +3 -3
  43. package/src/cron/cron-scheduler.test.ts +301 -175
  44. package/src/cron/cron-scheduler.ts +220 -57
  45. package/src/cron/index.ts +1 -1
  46. package/src/init.ts +27 -5
  47. package/src/storage/LocalStorageController.ts +37 -13
  48. package/src/storage/S3StorageController.ts +4 -1
  49. package/src/storage/routes.ts +51 -5
  50. package/test/backend-hooks-admin.test.ts +394 -0
  51. package/test/backend-hooks-data.test.ts +408 -0
  52. package/history_diff.log +0 -385
  53. package/scratch.ts +0 -9
  54. package/test-ast.ts +0 -28
  55. package/test_output.txt +0 -1133
@@ -0,0 +1,394 @@
1
+ /**
2
+ * BackendHooks — Admin Routes Integration Tests
3
+ *
4
+ * Verifies that BackendHooks (users + roles) are correctly applied
5
+ * within the admin route handlers.
6
+ */
7
+
8
+ import { Hono } from "hono";
9
+ import type { HonoEnv } from "../src/api/types";
10
+ import { errorHandler } from "../src/api/errors";
11
+ import { createAdminRoutes } from "../src/auth/admin-routes";
12
+ import { configureJwt, generateAccessToken } from "../src/auth/jwt";
13
+ import type { AuthModuleConfig } from "../src/auth/routes";
14
+ import type { BackendHooks } from "@rebasepro/types";
15
+
16
+ // ── Mocks ───────────────────────────────────────────────────────────────────
17
+
18
+ jest.mock("../src/auth/password");
19
+
20
+ import { hashPassword, validatePasswordStrength } from "../src/auth/password";
21
+
22
+ // ── Helpers ─────────────────────────────────────────────────────────────────
23
+
24
+ const TEST_SECRET = "backend-hooks-test-secret-that-is-32-chars-long!!!!!";
25
+
26
+ function mockUser(overrides: Partial<{
27
+ id: string;
28
+ email: string;
29
+ displayName: string | null;
30
+ photoUrl: string | null;
31
+ }> = {}) {
32
+ return {
33
+ id: overrides.id ?? "user-1",
34
+ email: overrides.email ?? "test@example.com",
35
+ passwordHash: "salt:hash",
36
+ displayName: overrides.displayName ?? "Test User",
37
+ photoUrl: overrides.photoUrl ?? null,
38
+ emailVerified: false,
39
+ emailVerificationToken: null,
40
+ emailVerificationSentAt: null,
41
+ createdAt: new Date("2024-01-01"),
42
+ updatedAt: new Date("2024-01-01")
43
+ };
44
+ }
45
+
46
+ function mockRole(id: string, isAdmin = false) {
47
+ return {
48
+ id,
49
+ name: id.charAt(0).toUpperCase() + id.slice(1),
50
+ isAdmin,
51
+ defaultPermissions: null,
52
+ collectionPermissions: null,
53
+ config: null
54
+ };
55
+ }
56
+
57
+ let mockAuthRepo: jest.Mocked<any>;
58
+
59
+ function createApp(hooks?: BackendHooks) {
60
+ mockAuthRepo = {
61
+ getUserByEmail: jest.fn().mockResolvedValue(null),
62
+ getUserByIdentity: jest.fn().mockResolvedValue(null),
63
+ linkUserIdentity: jest.fn().mockResolvedValue(undefined),
64
+ getUserIdentities: jest.fn().mockResolvedValue([]),
65
+ getUserById: jest.fn().mockResolvedValue(null),
66
+ createUser: jest.fn().mockImplementation((data) =>
67
+ Promise.resolve(mockUser({ email: data.email, displayName: data.displayName }))
68
+ ),
69
+ listUsers: jest.fn().mockResolvedValue([]),
70
+ listUsersPaginated: jest.fn().mockResolvedValue({ users: [], total: 0, limit: 25, offset: 0 }),
71
+ getUserRoles: jest.fn().mockResolvedValue([mockRole("editor")]),
72
+ getUserRoleIds: jest.fn().mockResolvedValue(["editor"]),
73
+ assignDefaultRole: jest.fn().mockResolvedValue(undefined),
74
+ setUserRoles: jest.fn().mockResolvedValue(undefined),
75
+ updateUser: jest.fn().mockImplementation((id, data) =>
76
+ Promise.resolve(mockUser({ id, ...data }))
77
+ ),
78
+ deleteUser: jest.fn().mockResolvedValue(undefined),
79
+ updatePassword: jest.fn().mockResolvedValue(undefined),
80
+ setEmailVerified: jest.fn().mockResolvedValue(undefined),
81
+ setVerificationToken: jest.fn().mockResolvedValue(undefined),
82
+ getUserByVerificationToken: jest.fn().mockResolvedValue(null),
83
+ getUserWithRoles: jest.fn().mockImplementation(async (userId) => {
84
+ const user = mockUser({ id: userId });
85
+ return { user, roles: [mockRole("editor")] };
86
+ }),
87
+ createRefreshToken: jest.fn().mockResolvedValue(undefined),
88
+ findRefreshTokenByHash: jest.fn().mockResolvedValue(null),
89
+ deleteRefreshToken: jest.fn().mockResolvedValue(undefined),
90
+ deleteAllRefreshTokensForUser: jest.fn().mockResolvedValue(undefined),
91
+ listRefreshTokensForUser: jest.fn().mockResolvedValue([]),
92
+ deleteRefreshTokenById: jest.fn().mockResolvedValue(undefined),
93
+ createPasswordResetToken: jest.fn().mockResolvedValue(undefined),
94
+ findValidPasswordResetToken: jest.fn().mockResolvedValue(null),
95
+ markPasswordResetTokenUsed: jest.fn().mockResolvedValue(undefined),
96
+ deleteExpiredPasswordResetTokens: jest.fn().mockResolvedValue(undefined),
97
+ listRoles: jest.fn().mockResolvedValue([]),
98
+ getRoleById: jest.fn().mockResolvedValue(null),
99
+ createRole: jest.fn().mockImplementation(r => Promise.resolve({
100
+ id: r.id, name: r.name, isAdmin: r.isAdmin || false,
101
+ defaultPermissions: null, collectionPermissions: null, config: null
102
+ })),
103
+ updateRole: jest.fn().mockImplementation((id, r) => Promise.resolve({
104
+ id, name: r.name, isAdmin: r.isAdmin || false,
105
+ defaultPermissions: null, collectionPermissions: null, config: null
106
+ })),
107
+ deleteRole: jest.fn().mockResolvedValue(undefined)
108
+ };
109
+
110
+ (validatePasswordStrength as jest.Mock).mockReturnValue({ valid: true, errors: [] });
111
+ (hashPassword as jest.Mock).mockResolvedValue("hashed-pw");
112
+
113
+ const config: AuthModuleConfig & { hooks?: BackendHooks } = {
114
+ authRepo: mockAuthRepo,
115
+ hooks
116
+ };
117
+
118
+ const app = new Hono<HonoEnv>();
119
+ app.onError(errorHandler);
120
+ app.route("/admin", createAdminRoutes(config));
121
+ return app;
122
+ }
123
+
124
+ function adminAuth(userId = "admin-1") {
125
+ return { Authorization: `Bearer ${generateAccessToken(userId, ["admin"])}` };
126
+ }
127
+
128
+ function json(body: Record<string, unknown>) {
129
+ return {
130
+ method: "POST" as const,
131
+ headers: { "Content-Type": "application/json" },
132
+ body: JSON.stringify(body)
133
+ };
134
+ }
135
+
136
+ // ═════════════════════════════════════════════════════════════════════════════
137
+ // TESTS
138
+ // ═════════════════════════════════════════════════════════════════════════════
139
+
140
+ describe("BackendHooks — Admin Routes", () => {
141
+ beforeAll(() => {
142
+ configureJwt({ secret: TEST_SECRET, accessExpiresIn: "1h" });
143
+ });
144
+
145
+ beforeEach(() => {
146
+ jest.clearAllMocks();
147
+ });
148
+
149
+ // ── users.afterRead ─────────────────────────────────────────────────
150
+ describe("users.afterRead", () => {
151
+ it("filters out users from GET /admin/users list", async () => {
152
+ const hooks: BackendHooks = {
153
+ users: {
154
+ afterRead(user) {
155
+ // Hide system users
156
+ if (user.email.endsWith("@system.internal")) return null;
157
+ return user;
158
+ }
159
+ }
160
+ };
161
+ const app = createApp(hooks);
162
+ mockAuthRepo.listUsers.mockResolvedValueOnce([
163
+ mockUser({ id: "u1", email: "alice@test.com" }),
164
+ mockUser({ id: "u2", email: "bot@system.internal" }),
165
+ mockUser({ id: "u3", email: "bob@test.com" })
166
+ ]);
167
+ mockAuthRepo.getUserRoleIds
168
+ .mockResolvedValueOnce(["editor"])
169
+ .mockResolvedValueOnce(["editor"])
170
+ .mockResolvedValueOnce(["editor"]);
171
+
172
+ const res = await app.request("/admin/users", { headers: { ...adminAuth() } });
173
+ expect(res.status).toBe(200);
174
+ const body = await res.json() as any;
175
+ expect(body.users).toHaveLength(2);
176
+ expect(body.users.map((u: any) => u.email)).toEqual(["alice@test.com", "bob@test.com"]);
177
+ });
178
+
179
+ it("transforms user data in GET /admin/users list", async () => {
180
+ const hooks: BackendHooks = {
181
+ users: {
182
+ afterRead(user) {
183
+ // Mask emails
184
+ return { ...user, email: "***@masked.com" };
185
+ }
186
+ }
187
+ };
188
+ const app = createApp(hooks);
189
+ mockAuthRepo.listUsers.mockResolvedValueOnce([
190
+ mockUser({ id: "u1", email: "alice@secret.com" })
191
+ ]);
192
+ mockAuthRepo.getUserRoleIds.mockResolvedValueOnce(["editor"]);
193
+
194
+ const res = await app.request("/admin/users", { headers: { ...adminAuth() } });
195
+ const body = await res.json() as any;
196
+ expect(body.users[0].email).toBe("***@masked.com");
197
+ });
198
+
199
+ it("returns 404 when afterRead filters single user GET /admin/users/:id", async () => {
200
+ const hooks: BackendHooks = {
201
+ users: {
202
+ afterRead(user) {
203
+ if (user.uid === "hidden-user") return null;
204
+ return user;
205
+ }
206
+ }
207
+ };
208
+ const app = createApp(hooks);
209
+ mockAuthRepo.getUserWithRoles.mockResolvedValueOnce({
210
+ user: mockUser({ id: "hidden-user" }),
211
+ roles: [mockRole("editor")]
212
+ });
213
+
214
+ const res = await app.request("/admin/users/hidden-user", { headers: { ...adminAuth() } });
215
+ expect(res.status).toBe(404);
216
+ });
217
+
218
+ it("passes context with request user info", async () => {
219
+ const afterReadSpy = jest.fn((user, ctx) => user);
220
+ const hooks: BackendHooks = { users: { afterRead: afterReadSpy } };
221
+ const app = createApp(hooks);
222
+ mockAuthRepo.listUsers.mockResolvedValueOnce([mockUser({ id: "u1" })]);
223
+ mockAuthRepo.getUserRoleIds.mockResolvedValueOnce(["editor"]);
224
+
225
+ await app.request("/admin/users", { headers: { ...adminAuth("admin-42") } });
226
+
227
+ expect(afterReadSpy).toHaveBeenCalledTimes(1);
228
+ const ctx = afterReadSpy.mock.calls[0][1];
229
+ expect(ctx.method).toBe("GET");
230
+ expect(ctx.requestUser).toBeDefined();
231
+ expect(ctx.requestUser.userId).toBe("admin-42");
232
+ expect(ctx.requestUser.roles).toContain("admin");
233
+ });
234
+ });
235
+
236
+ // ── users.beforeSave ────────────────────────────────────────────────
237
+ describe("users.beforeSave", () => {
238
+ it("transforms data before creating a user (POST)", async () => {
239
+ const hooks: BackendHooks = {
240
+ users: {
241
+ beforeSave(data) {
242
+ // Force lowercase display name
243
+ return { ...data, displayName: data.displayName?.toLowerCase() };
244
+ }
245
+ }
246
+ };
247
+ const app = createApp(hooks);
248
+
249
+ await app.request("/admin/users", {
250
+ ...json({ email: "new@test.com", displayName: "ALICE", password: "StrongPass1" }),
251
+ headers: { ...json({}).headers, ...adminAuth() }
252
+ });
253
+
254
+ expect(mockAuthRepo.createUser).toHaveBeenCalledWith(
255
+ expect.objectContaining({ displayName: "alice" })
256
+ );
257
+ });
258
+
259
+ it("transforms data before updating a user (PUT)", async () => {
260
+ const hooks: BackendHooks = {
261
+ users: {
262
+ beforeSave(data) {
263
+ return { ...data, displayName: "hook-modified" };
264
+ }
265
+ }
266
+ };
267
+ const app = createApp(hooks);
268
+ mockAuthRepo.getUserById.mockResolvedValueOnce(mockUser({ id: "u1" }));
269
+ mockAuthRepo.getUserWithRoles.mockResolvedValueOnce({
270
+ user: mockUser({ id: "u1", displayName: "hook-modified" }),
271
+ roles: [mockRole("editor")]
272
+ });
273
+
274
+ const res = await app.request("/admin/users/u1", {
275
+ method: "PUT",
276
+ headers: { "Content-Type": "application/json", ...adminAuth() },
277
+ body: JSON.stringify({ displayName: "Original" })
278
+ });
279
+
280
+ expect(res.status).toBe(200);
281
+ expect(mockAuthRepo.updateUser).toHaveBeenCalledWith("u1",
282
+ expect.objectContaining({ displayName: "hook-modified" })
283
+ );
284
+ });
285
+ });
286
+
287
+ // ── users.afterSave ─────────────────────────────────────────────────
288
+ describe("users.afterSave", () => {
289
+ it("fires afterSave after user creation", async () => {
290
+ const afterSaveSpy = jest.fn();
291
+ const hooks: BackendHooks = { users: { afterSave: afterSaveSpy } };
292
+ const app = createApp(hooks);
293
+
294
+ const res = await app.request("/admin/users", {
295
+ ...json({ email: "new@test.com", password: "StrongPass1" }),
296
+ headers: { ...json({}).headers, ...adminAuth() }
297
+ });
298
+
299
+ expect(res.status).toBe(201);
300
+ // afterSave is fire-and-forget, give it a tick
301
+ await new Promise(r => setTimeout(r, 50));
302
+ expect(afterSaveSpy).toHaveBeenCalledTimes(1);
303
+ expect(afterSaveSpy.mock.calls[0][0]).toMatchObject({ email: "new@test.com" });
304
+ });
305
+ });
306
+
307
+ // ── users.beforeDelete ──────────────────────────────────────────────
308
+ describe("users.beforeDelete", () => {
309
+ it("aborts deletion when beforeDelete throws", async () => {
310
+ const hooks: BackendHooks = {
311
+ users: {
312
+ beforeDelete(userId) {
313
+ if (userId === "protected-user") {
314
+ throw new Error("Cannot delete protected user");
315
+ }
316
+ }
317
+ }
318
+ };
319
+ const app = createApp(hooks);
320
+ mockAuthRepo.getUserById.mockResolvedValueOnce(mockUser({ id: "protected-user" }));
321
+
322
+ const res = await app.request("/admin/users/protected-user", {
323
+ method: "DELETE",
324
+ headers: { ...adminAuth("admin-1") }
325
+ });
326
+
327
+ expect(res.status).toBe(500);
328
+ expect(mockAuthRepo.deleteUser).not.toHaveBeenCalled();
329
+ });
330
+ });
331
+
332
+ // ── users.afterDelete ───────────────────────────────────────────────
333
+ describe("users.afterDelete", () => {
334
+ it("fires afterDelete after user is deleted", async () => {
335
+ const afterDeleteSpy = jest.fn();
336
+ const hooks: BackendHooks = { users: { afterDelete: afterDeleteSpy } };
337
+ const app = createApp(hooks);
338
+ mockAuthRepo.getUserById.mockResolvedValueOnce(mockUser({ id: "u1" }));
339
+
340
+ const res = await app.request("/admin/users/u1", {
341
+ method: "DELETE",
342
+ headers: { ...adminAuth("admin-1") }
343
+ });
344
+
345
+ expect(res.status).toBe(200);
346
+ await new Promise(r => setTimeout(r, 50));
347
+ expect(afterDeleteSpy).toHaveBeenCalledWith("u1", expect.objectContaining({ method: "DELETE" }));
348
+ });
349
+ });
350
+
351
+ // ── roles.afterRead ─────────────────────────────────────────────────
352
+ describe("roles.afterRead", () => {
353
+ it("filters out roles from GET /admin/roles", async () => {
354
+ const hooks: BackendHooks = {
355
+ roles: {
356
+ afterRead(role) {
357
+ // Hide internal roles
358
+ if (role.id === "internal") return null;
359
+ return role;
360
+ }
361
+ }
362
+ };
363
+ const app = createApp(hooks);
364
+ mockAuthRepo.listRoles.mockResolvedValueOnce([
365
+ mockRole("admin", true),
366
+ mockRole("internal"),
367
+ mockRole("editor")
368
+ ]);
369
+
370
+ const res = await app.request("/admin/roles", { headers: { ...adminAuth() } });
371
+ expect(res.status).toBe(200);
372
+ const body = await res.json() as any;
373
+ expect(body.roles).toHaveLength(2);
374
+ expect(body.roles.map((r: any) => r.id)).toEqual(["admin", "editor"]);
375
+ });
376
+ });
377
+
378
+ // ── no hooks (passthrough) ──────────────────────────────────────────
379
+ describe("no hooks configured", () => {
380
+ it("returns data unchanged when no hooks are provided", async () => {
381
+ const app = createApp(); // no hooks
382
+ mockAuthRepo.listUsers.mockResolvedValueOnce([
383
+ mockUser({ id: "u1", email: "alice@test.com" })
384
+ ]);
385
+ mockAuthRepo.getUserRoleIds.mockResolvedValueOnce(["editor"]);
386
+
387
+ const res = await app.request("/admin/users", { headers: { ...adminAuth() } });
388
+ expect(res.status).toBe(200);
389
+ const body = await res.json() as any;
390
+ expect(body.users).toHaveLength(1);
391
+ expect(body.users[0].email).toBe("alice@test.com");
392
+ });
393
+ });
394
+ });