@lostgradient/mcp 0.2.5 → 0.3.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 (123) hide show
  1. package/LICENSE +1 -1
  2. package/README.md +15 -173
  3. package/dist/http.d.ts +35 -0
  4. package/dist/http.js +251 -0
  5. package/dist/internal/cryptography/encryption.d.ts +108 -0
  6. package/dist/internal/cryptography/encryption.js +241 -0
  7. package/dist/internal/cryptography/hash.d.ts +72 -0
  8. package/dist/internal/cryptography/hash.js +233 -0
  9. package/dist/internal/cryptography/index.d.ts +4 -0
  10. package/dist/internal/cryptography/index.js +2 -0
  11. package/dist/oauth/canonicalize-ip-address.d.ts +0 -6
  12. package/dist/oauth/canonicalize-ip-address.js +113 -0
  13. package/dist/oauth/client-metadata-documents.d.ts +2 -22
  14. package/dist/oauth/client-metadata-documents.js +205 -19
  15. package/dist/oauth/index.d.ts +9 -213
  16. package/dist/oauth/index.js +6 -69
  17. package/dist/oauth/issuer.d.ts +103 -0
  18. package/dist/oauth/issuer.js +564 -0
  19. package/dist/oauth/postgres.d.ts +12 -0
  20. package/dist/oauth/postgres.js +76 -0
  21. package/dist/oauth/safe-public-https-fetch.d.ts +3 -5
  22. package/dist/oauth/safe-public-https-fetch.js +114 -0
  23. package/dist/oauth/security-utilities.d.ts +0 -3
  24. package/dist/oauth/security-utilities.js +93 -0
  25. package/dist/oauth-store.d.ts +108 -0
  26. package/dist/oauth-store.js +321 -0
  27. package/package.json +50 -124
  28. package/dist/chunk-3ek3knfm.js +0 -73
  29. package/dist/chunk-3rr24vhh.js +0 -28
  30. package/dist/chunk-6ekjtvcq.js +0 -273
  31. package/dist/chunk-88nhf6xt.js +0 -449
  32. package/dist/chunk-en76akaq.js +0 -1107
  33. package/dist/chunk-k6fm3cmk.js +0 -132
  34. package/dist/chunk-qxwd8est.js +0 -916
  35. package/dist/chunk-rxnyn7tf.js +0 -19
  36. package/dist/chunk-taxyscge.js +0 -67
  37. package/dist/chunk-wsnfttyg.js +0 -4
  38. package/dist/chunk-xcf742mf.js +0 -14
  39. package/dist/conformance-fixture-registration.d.ts +0 -30
  40. package/dist/conformance-server.d.ts +0 -1
  41. package/dist/conformance.d.ts +0 -43
  42. package/dist/env.d.ts +0 -59
  43. package/dist/env.js +0 -9
  44. package/dist/environment-schema.d.ts +0 -29
  45. package/dist/environment-schema.js +0 -6
  46. package/dist/golden-prompts.d.ts +0 -42
  47. package/dist/handler-context.d.ts +0 -16
  48. package/dist/http/authenticate.d.ts +0 -35
  49. package/dist/http/authorization-header.d.ts +0 -5
  50. package/dist/http/grant-revocation-channel.d.ts +0 -24
  51. package/dist/http/handler.d.ts +0 -32
  52. package/dist/http/index.d.ts +0 -27
  53. package/dist/http/index.js +0 -870
  54. package/dist/http/listen-inspection.d.ts +0 -11
  55. package/dist/http/request-context.d.ts +0 -17
  56. package/dist/http/responses.d.ts +0 -13
  57. package/dist/http/serving-layer.d.ts +0 -25
  58. package/dist/http/user-handler-cache.d.ts +0 -37
  59. package/dist/http/user-server-event-bus.d.ts +0 -35
  60. package/dist/index.d.ts +0 -29
  61. package/dist/index.js +0 -616
  62. package/dist/localhost-request-validation.d.ts +0 -2
  63. package/dist/logger.d.ts +0 -59
  64. package/dist/logger.js +0 -18
  65. package/dist/long-running-operation-support.d.ts +0 -34
  66. package/dist/metrics.d.ts +0 -64
  67. package/dist/metrics.js +0 -6
  68. package/dist/oauth/authorize-endpoint.d.ts +0 -5
  69. package/dist/oauth/client-authentication.d.ts +0 -10
  70. package/dist/oauth/discovery-metadata.d.ts +0 -19
  71. package/dist/oauth/endpoint-rate-limits.d.ts +0 -10
  72. package/dist/oauth/endpoint-responses.d.ts +0 -10
  73. package/dist/oauth/network-identity.d.ts +0 -32
  74. package/dist/oauth/pkce-validation.d.ts +0 -2
  75. package/dist/oauth/postgres/client-store.d.ts +0 -12
  76. package/dist/oauth/postgres/code-store.d.ts +0 -14
  77. package/dist/oauth/postgres/database.d.ts +0 -59
  78. package/dist/oauth/postgres/index.d.ts +0 -11
  79. package/dist/oauth/postgres/index.js +0 -616
  80. package/dist/oauth/postgres/schema.d.ts +0 -1476
  81. package/dist/oauth/postgres/token-store.d.ts +0 -16
  82. package/dist/oauth/postgres/transaction-store.d.ts +0 -14
  83. package/dist/oauth/redirect-uri-matching.d.ts +0 -2
  84. package/dist/oauth/registration-endpoint.d.ts +0 -2
  85. package/dist/oauth/request-body.d.ts +0 -14
  86. package/dist/oauth/revocation-endpoint.d.ts +0 -2
  87. package/dist/oauth/scope-utilities.d.ts +0 -15
  88. package/dist/oauth/stores.d.ts +0 -225
  89. package/dist/oauth/stores.js +0 -0
  90. package/dist/oauth/testing/contract-fixtures.d.ts +0 -134
  91. package/dist/oauth/testing/index.d.ts +0 -56
  92. package/dist/oauth/testing/index.js +0 -330
  93. package/dist/oauth/token-endpoint.d.ts +0 -2
  94. package/dist/oauth-scope-configuration.d.ts +0 -3
  95. package/dist/prompts/index.d.ts +0 -5
  96. package/dist/prompts/summarize.d.ts +0 -4
  97. package/dist/rate-limit/in-memory-sliding-window-store.d.ts +0 -3
  98. package/dist/rate-limit/index.d.ts +0 -23
  99. package/dist/rate-limit/index.js +0 -29
  100. package/dist/rate-limit/mcp-concurrency-limiter.d.ts +0 -26
  101. package/dist/rate-limit/rate-limit-response.d.ts +0 -1
  102. package/dist/rate-limit/redis-sliding-window-store.d.ts +0 -2
  103. package/dist/rate-limit/request-rate-limiter.d.ts +0 -10
  104. package/dist/rate-limit/sliding-window-rate-limiter.d.ts +0 -16
  105. package/dist/resources/index.d.ts +0 -4
  106. package/dist/resources/user-profile.d.ts +0 -1
  107. package/dist/scope-vocabulary.d.ts +0 -127
  108. package/dist/scopes.d.ts +0 -49
  109. package/dist/server.d.ts +0 -113
  110. package/dist/supported-scopes.d.ts +0 -25
  111. package/dist/sveltekit-mount-state.d.ts +0 -4
  112. package/dist/sveltekit-mount.d.ts +0 -43
  113. package/dist/sveltekit-mount.js +0 -344
  114. package/dist/template-registry.d.ts +0 -16
  115. package/dist/tool-response.d.ts +0 -100
  116. package/dist/tools/get-user-profile.d.ts +0 -8
  117. package/dist/tools/index.d.ts +0 -16
  118. package/dist/tools/list-audit-events.d.ts +0 -11
  119. package/dist/type-assertions.d.ts +0 -1
  120. package/dist/types/primitives.d.ts +0 -130
  121. package/dist/ui-extension-support.d.ts +0 -20
  122. package/dist/version.d.ts +0 -23
  123. package/dist/version.js +0 -6
