trustline 0.0.1 → 0.1.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 (62) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +301 -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 +125 -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 +87 -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 +129 -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,301 @@
1
+ # Trustline
2
+
3
+ [![npm version](https://img.shields.io/npm/v/trustline)](https://www.npmjs.com/package/trustline)
4
+ [![docs](https://img.shields.io/badge/docs-github%20pages-blue)](https://barddoo.github.io/trustline/)
5
+
6
+ Service identity and authorization for modern JavaScript runtimes.
7
+
8
+ Trustline is a machine-to-machine authentication library for internal services. It is designed around dedicated core and integration entry points:
9
+
10
+ - `trustline`: provider, guard, memory storage, and shared core exports
11
+ - `trustline/client`: token fetching and caching for outgoing requests
12
+ - `trustline/frameworks/*`: framework adapters for receiving services
13
+ - `trustline/adapters/*`: SQL storage adapters
14
+
15
+ The package now ships the first full stack: provider, client, guard, framework adapters, memory storage, and SQL storage adapters for SQLite, Postgres, and MySQL.
16
+
17
+ ## Installation
18
+
19
+ Trustline is intended to be consumed as the `trustline` package:
20
+
21
+ ```bash
22
+ bun add trustline
23
+ ```
24
+
25
+ Or with npm:
26
+
27
+ ```bash
28
+ npm install trustline
29
+ ```
30
+
31
+ Install only the integrations you use. For example, Express users install `express`; SQLite users install `better-sqlite3` and `kysely`.
32
+
33
+ Example installs:
34
+
35
+ ```bash
36
+ npm install trustline express
37
+ npm install trustline better-sqlite3 kysely
38
+ ```
39
+
40
+ If you are working from this repository before package publication, build the package locally and install or link it from the repo source.
41
+
42
+ ## Quick start
43
+
44
+ Provider:
45
+
46
+ ```ts
47
+ import { createProvider, memoryStorage } from "trustline";
48
+
49
+ const provider = createProvider({
50
+ issuer: "https://auth.internal",
51
+ storage: memoryStorage(),
52
+ env: "production",
53
+ });
54
+
55
+ const service = await provider.clients.create({
56
+ name: "order-processor",
57
+ scopes: ["read:orders", "write:inventory"],
58
+ });
59
+ ```
60
+
61
+ Client:
62
+
63
+ ```ts
64
+ import { createClient } from "trustline/client";
65
+
66
+ const client = createClient({
67
+ tokenUrl: "https://auth.internal/token",
68
+ clientId: service.clientId,
69
+ clientSecret: service.clientSecret,
70
+ audience: "inventory-service",
71
+ });
72
+
73
+ const token = await client.getToken();
74
+ ```
75
+
76
+ Guard:
77
+
78
+ ```ts
79
+ import { createGuard } from "trustline";
80
+
81
+ const guard = createGuard({
82
+ issuer: "https://auth.internal",
83
+ audience: "inventory-service",
84
+ scopes: ["read:orders"],
85
+ env: "production",
86
+ });
87
+
88
+ const identity = await guard.verify(token);
89
+ ```
90
+
91
+ Trustline derives the JWKS endpoint automatically for verification:
92
+
93
+ ```txt
94
+ issuer: https://auth.internal
95
+ jwks: https://auth.internal/.well-known/jwks.json
96
+ ```
97
+
98
+ ## Bun
99
+
100
+ 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.
101
+
102
+ ```ts
103
+ import { createGuard, createProvider, memoryStorage } from "trustline";
104
+
105
+ const provider = createProvider({
106
+ issuer: "https://auth.internal",
107
+ storage: memoryStorage(),
108
+ });
109
+
110
+ Bun.serve({
111
+ port: 3000,
112
+ fetch: provider.handle,
113
+ });
114
+
115
+ const guard = createGuard({
116
+ issuer: "https://auth.internal",
117
+ audience: "inventory-service",
118
+ });
119
+
120
+ Bun.serve({
121
+ port: 4000,
122
+ fetch: async (request) => {
123
+ const header = request.headers.get("authorization");
124
+ const token = header?.replace(/^Bearer\s+/, "") ?? "";
125
+ const identity = await guard.verify(token);
126
+
127
+ return Response.json({
128
+ caller: identity.name ?? identity.clientId,
129
+ });
130
+ },
131
+ });
132
+ ```
133
+
134
+ ## Express
135
+
136
+ ```ts
137
+ import express from "express";
138
+ import { createGuard, createProvider, memoryStorage } from "trustline";
139
+ import {
140
+ createExpressGuard,
141
+ createExpressProvider,
142
+ type TrustlineRequest,
143
+ } from "trustline/frameworks/express";
144
+
145
+ const app = express();
146
+
147
+ const provider = createProvider({
148
+ issuer: "https://auth.internal",
149
+ storage: memoryStorage(),
150
+ });
151
+
152
+ const guard = createGuard({
153
+ issuer: "https://auth.internal",
154
+ audience: "inventory-service",
155
+ });
156
+
157
+ app.use(createExpressProvider(provider));
158
+ app.use(createExpressGuard(guard));
159
+
160
+ app.get("/internal", (request: TrustlineRequest, response) => {
161
+ response.json({
162
+ caller: request.trustline?.name ?? request.trustline?.clientId,
163
+ });
164
+ });
165
+ ```
166
+
167
+ ## API
168
+
169
+ Current public API includes:
170
+
171
+ ```ts
172
+ interface ProviderOptions {
173
+ issuer: string;
174
+ storage: StorageAdapter;
175
+ signing?: {
176
+ algorithm?: "ES256" | "RS256";
177
+ privateKey?: string;
178
+ keyId?: string;
179
+ };
180
+ token?: {
181
+ ttl?: number;
182
+ };
183
+ env?: string;
184
+ }
185
+
186
+ interface GuardOptions {
187
+ issuer: string;
188
+ jwksUrl?: string;
189
+ audience?: string | string[];
190
+ scopes?: string[];
191
+ env?: string;
192
+ clockTolerance?: number;
193
+ }
194
+
195
+ interface ServiceIdentity {
196
+ clientId: string;
197
+ name: string | null;
198
+ scopes: string[];
199
+ env: string | null;
200
+ raw: Record<string, unknown>;
201
+ }
202
+ ```
203
+
204
+ Adapter surface:
205
+
206
+ - `provider.handle(request)`
207
+ - `guard.verify(token)`
208
+ - `createExpressProvider(provider)`
209
+ - `createExpressGuard(guard)`
210
+ - `createFastifyProvider(provider)`
211
+ - `createFastifyGuard(guard)`
212
+ - `createHonoProvider(provider)`
213
+ - `createHonoGuard(guard)`
214
+
215
+ Supported signing algorithms:
216
+
217
+ - `RS256`
218
+ - `ES256`
219
+
220
+ Bundled storage adapters via dedicated subpaths:
221
+
222
+ - `memoryStorage()`
223
+ - `sqliteStorage(path | database)`
224
+ - `postgresStorage(pool)`
225
+ - `mysqlStorage(pool)`
226
+
227
+ SQL adapters follow the Better Auth-style pattern of receiving ready-made database handles:
228
+
229
+ ```ts
230
+ import Database from "better-sqlite3";
231
+ import { createPool as createMysqlPool } from "mysql2";
232
+ import { Pool as PostgresPool } from "pg";
233
+ import { mysqlStorage } from "trustline/adapters/mysql";
234
+ import { postgresStorage } from "trustline/adapters/postgres";
235
+ import { sqliteStorage } from "trustline/adapters/sqlite";
236
+
237
+ const sqlite = sqliteStorage(new Database("./trustline.sqlite"));
238
+ const postgres = postgresStorage(
239
+ new PostgresPool({ connectionString: process.env.DATABASE_URL }),
240
+ );
241
+ const mysql = mysqlStorage(createMysqlPool(process.env.DATABASE_URL!));
242
+ ```
243
+
244
+ ## Documentation
245
+
246
+ The VitePress docs site lives in `docs/`.
247
+
248
+ Runnable examples live under `examples/`. For a full Hono-based flow with a dedicated auth provider plus caller and receiver services, see `examples/hono-services/`.
249
+
250
+ Key pages:
251
+
252
+ - `docs/index.md`
253
+ - `docs/get-started.md`
254
+ - `docs/concepts.md`
255
+ - `docs/middleware.md`
256
+ - `docs/reference.md`
257
+ - `docs/roadmap.md`
258
+
259
+ To run the docs locally:
260
+
261
+ ```bash
262
+ cd docs
263
+ bun run docs:dev
264
+ ```
265
+
266
+ To build the docs:
267
+
268
+ ```bash
269
+ cd docs
270
+ bun run docs:build
271
+ ```
272
+
273
+ ## Development
274
+
275
+ Build the package:
276
+
277
+ ```bash
278
+ bun run build
279
+ ```
280
+
281
+ Run type checks:
282
+
283
+ ```bash
284
+ bun run typecheck
285
+ ```
286
+
287
+ Run tests:
288
+
289
+ ```bash
290
+ bun run test
291
+ ```
292
+
293
+ Run formatting and lint checks:
294
+
295
+ ```bash
296
+ bun run check
297
+ ```
298
+
299
+ ## License
300
+
301
+ 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 type {\n SqlStorageOptions,\n StorageAdapter,\n} from \"../../storage/interface\";\nexport { mysqlStorage } from \"../../storage/mysql\";\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,UAAM;AAAA,EACR;AAEA,SAAO;AAAA,IACL,MAAM,WAAW,UAAU;AACzB,YAAM,aAAa;AAEnB,YAAM,MAAO,MAAM,SAChB,WAAW,OAAO,OAAO,EACzB,UAAU,EACV,MAAM,aAAa,KAAK,QAAQ,EAChC,iBAAiB;AAEpB,aAAO,MAAM,aAAa,GAAG,IAAI;AAAA,IACnC;AAAA,IACA,MAAM,aAAa,QAAQ;AACzB,YAAM,aAAa;AAEnB,YAAM,SACH,WAAW,OAAO,OAAO,EACzB,OAAO;AAAA,QACN,IAAI,OAAO;AAAA,QACX,WAAW,OAAO;AAAA,QAClB,eAAe,OAAO;AAAA,QACtB,MAAM,OAAO;AAAA,QACb,QAAQ,KAAK,UAAU,OAAO,MAAM;AAAA,QACpC,YAAY,OAAO,UAAU,YAAY;AAAA,QACzC,cAAc,OAAO,YAAY,Y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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 { S as SqlStorageOptions, a as StorageAdapter } from '../../interface-BzT_DC3u.cjs';
2
+ import { Pool } from 'mysql2';
3
+
4
+ declare function mysqlStorage(pool: Pool, options?: SqlStorageOptions): StorageAdapter;
5
+
6
+ export { SqlStorageOptions, StorageAdapter, mysqlStorage };
@@ -0,0 +1,6 @@
1
+ import { S as SqlStorageOptions, a as StorageAdapter } from '../../interface-BzT_DC3u.js';
2
+ import { Pool } from 'mysql2';
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":[]}