-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathauth-plugin.test.ts
More file actions
439 lines (358 loc) · 14.2 KB
/
Copy pathauth-plugin.test.ts
File metadata and controls
439 lines (358 loc) · 14.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.
import { describe, it, expect, vi, beforeEach } from 'vitest';
import { AuthPlugin } from './auth-plugin';
import type { PluginContext } from '@objectstack/core';
describe('AuthPlugin', () => {
let mockContext: PluginContext;
let authPlugin: AuthPlugin;
/** Shared hook capture utilities for tests that need kernel:ready simulation */
const createHookCapture = () => {
const handlers = new Map<string, Array<(...args: any[]) => Promise<void>>>();
const hookFn = vi.fn((name: string, handler: (...args: any[]) => Promise<void>) => {
if (!handlers.has(name)) handlers.set(name, []);
handlers.get(name)!.push(handler);
});
const trigger = async (name: string) => {
for (const h of handlers.get(name) || []) await h();
};
return { handlers, hookFn, trigger };
};
beforeEach(() => {
mockContext = {
registerService: vi.fn(),
getService: vi.fn(),
getServices: vi.fn(() => new Map()),
hook: vi.fn(),
trigger: vi.fn(),
logger: {
info: vi.fn(),
error: vi.fn(),
warn: vi.fn(),
debug: vi.fn(),
},
getKernel: vi.fn(),
};
});
describe('Plugin Metadata', () => {
it('should have correct plugin metadata', () => {
authPlugin = new AuthPlugin({
secret: 'test-secret',
});
expect(authPlugin.name).toBe('com.objectstack.auth');
expect(authPlugin.type).toBe('standard');
expect(authPlugin.version).toBe('1.0.0');
expect(authPlugin.dependencies).toEqual([]);
});
});
describe('Initialization', () => {
it('should throw error if secret is not provided', async () => {
authPlugin = new AuthPlugin({});
await expect(authPlugin.init(mockContext)).rejects.toThrow(
'AuthPlugin: secret is required'
);
});
it('should initialize successfully with required config', async () => {
authPlugin = new AuthPlugin({
secret: 'test-secret-at-least-32-chars-long',
baseUrl: 'http://localhost:3000',
});
await authPlugin.init(mockContext);
expect(mockContext.logger.info).toHaveBeenCalledWith('Initializing Auth Plugin...');
expect(mockContext.registerService).toHaveBeenCalledWith('auth', expect.anything());
expect(mockContext.logger.info).toHaveBeenCalledWith('Auth Plugin initialized successfully');
});
it('should configure OAuth providers', async () => {
authPlugin = new AuthPlugin({
secret: 'test-secret-at-least-32-chars-long',
baseUrl: 'http://localhost:3000',
providers: [
{
id: 'google',
clientId: 'google-client-id',
clientSecret: 'google-client-secret',
scope: ['email', 'profile'],
},
],
});
await authPlugin.init(mockContext);
expect(mockContext.registerService).toHaveBeenCalled();
});
it('should configure plugins', async () => {
authPlugin = new AuthPlugin({
secret: 'test-secret-at-least-32-chars-long',
baseUrl: 'http://localhost:3000',
plugins: {
organization: true,
twoFactor: true,
passkeys: true,
magicLink: true,
},
});
await authPlugin.init(mockContext);
expect(mockContext.registerService).toHaveBeenCalled();
});
});
describe('Start Phase', () => {
let hookCapture: ReturnType<typeof createHookCapture>;
beforeEach(async () => {
hookCapture = createHookCapture();
authPlugin = new AuthPlugin({
secret: 'test-secret-at-least-32-chars-long',
baseUrl: 'http://localhost:3000',
});
// Capture hook registrations so we can trigger them in tests
mockContext.hook = hookCapture.hookFn;
await authPlugin.init(mockContext);
});
it('should register a kernel:ready hook for route registration', async () => {
await authPlugin.start(mockContext);
expect(mockContext.hook).toHaveBeenCalledWith('kernel:ready', expect.any(Function));
});
it('should register routes with HTTP server on kernel:ready', async () => {
const mockRawApp = {
all: vi.fn(),
};
const mockHttpServer = {
post: vi.fn(),
get: vi.fn(),
put: vi.fn(),
delete: vi.fn(),
patch: vi.fn(),
use: vi.fn(),
getRawApp: vi.fn(() => mockRawApp),
};
mockContext.getService = vi.fn((name: string) => {
if (name === 'http-server') return mockHttpServer;
throw new Error(`Service not found: ${name}`);
});
await authPlugin.start(mockContext);
// Routes should NOT be registered yet (deferred to kernel:ready)
expect(mockRawApp.all).not.toHaveBeenCalled();
// Simulate kernel:ready
await hookCapture.trigger('kernel:ready');
expect(mockContext.getService).toHaveBeenCalledWith('http-server');
expect(mockHttpServer.getRawApp).toHaveBeenCalled();
expect(mockRawApp.all).toHaveBeenCalledWith('/api/v1/auth/*', expect.any(Function));
expect(mockContext.logger.info).toHaveBeenCalledWith(
expect.stringContaining('Auth routes registered')
);
});
it('should log via ctx.logger when better-auth returns a 500 response', async () => {
const mockRawApp = {
all: vi.fn(),
};
const mockHttpServer = {
post: vi.fn(),
get: vi.fn(),
put: vi.fn(),
delete: vi.fn(),
patch: vi.fn(),
use: vi.fn(),
getRawApp: vi.fn(() => mockRawApp),
};
mockContext.getService = vi.fn((name: string) => {
if (name === 'http-server') return mockHttpServer;
throw new Error(`Service not found: ${name}`);
});
await authPlugin.start(mockContext);
await hookCapture.trigger('kernel:ready');
// Extract the registered route handler
const routeHandler = mockRawApp.all.mock.calls[0][1];
// Create a mock Hono context with a request that will trigger a 500 response
const errorResponse = new Response(
JSON.stringify({ error: 'Database connection failed' }),
{ status: 500, headers: { 'Content-Type': 'application/json' } }
);
// Mock the authManager's handleRequest to return a 500 response
// We access the private authManager through the registered service
const registeredAuthManager = (mockContext.registerService as any).mock.calls[0][1];
vi.spyOn(registeredAuthManager, 'handleRequest').mockResolvedValue(errorResponse);
const mockHonoCtx = {
req: {
raw: new Request('http://localhost:3000/api/v1/auth/sign-up/email', {
method: 'POST',
body: JSON.stringify({ email: 'a@b.com', password: 'pass' }),
headers: { 'Content-Type': 'application/json' },
}),
},
};
const result = await routeHandler(mockHonoCtx);
expect(result.status).toBe(500);
expect(mockContext.logger.error).toHaveBeenCalledWith(
'[AuthPlugin] better-auth returned server error',
expect.any(Error)
);
});
it('should skip route registration when disabled', async () => {
authPlugin = new AuthPlugin({
secret: 'test-secret-at-least-32-chars-long',
baseUrl: 'http://localhost:3000',
registerRoutes: false,
});
await authPlugin.init(mockContext);
await authPlugin.start(mockContext);
// Should not register kernel:ready hook for routes
expect(mockContext.hook).not.toHaveBeenCalledWith('kernel:ready', expect.any(Function));
});
it('should gracefully skip routes when http-server is not available', async () => {
mockContext.getService = vi.fn(() => null);
await authPlugin.start(mockContext);
await hookCapture.trigger('kernel:ready');
expect(mockContext.getService).toHaveBeenCalledWith('http-server');
expect(mockContext.logger.warn).toHaveBeenCalledWith(
expect.stringContaining('No HTTP server available')
);
// Should NOT throw — auth service is still registered from init()
});
it('should gracefully handle http-server getService throwing', async () => {
mockContext.getService = vi.fn(() => {
throw new Error('Service not found: http-server');
});
await authPlugin.start(mockContext);
await hookCapture.trigger('kernel:ready');
expect(mockContext.logger.warn).toHaveBeenCalledWith(
expect.stringContaining('No HTTP server available')
);
// Auth service should still be registered from init()
expect(mockContext.registerService).toHaveBeenCalledWith('auth', expect.anything());
// Should NOT throw
});
it('should auto-detect baseUrl from http-server port when port differs', async () => {
const mockRawApp = { all: vi.fn() };
const mockHttpServer = {
post: vi.fn(), get: vi.fn(), put: vi.fn(), delete: vi.fn(),
patch: vi.fn(), use: vi.fn(),
getRawApp: vi.fn(() => mockRawApp),
getPort: vi.fn(() => 3002),
};
mockContext.getService = vi.fn((name: string) => {
if (name === 'http-server') return mockHttpServer;
throw new Error(`Service not found: ${name}`);
});
// AuthPlugin configured with default port 3000, but server will be on 3002
const registeredAuthManager = (mockContext.registerService as any).mock.calls[0][1];
const setRuntimeSpy = vi.spyOn(registeredAuthManager, 'setRuntimeBaseUrl');
await authPlugin.start(mockContext);
await hookCapture.trigger('kernel:ready');
expect(setRuntimeSpy).toHaveBeenCalledWith('http://localhost:3002');
expect(mockContext.logger.info).toHaveBeenCalledWith(
expect.stringContaining('Auth baseUrl auto-updated to http://localhost:3002'),
);
});
it('should NOT update baseUrl when port matches configured value', async () => {
const localHookCapture = createHookCapture();
const localPlugin = new AuthPlugin({
secret: 'test-secret-at-least-32-chars-long',
baseUrl: 'http://localhost:3000',
});
mockContext.hook = localHookCapture.hookFn;
(mockContext.registerService as any).mockClear();
await localPlugin.init(mockContext);
const mockRawApp = { all: vi.fn() };
const mockHttpServer = {
post: vi.fn(), get: vi.fn(), put: vi.fn(), delete: vi.fn(),
patch: vi.fn(), use: vi.fn(),
getRawApp: vi.fn(() => mockRawApp),
getPort: vi.fn(() => 3000),
};
mockContext.getService = vi.fn((name: string) => {
if (name === 'http-server') return mockHttpServer;
throw new Error(`Service not found: ${name}`);
});
const registeredAuthManager = (mockContext.registerService as any).mock.calls[0][1];
const setRuntimeSpy = vi.spyOn(registeredAuthManager, 'setRuntimeBaseUrl');
await localPlugin.start(mockContext);
await localHookCapture.trigger('kernel:ready');
expect(setRuntimeSpy).not.toHaveBeenCalled();
});
it('should auto-detect baseUrl when no baseUrl configured (uses default fallback)', async () => {
const localHookCapture = createHookCapture();
// No baseUrl — defaults to http://localhost:3000 internally
const localPlugin = new AuthPlugin({
secret: 'test-secret-at-least-32-chars-long',
});
mockContext.hook = localHookCapture.hookFn;
(mockContext.registerService as any).mockClear();
await localPlugin.init(mockContext);
const mockRawApp = { all: vi.fn() };
const mockHttpServer = {
post: vi.fn(), get: vi.fn(), put: vi.fn(), delete: vi.fn(),
patch: vi.fn(), use: vi.fn(),
getRawApp: vi.fn(() => mockRawApp),
getPort: vi.fn(() => 3002),
};
mockContext.getService = vi.fn((name: string) => {
if (name === 'http-server') return mockHttpServer;
throw new Error(`Service not found: ${name}`);
});
const registeredAuthManager = (mockContext.registerService as any).mock.calls[0][1];
const setRuntimeSpy = vi.spyOn(registeredAuthManager, 'setRuntimeBaseUrl');
await localPlugin.start(mockContext);
await localHookCapture.trigger('kernel:ready');
expect(setRuntimeSpy).toHaveBeenCalledWith('http://localhost:3002');
});
it('should throw error if auth not initialized', async () => {
const uninitializedPlugin = new AuthPlugin({
secret: 'test-secret',
});
await expect(uninitializedPlugin.start(mockContext)).rejects.toThrow(
'Auth manager not initialized'
);
});
});
describe('Destroy Phase', () => {
it('should cleanup resources', async () => {
authPlugin = new AuthPlugin({
secret: 'test-secret-at-least-32-chars-long',
});
await authPlugin.init(mockContext);
await authPlugin.destroy();
// Should not throw
expect(true).toBe(true);
});
});
describe('Configuration Options', () => {
it('should use custom base path', async () => {
const { hookFn, trigger } = createHookCapture();
mockContext.hook = hookFn;
authPlugin = new AuthPlugin({
secret: 'test-secret-at-least-32-chars-long',
baseUrl: 'http://localhost:3000',
basePath: '/custom/auth',
});
await authPlugin.init(mockContext);
const mockRawApp = {
all: vi.fn(),
};
const mockHttpServer = {
post: vi.fn(),
get: vi.fn(),
put: vi.fn(),
delete: vi.fn(),
patch: vi.fn(),
use: vi.fn(),
getRawApp: vi.fn(() => mockRawApp),
};
mockContext.getService = vi.fn(() => mockHttpServer);
await authPlugin.start(mockContext);
// Trigger kernel:ready to actually register routes
await trigger('kernel:ready');
expect(mockRawApp.all).toHaveBeenCalledWith(
'/custom/auth/*',
expect.any(Function)
);
});
it('should configure session options', async () => {
authPlugin = new AuthPlugin({
secret: 'test-secret-at-least-32-chars-long',
baseUrl: 'http://localhost:3000',
session: {
expiresIn: 60 * 60 * 24 * 30, // 30 days
updateAge: 60 * 60 * 24, // 1 day
},
});
await authPlugin.init(mockContext);
expect(mockContext.registerService).toHaveBeenCalled();
});
});
});