trustline 0.0.1 → 0.1.0

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 (62) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +339 -0
  3. package/dist/adapters/mysql/index.cjs +199 -0
  4. package/dist/adapters/mysql/index.cjs.map +1 -0
  5. package/dist/adapters/mysql/index.d.cts +6 -0
  6. package/dist/adapters/mysql/index.d.ts +6 -0
  7. package/dist/adapters/mysql/index.js +21 -0
  8. package/dist/adapters/mysql/index.js.map +1 -0
  9. package/dist/adapters/postgres/index.cjs +199 -0
  10. package/dist/adapters/postgres/index.cjs.map +1 -0
  11. package/dist/adapters/postgres/index.d.cts +6 -0
  12. package/dist/adapters/postgres/index.d.ts +6 -0
  13. package/dist/adapters/postgres/index.js +21 -0
  14. package/dist/adapters/postgres/index.js.map +1 -0
  15. package/dist/adapters/sqlite/index.cjs +216 -0
  16. package/dist/adapters/sqlite/index.cjs.map +1 -0
  17. package/dist/adapters/sqlite/index.d.cts +6 -0
  18. package/dist/adapters/sqlite/index.d.ts +6 -0
  19. package/dist/adapters/sqlite/index.js +28 -0
  20. package/dist/adapters/sqlite/index.js.map +1 -0
  21. package/dist/chunk-CTPFKR4O.js +157 -0
  22. package/dist/chunk-CTPFKR4O.js.map +1 -0
  23. package/dist/chunk-GF3NKEEK.js +18 -0
  24. package/dist/chunk-GF3NKEEK.js.map +1 -0
  25. package/dist/client/index.cjs +141 -0
  26. package/dist/client/index.cjs.map +1 -0
  27. package/dist/client/index.d.cts +18 -0
  28. package/dist/client/index.d.ts +18 -0
  29. package/dist/client/index.js +104 -0
  30. package/dist/client/index.js.map +1 -0
  31. package/dist/frameworks/express/index.cjs +121 -0
  32. package/dist/frameworks/express/index.cjs.map +1 -0
  33. package/dist/frameworks/express/index.d.cts +18 -0
  34. package/dist/frameworks/express/index.d.ts +18 -0
  35. package/dist/frameworks/express/index.js +83 -0
  36. package/dist/frameworks/express/index.js.map +1 -0
  37. package/dist/frameworks/fastify/index.cjs +158 -0
  38. package/dist/frameworks/fastify/index.cjs.map +1 -0
  39. package/dist/frameworks/fastify/index.d.cts +25 -0
  40. package/dist/frameworks/fastify/index.d.ts +25 -0
  41. package/dist/frameworks/fastify/index.js +120 -0
  42. package/dist/frameworks/fastify/index.js.map +1 -0
  43. package/dist/frameworks/hono/index.cjs +117 -0
  44. package/dist/frameworks/hono/index.cjs.map +1 -0
  45. package/dist/frameworks/hono/index.d.cts +17 -0
  46. package/dist/frameworks/hono/index.d.ts +17 -0
  47. package/dist/frameworks/hono/index.js +79 -0
  48. package/dist/frameworks/hono/index.js.map +1 -0
  49. package/dist/index-Dc4GFume.d.ts +34 -0
  50. package/dist/index-DqkKZOlH.d.cts +34 -0
  51. package/dist/index.cjs +571 -0
  52. package/dist/index.cjs.map +1 -0
  53. package/dist/index.d.cts +14 -0
  54. package/dist/index.d.ts +14 -0
  55. package/dist/index.js +537 -0
  56. package/dist/index.js.map +1 -0
  57. package/dist/interface-BzT_DC3u.d.cts +38 -0
  58. package/dist/interface-BzT_DC3u.d.ts +38 -0
  59. package/dist/token-BtfYGd9K.d.cts +33 -0
  60. package/dist/token-BtfYGd9K.d.ts +33 -0
  61. package/package.json +125 -3
  62. package/index.js +0 -1
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Charles Fonseca
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,339 @@
1
+ # Trustline
2
+
3
+ Service identity and authorization for modern JavaScript runtimes.
4
+
5
+ Trustline is a machine-to-machine authentication library for internal services. It is designed around dedicated core and integration entry points:
6
+
7
+ - `trustline`: provider, guard, memory storage, and shared core exports
8
+ - `trustline/client`: token fetching and caching for outgoing requests
9
+ - `trustline/frameworks/*`: framework adapters for receiving services
10
+ - `trustline/adapters/*`: SQL storage adapters
11
+
12
+ The package now ships the first full stack: provider, client, guard, framework adapters, memory storage, and SQL storage adapters for SQLite, Postgres, and MySQL.
13
+
14
+ ## Current status
15
+
16
+ Available now:
17
+
18
+ - `createProvider(options)`
19
+ - `createClient(options)`
20
+ - `createGuard(options)`
21
+ - `memoryStorage()`
22
+ - `createExpressProvider(provider)`
23
+ - `createExpressGuard(guard)`
24
+ - `createFastifyProvider(provider)`
25
+ - `createFastifyGuard(guard)`
26
+ - `createHonoProvider(provider)`
27
+ - `createHonoGuard(guard)`
28
+ - `sqliteStorage(path | database)`
29
+ - `postgresStorage(pool)`
30
+ - `mysqlStorage(pool)`
31
+
32
+ Implemented behavior:
33
+
34
+ - client credentials token issuance
35
+ - JWKS publishing
36
+ - token caching with proactive refresh and request deduplication
37
+ - issuer, audience, scope, and environment verification
38
+ - JWKS discovery and caching
39
+ - Express, Fastify, and Hono adapters
40
+
41
+ Planned next:
42
+
43
+ - key rotation overlap windows
44
+ - token revocation workflows
45
+ - requested-scope narrowing during issuance
46
+
47
+ ## Installation
48
+
49
+ Trustline is intended to be consumed as the `trustline` package:
50
+
51
+ ```bash
52
+ bun add trustline
53
+ ```
54
+
55
+ Or with npm:
56
+
57
+ ```bash
58
+ npm install trustline
59
+ ```
60
+
61
+ Install only the integrations you use. For example, Express users install `express`; SQLite users install `better-sqlite3` and `kysely`.
62
+
63
+ Example installs:
64
+
65
+ ```bash
66
+ npm install trustline express
67
+ npm install trustline better-sqlite3 kysely
68
+ ```
69
+
70
+ If you are working from this repository before package publication, build the package locally and install or link it from the repo source.
71
+
72
+ ## Releasing
73
+
74
+ Package releases are managed with Changesets and GitHub Actions. Add a changeset in each user-facing PR with:
75
+
76
+ ```bash
77
+ bun run changeset
78
+ ```
79
+
80
+ Merges to `main` update or create a release PR, and merging that release PR publishes to npm. See `RELEASING.md` for the full flow and npm trusted publishing setup.
81
+
82
+ ## Quick start
83
+
84
+ Provider:
85
+
86
+ ```ts
87
+ import { createProvider, memoryStorage } from "trustline";
88
+
89
+ const provider = createProvider({
90
+ issuer: "https://auth.internal",
91
+ storage: memoryStorage(),
92
+ env: "production",
93
+ });
94
+
95
+ const service = await provider.clients.create({
96
+ name: "order-processor",
97
+ scopes: ["read:orders", "write:inventory"],
98
+ });
99
+ ```
100
+
101
+ Client:
102
+
103
+ ```ts
104
+ import { createClient } from "trustline/client";
105
+
106
+ const client = createClient({
107
+ tokenUrl: "https://auth.internal/token",
108
+ clientId: service.clientId,
109
+ clientSecret: service.clientSecret,
110
+ audience: "inventory-service",
111
+ });
112
+
113
+ const token = await client.getToken();
114
+ ```
115
+
116
+ Guard:
117
+
118
+ ```ts
119
+ import { createGuard } from "trustline";
120
+
121
+ const guard = createGuard({
122
+ issuer: "https://auth.internal",
123
+ audience: "inventory-service",
124
+ scopes: ["read:orders"],
125
+ env: "production",
126
+ });
127
+
128
+ const identity = await guard.verify(token);
129
+ ```
130
+
131
+ Trustline derives the JWKS endpoint automatically for verification:
132
+
133
+ ```txt
134
+ issuer: https://auth.internal
135
+ jwks: https://auth.internal/.well-known/jwks.json
136
+ ```
137
+
138
+ ## Bun
139
+
140
+ Trustline does not need a Bun-specific adapter. Bun already uses the standard Web `Request` and `Response` APIs, so use the provider's `handle()` method directly and call `guard.verify()` inside your `fetch` handler.
141
+
142
+ ```ts
143
+ import { createGuard, createProvider, memoryStorage } from "trustline";
144
+
145
+ const provider = createProvider({
146
+ issuer: "https://auth.internal",
147
+ storage: memoryStorage(),
148
+ });
149
+
150
+ Bun.serve({
151
+ port: 3000,
152
+ fetch: provider.handle,
153
+ });
154
+
155
+ const guard = createGuard({
156
+ issuer: "https://auth.internal",
157
+ audience: "inventory-service",
158
+ });
159
+
160
+ Bun.serve({
161
+ port: 4000,
162
+ fetch: async (request) => {
163
+ const header = request.headers.get("authorization");
164
+ const token = header?.replace(/^Bearer\s+/, "") ?? "";
165
+ const identity = await guard.verify(token);
166
+
167
+ return Response.json({
168
+ caller: identity.name ?? identity.clientId,
169
+ });
170
+ },
171
+ });
172
+ ```
173
+
174
+ ## Express
175
+
176
+ ```ts
177
+ import express from "express";
178
+ import { createGuard, createProvider, memoryStorage } from "trustline";
179
+ import {
180
+ createExpressGuard,
181
+ createExpressProvider,
182
+ type TrustlineRequest,
183
+ } from "trustline/frameworks/express";
184
+
185
+ const app = express();
186
+
187
+ const provider = createProvider({
188
+ issuer: "https://auth.internal",
189
+ storage: memoryStorage(),
190
+ });
191
+
192
+ const guard = createGuard({
193
+ issuer: "https://auth.internal",
194
+ audience: "inventory-service",
195
+ });
196
+
197
+ app.use(createExpressProvider(provider));
198
+ app.use(createExpressGuard(guard));
199
+
200
+ app.get("/internal", (request: TrustlineRequest, response) => {
201
+ response.json({
202
+ caller: request.trustline?.name ?? request.trustline?.clientId,
203
+ });
204
+ });
205
+ ```
206
+
207
+ ## API
208
+
209
+ Current public API includes:
210
+
211
+ ```ts
212
+ interface ProviderOptions {
213
+ issuer: string;
214
+ storage: StorageAdapter;
215
+ signing?: {
216
+ algorithm?: "ES256" | "RS256";
217
+ privateKey?: string;
218
+ keyId?: string;
219
+ };
220
+ token?: {
221
+ ttl?: number;
222
+ };
223
+ env?: string;
224
+ }
225
+
226
+ interface GuardOptions {
227
+ issuer: string;
228
+ jwksUrl?: string;
229
+ audience?: string | string[];
230
+ scopes?: string[];
231
+ env?: string;
232
+ clockTolerance?: number;
233
+ }
234
+
235
+ interface ServiceIdentity {
236
+ clientId: string;
237
+ name: string | null;
238
+ scopes: string[];
239
+ env: string | null;
240
+ raw: Record<string, unknown>;
241
+ }
242
+ ```
243
+
244
+ Adapter surface:
245
+
246
+ - `provider.handle(request)`
247
+ - `guard.verify(token)`
248
+ - `createExpressProvider(provider)`
249
+ - `createExpressGuard(guard)`
250
+ - `createFastifyProvider(provider)`
251
+ - `createFastifyGuard(guard)`
252
+ - `createHonoProvider(provider)`
253
+ - `createHonoGuard(guard)`
254
+
255
+ Supported signing algorithms:
256
+
257
+ - `RS256`
258
+ - `ES256`
259
+
260
+ Bundled storage adapters via dedicated subpaths:
261
+
262
+ - `memoryStorage()`
263
+ - `sqliteStorage(path | database)`
264
+ - `postgresStorage(pool)`
265
+ - `mysqlStorage(pool)`
266
+
267
+ SQL adapters follow the Better Auth-style pattern of receiving ready-made database handles:
268
+
269
+ ```ts
270
+ import Database from "better-sqlite3";
271
+ import { createPool as createMysqlPool } from "mysql2";
272
+ import { Pool as PostgresPool } from "pg";
273
+ import { mysqlStorage } from "trustline/adapters/mysql";
274
+ import { postgresStorage } from "trustline/adapters/postgres";
275
+ import { sqliteStorage } from "trustline/adapters/sqlite";
276
+
277
+ const sqlite = sqliteStorage(new Database("./trustline.sqlite"));
278
+ const postgres = postgresStorage(
279
+ new PostgresPool({ connectionString: process.env.DATABASE_URL }),
280
+ );
281
+ const mysql = mysqlStorage(createMysqlPool(process.env.DATABASE_URL!));
282
+ ```
283
+
284
+ ## Documentation
285
+
286
+ The VitePress docs site lives in `docs/`.
287
+
288
+ Key pages:
289
+
290
+ - `docs/index.md`
291
+ - `docs/get-started.md`
292
+ - `docs/concepts.md`
293
+ - `docs/middleware.md`
294
+ - `docs/reference.md`
295
+ - `docs/roadmap.md`
296
+
297
+ To run the docs locally:
298
+
299
+ ```bash
300
+ cd docs
301
+ bun run docs:dev
302
+ ```
303
+
304
+ To build the docs:
305
+
306
+ ```bash
307
+ cd docs
308
+ bun run docs:build
309
+ ```
310
+
311
+ ## Development
312
+
313
+ Build the package:
314
+
315
+ ```bash
316
+ bun run build
317
+ ```
318
+
319
+ Run type checks:
320
+
321
+ ```bash
322
+ bun run typecheck
323
+ ```
324
+
325
+ Run tests:
326
+
327
+ ```bash
328
+ bun run test
329
+ ```
330
+
331
+ Run formatting and lint checks:
332
+
333
+ ```bash
334
+ bun run check
335
+ ```
336
+
337
+ ## License
338
+
339
+ MIT
@@ -0,0 +1,199 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // src/adapters/mysql/index.ts
21
+ var mysql_exports = {};
22
+ __export(mysql_exports, {
23
+ mysqlStorage: () => mysqlStorage
24
+ });
25
+ module.exports = __toCommonJS(mysql_exports);
26
+
27
+ // src/storage/mysql.ts
28
+ var import_kysely2 = require("kysely");
29
+
30
+ // src/storage/sql.ts
31
+ var import_kysely = require("kysely");
32
+ function createSqlStorage(database, dialect, options) {
33
+ const tables = resolveTables(options);
34
+ let schemaPromise = null;
35
+ async function ensureSchema() {
36
+ if (!schemaPromise) {
37
+ schemaPromise = createSchema(database, dialect, tables);
38
+ }
39
+ await schemaPromise;
40
+ }
41
+ return {
42
+ async findClient(clientId) {
43
+ await ensureSchema();
44
+ const row = await database.selectFrom(tables.clients).selectAll().where("client_id", "=", clientId).executeTakeFirst();
45
+ return row ? mapClientRow(row) : null;
46
+ },
47
+ async createClient(client) {
48
+ await ensureSchema();
49
+ await database.insertInto(tables.clients).values({
50
+ id: client.id,
51
+ client_id: client.clientId,
52
+ client_secret: client.clientSecret,
53
+ name: client.name,
54
+ scopes: JSON.stringify(client.scopes),
55
+ created_at: client.createdAt.toISOString(),
56
+ last_seen_at: client.lastSeenAt?.toISOString() ?? null
57
+ }).execute();
58
+ },
59
+ async deleteClient(clientId) {
60
+ await ensureSchema();
61
+ await database.deleteFrom(tables.clients).where("client_id", "=", clientId).execute();
62
+ },
63
+ async listClients() {
64
+ await ensureSchema();
65
+ const rows = await database.selectFrom(tables.clients).selectAll().orderBy("created_at", "asc").execute();
66
+ return rows.map(mapClientRow);
67
+ },
68
+ async touchClient(clientId, lastSeenAt) {
69
+ await ensureSchema();
70
+ await database.updateTable(tables.clients).set({
71
+ last_seen_at: lastSeenAt.toISOString()
72
+ }).where("client_id", "=", clientId).execute();
73
+ },
74
+ async getSigningKeys() {
75
+ await ensureSchema();
76
+ const rows = await database.selectFrom(tables.signingKeys).selectAll().orderBy("created_at", "asc").execute();
77
+ return rows.map(mapSigningKeyRow);
78
+ },
79
+ async addSigningKey(key) {
80
+ await ensureSchema();
81
+ await database.insertInto(tables.signingKeys).values({
82
+ key_id: key.keyId,
83
+ algorithm: key.algorithm,
84
+ private_key: key.privateKey,
85
+ public_key: key.publicKey,
86
+ created_at: key.createdAt.toISOString(),
87
+ retired_at: key.retiredAt?.toISOString() ?? null
88
+ }).execute();
89
+ },
90
+ async retireKey(keyId) {
91
+ await ensureSchema();
92
+ await database.updateTable(tables.signingKeys).set({
93
+ retired_at: (/* @__PURE__ */ new Date()).toISOString()
94
+ }).where("key_id", "=", keyId).execute();
95
+ }
96
+ };
97
+ }
98
+ function resolveTables(options) {
99
+ const prefix = options?.tablePrefix ?? "trustline_";
100
+ return {
101
+ clients: options?.tables?.clients ?? `${prefix}clients`,
102
+ signingKeys: options?.tables?.signingKeys ?? `${prefix}signing_keys`
103
+ };
104
+ }
105
+ async function createSchema(database, dialect, tables) {
106
+ await createClientsTable(database, dialect, tables.clients);
107
+ await createSigningKeysTable(database, dialect, tables.signingKeys);
108
+ }
109
+ async function createClientsTable(database, dialect, tableName) {
110
+ if (dialect === "mysql") {
111
+ await import_kysely.sql`
112
+ create table if not exists ${import_kysely.sql.table(tableName)} (
113
+ id varchar(255) not null,
114
+ client_id varchar(255) not null primary key,
115
+ client_secret text not null,
116
+ name varchar(255) not null,
117
+ scopes text not null,
118
+ created_at varchar(64) not null,
119
+ last_seen_at varchar(64) null
120
+ )
121
+ `.execute(database);
122
+ return;
123
+ }
124
+ await import_kysely.sql`
125
+ create table if not exists ${import_kysely.sql.table(tableName)} (
126
+ id varchar(255) not null,
127
+ client_id varchar(255) not null primary key,
128
+ client_secret text not null,
129
+ name varchar(255) not null,
130
+ scopes text not null,
131
+ created_at varchar(64) not null,
132
+ last_seen_at varchar(64)
133
+ )
134
+ `.execute(database);
135
+ }
136
+ async function createSigningKeysTable(database, dialect, tableName) {
137
+ if (dialect === "mysql") {
138
+ await import_kysely.sql`
139
+ create table if not exists ${import_kysely.sql.table(tableName)} (
140
+ key_id varchar(255) not null primary key,
141
+ algorithm varchar(32) not null,
142
+ private_key text not null,
143
+ public_key text not null,
144
+ created_at varchar(64) not null,
145
+ retired_at varchar(64) null
146
+ )
147
+ `.execute(database);
148
+ return;
149
+ }
150
+ await import_kysely.sql`
151
+ create table if not exists ${import_kysely.sql.table(tableName)} (
152
+ key_id varchar(255) not null primary key,
153
+ algorithm varchar(32) not null,
154
+ private_key text not null,
155
+ public_key text not null,
156
+ created_at varchar(64) not null,
157
+ retired_at varchar(64)
158
+ )
159
+ `.execute(database);
160
+ }
161
+ function mapClientRow(row) {
162
+ return {
163
+ id: row.id,
164
+ clientId: row.client_id,
165
+ clientSecret: row.client_secret,
166
+ name: row.name,
167
+ scopes: JSON.parse(row.scopes),
168
+ createdAt: new Date(row.created_at),
169
+ lastSeenAt: row.last_seen_at ? new Date(row.last_seen_at) : null
170
+ };
171
+ }
172
+ function mapSigningKeyRow(row) {
173
+ return {
174
+ keyId: row.key_id,
175
+ algorithm: row.algorithm,
176
+ privateKey: row.private_key,
177
+ publicKey: row.public_key,
178
+ createdAt: new Date(row.created_at),
179
+ retiredAt: row.retired_at ? new Date(row.retired_at) : null
180
+ };
181
+ }
182
+
183
+ // src/storage/mysql.ts
184
+ function mysqlStorage(pool, options) {
185
+ return createSqlStorage(
186
+ new import_kysely2.Kysely({
187
+ dialect: new import_kysely2.MysqlDialect({
188
+ pool
189
+ })
190
+ }),
191
+ "mysql",
192
+ options
193
+ );
194
+ }
195
+ // Annotate the CommonJS export names for ESM import in node:
196
+ 0 && (module.exports = {
197
+ mysqlStorage
198
+ });
199
+ //# sourceMappingURL=index.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../../src/adapters/mysql/index.ts","../../../src/storage/mysql.ts","../../../src/storage/sql.ts"],"sourcesContent":["export { mysqlStorage } from \"../../storage/mysql\";\nexport type { SqlStorageOptions, StorageAdapter } from \"../../storage/interface\";\n","import { Kysely, MysqlDialect } from \"kysely\";\nimport type { Pool } from \"mysql2\";\n\nimport type { SqlStorageOptions, StorageAdapter } from \"./interface\";\nimport { createSqlStorage } from \"./sql\";\n\nexport function mysqlStorage(\n pool: Pool,\n options?: SqlStorageOptions,\n): StorageAdapter {\n return createSqlStorage(\n new Kysely({\n dialect: new MysqlDialect({\n pool,\n }),\n }),\n \"mysql\",\n options,\n );\n}\n","import { type Kysely, sql } from \"kysely\";\n\nimport type {\n ServiceClient,\n SigningKey,\n SqlStorageOptions,\n StorageAdapter,\n} from \"./interface\";\n\ntype SqlDialect = \"mysql\" | \"postgres\" | \"sqlite\";\n\ninterface SqlTables {\n clients: string;\n signingKeys: string;\n}\n\ninterface SqlDatabase {\n [tableName: string]: SqlRow;\n}\n\ninterface SqlRow {\n algorithm?: SigningKey[\"algorithm\"];\n client_id?: string;\n client_secret?: string;\n created_at: string;\n id?: string;\n key_id?: string;\n last_seen_at?: string | null;\n name?: string;\n private_key?: string;\n public_key?: string;\n retired_at?: string | null;\n scopes?: string;\n}\n\ninterface ClientRow {\n id: string;\n client_id: string;\n client_secret: string;\n name: string;\n scopes: string;\n created_at: string;\n last_seen_at: string | null;\n}\n\ninterface SigningKeyRow {\n key_id: string;\n algorithm: SigningKey[\"algorithm\"];\n private_key: string;\n public_key: string;\n created_at: string;\n retired_at: string | null;\n}\n\nexport function createSqlStorage(\n database: Kysely<SqlDatabase>,\n dialect: SqlDialect,\n options?: SqlStorageOptions,\n): StorageAdapter {\n const tables = resolveTables(options);\n let schemaPromise: Promise<void> | null = null;\n\n async function ensureSchema(): Promise<void> {\n if (!schemaPromise) {\n schemaPromise = createSchema(database, dialect, tables);\n }\n\n await schemaPromise;\n }\n\n return {\n async findClient(clientId) {\n await ensureSchema();\n\n const row = (await database\n .selectFrom(tables.clients)\n .selectAll()\n .where(\"client_id\", \"=\", clientId)\n .executeTakeFirst()) as ClientRow | undefined;\n\n return row ? mapClientRow(row) : null;\n },\n async createClient(client) {\n await ensureSchema();\n\n await database\n .insertInto(tables.clients)\n .values({\n id: client.id,\n client_id: client.clientId,\n client_secret: client.clientSecret,\n name: client.name,\n scopes: JSON.stringify(client.scopes),\n created_at: client.createdAt.toISOString(),\n last_seen_at: client.lastSeenAt?.toISOString() ?? null,\n })\n .execute();\n },\n async deleteClient(clientId) {\n await ensureSchema();\n\n await database\n .deleteFrom(tables.clients)\n .where(\"client_id\", \"=\", clientId)\n .execute();\n },\n async listClients() {\n await ensureSchema();\n\n const rows = (await database\n .selectFrom(tables.clients)\n .selectAll()\n .orderBy(\"created_at\", \"asc\")\n .execute()) as ClientRow[];\n\n return rows.map(mapClientRow);\n },\n async touchClient(clientId, lastSeenAt) {\n await ensureSchema();\n\n await database\n .updateTable(tables.clients)\n .set({\n last_seen_at: lastSeenAt.toISOString(),\n })\n .where(\"client_id\", \"=\", clientId)\n .execute();\n },\n async getSigningKeys() {\n await ensureSchema();\n\n const rows = (await database\n .selectFrom(tables.signingKeys)\n .selectAll()\n .orderBy(\"created_at\", \"asc\")\n .execute()) as SigningKeyRow[];\n\n return rows.map(mapSigningKeyRow);\n },\n async addSigningKey(key) {\n await ensureSchema();\n\n await database\n .insertInto(tables.signingKeys)\n .values({\n key_id: key.keyId,\n algorithm: key.algorithm,\n private_key: key.privateKey,\n public_key: key.publicKey,\n created_at: key.createdAt.toISOString(),\n retired_at: key.retiredAt?.toISOString() ?? null,\n })\n .execute();\n },\n async retireKey(keyId) {\n await ensureSchema();\n\n await database\n .updateTable(tables.signingKeys)\n .set({\n retired_at: new Date().toISOString(),\n })\n .where(\"key_id\", \"=\", keyId)\n .execute();\n },\n };\n}\n\nfunction resolveTables(options?: SqlStorageOptions): SqlTables {\n const prefix = options?.tablePrefix ?? \"trustline_\";\n\n return {\n clients: options?.tables?.clients ?? `${prefix}clients`,\n signingKeys: options?.tables?.signingKeys ?? `${prefix}signing_keys`,\n };\n}\n\nasync function createSchema(\n database: Kysely<SqlDatabase>,\n dialect: SqlDialect,\n tables: SqlTables,\n): Promise<void> {\n await createClientsTable(database, dialect, tables.clients);\n await createSigningKeysTable(database, dialect, tables.signingKeys);\n}\n\nasync function createClientsTable(\n database: Kysely<SqlDatabase>,\n dialect: SqlDialect,\n tableName: string,\n): Promise<void> {\n if (dialect === \"mysql\") {\n await sql`\n create table if not exists ${sql.table(tableName)} (\n id varchar(255) not null,\n client_id varchar(255) not null primary key,\n client_secret text not null,\n name varchar(255) not null,\n scopes text not null,\n created_at varchar(64) not null,\n last_seen_at varchar(64) null\n )\n `.execute(database);\n return;\n }\n\n await sql`\n create table if not exists ${sql.table(tableName)} (\n id varchar(255) not null,\n client_id varchar(255) not null primary key,\n client_secret text not null,\n name varchar(255) not null,\n scopes text not null,\n created_at varchar(64) not null,\n last_seen_at varchar(64)\n )\n `.execute(database);\n}\n\nasync function createSigningKeysTable(\n database: Kysely<SqlDatabase>,\n dialect: SqlDialect,\n tableName: string,\n): Promise<void> {\n if (dialect === \"mysql\") {\n await sql`\n create table if not exists ${sql.table(tableName)} (\n key_id varchar(255) not null primary key,\n algorithm varchar(32) not null,\n private_key text not null,\n public_key text not null,\n created_at varchar(64) not null,\n retired_at varchar(64) null\n )\n `.execute(database);\n return;\n }\n\n await sql`\n create table if not exists ${sql.table(tableName)} (\n key_id varchar(255) not null primary key,\n algorithm varchar(32) not null,\n private_key text not null,\n public_key text not null,\n created_at varchar(64) not null,\n retired_at varchar(64)\n )\n `.execute(database);\n}\n\nfunction mapClientRow(row: ClientRow): ServiceClient {\n return {\n id: row.id,\n clientId: row.client_id,\n clientSecret: row.client_secret,\n name: row.name,\n scopes: JSON.parse(row.scopes) as string[],\n createdAt: new Date(row.created_at),\n lastSeenAt: row.last_seen_at ? new Date(row.last_seen_at) : null,\n };\n}\n\nfunction mapSigningKeyRow(row: SigningKeyRow): SigningKey {\n return {\n keyId: row.key_id,\n algorithm: row.algorithm,\n privateKey: row.private_key,\n publicKey: row.public_key,\n createdAt: new Date(row.created_at),\n retiredAt: row.retired_at ? new Date(row.retired_at) : null,\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAA,IAAAA,iBAAqC;;;ACArC,oBAAiC;AAsD1B,SAAS,iBACd,UACA,SACA,SACgB;AAChB,QAAM,SAAS,cAAc,OAAO;AACpC,MAAI,gBAAsC;AAE1C,iBAAe,eAA8B;AAC3C,QAAI,CAAC,eAAe;AAClB,sBAAgB,aAAa,UAAU,SAAS,MAAM;AAAA,IACxD;AAEA,UA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AAQ;AACpB;AAEA,eAAe,uBACb,UACA,SACA,WACe;AACf,MAAI,YAAY,SAAS;AACvB,UAAM;AAAA,mCACyB,kBAAI,MAAM,SAAS,CAAC;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,MAQjD,QAAQ,QAAQ;AAClB;AAAA,EACF;AAEA,QAAM;AAAA,iCACyB,kBAAI,MAAM,SAAS,CAAC;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,IAQjD,QAAQ,QAAQ;AACpB;AAEA,SAAS,aAAa,KAA+B;AACnD,SAAO;AAAA,IACL,IAAI,IAAI;AAAA,IACR,UAAU,IAAI;AAAA,IACd,cAAc,IAAI;AAAA,IAClB,MAAM,IAAI;AAAA,IACV,QAAQ,KAAK,MAAM,IAAI,MAAM;AAAA,IAC7B,WAAW,IAAI,KAAK,IAAI,UAAU;AAAA,IAClC,YAAY,IAAI,eAAe,IAAI,KAAK,IAAI,YAAY,IAAI;AAAA,EAC9D;AACF;AAEA,SAAS,iBAAiB,KAAgC;AACxD,SAAO;AAAA,IACL,OAAO,IAAI;AAAA,IACX,WAAW,IAAI;AAAA,IACf,YAAY,IAAI;AAAA,IAChB,WAAW,IAAI;AAAA,IACf,WAAW,IAAI,KAAK,IAAI,UAAU;AAAA,IAClC,WAAW,IAAI,aAAa,IAAI,KAAK,IAAI,UAAU,IAAI;AAAA,EACzD;AACF;;;ADzQO,SAAS,aACd,MACA,SACgB;AAChB,SAAO;AAAA,IACL,IAAI,sBAAO;AAAA,MACT,SAAS,IAAI,4BAAa;AAAA,QACxB;AAAA,MACF,CAAC;AAAA,IACH,CAAC;AAAA,IACD;AAAA,IACA;AAAA,EACF;AACF;","names":["import_kysely"]}
@@ -0,0 +1,6 @@
1
+ import { Pool } from 'mysql2';
2
+ import { S as SqlStorageOptions, a as StorageAdapter } from '../../interface-BzT_DC3u.cjs';
3
+
4
+ declare function mysqlStorage(pool: Pool, options?: SqlStorageOptions): StorageAdapter;
5
+
6
+ export { SqlStorageOptions, StorageAdapter, mysqlStorage };
@@ -0,0 +1,6 @@
1
+ import { Pool } from 'mysql2';
2
+ import { S as SqlStorageOptions, a as StorageAdapter } from '../../interface-BzT_DC3u.js';
3
+
4
+ declare function mysqlStorage(pool: Pool, options?: SqlStorageOptions): StorageAdapter;
5
+
6
+ export { SqlStorageOptions, StorageAdapter, mysqlStorage };
@@ -0,0 +1,21 @@
1
+ import {
2
+ createSqlStorage
3
+ } from "../../chunk-CTPFKR4O.js";
4
+
5
+ // src/storage/mysql.ts
6
+ import { Kysely, MysqlDialect } from "kysely";
7
+ function mysqlStorage(pool, options) {
8
+ return createSqlStorage(
9
+ new Kysely({
10
+ dialect: new MysqlDialect({
11
+ pool
12
+ })
13
+ }),
14
+ "mysql",
15
+ options
16
+ );
17
+ }
18
+ export {
19
+ mysqlStorage
20
+ };
21
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../../src/storage/mysql.ts"],"sourcesContent":["import { Kysely, MysqlDialect } from \"kysely\";\nimport type { Pool } from \"mysql2\";\n\nimport type { SqlStorageOptions, StorageAdapter } from \"./interface\";\nimport { createSqlStorage } from \"./sql\";\n\nexport function mysqlStorage(\n pool: Pool,\n options?: SqlStorageOptions,\n): StorageAdapter {\n return createSqlStorage(\n new Kysely({\n dialect: new MysqlDialect({\n pool,\n }),\n }),\n \"mysql\",\n options,\n );\n}\n"],"mappings":";;;;;AAAA,SAAS,QAAQ,oBAAoB;AAM9B,SAAS,aACd,MACA,SACgB;AAChB,SAAO;AAAA,IACL,IAAI,OAAO;AAAA,MACT,SAAS,IAAI,aAAa;AAAA,QACxB;AAAA,MACF,CAAC;AAAA,IACH,CAAC;AAAA,IACD;AAAA,IACA;AAAA,EACF;AACF;","names":[]}