@@ -1,616 +0,0 @@
1
- // src/oauth/postgres/schema.ts
2
- import {
3
- index,
4
- jsonb,
5
- pgTable,
6
- text,
7
- timestamp
8
- } from "drizzle-orm/pg-core";
9
- function createPostgresOAuthSchema({
10
- prefix,
11
- userId
12
- }) {
13
- const clients = pgTable(`${prefix}_clients`, {
14
- clientId: text("client_id").primaryKey(),
15
- clientSecretHash: text("client_secret_hash"),
16
- clientName: text("client_name").notNull(),
17
- clientType: text("client_type").notNull(),
18
- tokenEndpointAuthMethod: text("token_endpoint_auth_method").notNull(),
19
- applicationType: text("application_type"),
20
- redirectUris: jsonb("redirect_uris").$type().notNull(),
21
- grantTypes: jsonb("grant_types").$type().notNull(),
22
- responseTypes: jsonb("response_types").$type().notNull(),
23
- clientIdMetadataUrl: text("client_id_metadata_url"),
24
- clientSecretExpiresAt: timestamp("client_secret_expires_at", { withTimezone: true }),
25
- createdAt: timestamp("created_at", { withTimezone: true }).notNull(),
26
- updatedAt: timestamp("updated_at", { withTimezone: true }).notNull()
27
- });
28
- const transactions = pgTable(`${prefix}_authorization_transactions`, {
29
- transactionIdHash: text("transaction_id_hash").primaryKey(),
30
- csrfTokenHash: text("csrf_token_hash").notNull(),
31
- consentBindingHash: text("consent_binding_hash").notNull(),
32
- userId: userId(),
33
- clientId: text("client_id").notNull().references(() => clients.clientId, { onDelete: "cascade" }),
34
- redirectUri: text("redirect_uri").notNull(),
35
- codeChallenge: text("code_challenge").notNull(),
36
- codeChallengeMethod: text("code_challenge_method").notNull(),
37
- state: text("state"),
38
- issuer: text("issuer").notNull(),
39
- resource: text("resource").notNull(),
40
- scope: text("scope").notNull(),
41
- expiresAt: timestamp("expires_at", { withTimezone: true }).notNull(),
42
- consumedAt: timestamp("consumed_at", { withTimezone: true }),
43
- createdAt: timestamp("created_at", { withTimezone: true }).notNull()
44
- }, (table) => [
45
- index(`${prefix}_transactions_binding_idx`).on(table.consentBindingHash),
46
- index(`${prefix}_transactions_user_idx`).on(table.userId),
47
- index(`${prefix}_transactions_client_idx`).on(table.clientId),
48
- index(`${prefix}_transactions_expires_idx`).on(table.expiresAt)
49
- ]);
50
- const codes = pgTable(`${prefix}_codes`, {
51
- codeHash: text("code_hash").primaryKey(),
52
- clientId: text("client_id").notNull().references(() => clients.clientId, { onDelete: "cascade" }),
53
- userId: userId(),
54
- redirectUri: text("redirect_uri").notNull(),
55
- codeChallenge: text("code_challenge").notNull(),
56
- codeChallengeMethod: text("code_challenge_method").notNull(),
57
- scope: text("scope"),
58
- state: text("state"),
59
- resource: text("resource").notNull(),
60
- expiresAt: timestamp("expires_at", { withTimezone: true }).notNull(),
61
- usedAt: timestamp("used_at", { withTimezone: true }),
62
- createdAt: timestamp("created_at", { withTimezone: true }).notNull()
63
- }, (table) => [
64
- index(`${prefix}_codes_user_idx`).on(table.userId),
65
- index(`${prefix}_codes_client_idx`).on(table.clientId),
66
- index(`${prefix}_codes_expires_idx`).on(table.expiresAt)
67
- ]);
68
- const accessTokens = pgTable(`${prefix}_access_tokens`, {
69
- accessTokenHash: text("access_token_hash").primaryKey(),
70
- clientId: text("client_id").notNull().references(() => clients.clientId, { onDelete: "cascade" }),
71
- userId: userId(),
72
- scope: text("scope"),
73
- resource: text("resource").notNull(),
74
- expiresAt: timestamp("expires_at", { withTimezone: true }).notNull(),
75
- revokedAt: timestamp("revoked_at", { withTimezone: true }),
76
- createdAt: timestamp("created_at", { withTimezone: true }).notNull()
77
- }, (table) => [
78
- index(`${prefix}_access_user_idx`).on(table.userId),
79
- index(`${prefix}_access_client_idx`).on(table.clientId),
80
- index(`${prefix}_access_expires_idx`).on(table.expiresAt)
81
- ]);
82
- const refreshTokens = pgTable(`${prefix}_refresh_tokens`, {
83
- refreshTokenHash: text("refresh_token_hash").primaryKey(),
84
- clientId: text("client_id").notNull().references(() => clients.clientId, { onDelete: "cascade" }),
85
- userId: userId(),
86
- scope: text("scope"),
87
- resource: text("resource").notNull(),
88
- accessTokenHash: text("access_token_hash").notNull().references(() => accessTokens.accessTokenHash, { onDelete: "cascade" }),
89
- familyId: text("family_id").notNull(),
90
- expiresAt: timestamp("expires_at", { withTimezone: true }).notNull(),
91
- revokedAt: timestamp("revoked_at", { withTimezone: true }),
92
- createdAt: timestamp("created_at", { withTimezone: true }).notNull()
93
- }, (table) => [
94
- index(`${prefix}_refresh_user_idx`).on(table.userId),
95
- index(`${prefix}_refresh_client_idx`).on(table.clientId),
96
- index(`${prefix}_refresh_family_idx`).on(table.familyId),
97
- index(`${prefix}_refresh_access_idx`).on(table.accessTokenHash),
98
- index(`${prefix}_refresh_expires_idx`).on(table.expiresAt)
99
- ]);
100
- return { clients, transactions, codes, accessTokens, refreshTokens };
101
- }
102
- // src/oauth/postgres/database.ts
103
- import { createHash } from "node:crypto";
104
- import { sql } from "drizzle-orm";
105
- function hashOpaqueValue(value) {
106
- return createHash("sha256").update(value).digest("hex");
107
- }
108
- function resultRows(result) {
109
- if (Array.isArray(result))
110
- return result;
111
- if (result && typeof result === "object" && "rows" in result && Array.isArray(result.rows)) {
112
- return result.rows;
113
- }
114
- return [];
115
- }
116
- function toDate(value) {
117
- if (value === null || value === undefined) {
118
- throw new TypeError("OAuth store timestamp column was null; expected a NOT NULL timestamp.");
119
- }
120
- const date = value instanceof Date ? value : new Date(value);
121
- if (Number.isNaN(date.getTime())) {
122
- throw new TypeError(`OAuth store timestamp could not be parsed: ${String(value)}`);
123
- }
124
- return date;
125
- }
126
- function toNullableDate(value) {
127
- return value === null || value === undefined ? null : toDate(value);
128
- }
129
- function coerceRowDates(row, required, nullable = []) {
130
- const record = row;
131
- for (const key of required)
132
- record[key] = toDate(record[key]);
133
- for (const key of nullable)
134
- record[key] = toNullableDate(record[key]);
135
- return row;
136
- }
137
- function affectedRows(result) {
138
- if (result && typeof result === "object" && "rowCount" in result && typeof result.rowCount === "number") {
139
- return result.rowCount;
140
- }
141
- return resultRows(result).length;
142
- }
143
- function countRows(result) {
144
- const row = resultRows(result)[0];
145
- return row ? Number(row.count) : 0;
146
- }
147
- function columnIdentifier(column) {
148
- return sql.identifier(column.name);
149
- }
150
- function qualifiedColumnIdentifier(alias, column) {
151
- return sql`${sql.identifier(alias)}.${columnIdentifier(column)}`;
152
- }
153
-
154
- // src/oauth/postgres/transaction-store.ts
155
- class PostgresTransactionStore {
156
- database;
157
- schema;
158
- constructor(database, schema) {
159
- this.database = database;
160
- this.schema = schema;
161
- }
162
- async create(input) {
163
- const record = input.record;
164
- const userId = columnIdentifier(this.schema.transactions.userId);
165
- await this.database.execute(sql`INSERT INTO ${this.schema.transactions} (
166
- transaction_id_hash, csrf_token_hash, consent_binding_hash, ${userId}, client_id,
167
- redirect_uri, code_challenge, code_challenge_method, state, issuer, resource,
168
- scope, expires_at, consumed_at, created_at
169
- ) VALUES (${hashOpaqueValue(input.transactionId)}, ${hashOpaqueValue(input.csrfToken)},
170
- ${hashOpaqueValue(input.consentBinding)}, ${record.userId}, ${record.clientId},
171
- ${record.redirectUri}, ${record.codeChallenge}, ${record.codeChallengeMethod},
172
- ${record.state}, ${record.issuer}, ${record.resource}, ${record.scope},
173
- ${record.expiresAt}, ${record.consumedAt}, ${record.createdAt})`);
174
- }
175
- async consume(transactionId, csrfToken, binding, subjectId) {
176
- const userId = columnIdentifier(this.schema.transactions.userId);
177
- const result = await this.database.execute(sql`UPDATE ${this.schema.transactions}
178
- SET consumed_at = date_trunc('milliseconds', clock_timestamp())
179
- WHERE transaction_id_hash = ${hashOpaqueValue(transactionId)}
180
- AND csrf_token_hash = ${hashOpaqueValue(csrfToken)}
181
- AND consent_binding_hash = ${hashOpaqueValue(binding)}
182
- AND ${userId}::text = ${subjectId}
183
- AND consumed_at IS NULL AND expires_at > clock_timestamp()
184
- RETURNING transaction_id_hash AS "transactionIdHash", ${userId}::text AS "userId",
185
- client_id AS "clientId", redirect_uri AS "redirectUri", code_challenge AS "codeChallenge",
186
- code_challenge_method AS "codeChallengeMethod", state, issuer, resource, scope,
187
- expires_at AS "expiresAt", consumed_at AS "consumedAt", created_at AS "createdAt"`);
188
- const row = resultRows(result)[0];
189
- return row ? coerceRowDates(row, ["expiresAt", "consumedAt", "createdAt"]) : null;
190
- }
191
- async unconsume(transactionId, consumedAt) {
192
- return affectedRows(await this.database.execute(sql`UPDATE ${this.schema.transactions} SET consumed_at = NULL
193
- WHERE transaction_id_hash = ${hashOpaqueValue(transactionId)} AND consumed_at = ${consumedAt} RETURNING 1`)) === 1;
194
- }
195
- async deleteByBinding(value) {
196
- return affectedRows(await this.database.execute(sql`DELETE FROM ${this.schema.transactions}
197
- WHERE consent_binding_hash = ${hashOpaqueValue(value)} RETURNING 1`));
198
- }
199
- async deleteAllForUser(userId) {
200
- const userIdColumn = columnIdentifier(this.schema.transactions.userId);
201
- return affectedRows(await this.database.execute(sql`DELETE FROM ${this.schema.transactions} WHERE ${userIdColumn} = ${userId} RETURNING 1`));
202
- }
203
- async purgeExpired(now) {
204
- return affectedRows(await this.database.execute(sql`DELETE FROM ${this.schema.transactions} WHERE expires_at <= ${now} RETURNING 1`));
205
- }
206
- }
207
- // src/oauth/postgres/code-store.ts
208
- function returnedCode(userId) {
209
- return sql`code_hash AS "codeHash", client_id AS "clientId", ${userId}::text AS "userId",
210
- redirect_uri AS "redirectUri", code_challenge AS "codeChallenge", code_challenge_method AS "codeChallengeMethod",
211
- scope, state, resource, expires_at AS "expiresAt", used_at AS "usedAt", created_at AS "createdAt"`;
212
- }
213
-
214
- class PostgresCodeStore {
215
- database;
216
- schema;
217
- constructor(database, schema) {
218
- this.database = database;
219
- this.schema = schema;
220
- }
221
- async issue(record) {
222
- const userId = columnIdentifier(this.schema.codes.userId);
223
- await this.database.execute(sql`INSERT INTO ${this.schema.codes} (code_hash, client_id, ${userId},
224
- redirect_uri, code_challenge, code_challenge_method, scope, state, resource, expires_at, used_at, created_at)
225
- VALUES (${record.codeHash}, ${record.clientId}, ${record.userId}, ${record.redirectUri},
226
- ${record.codeChallenge}, ${record.codeChallengeMethod}, ${record.scope}, ${record.state},
227
- ${record.resource}, ${record.expiresAt}, ${record.usedAt}, ${record.createdAt})`);
228
- }
229
- async findByHash(codeHash) {
230
- const userId = columnIdentifier(this.schema.codes.userId);
231
- const result = await this.database.execute(sql`SELECT ${returnedCode(userId)} FROM ${this.schema.codes} WHERE code_hash = ${codeHash}`);
232
- const row = resultRows(result)[0];
233
- return row ? coerceRowDates(row, ["expiresAt", "createdAt"], ["usedAt"]) : null;
234
- }
235
- async consume(codeHash, now) {
236
- const userId = columnIdentifier(this.schema.codes.userId);
237
- const result = await this.database.execute(sql`UPDATE ${this.schema.codes} SET used_at = date_trunc('milliseconds', clock_timestamp())
238
- WHERE code_hash = ${codeHash} AND used_at IS NULL AND expires_at > ${now} RETURNING ${returnedCode(userId)}`);
239
- const row = resultRows(result)[0];
240
- return row ? coerceRowDates(row, ["expiresAt", "usedAt", "createdAt"]) : null;
241
- }
242
- async unconsume(codeHash, usedAt) {
243
- return affectedRows(await this.database.execute(sql`UPDATE ${this.schema.codes} SET used_at = NULL
244
- WHERE code_hash = ${codeHash} AND used_at = ${usedAt} RETURNING 1`)) === 1;
245
- }
246
- async deleteAllForUser(userId) {
247
- const userIdColumn = columnIdentifier(this.schema.codes.userId);
248
- return affectedRows(await this.database.execute(sql`DELETE FROM ${this.schema.codes} WHERE ${userIdColumn} = ${userId} RETURNING 1`));
249
- }
250
- async purgeExpired(now) {
251
- return affectedRows(await this.database.execute(sql`DELETE FROM ${this.schema.codes} WHERE expires_at <= ${now} RETURNING 1`));
252
- }
253
- }
254
- // src/oauth/postgres/token-store.ts
255
- function returnedAccessToken(userId) {
256
- return sql`access_token_hash AS "accessTokenHash", client_id AS "clientId", ${userId}::text AS "userId",
257
- scope, resource, expires_at AS "expiresAt", revoked_at AS "revokedAt", created_at AS "createdAt"`;
258
- }
259
-
260
- class PostgresTokenStore {
261
- database;
262
- schema;
263
- constructor(database, schema) {
264
- this.database = database;
265
- this.schema = schema;
266
- }
267
- async issueAuthorizationGrant(input) {
268
- const access = input.accessToken;
269
- const refresh = input.refreshToken;
270
- const accessUserId = columnIdentifier(this.schema.accessTokens.userId);
271
- const refreshUserId = columnIdentifier(this.schema.refreshTokens.userId);
272
- await this.database.execute(sql`WITH inserted_access AS (
273
- INSERT INTO ${this.schema.accessTokens} (access_token_hash, client_id, ${accessUserId}, scope, resource, expires_at, revoked_at, created_at)
274
- VALUES (${access.accessTokenHash}, ${access.clientId}, ${access.userId}, ${access.scope}, ${access.resource},
275
- ${access.expiresAt}, ${access.revokedAt}, ${access.createdAt}) RETURNING access_token_hash
276
- ) ${refresh ? sql`INSERT INTO ${this.schema.refreshTokens} (refresh_token_hash, client_id, ${refreshUserId}, scope, resource,
277
- access_token_hash, family_id, expires_at, revoked_at, created_at)
278
- SELECT ${refresh.refreshTokenHash}, ${refresh.clientId}, ${refresh.userId}, ${refresh.scope}, ${refresh.resource},
279
- access_token_hash, ${refresh.familyId}, ${refresh.expiresAt}, ${refresh.revokedAt}, ${refresh.createdAt} FROM inserted_access` : sql`SELECT access_token_hash FROM inserted_access`}`);
280
- }
281
- async findByHash(tokenHash) {
282
- const userId = columnIdentifier(this.schema.accessTokens.userId);
283
- const result = await this.database.execute(sql`SELECT ${returnedAccessToken(userId)} FROM ${this.schema.accessTokens}
284
- WHERE access_token_hash = ${tokenHash}`);
285
- const row = resultRows(result)[0];
286
- return row ? coerceRowDates(row, ["expiresAt", "createdAt"], ["revokedAt"]) : null;
287
- }
288
- async rotateRefreshToken(input) {
289
- return this.database.transaction(async (transaction) => {
290
- const accessUserId = columnIdentifier(this.schema.accessTokens.userId);
291
- const refreshUserId = columnIdentifier(this.schema.refreshTokens.userId);
292
- const priorUserId = qualifiedColumnIdentifier("prior", this.schema.refreshTokens.userId);
293
- const accessResultUserId = qualifiedColumnIdentifier("a", this.schema.accessTokens.userId);
294
- const refreshResultUserId = qualifiedColumnIdentifier("r", this.schema.refreshTokens.userId);
295
- const familyResult = await transaction.execute(sql`SELECT family_id AS "familyId" FROM ${this.schema.refreshTokens}
296
- WHERE refresh_token_hash = ${input.priorHash}
297
- AND client_id = ${input.clientId} AND resource = ${input.resource}`);
298
- const familyId = resultRows(familyResult)[0]?.familyId;
299
- if (!familyId)
300
- return { status: "invalid" };
301
- await transaction.execute(sql`SELECT pg_advisory_xact_lock(hashtextextended(${familyId}, 0))`);
302
- const result = await transaction.execute(sql`WITH prior AS MATERIALIZED (
303
- SELECT * FROM ${this.schema.refreshTokens} WHERE refresh_token_hash = ${input.priorHash}
304
- AND client_id = ${input.clientId} AND resource = ${input.resource} FOR UPDATE
305
- ), live AS (
306
- SELECT * FROM prior WHERE revoked_at IS NULL AND expires_at > ${input.createdAt}
307
- ), replayable AS (
308
- SELECT * FROM prior WHERE revoked_at IS NOT NULL
309
- ), eligible AS (
310
- SELECT * FROM live WHERE (${input.requestedScope ?? null}::text IS NULL OR NOT EXISTS (
311
- SELECT requested_scope FROM unnest(string_to_array(${input.requestedScope ?? ""}, ' ')) requested_scope
312
- WHERE requested_scope <> '' AND requested_scope <> ALL(string_to_array(COALESCE(live.scope, ''), ' '))))
313
- ), revoked_prior AS (
314
- UPDATE ${this.schema.refreshTokens} SET revoked_at = ${input.createdAt}
315
- WHERE refresh_token_hash IN (SELECT refresh_token_hash FROM eligible) RETURNING *
316
- ), revoked_access AS (
317
- UPDATE ${this.schema.accessTokens} SET revoked_at = ${input.createdAt}
318
- WHERE access_token_hash IN (SELECT access_token_hash FROM revoked_prior) RETURNING access_token_hash
319
- ), inserted_access AS (
320
- INSERT INTO ${this.schema.accessTokens} (access_token_hash, client_id, ${accessUserId}, scope, resource, expires_at, revoked_at, created_at)
321
- SELECT ${input.nextAccessTokenHash}, client_id, ${refreshUserId}, COALESCE(${input.requestedScope ?? null}::text, scope),
322
- resource, ${input.accessTokenExpiresAt}, NULL, ${input.createdAt} FROM revoked_prior
323
- RETURNING *
324
- ), inserted_refresh AS (
325
- INSERT INTO ${this.schema.refreshTokens} (refresh_token_hash, client_id, ${refreshUserId}, scope, resource,
326
- access_token_hash, family_id, expires_at, revoked_at, created_at)
327
- SELECT ${input.nextRefreshTokenHash}, prior.client_id, ${priorUserId},
328
- COALESCE(${input.requestedScope ?? null}::text, prior.scope), prior.resource,
329
- inserted_access.access_token_hash, prior.family_id, ${input.refreshTokenExpiresAt}, NULL, ${input.createdAt}
330
- FROM revoked_prior prior CROSS JOIN inserted_access RETURNING *
331
- ), replay_refresh AS (
332
- UPDATE ${this.schema.refreshTokens} SET revoked_at = COALESCE(revoked_at, ${input.createdAt})
333
- WHERE family_id IN (SELECT family_id FROM replayable) AND revoked_at IS NULL RETURNING access_token_hash
334
- ), replay_access AS (
335
- UPDATE ${this.schema.accessTokens} SET revoked_at = COALESCE(revoked_at, ${input.createdAt})
336
- WHERE access_token_hash IN (SELECT access_token_hash FROM replay_refresh) RETURNING access_token_hash
337
- )
338
- SELECT CASE
339
- WHEN EXISTS (SELECT 1 FROM inserted_refresh) THEN 'rotated'
340
- WHEN EXISTS (SELECT 1 FROM replayable) THEN 'replay_revoked'
341
- WHEN EXISTS (SELECT 1 FROM live) AND ${input.requestedScope ?? null}::text IS NOT NULL THEN 'scope_rejected'
342
- ELSE 'invalid' END AS status,
343
- (SELECT ${refreshUserId}::text FROM prior LIMIT 1) AS "userId",
344
- (SELECT family_id FROM prior LIMIT 1) AS "familyId",
345
- (SELECT jsonb_set(to_jsonb(a), '{user_id}', to_jsonb(${accessResultUserId}::text))
346
- FROM inserted_access a LIMIT 1) AS access,
347
- (SELECT jsonb_set(to_jsonb(r), '{user_id}', to_jsonb(${refreshResultUserId}::text))
348
- FROM inserted_refresh r LIMIT 1) AS refresh`);
349
- const row = resultRows(result)[0];
350
- if (!row || row.status === "invalid")
351
- return { status: "invalid" };
352
- if (row.status === "scope_rejected")
353
- return { status: "scope_rejected" };
354
- if (row.status === "replay_revoked")
355
- return { status: "replay_revoked", userId: row.userId, familyId: row.familyId };
356
- return {
357
- status: "rotated",
358
- accessToken: mapAccess(row.access),
359
- refreshToken: mapRefresh(row.refresh)
360
- };
361
- });
362
- }
363
- async revokeAccessToken(tokenHash, clientId) {
364
- return this.database.transaction(async (transaction) => {
365
- const familyResult = await transaction.execute(sql`SELECT family_id AS "familyId" FROM ${this.schema.refreshTokens}
366
- WHERE access_token_hash = ${tokenHash} AND client_id = ${clientId}`);
367
- const familyId = resultRows(familyResult)[0]?.familyId;
368
- if (familyId) {
369
- await transaction.execute(sql`SELECT pg_advisory_xact_lock(hashtextextended(${familyId}, 0))`);
370
- }
371
- const result = await transaction.execute(sql`WITH target AS MATERIALIZED (
372
- SELECT access.revoked_at AS "revokedAt", refresh.family_id AS "familyId"
373
- FROM ${this.schema.accessTokens} access
374
- LEFT JOIN ${this.schema.refreshTokens} refresh
375
- ON refresh.access_token_hash = access.access_token_hash
376
- AND refresh.client_id = access.client_id
377
- WHERE access.access_token_hash = ${tokenHash} AND access.client_id = ${clientId}
378
- ), family_members AS MATERIALIZED (
379
- SELECT access_token_hash FROM ${this.schema.refreshTokens}
380
- WHERE family_id IN (SELECT "familyId" FROM target WHERE "revokedAt" IS NOT NULL)
381
- ), revoked_refresh AS (
382
- UPDATE ${this.schema.refreshTokens} SET revoked_at = clock_timestamp()
383
- WHERE revoked_at IS NULL AND (
384
- access_token_hash IN (SELECT ${tokenHash} FROM target WHERE "revokedAt" IS NULL)
385
- OR access_token_hash IN (SELECT access_token_hash FROM family_members)
386
- )
387
- RETURNING 1
388
- ), revoked_access AS (
389
- UPDATE ${this.schema.accessTokens} SET revoked_at = clock_timestamp()
390
- WHERE revoked_at IS NULL AND client_id = ${clientId} AND (
391
- access_token_hash IN (SELECT ${tokenHash} FROM target)
392
- OR access_token_hash IN (SELECT access_token_hash FROM family_members)
393
- )
394
- RETURNING 1
395
- ) SELECT
396
- (SELECT count(*) FROM revoked_access) + (SELECT count(*) FROM revoked_refresh) AS count`);
397
- return countRows(result) > 0;
398
- });
399
- }
400
- async revokeRefreshToken(tokenHash, clientId) {
401
- return this.database.transaction(async (transaction) => {
402
- const priorUserId = columnIdentifier(this.schema.refreshTokens.userId);
403
- const familyResult = await transaction.execute(sql`SELECT family_id AS "familyId" FROM ${this.schema.refreshTokens}
404
- WHERE refresh_token_hash = ${tokenHash}
405
- AND client_id = ${clientId}`);
406
- const familyId = resultRows(familyResult)[0]?.familyId;
407
- if (!familyId)
408
- return { status: "invalid" };
409
- await transaction.execute(sql`SELECT pg_advisory_xact_lock(hashtextextended(${familyId}, 0))`);
410
- const result = await transaction.execute(sql`WITH prior AS MATERIALIZED (
411
- SELECT * FROM ${this.schema.refreshTokens} WHERE refresh_token_hash = ${tokenHash}
412
- AND client_id = ${clientId} FOR UPDATE
413
- ), family_members AS MATERIALIZED (
414
- SELECT access_token_hash FROM ${this.schema.refreshTokens}
415
- WHERE family_id IN (SELECT family_id FROM prior WHERE revoked_at IS NOT NULL)
416
- ), revoked_family_refresh AS (
417
- UPDATE ${this.schema.refreshTokens} SET revoked_at = clock_timestamp()
418
- WHERE family_id IN (SELECT family_id FROM prior WHERE revoked_at IS NOT NULL) AND revoked_at IS NULL
419
- ), revoked_family_access AS (
420
- UPDATE ${this.schema.accessTokens} SET revoked_at = clock_timestamp()
421
- WHERE access_token_hash IN (SELECT access_token_hash FROM family_members) AND revoked_at IS NULL
422
- ), revoked_refresh AS (
423
- UPDATE ${this.schema.refreshTokens} SET revoked_at = clock_timestamp()
424
- WHERE refresh_token_hash IN (
425
- SELECT refresh_token_hash FROM prior
426
- WHERE revoked_at IS NULL AND expires_at > clock_timestamp()
427
- )
428
- RETURNING access_token_hash
429
- ), revoked_access AS (
430
- UPDATE ${this.schema.accessTokens} SET revoked_at = clock_timestamp()
431
- WHERE access_token_hash IN (SELECT access_token_hash FROM revoked_refresh) AND revoked_at IS NULL
432
- )
433
- SELECT CASE WHEN NOT EXISTS (SELECT 1 FROM prior) THEN 'invalid'
434
- WHEN EXISTS (SELECT 1 FROM prior WHERE revoked_at IS NOT NULL) THEN 'replay_revoked'
435
- WHEN EXISTS (SELECT 1 FROM revoked_refresh) THEN 'revoked'
436
- ELSE 'invalid' END AS status,
437
- (SELECT ${priorUserId}::text FROM prior LIMIT 1) AS "userId",
438
- (SELECT family_id FROM prior LIMIT 1) AS "familyId"`);
439
- const row = resultRows(result)[0];
440
- if (!row || row.status === "invalid")
441
- return { status: "invalid" };
442
- return { status: row.status, userId: row.userId, familyId: row.familyId };
443
- });
444
- }
445
- async revokeFamily(familyId) {
446
- return this.database.transaction(async (transaction) => {
447
- await transaction.execute(sql`SELECT pg_advisory_xact_lock(hashtextextended(${familyId}, 0))`);
448
- const result = await transaction.execute(sql`WITH family_members AS MATERIALIZED (
449
- SELECT access_token_hash FROM ${this.schema.refreshTokens} WHERE family_id = ${familyId}
450
- ), revoked_refresh AS (
451
- UPDATE ${this.schema.refreshTokens} SET revoked_at = clock_timestamp()
452
- WHERE family_id = ${familyId} AND revoked_at IS NULL RETURNING 1
453
- ), revoked_access AS (
454
- UPDATE ${this.schema.accessTokens} SET revoked_at = clock_timestamp()
455
- WHERE access_token_hash IN (SELECT access_token_hash FROM family_members) AND revoked_at IS NULL RETURNING 1
456
- ) SELECT (SELECT count(*) FROM revoked_refresh) + (SELECT count(*) FROM revoked_access) AS count`);
457
- return countRows(result);
458
- });
459
- }
460
- async deleteAllForUser(userId) {
461
- const accessUserId = columnIdentifier(this.schema.accessTokens.userId);
462
- const refreshUserId = columnIdentifier(this.schema.refreshTokens.userId);
463
- const result = await this.database.execute(sql`WITH deleted_refresh AS (
464
- DELETE FROM ${this.schema.refreshTokens} WHERE ${refreshUserId} = ${userId} RETURNING 1
465
- ), deleted_access AS (
466
- DELETE FROM ${this.schema.accessTokens} WHERE ${accessUserId} = ${userId} RETURNING 1
467
- ) SELECT (SELECT count(*) FROM deleted_refresh) + (SELECT count(*) FROM deleted_access) AS count`);
468
- return countRows(result);
469
- }
470
- async purgeExpired(now) {
471
- const result = await this.database.execute(sql`WITH deleted_refresh AS (
472
- DELETE FROM ${this.schema.refreshTokens} WHERE expires_at <= ${now} RETURNING 1
473
- ), deleted_access AS (
474
- DELETE FROM ${this.schema.accessTokens} access WHERE expires_at <= ${now}
475
- AND NOT EXISTS (SELECT 1 FROM ${this.schema.refreshTokens} refresh
476
- WHERE refresh.access_token_hash = access.access_token_hash AND refresh.expires_at > ${now}) RETURNING 1
477
- ) SELECT (SELECT count(*) FROM deleted_refresh) + (SELECT count(*) FROM deleted_access) AS count`);
478
- return countRows(result);
479
- }
480
- }
481
- function mapAccess(row) {
482
- return {
483
- accessTokenHash: row.access_token_hash,
484
- clientId: row.client_id,
485
- userId: String(row.user_id),
486
- scope: row.scope,
487
- resource: row.resource,
488
- expiresAt: new Date(row.expires_at),
489
- revokedAt: row.revoked_at ? new Date(row.revoked_at) : null,
490
- createdAt: new Date(row.created_at)
491
- };
492
- }
493
- function mapRefresh(row) {
494
- return {
495
- refreshTokenHash: row.refresh_token_hash,
496
- clientId: row.client_id,
497
- userId: String(row.user_id),
498
- scope: row.scope,
499
- resource: row.resource,
500
- accessTokenHash: row.access_token_hash,
501
- familyId: row.family_id,
502
- expiresAt: new Date(row.expires_at),
503
- revokedAt: row.revoked_at ? new Date(row.revoked_at) : null,
504
- createdAt: new Date(row.created_at)
505
- };
506
- }
507
- // src/oauth/postgres/client-store.ts
508
- var returnedClient = sql`client_id AS "clientId", client_secret_hash AS "clientSecretHash",
509
- client_name AS "clientName", client_type AS "clientType", token_endpoint_auth_method AS "tokenEndpointAuthMethod",
510
- application_type AS "applicationType", redirect_uris AS "redirectUris", grant_types AS "grantTypes",
511
- response_types AS "responseTypes", client_id_metadata_url AS "clientIdMetadataUrl",
512
- client_secret_expires_at AS "clientSecretExpiresAt", created_at AS "createdAt", updated_at AS "updatedAt"`;
513
-
514
- class PostgresClientStore {
515
- database;
516
- schema;
517
- constructor(database, schema) {
518
- this.database = database;
519
- this.schema = schema;
520
- }
521
- async register(record) {
522
- await this.database.execute(sql`INSERT INTO ${this.schema.clients} (client_id, client_secret_hash,
523
- client_name, client_type, token_endpoint_auth_method, application_type, redirect_uris,
524
- grant_types, response_types, client_id_metadata_url, client_secret_expires_at, created_at, updated_at)
525
- VALUES (${record.clientId}, ${record.clientSecretHash}, ${record.clientName}, ${record.clientType},
526
- ${record.tokenEndpointAuthMethod}, ${record.applicationType}, ${JSON.stringify(record.redirectUris)}::jsonb,
527
- ${JSON.stringify(record.grantTypes)}::jsonb, ${JSON.stringify(record.responseTypes)}::jsonb,
528
- ${record.clientIdMetadataUrl}, ${record.clientSecretExpiresAt}, ${record.createdAt}, ${record.updatedAt})`);
529
- }
530
- async upsert(record) {
531
- await this.database.execute(sql`INSERT INTO ${this.schema.clients} (client_id, client_secret_hash,
532
- client_name, client_type, token_endpoint_auth_method, application_type, redirect_uris,
533
- grant_types, response_types, client_id_metadata_url, client_secret_expires_at, created_at, updated_at)
534
- VALUES (${record.clientId}, ${record.clientSecretHash}, ${record.clientName}, ${record.clientType},
535
- ${record.tokenEndpointAuthMethod}, ${record.applicationType}, ${JSON.stringify(record.redirectUris)}::jsonb,
536
- ${JSON.stringify(record.grantTypes)}::jsonb, ${JSON.stringify(record.responseTypes)}::jsonb,
537
- ${record.clientIdMetadataUrl}, ${record.clientSecretExpiresAt}, ${record.createdAt}, ${record.updatedAt})
538
- ON CONFLICT (client_id) DO UPDATE SET client_secret_hash = EXCLUDED.client_secret_hash,
539
- client_name = EXCLUDED.client_name, client_type = EXCLUDED.client_type,
540
- token_endpoint_auth_method = EXCLUDED.token_endpoint_auth_method, application_type = EXCLUDED.application_type,
541
- redirect_uris = EXCLUDED.redirect_uris, grant_types = EXCLUDED.grant_types,
542
- response_types = EXCLUDED.response_types, client_id_metadata_url = EXCLUDED.client_id_metadata_url,
543
- client_secret_expires_at = EXCLUDED.client_secret_expires_at, created_at = EXCLUDED.created_at,
544
- updated_at = EXCLUDED.updated_at`);
545
- }
546
- async findById(clientId) {
547
- const result = await this.database.execute(sql`SELECT ${returnedClient} FROM ${this.schema.clients} WHERE client_id = ${clientId}`);
548
- const client = resultRows(result)[0];
549
- if (!client)
550
- return null;
551
- coerceRowDates(client, ["createdAt", "updatedAt"], ["clientSecretExpiresAt"]);
552
- return structuredClone(client);
553
- }
554
- async update(clientId, patch) {
555
- const columns = {
556
- clientSecretHash: "client_secret_hash",
557
- clientName: "client_name",
558
- clientType: "client_type",
559
- tokenEndpointAuthMethod: "token_endpoint_auth_method",
560
- applicationType: "application_type",
561
- redirectUris: "redirect_uris",
562
- grantTypes: "grant_types",
563
- responseTypes: "response_types",
564
- clientIdMetadataUrl: "client_id_metadata_url",
565
- clientSecretExpiresAt: "client_secret_expires_at",
566
- createdAt: "created_at",
567
- updatedAt: "updated_at"
568
- };
569
- const jsonKeys = new Set([
570
- "redirectUris",
571
- "grantTypes",
572
- "responseTypes"
573
- ]);
574
- const assignments = Object.entries(patch).flatMap(([rawKey, value]) => {
575
- if (rawKey === "clientId" || value === undefined || !(rawKey in columns))
576
- return [];
577
- const key = rawKey;
578
- const column = sql.identifier(columns[key]);
579
- return [
580
- jsonKeys.has(key) ? sql`${column} = ${JSON.stringify(value)}::jsonb` : sql`${column} = ${value}`
581
- ];
582
- });
583
- if (assignments.length === 0)
584
- return;
585
- await this.database.execute(sql`UPDATE ${this.schema.clients} SET ${sql.join(assignments, sql`, `)} WHERE client_id = ${clientId}`);
586
- }
587
- }
588
- // src/oauth/postgres/index.ts
589
- function createPostgresOAuthStores(database, schema) {
590
- const transactions = new PostgresTransactionStore(database, schema);
591
- const codes = new PostgresCodeStore(database, schema);
592
- const tokens = new PostgresTokenStore(database, schema);
593
- const clients = new PostgresClientStore(database, schema);
594
- return {
595
- transactions,
596
- codes,
597
- tokens,
598
- clients,
599
- async deleteAllForUser(userId) {
600
- const [transactionCount, codeCount, tokenCount] = await Promise.all([
601
- transactions.deleteAllForUser(userId),
602
- codes.deleteAllForUser(userId),
603
- tokens.deleteAllForUser(userId)
604
- ]);
605
- return { transactions: transactionCount, codes: codeCount, tokens: tokenCount };
606
- }
607
- };
608
- }
609
- export {
610
- PostgresClientStore,
611
- PostgresCodeStore,
612
- PostgresTokenStore,
613
- PostgresTransactionStore,
614
- createPostgresOAuthSchema,
615
- createPostgresOAuthStores
616
- };