@enbox/dwn-server 0.0.6 → 0.0.8

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 (92) hide show
  1. package/dist/esm/src/admin/admin-api.d.ts +5 -1
  2. package/dist/esm/src/admin/admin-api.d.ts.map +1 -1
  3. package/dist/esm/src/admin/admin-api.js +327 -7
  4. package/dist/esm/src/admin/admin-api.js.map +1 -1
  5. package/dist/esm/src/admin/admin-auth.d.ts +21 -3
  6. package/dist/esm/src/admin/admin-auth.d.ts.map +1 -1
  7. package/dist/esm/src/admin/admin-auth.js +17 -9
  8. package/dist/esm/src/admin/admin-auth.js.map +1 -1
  9. package/dist/esm/src/admin/admin-passkey-store.d.ts +68 -0
  10. package/dist/esm/src/admin/admin-passkey-store.d.ts.map +1 -0
  11. package/dist/esm/src/admin/admin-passkey-store.js +132 -0
  12. package/dist/esm/src/admin/admin-passkey-store.js.map +1 -0
  13. package/dist/esm/src/admin/admin-session.d.ts +35 -0
  14. package/dist/esm/src/admin/admin-session.d.ts.map +1 -0
  15. package/dist/esm/src/admin/admin-session.js +91 -0
  16. package/dist/esm/src/admin/admin-session.js.map +1 -0
  17. package/dist/esm/src/admin/audit-log.d.ts.map +1 -1
  18. package/dist/esm/src/admin/audit-log.js +5 -43
  19. package/dist/esm/src/admin/audit-log.js.map +1 -1
  20. package/dist/esm/src/admin/index.d.ts +5 -1
  21. package/dist/esm/src/admin/index.d.ts.map +1 -1
  22. package/dist/esm/src/admin/index.js +2 -0
  23. package/dist/esm/src/admin/index.js.map +1 -1
  24. package/dist/esm/src/admin/types.d.ts +22 -0
  25. package/dist/esm/src/admin/types.d.ts.map +1 -1
  26. package/dist/esm/src/admin/webhook-manager.d.ts.map +1 -1
  27. package/dist/esm/src/admin/webhook-manager.js +11 -10
  28. package/dist/esm/src/admin/webhook-manager.js.map +1 -1
  29. package/dist/esm/src/config.d.ts +18 -0
  30. package/dist/esm/src/config.d.ts.map +1 -1
  31. package/dist/esm/src/config.js +18 -0
  32. package/dist/esm/src/config.js.map +1 -1
  33. package/dist/esm/src/dwn-server.d.ts +20 -1
  34. package/dist/esm/src/dwn-server.d.ts.map +1 -1
  35. package/dist/esm/src/dwn-server.js +111 -52
  36. package/dist/esm/src/dwn-server.js.map +1 -1
  37. package/dist/esm/src/http-api.d.ts +4 -0
  38. package/dist/esm/src/http-api.d.ts.map +1 -1
  39. package/dist/esm/src/http-api.js +14 -4
  40. package/dist/esm/src/http-api.js.map +1 -1
  41. package/dist/esm/src/index.d.ts +2 -0
  42. package/dist/esm/src/index.d.ts.map +1 -1
  43. package/dist/esm/src/index.js +2 -0
  44. package/dist/esm/src/index.js.map +1 -1
  45. package/dist/esm/src/migrations/001-initial-server-schema.d.ts +21 -0
  46. package/dist/esm/src/migrations/001-initial-server-schema.d.ts.map +1 -0
  47. package/dist/esm/src/migrations/001-initial-server-schema.js +97 -0
  48. package/dist/esm/src/migrations/001-initial-server-schema.js.map +1 -0
  49. package/dist/esm/src/migrations/index.d.ts +13 -0
  50. package/dist/esm/src/migrations/index.d.ts.map +1 -0
  51. package/dist/esm/src/migrations/index.js +5 -0
  52. package/dist/esm/src/migrations/index.js.map +1 -0
  53. package/dist/esm/src/registration/registration-store.d.ts +4 -0
  54. package/dist/esm/src/registration/registration-store.d.ts.map +1 -1
  55. package/dist/esm/src/registration/registration-store.js +11 -34
  56. package/dist/esm/src/registration/registration-store.js.map +1 -1
  57. package/dist/esm/src/server-migration-runner.d.ts +23 -0
  58. package/dist/esm/src/server-migration-runner.d.ts.map +1 -0
  59. package/dist/esm/src/server-migration-runner.js +57 -0
  60. package/dist/esm/src/server-migration-runner.js.map +1 -0
  61. package/dist/esm/src/storage.d.ts +15 -0
  62. package/dist/esm/src/storage.d.ts.map +1 -1
  63. package/dist/esm/src/storage.js +135 -17
  64. package/dist/esm/src/storage.js.map +1 -1
  65. package/dist/esm/src/web5-connect/sql-ttl-cache.d.ts +11 -1
  66. package/dist/esm/src/web5-connect/sql-ttl-cache.d.ts.map +1 -1
  67. package/dist/esm/src/web5-connect/sql-ttl-cache.js +19 -20
  68. package/dist/esm/src/web5-connect/sql-ttl-cache.js.map +1 -1
  69. package/dist/esm/src/web5-connect/web5-connect-server.d.ts +10 -3
  70. package/dist/esm/src/web5-connect/web5-connect-server.d.ts.map +1 -1
  71. package/dist/esm/src/web5-connect/web5-connect-server.js +10 -4
  72. package/dist/esm/src/web5-connect/web5-connect-server.js.map +1 -1
  73. package/package.json +3 -2
  74. package/src/admin/admin-api.ts +403 -10
  75. package/src/admin/admin-auth.ts +38 -9
  76. package/src/admin/admin-passkey-store.ts +190 -0
  77. package/src/admin/admin-session.ts +116 -0
  78. package/src/admin/audit-log.ts +7 -44
  79. package/src/admin/index.ts +5 -0
  80. package/src/admin/types.ts +28 -0
  81. package/src/admin/webhook-manager.ts +12 -10
  82. package/src/config.ts +21 -0
  83. package/src/dwn-server.ts +137 -55
  84. package/src/http-api.ts +20 -5
  85. package/src/index.ts +2 -0
  86. package/src/migrations/001-initial-server-schema.ts +114 -0
  87. package/src/migrations/index.ts +18 -0
  88. package/src/registration/registration-store.ts +13 -36
  89. package/src/server-migration-runner.ts +74 -0
  90. package/src/storage.ts +145 -17
  91. package/src/web5-connect/sql-ttl-cache.ts +21 -22
  92. package/src/web5-connect/web5-connect-server.ts +14 -5
