@structured-world/gitlab-mcp-db 10.1.0 → 12.0.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 (35) hide show
  1. package/README.md +8 -8
  2. package/dist/generated/prisma/client.d.ts +2 -0
  3. package/dist/generated/prisma/commonInputTypes.d.ts +178 -9
  4. package/dist/generated/prisma/internal/class.d.ts +6 -0
  5. package/dist/generated/prisma/internal/class.js +6 -6
  6. package/dist/generated/prisma/internal/class.js.map +1 -1
  7. package/dist/generated/prisma/internal/prismaNamespace.d.ts +209 -1
  8. package/dist/generated/prisma/internal/prismaNamespace.js +56 -5
  9. package/dist/generated/prisma/internal/prismaNamespace.js.map +1 -1
  10. package/dist/generated/prisma/models/AccountSettings.d.ts +400 -0
  11. package/dist/generated/prisma/models/AccountSettings.js +3 -0
  12. package/dist/generated/prisma/models/AccountSettings.js.map +1 -0
  13. package/dist/generated/prisma/models/AuthCodeFlowState.d.ts +174 -2
  14. package/dist/generated/prisma/models/DeviceFlowState.d.ts +214 -2
  15. package/dist/generated/prisma/models/OAuthClient.d.ts +577 -0
  16. package/dist/generated/prisma/models/OAuthClient.js +3 -0
  17. package/dist/generated/prisma/models/OAuthClient.js.map +1 -0
  18. package/dist/generated/prisma/models/OAuthSession.d.ts +555 -3
  19. package/dist/generated/prisma/models.d.ts +2 -0
  20. package/dist/src/migrate.d.ts +16 -0
  21. package/dist/src/migrate.js +115 -0
  22. package/dist/src/migrate.js.map +1 -0
  23. package/dist/src/postgresql.d.ts +29 -1
  24. package/dist/src/postgresql.js +580 -86
  25. package/dist/src/postgresql.js.map +1 -1
  26. package/dist/tsconfig.tsbuildinfo +1 -1
  27. package/package.json +12 -6
  28. package/prisma/migrations/0_init/migration.sql +115 -0
  29. package/prisma/migrations/20261008000000_released_schema_columns/migration.sql +15 -0
  30. package/prisma/migrations/20261009000000_oauth_account_linking/migration.sql +47 -0
  31. package/prisma/migrations/20261010000000_account_settings/migration.sql +12 -0
  32. package/prisma/migrations/20261017000000_linked_accounts/migration.sql +15 -0
  33. package/prisma/migrations/migration_lock.toml +3 -0
  34. package/prisma/schema.prisma +66 -0
  35. package/prisma.config.ts +19 -0
@@ -34,21 +34,98 @@ var __importStar = (this && this.__importStar) || (function () {
34
34
  })();
35
35
  Object.defineProperty(exports, "__esModule", { value: true });
36
36
  exports.PostgreSQLStorageBackend = void 0;
37
+ const node_crypto_1 = require("node:crypto");
37
38
  const logger_1 = require("./logger");
