@syncular/server-hono 0.0.6-96 → 0.2.1

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 (104) hide show
  1. package/README.md +5 -23
  2. package/dist/admin-page.d.ts +14 -0
  3. package/dist/admin-page.js +217 -0
  4. package/dist/admin.d.ts +39 -0
  5. package/dist/admin.js +142 -0
  6. package/dist/index.d.ts +16 -14
  7. package/dist/index.js +134 -23
  8. package/package.json +19 -53
  9. package/src/admin-page.ts +217 -0
  10. package/src/admin.ts +193 -0
  11. package/src/index.ts +175 -31
  12. package/dist/api-key-auth.d.ts +0 -49
  13. package/dist/api-key-auth.d.ts.map +0 -1
  14. package/dist/api-key-auth.js +0 -110
  15. package/dist/api-key-auth.js.map +0 -1
  16. package/dist/blobs.d.ts +0 -69
  17. package/dist/blobs.d.ts.map +0 -1
  18. package/dist/blobs.js +0 -383
  19. package/dist/blobs.js.map +0 -1
  20. package/dist/console/gateway.d.ts +0 -33
  21. package/dist/console/gateway.d.ts.map +0 -1
  22. package/dist/console/gateway.js +0 -2534
  23. package/dist/console/gateway.js.map +0 -1
  24. package/dist/console/index.d.ts +0 -11
  25. package/dist/console/index.d.ts.map +0 -1
  26. package/dist/console/index.js +0 -11
  27. package/dist/console/index.js.map +0 -1
  28. package/dist/console/routes.d.ts +0 -33
  29. package/dist/console/routes.d.ts.map +0 -1
  30. package/dist/console/routes.js +0 -3029
  31. package/dist/console/routes.js.map +0 -1
  32. package/dist/console/schemas.d.ts +0 -490
  33. package/dist/console/schemas.d.ts.map +0 -1
  34. package/dist/console/schemas.js +0 -303
  35. package/dist/console/schemas.js.map +0 -1
  36. package/dist/console/types.d.ts +0 -175
  37. package/dist/console/types.d.ts.map +0 -1
  38. package/dist/console/types.js +0 -2
  39. package/dist/console/types.js.map +0 -1
  40. package/dist/console/ui.d.ts +0 -38
  41. package/dist/console/ui.d.ts.map +0 -1
  42. package/dist/console/ui.js +0 -43
  43. package/dist/console/ui.js.map +0 -1
  44. package/dist/create-server.d.ts +0 -68
  45. package/dist/create-server.d.ts.map +0 -1
  46. package/dist/create-server.js +0 -110
  47. package/dist/create-server.js.map +0 -1
  48. package/dist/index.d.ts.map +0 -1
  49. package/dist/index.js.map +0 -1
  50. package/dist/openapi.d.ts +0 -45
  51. package/dist/openapi.d.ts.map +0 -1
  52. package/dist/openapi.js +0 -59
  53. package/dist/openapi.js.map +0 -1
  54. package/dist/proxy/connection-manager.d.ts +0 -78
  55. package/dist/proxy/connection-manager.d.ts.map +0 -1
  56. package/dist/proxy/connection-manager.js +0 -251
  57. package/dist/proxy/connection-manager.js.map +0 -1
  58. package/dist/proxy/index.d.ts +0 -8
  59. package/dist/proxy/index.d.ts.map +0 -1
  60. package/dist/proxy/index.js +0 -8
  61. package/dist/proxy/index.js.map +0 -1
  62. package/dist/proxy/routes.d.ts +0 -74
  63. package/dist/proxy/routes.d.ts.map +0 -1
  64. package/dist/proxy/routes.js +0 -147
  65. package/dist/proxy/routes.js.map +0 -1
  66. package/dist/rate-limit.d.ts +0 -101
  67. package/dist/rate-limit.d.ts.map +0 -1
  68. package/dist/rate-limit.js +0 -186
  69. package/dist/rate-limit.js.map +0 -1
  70. package/dist/routes.d.ts +0 -161
  71. package/dist/routes.d.ts.map +0 -1
  72. package/dist/routes.js +0 -1493
  73. package/dist/routes.js.map +0 -1
  74. package/dist/ws.d.ts +0 -235
  75. package/dist/ws.d.ts.map +0 -1
  76. package/dist/ws.js +0 -614
  77. package/dist/ws.js.map +0 -1
  78. package/src/__tests__/blob-routes.test.ts +0 -424
  79. package/src/__tests__/console-gateway-live-routes.test.ts +0 -297
  80. package/src/__tests__/console-gateway-routes.test.ts +0 -1364
  81. package/src/__tests__/console-routes.test.ts +0 -1626
  82. package/src/__tests__/console-ui.test.ts +0 -114
  83. package/src/__tests__/create-server.test.ts +0 -485
  84. package/src/__tests__/pull-chunk-storage.test.ts +0 -576
  85. package/src/__tests__/rate-limit.test.ts +0 -78
  86. package/src/__tests__/realtime-bridge.test.ts +0 -135
  87. package/src/__tests__/sync-rate-limit-routing.test.ts +0 -185
  88. package/src/__tests__/ws-connection-manager.test.ts +0 -176
  89. package/src/api-key-auth.ts +0 -179
  90. package/src/blobs.ts +0 -534
  91. package/src/console/gateway.ts +0 -3603
  92. package/src/console/index.ts +0 -11
  93. package/src/console/routes.ts +0 -3936
  94. package/src/console/schemas.ts +0 -434
  95. package/src/console/types.ts +0 -185
  96. package/src/console/ui.ts +0 -100
  97. package/src/create-server.ts +0 -207
  98. package/src/openapi.ts +0 -74
  99. package/src/proxy/connection-manager.ts +0 -340
  100. package/src/proxy/index.ts +0 -8
  101. package/src/proxy/routes.ts +0 -223
  102. package/src/rate-limit.ts +0 -321
  103. package/src/routes.ts +0 -2059
  104. package/src/ws.ts +0 -802