package/src/storage.ts CHANGED
@@ -20,6 +20,7 @@ import { Kysely } from 'kysely';
20
20
 
21
21
  import { createBunSqliteDatabase } from '@enbox/dwn-sql-store';
22
22
  import { PluginLoader } from './plugin-loader.js';
23
+ import { runServerMigrations } from './server-migration-runner.js';
23
24
 
24
25
  import {
25
26
  DataStoreLevel,
@@ -55,26 +56,27 @@ export enum BackendTypes {
55
56
  export type DwnStore = DataStore | StateIndex | MessageStore | ResumableTaskStore;
56
57
 
57
58
  /**
58
- * Cache of shared PostgreSQL dialects keyed by connection URL. When multiple
59
- * DWN stores share the same Postgres URL, they reuse a single dialect (and
60
- * thus a single `pg.Pool`) instead of each creating their own. This reduces
61
- * connection count from 4 × pool_max to 1 × pool_max per DWN process.
59
+ * Returns a (potentially cached) dialect for the given connection URL. For
60
+ * Postgres, creates a pool with configurable sizing from the server config.
61
+ * For other backends, delegates to `getDialectFromUrl()` which handles its
62
+ * own caching (critical for in-memory SQLite).
63
+ *
64
+ * All Postgres dialects are cached in a separate map keyed by URL so that
65
+ * multiple DWN stores sharing the same Postgres URL reuse a single
66
+ * `pg.Pool`, reducing connection count from 4 × pool_max to 1 × pool_max.
62
67
  */
63
- const sharedDialectCache: Map<string, Dialect> = new Map();
68
+ const postgresDialectCache: Map<string, Dialect> = new Map();
64
69
 
65
- /**
66
- * Returns a (potentially cached) dialect for the given Postgres connection URL.
67
- * Non-Postgres URLs always return a fresh dialect (no caching).
68
- */
69
70
  function getOrCreateDialect(connectionUrl: URL, config: DwnServerConfig): Dialect {
70
71
  const protocol = connectionUrl.protocol.slice(0, -1);
71
72
 
72
73
  if (protocol !== BackendTypes.POSTGRES) {
74
+ // getDialectFromUrl handles its own caching for SQLite/MySQL.
73
75
  return getDialectFromUrl(connectionUrl);
74
76
  }
75
77
 
76
78
  const key = connectionUrl.toString();
77
- const cached = sharedDialectCache.get(key);
79
+ const cached = postgresDialectCache.get(key);
78
80
  if (cached !== undefined) {
79
81
  return cached;
80
82
  }
@@ -92,7 +94,7 @@ function getOrCreateDialect(connectionUrl: URL, config: DwnServerConfig): Dialec
92
94
  cursor : Cursor,
93
95
  });
94
96
 
95
- sharedDialectCache.set(key, dialect);
97
+ postgresDialectCache.set(key, dialect);
96
98
  return dialect;
97
99
  }
