-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathhono-plugin.test.ts
More file actions
332 lines (268 loc) · 12.4 KB
/
Copy pathhono-plugin.test.ts
File metadata and controls
332 lines (268 loc) · 12.4 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
import { describe, it, expect, vi, beforeEach } from 'vitest';
import { HonoServerPlugin } from './hono-plugin';
import { PluginContext } from '@objectstack/core';
import { HonoHttpServer } from './adapter';
vi.mock('fs', async (importOriginal) => {
const actual = await importOriginal<typeof import('fs')>();
return {
...actual,
existsSync: vi.fn().mockReturnValue(true)
};
});
vi.mock('@hono/node-server/serve-static', () => ({
serveStatic: vi.fn(() => (c: any, next: any) => next())
}));
vi.mock('./adapter', () => ({
HonoHttpServer: vi.fn(function() {
return {
mount: vi.fn(),
start: vi.fn(),
stop: vi.fn(),
getApp: vi.fn(),
listen: vi.fn(),
getPort: vi.fn().mockReturnValue(3000),
close: vi.fn(),
getRawApp: vi.fn().mockReturnValue({
get: vi.fn(),
use: vi.fn(),
})
};
})
}));
// Capture the config passed to hono/cors so we can assert allowHeaders / exposeHeaders.
const corsConfigCapture: { last?: any } = {};
vi.mock('hono/cors', () => ({
cors: vi.fn((config: any) => {
corsConfigCapture.last = config;
// Return a no-op middleware
return async (_c: any, next: any) => next();
}),
}));
describe('HonoServerPlugin', () => {
let context: any;
let logger: any;
let kernel: any;
beforeEach(() => {
vi.clearAllMocks();
logger = {
info: vi.fn(),
debug: vi.fn(),
warn: vi.fn(),
error: vi.fn()
};
kernel = {
getService: vi.fn(),
};
context = {
logger,
getKernel: vi.fn().mockReturnValue(kernel),
registerService: vi.fn(),
hook: vi.fn(),
getService: vi.fn()
};
});
it('should initialize and register server', async () => {
const plugin = new HonoServerPlugin();
await plugin.init(context as PluginContext);
expect(context.registerService).toHaveBeenCalledWith('http-server', expect.any(Object));
expect(HonoHttpServer).toHaveBeenCalled();
});
it('should register IHttpServer service on init', async () => {
const plugin = new HonoServerPlugin();
await plugin.init(context as PluginContext);
expect(context.registerService).toHaveBeenCalledWith('http.server', expect.any(Object));
expect(context.registerService).toHaveBeenCalledWith('http-server', expect.any(Object));
});
it('should start without errors', async () => {
const plugin = new HonoServerPlugin();
await plugin.init(context as PluginContext);
await plugin.start(context as PluginContext);
// Plugin should register kernel:ready hook to start listening
expect(context.hook).toHaveBeenCalledWith('kernel:ready', expect.any(Function));
});
it('should handle errors gracefully on start', async () => {
// Simulate a start that doesn't crash even without routes
const plugin = new HonoServerPlugin();
await plugin.init(context as PluginContext);
await expect(plugin.start(context as PluginContext)).resolves.not.toThrow();
});
it('standalone discovery advertises transactionalBatch=false — the /batch route is not mounted here (#3298)', async () => {
// This standalone surface registers CRUD + auth only; the cross-object
// /batch endpoint ships with @objectstack/rest. declared === enforced:
// discovery must report the capability as disabled so a client never
// drops its non-atomic fallback against this backend.
const plugin = new HonoServerPlugin({ registerStandardEndpoints: true });
await plugin.init(context as PluginContext);
// Capture the routes the producer registers on the raw app.
const routes: Record<string, any> = {};
const rawApp = {
get: vi.fn((path: string, h: any) => { routes[`GET ${path}`] = h; }),
post: vi.fn((path: string, h: any) => { routes[`POST ${path}`] = h; }),
use: vi.fn(),
};
(plugin as any).server.getRawApp = () => rawApp;
(plugin as any).registerDiscoveryAndCrudEndpoints(context);
const handler = routes['GET /api/v1/discovery'];
expect(handler).toBeDefined();
const c = { json: vi.fn((x: any) => x) };
const res = handler(c);
expect(res.data.capabilities.transactionalBatch).toEqual({ enabled: false });
// Sanity: the standalone surface really has no /batch route (so `false`
// is honest, not merely conservative).
expect(routes['POST /api/v1/batch']).toBeUndefined();
});
it('should configure static files and SPA fallback when enabled', async () => {
const plugin = new HonoServerPlugin({
staticRoot: './public',
spaFallback: true
});
await plugin.init(context as PluginContext);
await plugin.start(context as PluginContext);
const serverInstance = (HonoHttpServer as any).mock.instances[0];
const rawApp = serverInstance.getRawApp();
expect(serverInstance.getRawApp).toHaveBeenCalled();
// Should register static files middleware
expect(rawApp.get).toHaveBeenCalledWith('/*', expect.anything());
// Should register SPA fallback middleware
expect(rawApp.get).toHaveBeenCalledWith('/*', expect.anything());
});
describe('CORS wildcard pattern matching', () => {
beforeEach(() => {
vi.clearAllMocks();
});
it('should enable CORS middleware with wildcard subdomain patterns', async () => {
const plugin = new HonoServerPlugin({
cors: {
origins: ['https://*.objectui.org', 'https://*.objectstack.ai'],
credentials: true
}
});
await plugin.init(context as PluginContext);
const serverInstance = (HonoHttpServer as any).mock.instances[0];
const rawApp = serverInstance.getRawApp();
// CORS middleware should be registered
expect(rawApp.use).toHaveBeenCalledWith('*', expect.any(Function));
});
it('should enable CORS middleware with port wildcard patterns', async () => {
const plugin = new HonoServerPlugin({
cors: {
origins: 'http://localhost:*',
}
});
await plugin.init(context as PluginContext);
const serverInstance = (HonoHttpServer as any).mock.instances[0];
const rawApp = serverInstance.getRawApp();
expect(rawApp.use).toHaveBeenCalledWith('*', expect.any(Function));
});
it('should support comma-separated wildcard patterns', async () => {
const plugin = new HonoServerPlugin({
cors: {
origins: 'https://*.objectui.org,https://*.objectstack.ai',
}
});
await plugin.init(context as PluginContext);
const serverInstance = (HonoHttpServer as any).mock.instances[0];
const rawApp = serverInstance.getRawApp();
expect(rawApp.use).toHaveBeenCalledWith('*', expect.any(Function));
});
it('should support exact origins without wildcards', async () => {
const plugin = new HonoServerPlugin({
cors: {
origins: ['https://app.example.com', 'https://api.example.com'],
}
});
await plugin.init(context as PluginContext);
const serverInstance = (HonoHttpServer as any).mock.instances[0];
const rawApp = serverInstance.getRawApp();
expect(rawApp.use).toHaveBeenCalledWith('*', expect.any(Function));
});
it('should support CORS_ORIGIN environment variable with wildcards', async () => {
const originalEnv = process.env.OS_CORS_ORIGIN;
process.env.OS_CORS_ORIGIN = 'https://*.objectui.org,https://*.objectstack.ai';
const plugin = new HonoServerPlugin();
await plugin.init(context as PluginContext);
const serverInstance = (HonoHttpServer as any).mock.instances[0];
const rawApp = serverInstance.getRawApp();
expect(rawApp.use).toHaveBeenCalledWith('*', expect.any(Function));
// Restore environment
if (originalEnv !== undefined) {
process.env.OS_CORS_ORIGIN = originalEnv;
} else {
delete process.env.OS_CORS_ORIGIN;
}
});
it('should disable CORS when cors option is false', async () => {
corsConfigCapture.last = undefined;
const plugin = new HonoServerPlugin({
cors: false
});
await plugin.init(context as PluginContext);
// CORS middleware must NOT be configured. (Assert on the CORS config,
// not the raw `use` count: the perf-timing middleware registers its
// own `use('*')` by default to catch the `X-OS-Debug-Timing` header.)
expect(corsConfigCapture.last).toBeUndefined();
});
it('should disable CORS when CORS_ENABLED env is false', async () => {
const originalEnv = process.env.OS_CORS_ENABLED;
process.env.OS_CORS_ENABLED = 'false';
corsConfigCapture.last = undefined;
try {
const plugin = new HonoServerPlugin();
await plugin.init(context as PluginContext);
// CORS not configured — see the note above re: the perf-timing
// middleware's own `use('*')`.
expect(corsConfigCapture.last).toBeUndefined();
} finally {
// Restore environment even if the assertion fails, so a leaked
// `OS_CORS_ENABLED=false` can't disable CORS in later tests.
if (originalEnv !== undefined) {
process.env.OS_CORS_ENABLED = originalEnv;
} else {
delete process.env.OS_CORS_ENABLED;
}
}
});
it('should always expose set-auth-token header (for better-auth bearer plugin)', async () => {
corsConfigCapture.last = undefined;
const plugin = new HonoServerPlugin();
await plugin.init(context as PluginContext);
expect(corsConfigCapture.last).toBeDefined();
expect(corsConfigCapture.last.exposeHeaders).toContain('set-auth-token');
// Default allowHeaders should include Authorization so Bearer tokens work
expect(corsConfigCapture.last.allowHeaders).toContain('Authorization');
});
it('should allow If-Match by default (OCC token on cross-origin record PATCHes)', async () => {
corsConfigCapture.last = undefined;
const plugin = new HonoServerPlugin();
await plugin.init(context as PluginContext);
// objectui#2572 dogfood find: the record-level inline edit sends the
// OCC token as an `If-Match` header; a preflight that doesn't allow
// it makes every split-origin save fail with "Failed to fetch".
expect(corsConfigCapture.last.allowHeaders).toContain('If-Match');
});
it('should merge user-supplied exposeHeaders with set-auth-token default', async () => {
corsConfigCapture.last = undefined;
const plugin = new HonoServerPlugin({
cors: {
exposeHeaders: ['X-Request-Id', 'X-Rate-Limit'],
},
});
await plugin.init(context as PluginContext);
expect(corsConfigCapture.last.exposeHeaders).toEqual(
expect.arrayContaining(['set-auth-token', 'X-Request-Id', 'X-Rate-Limit']),
);
});
it('should honor custom allowHeaders while still allowing bearer auth header when explicitly provided', async () => {
corsConfigCapture.last = undefined;
const plugin = new HonoServerPlugin({
cors: {
allowHeaders: ['Content-Type', 'Authorization', 'X-Tenant-Id'],
},
});
await plugin.init(context as PluginContext);
expect(corsConfigCapture.last.allowHeaders).toEqual(
['Content-Type', 'Authorization', 'X-Tenant-Id'],
);
});
});
});