@@ -1,8 +0,0 @@
1
- /**
2
- * @syncular/server-hono - Proxy Exports
3
- *
4
- * WebSocket endpoint for admin database proxy.
5
- */
6
-
7
- export * from './connection-manager';
8
- export * from './routes';
@@ -1,223 +0,0 @@
1
- /**
2
- * @syncular/server-hono - Proxy Routes
3
- *
4
- * WebSocket endpoint for database proxy.
5
- */
6
-
7
- import type {
8
- ProxyHandshake,
9
- ProxyHandshakeAck,
10
- ProxyMessage,
11
- ProxyResponse,
12
- } from '@syncular/core';
13
- import { logSyncEvent } from '@syncular/core';
14
- import type {
15
- ProxyHandlerCollection,
16
- ServerSyncDialect,
17
- SyncCoreDb,
18
- } from '@syncular/server';
19
- import type { Context } from 'hono';
20
- import { Hono } from 'hono';
21
- import type { UpgradeWebSocket, WSContext } from 'hono/ws';
22
- import type { Kysely } from 'kysely';
23
- import { ProxyConnectionManager } from './connection-manager';
24
-
25
- /**
26
- * WeakMap for storing proxy connection manager per Hono instance.
27
- */
28
- interface ProxyConnectionManagerHandle {
29
- canAccept(): boolean;
30
- getConnectionCount(): number;
31
- register(ws: WSContext, handshake: ProxyHandshake): unknown;
32
- handleMessage(ws: WSContext, message: ProxyMessage): Promise<ProxyResponse>;
33
- unregister(ws: WSContext): Promise<void>;
34
- }
35
-
36
- const proxyConnectionManagerMap = new WeakMap<
37
- Hono,
38
- ProxyConnectionManagerHandle
39
- >();
40
-
41
- interface ProxyAuthResult {
42
- /** Actor ID for oplog tracking */
43
- actorId: string;
44
- }
45
-
46
- interface CreateProxyRoutesConfig<DB extends SyncCoreDb = SyncCoreDb> {
47
- /** Database connection */
48
- db: Kysely<DB>;
49
- /** Server sync dialect */
50
- dialect: ServerSyncDialect;
51
- /** Proxy table handlers for oplog generation */
52
- handlers: ProxyHandlerCollection;
53
- /** Authenticate the request and return actor info */
54
- authenticate: (c: Context) => Promise<ProxyAuthResult | null>;
55
- /** WebSocket upgrade function from Hono */
56
- upgradeWebSocket: UpgradeWebSocket;
57
- /** Maximum concurrent connections (default: 100) */
58
- maxConnections?: number;
59
- /** Idle connection timeout in ms (default: 30000) */
60
- idleTimeoutMs?: number;
61
- }
62
-
63
- /**
64
- * Create Hono routes for the proxy WebSocket endpoint.
65
- *
66
- * @example
67
- * ```typescript
68
- * import { Hono } from 'hono';
69
- * import { createBunWebSocket } from 'hono/bun';
70
- * import { createProxyRoutes } from '@syncular/server-hono/proxy';
71
- *
72
- * const { upgradeWebSocket, websocket } = createBunWebSocket();
73
- *
74
- * const app = new Hono();
75
- *
76
- * app.route('/proxy', createProxyRoutes({
77
- * db,
78
- * handlers: proxyHandlers,
79
- * authenticate: async (c) => {
80
- * // Verify admin auth
81
- * return { actorId: 'admin:123' };
82
- * },
83
- * upgradeWebSocket,
84
- * }));
85
- *
86
- * export default { fetch: app.fetch, websocket };
87
- * ```
88
- */
89
- export function createProxyRoutes<DB extends SyncCoreDb>(
90
- config: CreateProxyRoutesConfig<DB>
91
- ): Hono {
92
- const app = new Hono();
93
-
94
- const manager = new ProxyConnectionManager({
95
- db: config.db,
96
- dialect: config.dialect,
97
- handlers: config.handlers,
98
- maxConnections: config.maxConnections,
99
- idleTimeoutMs: config.idleTimeoutMs,
100
- });
101
-
102
- // Store manager for external access if needed
103
- proxyConnectionManagerMap.set(app, manager);
104
-
105
- // WebSocket upgrade endpoint - using regular route since WebSocket doesn't fit OpenAPI well
106
- app.get('/', async (c) => {
107
- // Authenticate before upgrade
108
- const auth = await config.authenticate(c);
109
- if (!auth) {
110
- return c.json({ error: 'UNAUTHENTICATED' }, 401);
111
- }
112
-
113
- // Check connection limit
114
- if (!manager.canAccept()) {
115
- logSyncEvent({
116
- event: 'proxy.rejected',
117
- userId: auth.actorId,
118
- reason: 'max_connections',
119
- });
120
- return c.json({ error: 'PROXY_CONNECTION_LIMIT' }, 429);
121
- }
122
-
123
- logSyncEvent({
124
- event: 'proxy.connect',
125
- userId: auth.actorId,
126
- });
127
-
128
- return config.upgradeWebSocket(c, {
129
- onOpen(_evt, _ws) {
130
- // Connection opened, wait for handshake message
131
- },
132
-
133
- async onMessage(evt, ws) {
134
- try {
135
- const data =
136
- typeof evt.data === 'string'
137
- ? evt.data
138
- : new TextDecoder().decode(evt.data as ArrayBuffer);
139
-
140
- const message = JSON.parse(data);
141
-
142
- // Handle handshake
143
- if (message.type === 'handshake') {
144
- const handshake = message as ProxyHandshake;
145
-
146
- // Validate that the handshake actor matches authenticated actor
147
- if (handshake.actorId !== auth.actorId) {
148
- const ack: ProxyHandshakeAck = {
149
- type: 'handshake_ack',
150
- ok: false,
151
- error: 'Actor ID mismatch',
152
- };
153
- ws.send(JSON.stringify(ack));
154
- ws.close(4001, 'Unauthorized');
155
- return;
156
- }
157
-
158
- manager.register(ws, handshake);
159
-
160
- const ack: ProxyHandshakeAck = {
161
- type: 'handshake_ack',
162
- ok: true,
163
- };
164
- ws.send(JSON.stringify(ack));
165
- return;
166
- }
167
-
168
- // Handle proxy messages
169
- const proxyMessage = message as ProxyMessage;
170
- const response = await manager.handleMessage(ws, proxyMessage);
171
- ws.send(JSON.stringify(response));
172
- } catch (err) {
173
- // Send error response if we can parse the message ID
174
- try {
175
- const parsed = JSON.parse(
176
- typeof evt.data === 'string'
177
- ? evt.data
178
- : new TextDecoder().decode(evt.data as ArrayBuffer)
179
- );
180
- if (parsed.id) {
181
- ws.send(
182
- JSON.stringify({
183
- id: parsed.id,
184
- type: 'error',
185
- error: err instanceof Error ? err.message : 'Unknown error',
186
- })
187
- );
188
- }
189
- } catch {
190
- // Ignore parse errors
191
- }
192
- }
193
- },
194
-
195
- async onClose(_evt, ws) {
196
- await manager.unregister(ws);
197
- logSyncEvent({
198
- event: 'proxy.disconnect',
199
- userId: auth.actorId,
200
- });
201
- },
202
-
203
- async onError(_evt, ws) {
204
- await manager.unregister(ws);
205
- logSyncEvent({
206
- event: 'proxy.error',
207
- userId: auth.actorId,
208
- });
209
- },
210
- });
211
- });
212
-
213
- return app;
214
- }
215
-
216
- /**
217
- * Get the ProxyConnectionManager from a proxy routes instance.
218
- */
219
- export function getProxyConnectionManager(
220
- routes: Hono
221
- ): ProxyConnectionManagerHandle | undefined {
222
- return proxyConnectionManagerMap.get(routes);
223
- }
package/src/rate-limit.ts DELETED
@@ -1,321 +0,0 @@
1
- /**
2
- * @syncular/server-hono - Rate limiting middleware for sync endpoints
3
- *
4
- * Provides per-user rate limiting to prevent DoS attacks and excessive
5
- * server load from misbehaving clients.
6
- */
7
-
8
- import { logSyncEvent } from '@syncular/core';
9
- import type { Context, MiddlewareHandler } from 'hono';
10
-
11
- /**
12
- * Rate limit configuration
13
- */
14
- export interface RateLimitConfig {
15
- /**
16
- * Maximum requests per window (default: 60)
17
- */
18
- maxRequests: number;
19
-
20
- /**
21
- * Time window in milliseconds (default: 60000 = 1 minute)
22
- */
23
- windowMs: number;
24
-
25
- /**
26
- * Function to extract the rate limit key from a request.
27
- * Typically returns userId, deviceId, or IP address.
28
- * Return null to skip rate limiting for this request.
29
- */
30
- keyGenerator: (c: Context) => string | null | Promise<string | null>;
31
-
32
- /**
33
- * Whether to include rate limit headers in responses (default: true)
34
- */
35
- includeHeaders?: boolean;
36
-
37
- /**
38
- * Custom handler for rate-limited requests (optional)
39
- * If not provided, returns a 429 JSON response
40
- */
41
- onRateLimited?: (
42
- c: Context,
43
- retryAfterMs: number
44
- ) => Response | Promise<Response>;
45
-
46
- /**
47
- * Whether to skip rate limiting in test environments (default: false)
48
- */
49
- skipInTest?: boolean;
50
- }
51
-
52
- /**
53
- * Default rate limit configuration
54
- */
55
- const DEFAULT_RATE_LIMIT_CONFIG: Omit<RateLimitConfig, 'keyGenerator'> = {
56
- maxRequests: 60,
57
- windowMs: 60_000,
58
- includeHeaders: true,
59
- skipInTest: false,
60
- };
61
-
62
- /**
63
- * Rate limit entry for tracking request counts
64
- */
65
- interface RateLimitEntry {
66
- /** Request count in current window */
67
- count: number;
68
- /** Window start timestamp */
69
- windowStart: number;
70
- }
71
-
72
- /**
73
- * In-memory rate limiter store
74
- *
75
- * Note: This is suitable for single-instance deployments.
76
- * For distributed deployments, use Redis or similar.
77
- */
78
- class RateLimitStore {
79
- private entries = new Map<string, RateLimitEntry>();
80
- private cleanupInterval: ReturnType<typeof setInterval> | null = null;
81
-
82
- constructor(private windowMs: number) {
83
- // Clean up expired entries periodically
84
- this.cleanupInterval = setInterval(
85
- () => this.cleanup(),
86
- Math.max(windowMs, 60_000)
87
- );
88
- }
89
-
90
- /**
91
- * Check and increment the rate limit counter for a key.
92
- *
93
- * @param key - Rate limit key (e.g., userId)
94
- * @param maxRequests - Maximum requests allowed
95
- * @returns Rate limit check result
96
- */
97
- check(
98
- key: string,
99
- maxRequests: number
100
- ): {
101
- allowed: boolean;
102
- current: number;
103
- remaining: number;
104
- resetAt: number;
105
- } {
106
- const now = Date.now();
107
- let entry = this.entries.get(key);
108
-
109
- // Check if window has expired
110
- if (!entry || now - entry.windowStart >= this.windowMs) {
111
- entry = { count: 0, windowStart: now };
112
- this.entries.set(key, entry);
113
- }
114
-
115
- const resetAt = entry.windowStart + this.windowMs;
116
- const allowed = entry.count < maxRequests;
117
-
118
- if (allowed) {
119
- entry.count++;
120
- }
121
-
122
- return {
123
- allowed,
124
- current: entry.count,
125
- remaining: Math.max(0, maxRequests - entry.count),
126
- resetAt,
127
- };
128
- }
129
-
130
- /**
131
- * Clean up expired entries
132
- */
133
- cleanup(): void {
134
- const now = Date.now();
135
- for (const [key, entry] of this.entries) {
136
- if (now - entry.windowStart >= this.windowMs) {
137
- this.entries.delete(key);
138
- }
139
- }
140
- }
141
-
142
- /**
143
- * Stop the cleanup interval
144
- */
145
- stop(): void {
146
- if (this.cleanupInterval) {
147
- clearInterval(this.cleanupInterval);
148
- this.cleanupInterval = null;
149
- }
150
- }
151
-
152
- /**
153
- * Clear all entries (for testing)
154
- */
155
- clear(): void {
156
- this.entries.clear();
157
- }
158
-
159
- /**
160
- * Get current entry count (for monitoring)
161
- */
162
- get size(): number {
163
- return this.entries.size;
164
- }
165
- }
166
-
167
- // Track created stores so tests can reset state deterministically.
168
- const activeStores = new Set<RateLimitStore>();
169
-
170
- /**
171
- * Reset the global store (for testing)
172
- */
173
- export function resetRateLimitStore(): void {
174
- for (const store of activeStores) {
175
- store.stop();
176
- }
177
- activeStores.clear();
178
- }
179
-
180
- /**
181
- * Create a rate limiting middleware for Hono.
182
- *
183
- * @example
184
- * ```typescript
185
- * import { createRateLimiter } from '@syncular/server-hono';
186
- *
187
- * const rateLimiter = createRateLimiter({
188
- * maxRequests: 60,
189
- * windowMs: 60_000,
190
- * keyGenerator: async (c) => {
191
- * const auth = await authenticate(c);
192
- * return auth?.userId ?? null;
193
- * },
194
- * });
195
- *
196
- * app.use('/sync/*', rateLimiter);
197
- * ```
198
- */
199
- export function createRateLimiter(
200
- config: Partial<RateLimitConfig> & Pick<RateLimitConfig, 'keyGenerator'>
201
- ): MiddlewareHandler {
202
- const {
203
- maxRequests = DEFAULT_RATE_LIMIT_CONFIG.maxRequests,
204
- windowMs = DEFAULT_RATE_LIMIT_CONFIG.windowMs,
205
- keyGenerator,
206
- includeHeaders = DEFAULT_RATE_LIMIT_CONFIG.includeHeaders,
207
- onRateLimited,
208
- skipInTest = DEFAULT_RATE_LIMIT_CONFIG.skipInTest,
209
- } = config;
210
-
211
- const store = new RateLimitStore(windowMs);
212
- activeStores.add(store);
213
-
214
- return async (c, next) => {
215
- // Skip in test environment if configured
216
- if (skipInTest && process.env.NODE_ENV === 'test') {
217
- return next();
218
- }
219
-
220
- // Get the rate limit key
221
- const key = await keyGenerator(c);
222
- if (key === null) {
223
- // Skip rate limiting for this request
224
- return next();
225
- }
226
-
227
- const result = store.check(key, maxRequests);
228
-
229
- // Add rate limit headers if configured
230
- if (includeHeaders) {
231
- c.header('X-RateLimit-Limit', String(maxRequests));
232
- c.header('X-RateLimit-Remaining', String(result.remaining));
233
- c.header('X-RateLimit-Reset', String(Math.ceil(result.resetAt / 1000)));
234
- }
235
-
236
- if (!result.allowed) {
237
- const retryAfterMs = result.resetAt - Date.now();
238
- const retryAfterSec = Math.ceil(retryAfterMs / 1000);
239
-
240
- // Log rate limit event
241
- logSyncEvent({
242
- event: 'sync.rate_limit',
243
- key,
244
- current: result.current,
245
- maxRequests,
246
- retryAfterMs,
247
- });
248
-
249
- // Add Retry-After header
250
- c.header('Retry-After', String(retryAfterSec));
251
-
252
- // Use custom handler or default response
253
- if (onRateLimited) {
254
- return onRateLimited(c, retryAfterMs);
255
- }
256
-
257
- return c.json(
258
- {
259
- error: 'RATE_LIMITED',
260
- message: 'Too many requests. Please try again later.',
261
- retryAfterMs,
262
- retryAfterSec,
263
- },
264
- 429
265
- );
266
- }
267
-
268
- return next();
269
- };
270
- }
271
-
272
- /**
273
- * Create a rate limiter that uses userId from auth context.
274
- *
275
- * This is a convenience function for the common case of rate limiting
276
- * by authenticated user.
277
- *
278
- * @example
279
- * ```typescript
280
- * const syncRoutes = createSyncRoutes({
281
- * db,
282
- * handlers: [tasksHandler],
283
- * authenticate,
284
- * sync: {
285
- * rateLimit: {
286
- * pull: { maxRequests: 120, windowMs: 60_000 },
287
- * push: { maxRequests: 60, windowMs: 60_000 },
288
- * },
289
- * },
290
- * });
291
- * ```
292
- */
293
- export interface SyncRateLimitConfig {
294
- /**
295
- * Rate limit config for pull requests.
296
- * Set to false to disable rate limiting for pulls.
297
- */
298
- pull?: Omit<RateLimitConfig, 'keyGenerator'> | false;
299
-
300
- /**
301
- * Rate limit config for push requests.
302
- * Set to false to disable rate limiting for pushes.
303
- */
304
- push?: Omit<RateLimitConfig, 'keyGenerator'> | false;
305
- }
306
-
307
- /**
308
- * Default sync rate limit configuration
309
- */
310
- export const DEFAULT_SYNC_RATE_LIMITS: SyncRateLimitConfig = {
311
- pull: {
312
- maxRequests: 120, // 2 requests per second average
313
- windowMs: 60_000,
314
- includeHeaders: true,
315
- },
316
- push: {
317
- maxRequests: 60, // 1 request per second average
318
- windowMs: 60_000,
319
- includeHeaders: true,
320
- },
321
- };