98
100
 
@@ -152,13 +154,99 @@ async function runSqlMigrationsIfNeeded(config: DwnServerConfig): Promise<void>
152
154
  console.log(`DWN migrations applied: ${applied.join(', ')}`);
153
155
  }
154
156
  } finally {
155
- // Don't destroy the Kysely instance if using a shared Postgres pool
156
- // the pool is cached in sharedDialectCache and will be reused by stores.
157
- // Only destroy for non-cached dialects (SQLite, MySQL).
158
- if (protocol !== BackendTypes.POSTGRES) {
159
- await db.destroy();
157
+ // Do NOT destroy the Kysely instance the dialect is cached and will be
158
+ // reused by stores. For in-memory SQLite, destroying would close the
159
+ // database and lose all migrated schema. For Postgres, the pool is shared.
160
+ }
161
+ }
162
+
163
+ /**
164
+ * Runs DWN server schema migrations (admin stores, registration, TTL cache)
165
+ * if the given URL points to a SQL backend. Uses the `registrationStoreUrl`
166
+ * (or the TTL cache URL) as the target database.
167
+ *
168
+ * Server migrations use a separate tracking table (`dwn_server_migration`)
169
+ * so they do not conflict with the DWN store migrations.
170
+ *
171
+ * Call this once during server startup, before creating admin stores.
172
+ *
173
+ * @returns The dialect used for the target database (so the caller can reuse
174
+ * it for the TTL cache and admin stores), or `undefined` if no SQL
175
+ * backend was configured or needed.
176
+ */
177
+ export async function runServerMigrationsIfNeeded(config: DwnServerConfig): Promise<Dialect | undefined> {
178
+ const sqlBackends: string[] = [BackendTypes.SQLITE, BackendTypes.MYSQL, BackendTypes.POSTGRES];
179
+
180
+ // Determine the target URL for server migrations. Prefer registrationStoreUrl
181
+ // since admin stores and the TTL cache share that database. Fall back to
182
+ // ttlCacheUrl when no registration store is configured (the cacheEntries
183
+ // table still needs a schema).
184
+ const targetUrl = config.registrationStoreUrl ?? config.ttlCacheUrl;
185
+ if (!targetUrl) {
186
+ return undefined;
187
+ }
188
+
189
+ if (isFilePath(targetUrl)) {
190
+ return undefined;
191
+ }
192
+
193
+ let parsedUrl: URL;
194
+ try {
195
+ parsedUrl = new URL(targetUrl);
196
+ } catch {
197
+ return undefined;
198
+ }
199
+
200
+ const protocol = parsedUrl.protocol.slice(0, -1);
201
+ if (!sqlBackends.includes(protocol)) {
202
+ return undefined;
203
+ }
204
+
205
+ // When both registrationStoreUrl and ttlCacheUrl are set and differ,
206
+ // validate they point at the same database — the cacheEntries table is
207
+ // included in the server migration so it must live alongside the other
208
+ // server tables.
209
+ if (config.registrationStoreUrl && config.ttlCacheUrl
210
+ && config.ttlCacheUrl !== config.registrationStoreUrl) {
211
+ let ttlUrl: URL | undefined;
212
+ try {
213
+ ttlUrl = new URL(config.ttlCacheUrl);
214
+ } catch { /* not a URL */ }
215
+
216
+ if (ttlUrl) {
217
+ const ttlProtocol = ttlUrl.protocol.slice(0, -1);
218
+ if (sqlBackends.includes(ttlProtocol)) {
219
+ throw new Error(
220
+ 'DWN server misconfiguration: DWN_TTL_CACHE_URL must point to the same database as ' +
221
+ 'DWN_REGISTRATION_STORE_URL (or DWN_STORAGE) because the cacheEntries table is managed ' +
222
+ 'by the server migration system. ' +
223
+ `Got registrationStoreUrl="${config.registrationStoreUrl}", ttlCacheUrl="${config.ttlCacheUrl}".`
224
+ );
225
+ }
226
+ }
227
+ }
228
+
229
+ const dialect = getOrCreateDialect(parsedUrl, config);
230
+ const db = new Kysely<Record<string, unknown>>({ dialect });
231
+ try {
232
+ const applied = await runServerMigrations(db, dialect);
233
+ if (applied.length > 0) {
234
+ console.log(`Server migrations applied: ${applied.join(', ')}`);
235
+ }
236
+ } finally {
237
+ // For Postgres, don't destroy — the pool is cached in sharedDialectCache.
238
+ // For SQLite/MySQL, we also keep the Kysely instance alive so the caller
239
+ // can reuse the same dialect (critical for in-memory SQLite).
240
+ if (protocol === BackendTypes.POSTGRES) {
241
+ // Pool stays alive via sharedDialectCache.
160
242
  }
243
+ // NOTE: We intentionally do NOT destroy the Kysely instance for any
244
+ // backend. The dialect is returned to the caller for reuse (e.g. by the
245
+ // TTL cache and admin stores). For in-memory SQLite, destroying would
246
+ // lose the database.
161
247
  }
248
+
249
+ return dialect;
162
250
  }