39
+ const CLAIMED_FLOW_PREFIX = 'cleanup:';
40
+ class LinkCommitConflict extends Error {
41
+ }
42
+ const CLEANUP_BATCH = 5;
43
+ async function inBatches(items, run, from = 0) {
44
+ if (from >= items.length)
45
+ return;
46
+ await Promise.all(items.slice(from, from + CLEANUP_BATCH).map((item) => run(item)));
47
+ return inBatches(items, run, from + CLEANUP_BATCH);
48
+ }
49
+ function storedGitlabScopes(value) {
50
+ if (value == null)
51
+ return undefined;
52
+ if (!Array.isArray(value) || !value.every((scope) => typeof scope === 'string')) {
53
+ throw new Error('Invalid stored GitLab scopes');
54
+ }
55
+ return value;
56
+ }
57
+ function storedMcpScopes(value) {
58
+ if (value == null)
59
+ return undefined;
60
+ if (!Array.isArray(value) || !value.every((scope) => typeof scope === 'string')) {
61
+ throw new Error('Invalid stored MCP scopes');
62
+ }
63
+ return value;
64
+ }
65
+ function storedGitlabTokens(value) {
66
+ if (value == null)
67
+ return undefined;
68
+ const tokens = value;
69
+ if (typeof tokens.access_token !== 'string' ||
70
+ typeof tokens.refresh_token !== 'string' ||
71
+ typeof tokens.token_type !== 'string' ||
72
+ typeof tokens.expires_in !== 'number' ||
73
+ typeof tokens.created_at !== 'number' ||
74
+ (tokens.scope !== undefined && typeof tokens.scope !== 'string')) {
75
+ throw new Error('Invalid stored GitLab tokens');
76
+ }
77
+ return value;
78
+ }
79
+ function storedLinkStep(value) {
80
+ if (value == null)
81
+ return undefined;
82
+ const step = value;
83
+ if (typeof step.sessionId !== 'string' ||
84
+ (step.stage !== 'verify' && step.stage !== 'connect') ||
85
+ typeof step.instance !== 'string' ||
86
+ (step.instanceLabel !== undefined && typeof step.instanceLabel !== 'string') ||
87
+ (step.browserBinding !== undefined && typeof step.browserBinding !== 'string') ||
88
+ (step.mcpSessionId !== undefined && typeof step.mcpSessionId !== 'string') ||
89
+ (step.elicitationId !== undefined && typeof step.elicitationId !== 'string')) {
90
+ throw new Error('Invalid stored account link step');
91
+ }
92
+ return value;
93
+ }
94
+ function optional(value) {
95
+ return value ?? undefined;
96
+ }
38
97
  class PostgreSQLStorageBackend {
39
98
  type = 'postgresql';
40
99
  prisma = null;
41
100
  cleanupIntervalId = null;
101
+ abandonedFlowGrant;
102
+ expiredSession;
103
+ connectionString;
104
+ constructor(options = {}) {
105
+ this.connectionString =
106
+ options.connectionString ??
107
+ process.env.OAUTH_STORAGE_POSTGRESQL_URL ??
108
+ process.env.DATABASE_URL;
109
+ }
42
110
  async initialize() {
43
111
  try {
112
+ if (!this.connectionString) {
113
+ throw new Error('PostgreSQL storage requires OAUTH_STORAGE_POSTGRESQL_URL or DATABASE_URL');
114
+ }
44
115
  const prismaModule = (await Promise.resolve().then(() => __importStar(require('../generated/prisma/client'))));
45
- this.prisma = new prismaModule.PrismaClient({});
116
+ const { PrismaPg } = await Promise.resolve().then(() => __importStar(require('@prisma/adapter-pg')));
117
+ const schema = new URL(this.connectionString).searchParams.get('schema') ?? undefined;
118
+ this.prisma = new prismaModule.PrismaClient({
119
+ adapter: new PrismaPg({ connectionString: this.connectionString }, schema ? { schema } : undefined),
120
+ });
46
121
  await this.prisma.$connect();
47
122
  this.startCleanupInterval();
48
123
  (0, logger_1.logInfo)('PostgreSQL storage backend initialized via Prisma');
49
124
  }
50
125
  catch (error) {
51
- (0, logger_1.logError)('Failed to initialize PostgreSQL storage backend', { err: error });
126
+ (0, logger_1.logError)('Failed to initialize PostgreSQL storage backend', {
127
+ err: error,
128
+ });
52
129
  throw error;
53
130
  }
54
131
  }
@@ -58,8 +135,85 @@ class PostgreSQLStorageBackend {
58
135
  }
59
136
  return this.prisma;
60
137
  }