163
251
 
164
252
  function getLevelStore(
@@ -264,6 +352,21 @@ async function loadStoreFromFilePath(
264
352
  }
265
353
  }
266
354
 
355
+ /**
356
+ * Cache for the in-memory SQLite dialect. Since every call to
357
+ * `createBunSqliteDatabase(':memory:')` creates a separate, empty database,
358
+ * we must ensure that `getDialectFromUrl(new URL('sqlite://'))` always
359
+ * returns the same dialect (and thus the same underlying database) within a
360
+ * process. This is critical for the DWN server startup flow where migrations,
361
+ * the registration store, and the TTL cache all need to share the same
362
+ * in-memory database.
363
+ *
364
+ * File-based SQLite and other backends are NOT cached here — file-based SQLite
365
+ * connections naturally share state through the filesystem, and caching would
366
+ * break test isolation when multiple test files run in the same process.
367
+ */
368
+ let inMemorySqliteDialect: Dialect | undefined;
369
+
267
370
  export function getDialectFromUrl(connectionUrl: URL): Dialect {
268
371
  switch (connectionUrl.protocol.slice(0, -1)) {
269
372
  case BackendTypes.SQLITE: {
@@ -275,9 +378,32 @@ export function getDialectFromUrl(connectionUrl: URL): Dialect {
275
378
  fs.mkdirSync(connectionUrl.host, { recursive: true });
276
379
  }
277
380
 
278
- // Use in-memory database if no path is provided (for tests)
381
+ // Use in-memory database if no path is provided (for tests).
279
382
  const dbPath = path || ':memory:';
280
383
 
384
+ // For in-memory SQLite, return a cached dialect so that all callers
385
+ // (migrations, registration store, TTL cache) share the same database.
386
+ // The wrapper makes close() a no-op so that individual consumers (e.g.
387
+ // DwnServer.stop() → Dwn.close() → store.close()) cannot destroy the
388
+ // shared database out from under other consumers.
389
+ if (dbPath === ':memory:') {
390
+ if (inMemorySqliteDialect === undefined) {
391
+ const sharedDb = createBunSqliteDatabase(':memory:');
392
+ const nonCloseableDb = {
393
+ close(): void {
394
+ // no-op — shared instance must survive the process
395
+ },
396
+ prepare(sql: string): ReturnType<typeof sharedDb.prepare> {
397
+ return sharedDb.prepare(sql);
398
+ },
399
+ };
400
+ inMemorySqliteDialect = new SqliteDialect({
401
+ database: async (): Promise<typeof nonCloseableDb> => nonCloseableDb,
402
+ });
403
+ }
404
+ return inMemorySqliteDialect;
405
+ }
406
+
281
407
  return new SqliteDialect({
282
408
  database: async () => createBunSqliteDatabase(dbPath),
283
409
  });
@@ -291,6 +417,8 @@ export function getDialectFromUrl(connectionUrl: URL): Dialect {
291
417
  pool : async () => new pg.Pool({ connectionString: connectionUrl.toString() }),
292
418
  cursor : Cursor,
293
419
  });
420
+ default:
421
+ throw new Error(`Unsupported database protocol: ${connectionUrl.protocol}`);
294
422
  }
295
423
  }
296
424
 
@@ -1,5 +1,5 @@
1
1
  import type { Dialect } from '@enbox/dwn-sql-store';
2
- import { Kysely } from 'kysely';
2
+ import { Kysely, sql } from 'kysely';
3
3
 
4
4
  /**
5
5
  * The SqlTtlCache is responsible for storing and retrieving cache data with TTL (Time-to-Live).
@@ -8,13 +8,11 @@ export class SqlTtlCache {
8
8
  private static readonly cacheTableName = 'cacheEntries';
9
9
  private static readonly cleanupIntervalInSeconds = 60;
10
10
 
11
- private sqlDialect: Dialect;
12
11
  private db: Kysely<CacheDatabase>;
13
12
  private cleanupTimer: NodeJS.Timeout;
14
13
 
15
14
  private constructor(sqlDialect: Dialect) {
16
15
  this.db = new Kysely<CacheDatabase>({ dialect: sqlDialect });
17
- this.sqlDialect = sqlDialect;
18
16
  }
19
17
 
20
18
  /**
@@ -28,26 +26,17 @@ export class SqlTtlCache {
28
26
  return cacheManager;
29
27
  }
30
28
 
29
+ /**
30
+ * Verifies that the required table exists and starts the cleanup timer.
31
+ * Throws a clear error directing the caller to run server migrations first.
32
+ */
31
33
  private async initialize(): Promise<void> {
32
-
33
- // create table if it doesn't exist
34
- const tableExists = await this.sqlDialect.hasTable(this.db, SqlTtlCache.cacheTableName);
35
- if (!tableExists) {
36
- await this.db.schema
37
- .createTable(SqlTtlCache.cacheTableName)
38
- .ifNotExists() // kept to show supported by all dialects in contrast to ifNotExists() below, though not needed due to tableExists check above
39
- // 512 chars to accommodate potentially large `state` in Web5 Connect flow
40
- .addColumn('key', 'varchar(512)', (column) => column.primaryKey())
41
- .addColumn('value', 'text', (column) => column.notNull())
42
- .addColumn('expiry', 'bigint', (column) => column.notNull())
43
- .execute();
44
-
45
- await this.db.schema
46
- .createIndex('index_expiry')
47
- // .ifNotExists() // intentionally kept commented out code to show that it is not supported by all dialects (ie. MySQL)
48
- .on(SqlTtlCache.cacheTableName)
49
- .column('expiry')
50
- .execute();
34
+ try {
35
+ await sql`SELECT 1 FROM ${sql.table(SqlTtlCache.cacheTableName)} LIMIT 0`.execute(this.db);
36
+ } catch {
37
+ throw new Error(
38
+ `SqlTtlCache: table '${SqlTtlCache.cacheTableName}' does not exist. Run server migrations before starting.`
39
+ );
51
40
  }
52
41
 
53
42
  // Start the cleanup timer
@@ -131,6 +120,16 @@ export class SqlTtlCache {
131
120
  .where('expiry', '<', Date.now())
132
121
  .execute();
133
122
  }
123
+
124
+ /**
125
+ * Stops the background cleanup timer. The underlying database connection is
126
+ * NOT destroyed here because the dialect is shared with other components
127
+ * (e.g. DWN stores, registration store) and its lifecycle is managed by the
128
+ * dialect owner.
129
+ */
130
+ public close(): void {
131
+ clearInterval(this.cleanupTimer);
132
+ }
134
133
  }
135
134
 
136
135
  interface CacheEntry {
@@ -1,6 +1,7 @@
1
+ import type { Dialect } from '@enbox/dwn-sql-store';
2
+
1
3
  import { CryptoUtils } from '@enbox/crypto';
2
4
 
3
- import { getDialectFromUrl } from '../storage.js';
4
5
  import { SqlTtlCache } from './sql-ttl-cache.js';
5
6
 
6
7
  /**
@@ -41,16 +42,16 @@ export class Web5ConnectServer {
41
42
  * Creates a new instance of the Web5 Connect Server.
42
43
  * @param params.baseUrl The the base URL of the connect server including the port.
43
44
  * This is given to the Identity Provider (wallet) to fetch the Web5 Connect Request object.
44
- * @param params.sqlTtlCacheUrl The URL of the SQL database to use as the TTL cache.
45
+ * @param params.sqlDialect The SQL dialect to use for the TTL cache. Must point to a database
46
+ * where server migrations have already been run.
45
47
  */
46
- public static async create({ baseUrl, sqlTtlCacheUrl }: {
48
+ public static async create({ baseUrl, sqlDialect }: {
47
49
  baseUrl: string;
48
- sqlTtlCacheUrl: string;
50
+ sqlDialect: Dialect;
49
51
  }): Promise<Web5ConnectServer> {
50
52
  const web5ConnectServer = new Web5ConnectServer({ baseUrl });
51
53
 
52
54
  // Initialize TTL cache.
53
- const sqlDialect = getDialectFromUrl(new URL(sqlTtlCacheUrl));
54
55
  web5ConnectServer.cache = await SqlTtlCache.create(sqlDialect);
55
56
 
56
57
  return web5ConnectServer;
@@ -120,4 +121,12 @@ export class Web5ConnectServer {
120
121
 
121
122
  return response;
122
123
  }
124
+
125
+ /**
126
+ * Stops the TTL cache cleanup timer. Must be called during shutdown to
127
+ * prevent leaked timers.
128
+ */
129
+ public close(): void {
130
+ this.cache.close();
131
+ }
123
132
  }