61
- async createSession(session) {
62
- const prisma = this.getPrisma();
138
+ async commitLinkedAccount(commit) {
139
+ const { Prisma } = await Promise.resolve().then(() => __importStar(require('../generated/prisma/client')));
140
+ const { account, internalState, primaryLeaseUntil, existing } = commit;
141
+ const updates = this.sessionUpdateData({
142
+ gitlabAccessToken: account.gitlabAccessToken,
143
+ gitlabRefreshToken: account.gitlabRefreshToken,
144
+ gitlabTokenExpiry: account.gitlabTokenExpiry,
145
+ gitlabScopes: account.gitlabScopes,
146
+ gitlabUsername: account.gitlabUsername,
147
+ });
148
+ if (existing && account.gitlabScopes === undefined) {
149
+ updates.gitlabScopes = Prisma.DbNull;
150
+ }
151
+ try {
152
+ return await this.getPrisma().$transaction(async (tx) => {
153
+ const now = Date.now();
154
+ const primary = (await tx.oAuthSession.updateMany({
155
+ where: {
156
+ id: account.linkedToSessionId,
157
+ gitlabRefreshLeaseUntil: { equals: BigInt(primaryLeaseUntil), gt: BigInt(now) },
158
+ },
159
+ data: { updatedAt: BigInt(now) },
160
+ }));
161
+ if (primary.count !== 1)
162
+ throw new LinkCommitConflict();
163
+ const flow = (await tx.authCodeFlowState.deleteMany({
164
+ where: {
165
+ internalState,
166
+ expiresAt: { gt: BigInt(now) },
167
+ NOT: { internalState: { startsWith: CLAIMED_FLOW_PREFIX } },
168
+ AND: [
169
+ { link: { path: ['sessionId'], equals: account.linkedToSessionId } },
170
+ { link: { path: ['stage'], equals: 'connect' } },
171
+ ],
172
+ OR: [
173
+ { gitlabTokens: { equals: Prisma.AnyNull } },
174
+ {
175
+ AND: [
176
+ { gitlabTokens: { path: ['access_token'], equals: account.gitlabAccessToken } },
177
+ { gitlabTokens: { path: ['refresh_token'], equals: account.gitlabRefreshToken } },
178
+ ],
179
+ },
180
+ ],
181
+ },
182
+ }));
183
+ if (flow.count !== 1)
184
+ throw new LinkCommitConflict();
185
+ if (existing) {
186
+ const updated = (await tx.oAuthSession.updateMany({
187
+ where: {
188
+ id: account.id,
189
+ linkedToSessionId: account.linkedToSessionId,
190
+ gitlabRefreshToken: existing.refreshToken,
191
+ gitlabRefreshLeaseUntil: { equals: BigInt(existing.leaseUntil), gt: BigInt(now) },
192
+ },
193
+ data: { ...updates, updatedAt: BigInt(now) },
194
+ }));
195
+ if (updated.count !== 1)
196
+ throw new LinkCommitConflict();
197
+ }
198
+ else {
199
+ await this.insertSession(tx, account);
200
+ }
201
+ return true;
202
+ });
203
+ }
204
+ catch (error) {
205
+ if (error instanceof LinkCommitConflict)
206
+ return false;
207
+ if (!existing &&
208
+ typeof error === 'object' &&
209
+ error !== null &&
210
+ 'code' in error &&
211
+ error.code === 'P2002')
212
+ return false;
213
+ throw error;
214
+ }
215
+ }
216
+ async insertSession(prisma, session) {
63
217
  await prisma.oAuthSession.create({
64
218
  data: {
65
219
  id: session.id,
@@ -69,16 +223,22 @@ class PostgreSQLStorageBackend {
69
223
  gitlabAccessToken: session.gitlabAccessToken,
70
224
  gitlabRefreshToken: session.gitlabRefreshToken,
71
225
  gitlabTokenExpiry: BigInt(session.gitlabTokenExpiry),
226
+ gitlabScopes: session.gitlabScopes,
72
227
  gitlabUserId: session.gitlabUserId,
73
228
  gitlabUsername: session.gitlabUsername,
74
229
  gitlabApiUrl: session.gitlabApiUrl,
75
230
  instanceLabel: session.instanceLabel,
76
231
  clientId: session.clientId,
77
232
  scopes: session.scopes,
233
+ resource: session.resource ?? null,
234
+ linkedToSessionId: session.linkedToSessionId ?? null,
78
235
  createdAt: BigInt(session.createdAt),
79
236
  updatedAt: BigInt(session.updatedAt),
80
237
  },
81
238
  });
239
+ }
240
+ async createSession(session) {
241
+ await this.insertSession(this.getPrisma(), session);
82
242
  (0, logger_1.logDebug)('Session created in PostgreSQL', { sessionId: session.id });
83
243
  }
84
244
  async getSession(sessionId) {
@@ -104,6 +264,21 @@ class PostgreSQLStorageBackend {
104
264
  }
105
265
  async updateSession(sessionId, updates) {
106
266
  const prisma = this.getPrisma();
267
+ const result = (await prisma.oAuthSession.updateMany({
268
+ where: { id: sessionId },
269
+ data: this.sessionUpdateData(updates),
270
+ }));
271
+ return result.count === 1;
272
+ }
273
+ async rotateSession(sessionId, expectedRefreshToken, updates) {
274
+ const prisma = this.getPrisma();
275
+ const result = (await prisma.oAuthSession.updateMany({
276
+ where: { id: sessionId, mcpRefreshToken: expectedRefreshToken },
277
+ data: this.sessionUpdateData(updates),
278
+ }));
279
+ return result.count === 1;
280
+ }
281
+ sessionUpdateData(updates) {
107
282
  const data = {
108
283
  updatedAt: BigInt(Date.now()),
109
284
  };
@@ -125,34 +300,37 @@ class PostgreSQLStorageBackend {
125
300
  if (updates.gitlabTokenExpiry !== undefined) {
126
301
  data.gitlabTokenExpiry = BigInt(updates.gitlabTokenExpiry);
127
302
  }
128
- try {
129
- await prisma.oAuthSession.update({
130
- where: { id: sessionId },
131
- data,
132
- });
133
- return true;
303
+ if (updates.gitlabScopes !== undefined) {
304
+ data.gitlabScopes = updates.gitlabScopes;
134
305
  }
135
- catch {
136
- return false;
306
+ if (updates.gitlabUsername !== undefined) {
307
+ data.gitlabUsername = updates.gitlabUsername;
137
308
  }
309
+ if (updates.resource !== undefined) {
310
+ data.resource = updates.resource;
311
+ }
312
+ return data;
138
313
  }
139
314
  async deleteSession(sessionId) {
140
315
  const prisma = this.getPrisma();
141
- try {
142
- await prisma.oAuthSession.delete({
143
- where: { id: sessionId },
144
- });
145
- return true;
146
- }
147
- catch {
148
- return false;
149
- }
316
+ const result = (await prisma.oAuthSession.deleteMany({
317
+ where: { id: sessionId },
318
+ }));
319
+ return result.count === 1;
150
320
  }
151
321
  async getAllSessions() {
152
322
  const prisma = this.getPrisma();
153
323
  const rows = (await prisma.oAuthSession.findMany());
154
324
  return rows.map((row) => this.rowToSession(row));
155
325
  }
326
+ async getLinkedSessions(sessionId) {
327
+ const prisma = this.getPrisma();
328
+ const rows = (await prisma.oAuthSession.findMany({
329
+ where: { linkedToSessionId: sessionId },
330
+ orderBy: { createdAt: 'asc' },
331
+ }));
332
+ return rows.map((row) => this.rowToSession(row));
333
+ }
156
334
  rowToSession(row) {
157
335
  return {
158
336
  id: row.id,
@@ -162,38 +340,45 @@ class PostgreSQLStorageBackend {
162
340
  gitlabAccessToken: row.gitlabAccessToken,
163
341
  gitlabRefreshToken: row.gitlabRefreshToken,
164
342
  gitlabTokenExpiry: Number(row.gitlabTokenExpiry),
343
+ gitlabScopes: storedGitlabScopes(row.gitlabScopes),
165
344
  gitlabUserId: row.gitlabUserId,
166
345
  gitlabUsername: row.gitlabUsername,
167
346
  gitlabApiUrl: row.gitlabApiUrl ?? undefined,
168
347
  instanceLabel: row.instanceLabel ?? undefined,
169
348
  clientId: row.clientId,
170
349
  scopes: row.scopes,
350
+ resource: optional(row.resource),
351
+ linkedToSessionId: optional(row.linkedToSessionId),
171
352
  createdAt: Number(row.createdAt),
172
353
  updatedAt: Number(row.updatedAt),
173
354
  };
174
355
  }
175
356
  async storeDeviceFlow(state, flow) {
176
357
  const prisma = this.getPrisma();
358
+ const data = {
359
+ deviceCode: flow.deviceCode,
360
+ userCode: flow.userCode,
361
+ verificationUri: flow.verificationUri,
362
+ verificationUriComplete: flow.verificationUriComplete ?? null,
363
+ expiresAt: BigInt(flow.expiresAt),
364
+ interval: flow.interval,
365
+ clientId: flow.clientId,
366
+ codeChallenge: flow.codeChallenge,
367
+ codeChallengeMethod: flow.codeChallengeMethod,
368
+ redirectUri: flow.redirectUri ?? null,
369
+ requestedGitlabScopes: flow.requestedGitlabScopes,
370
+ clientState: flow.state,
371
+ nextPollAt: flow.nextPollAt === undefined ? null : BigInt(flow.nextPollAt),
372
+ selectedInstance: flow.selectedInstance ?? null,
373
+ selectedInstanceLabel: flow.selectedInstanceLabel ?? null,
374
+ mcpScopes: flow.scopes,
375
+ resource: flow.resource ?? null,
376
+ gitlabTokens: flow.gitlabTokens,
377
+ };
177
378
  await prisma.deviceFlowState.upsert({
178
379
  where: { state },
179
- update: {
180
- deviceCode: flow.deviceCode,
181
- userCode: flow.userCode,
182
- expiresAt: BigInt(flow.expiresAt),
183
- },
184
- create: {
185
- state,
186
- deviceCode: flow.deviceCode,
187
- userCode: flow.userCode,
188
- verificationUri: flow.verificationUri,
189
- verificationUriComplete: flow.verificationUriComplete ?? null,
190
- expiresAt: BigInt(flow.expiresAt),
191
- interval: flow.interval,
192
- clientId: flow.clientId,
193
- codeChallenge: flow.codeChallenge,
194
- codeChallengeMethod: flow.codeChallengeMethod,
195
- redirectUri: flow.redirectUri ?? null,
196
- },
380
+ update: data,
381
+ create: { state, ...data },
197
382
  });
198
383
  }
199
384
  async getDeviceFlow(state) {
@@ -212,18 +397,14 @@ class PostgreSQLStorageBackend {
212
397
  }
213
398
  async deleteDeviceFlow(state) {
214
399
  const prisma = this.getPrisma();
215
- try {
216
- await prisma.deviceFlowState.delete({
217
- where: { state },
218
- });
219
- return true;
220
- }
221
- catch {
222
- return false;
223
- }
400
+ const result = (await prisma.deviceFlowState.deleteMany({
401
+ where: { state },
402
+ }));
403
+ return result.count === 1;
224
404
  }
225
405
  rowToDeviceFlow(row) {
226
406
  return {
407
+ requestedGitlabScopes: storedGitlabScopes(row.requestedGitlabScopes),
227
408
  deviceCode: row.deviceCode,
228
409
  userCode: row.userCode,
229
410
  verificationUri: row.verificationUri,
@@ -233,26 +414,99 @@ class PostgreSQLStorageBackend {
233
414
  clientId: row.clientId,
234
415
  codeChallenge: row.codeChallenge,
235
416
  codeChallengeMethod: row.codeChallengeMethod,
236
- state: row.state,
417
+ state: row.clientState ?? '',
237
418
  redirectUri: row.redirectUri ?? undefined,
419
+ nextPollAt: row.nextPollAt == null ? undefined : Number(row.nextPollAt),
420
+ selectedInstance: optional(row.selectedInstance),
421
+ selectedInstanceLabel: optional(row.selectedInstanceLabel),
422
+ scopes: storedMcpScopes(row.mcpScopes),
423
+ resource: optional(row.resource),
424
+ gitlabTokens: storedGitlabTokens(row.gitlabTokens),
238
425
  };
239
426
  }
240
- async storeAuthCodeFlow(internalState, flow) {
427
+ async cacheLinkedFlowTokens(flow, tokens) {
428
+ if (!flow.link)
429
+ throw new Error('An account-link flow is required');
241
430
  const prisma = this.getPrisma();
242
- await prisma.authCodeFlowState.create({
243
- data: {
244
- internalState,
245
- clientId: flow.clientId,
246
- codeChallenge: flow.codeChallenge,
247
- codeChallengeMethod: flow.codeChallengeMethod,
248
- clientState: flow.clientState,
249
- clientRedirectUri: flow.clientRedirectUri,
250
- callbackUri: flow.callbackUri,
251
- expiresAt: BigInt(flow.expiresAt),
431
+ const { Prisma } = await Promise.resolve().then(() => __importStar(require('../generated/prisma/client')));
432
+ const active = {
433
+ internalState: flow.internalState,
434
+ expiresAt: { gt: BigInt(Date.now()) },
435
+ NOT: { internalState: { startsWith: CLAIMED_FLOW_PREFIX } },
436
+ AND: [
437
+ { link: { path: ['sessionId'], equals: flow.link.sessionId } },
438
+ { link: { path: ['stage'], equals: flow.link.stage } },
439
+ ],
440
+ };
441
+ const updated = (await prisma.authCodeFlowState.updateMany({
442
+ where: { ...active, gitlabTokens: { equals: Prisma.AnyNull } },
443
+ data: { gitlabTokens: tokens },
444
+ }));
445
+ if (updated.count === 1)
446
+ return true;
447
+ const cached = await prisma.authCodeFlowState.findFirst({
448
+ where: {
449
+ ...active,
450
+ expiresAt: { gt: BigInt(Date.now()) },
451
+ AND: [
452
+ ...active.AND,
453
+ { gitlabTokens: { path: ['access_token'], equals: tokens.access_token } },
454
+ { gitlabTokens: { path: ['refresh_token'], equals: tokens.refresh_token } },
455
+ ],
252
456
  },
457
+ select: { internalState: true },
458
+ });
459
+ if (cached)
460
+ return true;
461
+ const grant = (0, node_crypto_1.createHash)('sha256')
462
+ .update(JSON.stringify([tokens.access_token, tokens.refresh_token]))
463
+ .digest('hex');
464
+ const internalState = `${CLAIMED_FLOW_PREFIX}issued:${flow.internalState}:${grant}`;
465
+ await prisma.authCodeFlowState.createMany({
466
+ skipDuplicates: true,
467
+ data: [
468
+ {
469
+ internalState,
470
+ ...this.authCodeFlowData({
471
+ ...flow,
472
+ gitlabTokens: tokens,
473
+ expiresAt: Date.now() - 1,
474
+ }),
475
+ },
476
+ ],
477
+ });
478
+ return false;
479
+ }
480
+ authCodeFlowData(flow) {
481
+ return {
482
+ clientId: flow.clientId,
483
+ codeChallenge: flow.codeChallenge,
484
+ codeChallengeMethod: flow.codeChallengeMethod,
485
+ clientState: flow.clientState,
486
+ clientRedirectUri: flow.clientRedirectUri,
487
+ callbackUri: flow.callbackUri,
488
+ expiresAt: BigInt(flow.expiresAt),
489
+ requestedGitlabScopes: flow.requestedGitlabScopes,
490
+ selectedInstance: flow.selectedInstance ?? null,
491
+ selectedInstanceLabel: flow.selectedInstanceLabel ?? null,
492
+ mcpScopes: flow.scopes,
493
+ resource: flow.resource ?? null,
494
+ gitlabTokens: flow.gitlabTokens,
495
+ link: flow.link,
496
+ };
497
+ }
498
+ async storeAuthCodeFlow(internalState, flow) {
499
+ const prisma = this.getPrisma();
500
+ const data = this.authCodeFlowData(flow);
501
+ await prisma.authCodeFlowState.upsert({
502
+ where: { internalState },
503
+ update: data,
504
+ create: { internalState, ...data },
253
505
  });
254
506
  }
255
507
  async getAuthCodeFlow(internalState) {
508
+ if (internalState.startsWith(CLAIMED_FLOW_PREFIX))
509
+ return undefined;
256
510
  const prisma = this.getPrisma();
257
511
  const row = (await prisma.authCodeFlowState.findUnique({
258
512
  where: { internalState },
@@ -263,18 +517,14 @@ class PostgreSQLStorageBackend {
263
517
  }
264
518
  async deleteAuthCodeFlow(internalState) {
265
519
  const prisma = this.getPrisma();
266
- try {
267
- await prisma.authCodeFlowState.delete({
268
- where: { internalState },
269
- });
270
- return true;
271
- }
272
- catch {
273
- return false;
274
- }
520
+ const result = (await prisma.authCodeFlowState.deleteMany({
521
+ where: { internalState },
522
+ }));
523
+ return result.count === 1;
275
524
  }
276
525
  rowToAuthCodeFlow(row) {
277
526
  return {
527
+ requestedGitlabScopes: storedGitlabScopes(row.requestedGitlabScopes),
278
528
  clientId: row.clientId,
279
529
  codeChallenge: row.codeChallenge,
280
530
  codeChallengeMethod: row.codeChallengeMethod,
@@ -283,6 +533,12 @@ class PostgreSQLStorageBackend {
283
533
  clientRedirectUri: row.clientRedirectUri,
284
534
  callbackUri: row.callbackUri,
285
535
  expiresAt: Number(row.expiresAt),
536
+ selectedInstance: optional(row.selectedInstance),
537
+ selectedInstanceLabel: optional(row.selectedInstanceLabel),
538
+ scopes: storedMcpScopes(row.mcpScopes),
539
+ resource: optional(row.resource),
540
+ gitlabTokens: storedGitlabTokens(row.gitlabTokens),
541
+ link: storedLinkStep(row.link),
286
542
  };
287
543
  }
288
544
  async storeAuthCode(code) {
@@ -310,15 +566,10 @@ class PostgreSQLStorageBackend {
310
566
  }
311
567
  async deleteAuthCode(code) {
312
568
  const prisma = this.getPrisma();
313
- try {
314
- await prisma.authorizationCode.delete({
315
- where: { code },
316
- });
317
- return true;
318
- }
319
- catch {
320
- return false;
321
- }
569
+ const result = (await prisma.authorizationCode.deleteMany({
570
+ where: { code },
571
+ }));
572
+ return result.count === 1;
322
573
  }
323
574
  rowToAuthCode(row) {
324
575
  return {
@@ -349,21 +600,261 @@ class PostgreSQLStorageBackend {
349
600
  }
350
601
  async removeMcpSessionAssociation(mcpSessionId) {
351
602
  const prisma = this.getPrisma();
352
- try {
353
- await prisma.mcpSessionMapping.delete({
354
- where: { mcpSessionId },
355
- });
356
- return true;
603
+ const result = (await prisma.mcpSessionMapping.deleteMany({
604
+ where: { mcpSessionId },
605
+ }));
606
+ return result.count === 1;
607
+ }
608
+ async consumeAuthCode(code) {
609
+ const prisma = this.getPrisma();
610
+ const row = (await prisma.authorizationCode.findUnique({
611
+ where: { code },
612
+ }));
613
+ if (!row)
614
+ return undefined;
615
+ const removed = (await prisma.authorizationCode.deleteMany({
616
+ where: { code },
617
+ }));
618
+ return removed.count === 1 ? this.rowToAuthCode(row) : undefined;
619
+ }
620
+ async consumeAuthCodeFlow(internalState) {
621
+ if (internalState.startsWith(CLAIMED_FLOW_PREFIX))
622
+ return undefined;
623
+ const prisma = this.getPrisma();
624
+ const row = (await prisma.authCodeFlowState.findUnique({
625
+ where: { internalState },
626
+ }));
627
+ if (!row)
628
+ return undefined;
629
+ const removed = (await prisma.authCodeFlowState.deleteMany({
630
+ where: { internalState },
631
+ }));
632
+ return removed.count === 1 ? this.rowToAuthCodeFlow(row) : undefined;
633
+ }
634
+ async consumeDeviceFlow(state) {
635
+ const prisma = this.getPrisma();
636
+ const row = (await prisma.deviceFlowState.findUnique({
637
+ where: { state },
638
+ }));
639
+ if (!row)
640
+ return undefined;
641
+ const removed = (await prisma.deviceFlowState.deleteMany({
642
+ where: { state },
643
+ }));
644
+ return removed.count === 1 ? this.rowToDeviceFlow(row) : undefined;
645
+ }
646
+ async claimGitLabRefresh(sessionId, expectedRefreshToken, now, leaseUntil) {
647
+ const prisma = this.getPrisma();
648
+ const claimed = (await prisma.oAuthSession.updateMany({
649
+ where: {
650
+ id: sessionId,
651
+ gitlabRefreshToken: expectedRefreshToken,
652
+ OR: [{ gitlabRefreshLeaseUntil: null }, { gitlabRefreshLeaseUntil: { lte: BigInt(now) } }],
653
+ },
654
+ data: { gitlabRefreshLeaseUntil: BigInt(leaseUntil) },
655
+ }));
656
+ return claimed.count === 1;
657
+ }
658
+ async releaseGitLabRefresh(sessionId, leaseUntil) {
659
+ const prisma = this.getPrisma();
660
+ await prisma.oAuthSession.updateMany({
661
+ where: { id: sessionId, gitlabRefreshLeaseUntil: BigInt(leaseUntil) },
662
+ data: { gitlabRefreshLeaseUntil: null },
663
+ });
664
+ }
665
+ async claimDevicePoll(state, now, nextPollAt) {
666
+ const prisma = this.getPrisma();
667
+ const claimed = (await prisma.deviceFlowState.updateMany({
668
+ where: {
669
+ state,
670
+ OR: [{ nextPollAt: null }, { nextPollAt: { lte: BigInt(now) } }],
671
+ },
672
+ data: { nextPollAt: BigInt(nextPollAt) },
673
+ }));
674
+ if (claimed.count !== 1)
675
+ return undefined;
676
+ return this.getDeviceFlow(state);
677
+ }
678
+ async storeClient(client) {
679
+ const prisma = this.getPrisma();
680
+ await prisma.oAuthClient.create({
681
+ data: {
682
+ clientId: client.clientId,
683
+ clientSecret: client.clientSecret ?? null,
684
+ redirectUris: client.redirectUris,
685
+ clientName: client.clientName ?? null,
686
+ tokenEndpointAuthMethod: client.tokenEndpointAuthMethod,
687
+ grantTypes: client.grantTypes,
688
+ responseTypes: client.responseTypes,
689
+ createdAt: BigInt(client.createdAt),
690
+ registeredFrom: client.registeredFrom ?? null,
691
+ expiresAt: client.expiresAt === undefined ? null : BigInt(client.expiresAt),
692
+ },
693
+ });
694
+ }
695
+ async markClientUsed(clientId) {
696
+ const prisma = this.getPrisma();
697
+ await prisma.oAuthClient.updateMany({
698
+ where: { clientId },
699
+ data: { expiresAt: null },
700
+ });
701
+ }
702
+ async countClientsRegisteredSince(registeredFrom, since) {
703
+ const prisma = this.getPrisma();
704
+ return prisma.oAuthClient.count({
705
+ where: { registeredFrom, createdAt: { gte: BigInt(since) } },
706
+ });
707
+ }
708
+ async getClient(clientId) {
709
+ const prisma = this.getPrisma();
710
+ const row = (await prisma.oAuthClient.findUnique({
711
+ where: { clientId },
712
+ }));
713
+ if (!row)
714
+ return undefined;
715
+ return {
716
+ clientId: row.clientId,
717
+ clientSecret: optional(row.clientSecret),
718
+ redirectUris: row.redirectUris,
719
+ clientName: optional(row.clientName),
720
+ tokenEndpointAuthMethod: row.tokenEndpointAuthMethod,
721
+ grantTypes: row.grantTypes,
722
+ responseTypes: row.responseTypes,
723
+ createdAt: Number(row.createdAt),
724
+ registeredFrom: optional(row.registeredFrom),
725
+ expiresAt: row.expiresAt == null ? undefined : Number(row.expiresAt),
726
+ };
727
+ }
728
+ async getAccountSettings(accountKey) {
729
+ const prisma = this.getPrisma();
730
+ const row = (await prisma.accountSettings.findUnique({
731
+ where: { accountKey },
732
+ }));
733
+ if (!row)
734
+ return undefined;
735
+ return {
736
+ accountKey: row.accountKey,
737
+ settings: row.settings,
738
+ version: row.version,
739
+ updatedAt: Number(row.updatedAt),
740
+ };
741
+ }
742
+ async putAccountSettings(accountKey, settings, expectedVersion) {
743
+ const prisma = this.getPrisma();
744
+ const version = expectedVersion + 1;
745
+ const updatedAt = Date.now();
746
+ if (expectedVersion === 0) {
747
+ try {
748
+ await prisma.accountSettings.create({
749
+ data: { accountKey, settings, version, updatedAt: BigInt(updatedAt) },
750
+ });
751
+ }
752
+ catch (error) {
753
+ if (error.code === 'P2002')
754
+ return undefined;
755
+ throw error;
756
+ }
757
+ }
758
+ else {
759
+ const result = (await prisma.accountSettings.updateMany({
760
+ where: { accountKey, version: expectedVersion },
761
+ data: { settings, version, updatedAt: BigInt(updatedAt) },
762
+ }));
763
+ if (result.count !== 1)
764
+ return undefined;
357
765
  }
358
- catch {
359
- return false;
766
+ return { accountKey, settings, version, updatedAt };
767
+ }
768
+ onAbandonedFlowGrant(handler, leaseMs) {
769
+ if (!Number.isSafeInteger(leaseMs) || leaseMs <= 0) {
770
+ throw new Error('Abandoned-flow cleanup requires a positive integer lease duration');
360
771
  }
772
+ this.abandonedFlowGrant = { run: handler, leaseMs };
773
+ }
774
+ onExpiredSession(handler) {
775
+ this.expiredSession = handler;
776
+ }
777
+ async expireSessions(cutoff) {
778
+ const handler = this.expiredSession;
779
+ if (!handler)
780
+ return;
781
+ const rows = (await this.getPrisma().oAuthSession.findMany({
782
+ where: { createdAt: { lt: cutoff }, linkedToSessionId: null },
783
+ }));
784
+ await inBatches(rows, async (row) => {
785
+ try {
786
+ await handler(this.rowToSession(row));
787
+ }
788
+ catch (error) {
789
+ (0, logger_1.logError)('Could not end the grants of an expired session', { err: error });
790
+ }
791
+ });
792
+ }
793
+ async claimAbandonedFlow(internalState, now, leaseUntil) {
794
+ const claimedState = internalState.startsWith(CLAIMED_FLOW_PREFIX)
795
+ ? internalState
796
+ : CLAIMED_FLOW_PREFIX + internalState;
797
+ const claimed = (await this.getPrisma().authCodeFlowState.updateMany({
798
+ where: { internalState, expiresAt: { lt: now } },
799
+ data: { internalState: claimedState, expiresAt: leaseUntil },
800
+ }));
801
+ return claimed.count === 1 ? claimedState : undefined;
802
+ }
803
+ async endAbandonedFlows(now) {
804
+ const registration = this.abandonedFlowGrant;
805
+ if (!registration)
806
+ return;
807
+ const prisma = this.getPrisma();
808
+ const rows = (await prisma.authCodeFlowState.findMany({
809
+ where: { expiresAt: { lt: now } },
810
+ })).filter((row) => row.gitlabTokens != null);
811
+ await inBatches(rows, async (row) => {
812
+ try {
813
+ const leaseUntil = BigInt(Date.now() + registration.leaseMs);
814
+ const claimedState = await this.claimAbandonedFlow(row.internalState, now, leaseUntil);
815
+ if (!claimedState)
816
+ return;
817
+ const current = (await prisma.authCodeFlowState.findUnique({
818
+ where: { internalState: claimedState },
819
+ }));
820
+ if (!current)
821
+ throw new Error('Claimed authorization flow could not be read');
822
+ const flow = this.rowToAuthCodeFlow(current);
823
+ const ownership = {
824
+ internalState: claimedState,
825
+ expiresAt: leaseUntil,
826
+ };
827
+ await registration.run(flow, async (tokens) => {
828
+ const updated = (await prisma.authCodeFlowState.updateMany({
829
+ where: ownership,
830
+ data: { gitlabTokens: tokens },
831
+ }));
832
+ if (updated.count !== 1)
833
+ throw new Error('Authorization-flow cleanup lease was lost');
834
+ flow.gitlabTokens = tokens;
835
+ }, Number(leaseUntil));
836
+ await prisma.authCodeFlowState.deleteMany({ where: ownership });
837
+ }
838
+ catch (error) {
839
+ (0, logger_1.logError)('Could not end the grant of an abandoned flow', { err: error });
840
+ }
841
+ });
361
842
  }
362
843
  async cleanup() {
363
844
  const prisma = this.getPrisma();
364
845
  const now = BigInt(Date.now());
365
846
  const maxSessionAge = BigInt(7 * 24 * 60 * 60 * 1000);
366
847
  try {
848
+ await this.endAbandonedFlows(now);
849
+ await this.expireSessions(now - maxSessionAge);
850
+ const expiredFlowWhere = {
851
+ expiresAt: { lt: now },
852
+ NOT: { internalState: { startsWith: CLAIMED_FLOW_PREFIX } },
853
+ };
854
+ if (this.abandonedFlowGrant) {
855
+ const { Prisma } = await Promise.resolve().then(() => __importStar(require('../generated/prisma/client')));
856
+ expiredFlowWhere.gitlabTokens = { equals: Prisma.AnyNull };
857
+ }
367
858
  const results = (await prisma.$transaction([
368
859
  prisma.oAuthSession.deleteMany({
369
860
  where: {
@@ -374,11 +865,14 @@ class PostgreSQLStorageBackend {
374
865
  where: { expiresAt: { lt: now } },
375
866
  }),
376
867
  prisma.authCodeFlowState.deleteMany({
377
- where: { expiresAt: { lt: now } },
868
+ where: expiredFlowWhere,
378
869
  }),
379
870
  prisma.authorizationCode.deleteMany({
380
871
  where: { expiresAt: { lt: now } },
381
872
  }),
873
+ prisma.oAuthClient.deleteMany({
874
+ where: { expiresAt: { lt: now } },
875
+ }),
382
876
  ]));
383
877
  const expiredSessions = results[0].count;
384
878
  const expiredDeviceFlows = results[1].count;