@structured-world/gitlab-mcp-db 10.1.0 → 11.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 (34) hide show
  1. package/README.md +7 -7
  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 +4 -4
  6. package/dist/generated/prisma/internal/class.js.map +1 -1
  7. package/dist/generated/prisma/internal/prismaNamespace.d.ts +207 -1
  8. package/dist/generated/prisma/internal/prismaNamespace.js +52 -3
  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 +152 -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 +116 -1
  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 +17 -1
  24. package/dist/src/postgresql.js +309 -83
  25. package/dist/src/postgresql.js.map +1 -1
  26. package/dist/tsconfig.tsbuildinfo +1 -1
  27. package/package.json +8 -3
  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/migration_lock.toml +3 -0
  33. package/prisma/schema.prisma +59 -0
  34. package/prisma.config.ts +19 -0
@@ -0,0 +1,115 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
35
+ Object.defineProperty(exports, "__esModule", { value: true });
36
+ exports.migrate = migrate;
37
+ exports.connectPostgres = connectPostgres;
38
+ const node_child_process_1 = require("node:child_process");
39
+ const path = __importStar(require("node:path"));
40
+ const pg_1 = require("pg");
41
+ const BASELINE_MIGRATION = '0_init';
42
+ const WAIT_MS = 60_000;
43
+ const RETRY_MS = 1_000;
44
+ async function waitForDatabase(url, deps) {
45
+ const deadline = deps.now() + WAIT_MS;
46
+ for (;;) {
47
+ try {
48
+ return await deps.connect(url, Math.max(1, deadline - deps.now()));
49
+ }
50
+ catch (error) {
51
+ if (deps.now() >= deadline) {
52
+ deps.log(`Database is not reachable: ${error.message}`);
53
+ return undefined;
54
+ }
55
+ await deps.sleep(RETRY_MS);
56
+ }
57
+ }
58
+ }
59
+ async function needsBaseline(client, url) {
60
+ const schema = new URL(url).searchParams.get('schema') ?? 'public';
61
+ const { rows } = await client.query(`SELECT to_regclass(quote_ident($1) || '.oauth_sessions') IS NOT NULL AS has_tables,
62
+ to_regclass(quote_ident($1) || '._prisma_migrations') IS NOT NULL AS has_history`, [schema]);
63
+ const state = rows[0];
64
+ return state.has_tables && !state.has_history;
65
+ }
66
+ async function migrate(url, deps) {
67
+ if (!url) {
68
+ deps.log('Set OAUTH_STORAGE_POSTGRESQL_URL or DATABASE_URL');
69
+ return 1;
70
+ }
71
+ const client = await waitForDatabase(url, deps);
72
+ if (!client)
73
+ return 1;
74
+ let baseline;
75
+ try {
76
+ baseline = await needsBaseline(client, url);
77
+ }
78
+ finally {
79
+ await client.end();
80
+ }
81
+ if (baseline) {
82
+ deps.log(`Existing tables without migration history: marking ${BASELINE_MIGRATION} applied`);
83
+ const status = deps.prisma(['migrate', 'resolve', '--applied', BASELINE_MIGRATION]);
84
+ if (status !== 0)
85
+ return status;
86
+ }
87
+ return deps.prisma(['migrate', 'deploy']);
88
+ }
89
+ const PACKAGE_DIR = path.resolve(__dirname, '..', '..');
90
+ async function connectPostgres(url, timeoutMs) {
91
+ const client = new pg_1.Client({ connectionString: url, connectionTimeoutMillis: timeoutMs });
92
+ await client.connect();
93
+ return client;
94
+ }
95
+ const defaultDeps = {
96
+ connect: connectPostgres,
97
+ prisma(args) {
98
+ const cli = path.join(path.dirname(require.resolve('prisma/package.json')), 'build/index.js');
99
+ const result = (0, node_child_process_1.spawnSync)(process.execPath, [cli, ...args], {
100
+ cwd: PACKAGE_DIR,
101
+ stdio: 'inherit',
102
+ });
103
+ return result.status ?? 1;
104
+ },
105
+ sleep: (ms) => new Promise((resolve) => setTimeout(resolve, ms)),
106
+ now: () => Date.now(),
107
+ log: (message) => console.error(message),
108
+ };
109
+ if (require.main === module) {
110
+ migrate(process.env.OAUTH_STORAGE_POSTGRESQL_URL ?? process.env.DATABASE_URL, defaultDeps).then((status) => process.exit(status), (error) => {
111
+ console.error('Migration failed:', error);
112
+ process.exit(1);
113
+ });
114
+ }
115
+ //# sourceMappingURL=migrate.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"migrate.js","sourceRoot":"","sources":["../../src/migrate.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAyEA,0BAmBC;AAMD,0CAIC;AA1FD,2DAA+C;AAC/C,gDAAkC;AAClC,2BAA4B;AAG5B,MAAM,kBAAkB,GAAG,QAAQ,CAAC;AAEpC,MAAM,OAAO,GAAG,MAAM,CAAC;AACvB,MAAM,QAAQ,GAAG,KAAK,CAAC;AAkBvB,KAAK,UAAU,eAAe,CAAC,GAAW,EAAE,IAAiB;IAC3D,MAAM,QAAQ,GAAG,IAAI,CAAC,GAAG,EAAE,GAAG,OAAO,CAAC;IACtC,SAAS,CAAC;QACR,IAAI,CAAC;YAGH,OAAO,MAAM,IAAI,CAAC,OAAO,CAAC,GAAG,EAAE,IAAI,CAAC,GAAG,CAAC,CAAC,EAAE,QAAQ,GAAG,IAAI,CAAC,GAAG,EAAE,CAAC,CAAC,CAAC;QACrE,CAAC;QAAC,OAAO,KAAc,EAAE,CAAC;YACxB,IAAI,IAAI,CAAC,GAAG,EAAE,IAAI,QAAQ,EAAE,CAAC;gBAC3B,IAAI,CAAC,GAAG,CAAC,8BAA+B,KAAe,CAAC,OAAO,EAAE,CAAC,CAAC;gBACnE,OAAO,SAAS,CAAC;YACnB,CAAC;YACD,MAAM,IAAI,CAAC,KAAK,CAAC,QAAQ,CAAC,CAAC;QAC7B,CAAC;IACH,CAAC;AACH,CAAC;AAQD,KAAK,UAAU,aAAa,CA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AC,CAAC,IAAI,CAC7F,CAAC,MAAM,EAAE,EAAE,CAAC,OAAO,CAAC,IAAI,CAAC,MAAM,CAAC,EAChC,CAAC,KAAc,EAAE,EAAE;QACjB,OAAO,CAAC,KAAK,CAAC,mBAAmB,EAAE,KAAK,CAAC,CAAC;QAC1C,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;IAClB,CAAC,CACF,CAAC;AACJ,CAAC"}
@@ -1,4 +1,4 @@
1
- import type { OAuthSession, DeviceFlowState as DeviceFlowStateType, AuthCodeFlowState as AuthCodeFlowStateType, AuthorizationCode as AuthorizationCodeType, SessionStorageBackend, SessionStorageStats } from '@structured-world/gitlab-mcp/storage-contract';
1
+ import type { OAuthSession, DeviceFlowState as DeviceFlowStateType, AuthCodeFlowState as AuthCodeFlowStateType, AuthorizationCode as AuthorizationCodeType, RegisteredOAuthClient as RegisteredOAuthClientType, SessionStorageBackend, SessionStorageStats, AccountSettings, AccountSettingsRecord } from '@structured-world/gitlab-mcp/storage-contract';
2
2
  export interface PostgreSQLStorageOptions {
3
3
  connectionString?: string;
4
4
  }
@@ -6,6 +6,8 @@ export declare class PostgreSQLStorageBackend implements SessionStorageBackend {
6
6
  readonly type: "postgresql";
7
7
  private prisma;
8
8
  private cleanupIntervalId;
9
+ private readonly connectionString;
10
+ constructor(options?: PostgreSQLStorageOptions);
9
11
  initialize(): Promise<void>;
10
12
  private getPrisma;
11
13
  createSession(session: OAuthSession): Promise<void>;
@@ -13,6 +15,8 @@ export declare class PostgreSQLStorageBackend implements SessionStorageBackend {
13
15
  getSessionByToken(token: string): Promise<OAuthSession | undefined>;
14
16
  getSessionByRefreshToken(refreshToken: string): Promise<OAuthSession | undefined>;
15
17
  updateSession(sessionId: string, updates: Partial<OAuthSession>): Promise<boolean>;
18
+ rotateSession(sessionId: string, expectedRefreshToken: string, updates: Partial<OAuthSession>): Promise<boolean>;
19
+ private sessionUpdateData;
16
20
  deleteSession(sessionId: string): Promise<boolean>;
17
21
  getAllSessions(): Promise<OAuthSession[]>;
18
22
  private rowToSession;
@@ -32,6 +36,18 @@ export declare class PostgreSQLStorageBackend implements SessionStorageBackend {
32
36
  associateMcpSession(mcpSessionId: string, oauthSessionId: string): Promise<void>;
33
37
  getSessionByMcpSessionId(mcpSessionId: string): Promise<OAuthSession | undefined>;
34
38
  removeMcpSessionAssociation(mcpSessionId: string): Promise<boolean>;
39
+ consumeAuthCode(code: string): Promise<AuthorizationCodeType | undefined>;
40
+ consumeAuthCodeFlow(internalState: string): Promise<AuthCodeFlowStateType | undefined>;
41
+ consumeDeviceFlow(state: string): Promise<DeviceFlowStateType | undefined>;
42
+ claimGitLabRefresh(sessionId: string, expectedRefreshToken: string, now: number, leaseUntil: number): Promise<boolean>;
43
+ releaseGitLabRefresh(sessionId: string, leaseUntil: number): Promise<void>;
44
+ claimDevicePoll(state: string, now: number, nextPollAt: number): Promise<DeviceFlowStateType | undefined>;
45
+ storeClient(client: RegisteredOAuthClientType): Promise<void>;
46
+ markClientUsed(clientId: string): Promise<void>;
47
+ countClientsRegisteredSince(registeredFrom: string, since: number): Promise<number>;
48
+ getClient(clientId: string): Promise<RegisteredOAuthClientType | undefined>;
49
+ getAccountSettings(accountKey: string): Promise<AccountSettingsRecord | undefined>;
50
+ putAccountSettings(accountKey: string, settings: AccountSettings, expectedVersion: number): Promise<AccountSettingsRecord | undefined>;
35
51
  cleanup(): Promise<void>;
36
52
  close(): Promise<void>;
37
53
  getStats(): Promise<SessionStorageStats>;
@@ -35,20 +35,69 @@ var __importStar = (this && this.__importStar) || (function () {
35
35
  Object.defineProperty(exports, "__esModule", { value: true });
36
36
  exports.PostgreSQLStorageBackend = void 0;
37
37
  const logger_1 = require("./logger");
38
+ function storedGitlabScopes(value) {
39
+ if (value == null)
40
+ return undefined;
41
+ if (!Array.isArray(value) || !value.every((scope) => typeof scope === 'string')) {
42
+ throw new Error('Invalid stored GitLab scopes');
43
+ }
44
+ return value;
45
+ }
46
+ function storedMcpScopes(value) {
47
+ if (value == null)
48
+ return undefined;
49
+ if (!Array.isArray(value) || !value.every((scope) => typeof scope === 'string')) {
50
+ throw new Error('Invalid stored MCP scopes');
51
+ }
52
+ return value;
53
+ }
54
+ function storedGitlabTokens(value) {
55
+ if (value == null)
56
+ return undefined;
57
+ const tokens = value;
58
+ if (typeof tokens.access_token !== 'string' ||
59
+ typeof tokens.refresh_token !== 'string' ||
60
+ typeof tokens.token_type !== 'string' ||
61
+ typeof tokens.expires_in !== 'number' ||
62
+ typeof tokens.created_at !== 'number' ||
63
+ (tokens.scope !== undefined && typeof tokens.scope !== 'string')) {
64
+ throw new Error('Invalid stored GitLab tokens');
65
+ }
66
+ return value;
67
+ }
68
+ function optional(value) {
69
+ return value ?? undefined;
70
+ }
38
71
  class PostgreSQLStorageBackend {
39
72
  type = 'postgresql';
40
73
  prisma = null;
41
74
  cleanupIntervalId = null;
75
+ connectionString;
76
+ constructor(options = {}) {
77
+ this.connectionString =
78
+ options.connectionString ??
79
+ process.env.OAUTH_STORAGE_POSTGRESQL_URL ??
80
+ process.env.DATABASE_URL;
81
+ }
42
82
  async initialize() {
43
83
  try {
84
+ if (!this.connectionString) {
85
+ throw new Error('PostgreSQL storage requires OAUTH_STORAGE_POSTGRESQL_URL or DATABASE_URL');
86
+ }
44
87
  const prismaModule = (await Promise.resolve().then(() => __importStar(require('../generated/prisma/client'))));
45
- this.prisma = new prismaModule.PrismaClient({});
88
+ const { PrismaPg } = await Promise.resolve().then(() => __importStar(require('@prisma/adapter-pg')));
89
+ const schema = new URL(this.connectionString).searchParams.get('schema') ?? undefined;
90
+ this.prisma = new prismaModule.PrismaClient({
91
+ adapter: new PrismaPg({ connectionString: this.connectionString }, schema ? { schema } : undefined),
92
+ });
46
93
  await this.prisma.$connect();
47
94
  this.startCleanupInterval();
48
95
  (0, logger_1.logInfo)('PostgreSQL storage backend initialized via Prisma');
49
96
  }
50
97
  catch (error) {
51
- (0, logger_1.logError)('Failed to initialize PostgreSQL storage backend', { err: error });
98
+ (0, logger_1.logError)('Failed to initialize PostgreSQL storage backend', {
99
+ err: error,
100
+ });
52
101
  throw error;
53
102
  }
54
103
  }
@@ -69,12 +118,14 @@ class PostgreSQLStorageBackend {
69
118
  gitlabAccessToken: session.gitlabAccessToken,
70
119
  gitlabRefreshToken: session.gitlabRefreshToken,
71
120
  gitlabTokenExpiry: BigInt(session.gitlabTokenExpiry),
121
+ gitlabScopes: session.gitlabScopes,
72
122
  gitlabUserId: session.gitlabUserId,
73
123
  gitlabUsername: session.gitlabUsername,
74
124
  gitlabApiUrl: session.gitlabApiUrl,
75
125
  instanceLabel: session.instanceLabel,
76
126
  clientId: session.clientId,
77
127
  scopes: session.scopes,
128
+ resource: session.resource ?? null,
78
129
  createdAt: BigInt(session.createdAt),
79
130
  updatedAt: BigInt(session.updatedAt),
80
131
  },
@@ -104,6 +155,21 @@ class PostgreSQLStorageBackend {
104
155
  }
105
156
  async updateSession(sessionId, updates) {
106
157
  const prisma = this.getPrisma();
158
+ const result = (await prisma.oAuthSession.updateMany({
159
+ where: { id: sessionId },
160
+ data: this.sessionUpdateData(updates),
161
+ }));
162
+ return result.count === 1;
163
+ }
164
+ async rotateSession(sessionId, expectedRefreshToken, updates) {
165
+ const prisma = this.getPrisma();
166
+ const result = (await prisma.oAuthSession.updateMany({
167
+ where: { id: sessionId, mcpRefreshToken: expectedRefreshToken },
168
+ data: this.sessionUpdateData(updates),
169
+ }));
170
+ return result.count === 1;
171
+ }
172
+ sessionUpdateData(updates) {
107
173
  const data = {
108
174
  updatedAt: BigInt(Date.now()),
109
175
  };
@@ -125,28 +191,20 @@ class PostgreSQLStorageBackend {
125
191
  if (updates.gitlabTokenExpiry !== undefined) {
126
192
  data.gitlabTokenExpiry = BigInt(updates.gitlabTokenExpiry);
127
193
  }
128
- try {
129
- await prisma.oAuthSession.update({
130
- where: { id: sessionId },
131
- data,
132
- });
133
- return true;
194
+ if (updates.gitlabScopes !== undefined) {
195
+ data.gitlabScopes = updates.gitlabScopes;
134
196
  }
135
- catch {
136
- return false;
197
+ if (updates.resource !== undefined) {
198
+ data.resource = updates.resource;
137
199
  }
200
+ return data;
138
201
  }
139
202
  async deleteSession(sessionId) {
140
203
  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
- }
204
+ const result = (await prisma.oAuthSession.deleteMany({
205
+ where: { id: sessionId },
206
+ }));
207
+ return result.count === 1;
150
208
  }
151
209
  async getAllSessions() {
152
210
  const prisma = this.getPrisma();
@@ -162,38 +220,44 @@ class PostgreSQLStorageBackend {
162
220
  gitlabAccessToken: row.gitlabAccessToken,
163
221
  gitlabRefreshToken: row.gitlabRefreshToken,
164
222
  gitlabTokenExpiry: Number(row.gitlabTokenExpiry),
223
+ gitlabScopes: storedGitlabScopes(row.gitlabScopes),
165
224
  gitlabUserId: row.gitlabUserId,
166
225
  gitlabUsername: row.gitlabUsername,
167
226
  gitlabApiUrl: row.gitlabApiUrl ?? undefined,
168
227
  instanceLabel: row.instanceLabel ?? undefined,
169
228
  clientId: row.clientId,
170
229
  scopes: row.scopes,
230
+ resource: optional(row.resource),
171
231
  createdAt: Number(row.createdAt),
172
232
  updatedAt: Number(row.updatedAt),
173
233
  };
174
234
  }
175
235
  async storeDeviceFlow(state, flow) {
176
236
  const prisma = this.getPrisma();
237
+ const data = {
238
+ deviceCode: flow.deviceCode,
239
+ userCode: flow.userCode,
240
+ verificationUri: flow.verificationUri,
241
+ verificationUriComplete: flow.verificationUriComplete ?? null,
242
+ expiresAt: BigInt(flow.expiresAt),
243
+ interval: flow.interval,
244
+ clientId: flow.clientId,
245
+ codeChallenge: flow.codeChallenge,
246
+ codeChallengeMethod: flow.codeChallengeMethod,
247
+ redirectUri: flow.redirectUri ?? null,
248
+ requestedGitlabScopes: flow.requestedGitlabScopes,
249
+ clientState: flow.state,
250
+ nextPollAt: flow.nextPollAt === undefined ? null : BigInt(flow.nextPollAt),
251
+ selectedInstance: flow.selectedInstance ?? null,
252
+ selectedInstanceLabel: flow.selectedInstanceLabel ?? null,
253
+ mcpScopes: flow.scopes,
254
+ resource: flow.resource ?? null,
255
+ gitlabTokens: flow.gitlabTokens,
256
+ };
177
257
  await prisma.deviceFlowState.upsert({
178
258
  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
- },
259
+ update: data,
260
+ create: { state, ...data },
197
261
  });
198
262
  }
199
263
  async getDeviceFlow(state) {
@@ -212,18 +276,14 @@ class PostgreSQLStorageBackend {
212
276
  }
213
277
  async deleteDeviceFlow(state) {
214
278
  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
- }
279
+ const result = (await prisma.deviceFlowState.deleteMany({
280
+ where: { state },
281
+ }));
282
+ return result.count === 1;
224
283
  }
225
284
  rowToDeviceFlow(row) {
226
285
  return {
286
+ requestedGitlabScopes: storedGitlabScopes(row.requestedGitlabScopes),
227
287
  deviceCode: row.deviceCode,
228
288
  userCode: row.userCode,
229
289
  verificationUri: row.verificationUri,
@@ -233,23 +293,37 @@ class PostgreSQLStorageBackend {
233
293
  clientId: row.clientId,
234
294
  codeChallenge: row.codeChallenge,
235
295
  codeChallengeMethod: row.codeChallengeMethod,
236
- state: row.state,
296
+ state: row.clientState ?? '',
237
297
  redirectUri: row.redirectUri ?? undefined,
298
+ nextPollAt: row.nextPollAt == null ? undefined : Number(row.nextPollAt),
299
+ selectedInstance: optional(row.selectedInstance),
300
+ selectedInstanceLabel: optional(row.selectedInstanceLabel),
301
+ scopes: storedMcpScopes(row.mcpScopes),
302
+ resource: optional(row.resource),
303
+ gitlabTokens: storedGitlabTokens(row.gitlabTokens),
238
304
  };
239
305
  }
240
306
  async storeAuthCodeFlow(internalState, flow) {
241
307
  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),
252
- },
308
+ const data = {
309
+ clientId: flow.clientId,
310
+ codeChallenge: flow.codeChallenge,
311
+ codeChallengeMethod: flow.codeChallengeMethod,
312
+ clientState: flow.clientState,
313
+ clientRedirectUri: flow.clientRedirectUri,
314
+ callbackUri: flow.callbackUri,
315
+ expiresAt: BigInt(flow.expiresAt),
316
+ requestedGitlabScopes: flow.requestedGitlabScopes,
317
+ selectedInstance: flow.selectedInstance ?? null,
318
+ selectedInstanceLabel: flow.selectedInstanceLabel ?? null,
319
+ mcpScopes: flow.scopes,
320
+ resource: flow.resource ?? null,
321
+ gitlabTokens: flow.gitlabTokens,
322
+ };
323
+ await prisma.authCodeFlowState.upsert({
324
+ where: { internalState },
325
+ update: data,
326
+ create: { internalState, ...data },
253
327
  });
254
328
  }
255
329
  async getAuthCodeFlow(internalState) {
@@ -263,18 +337,14 @@ class PostgreSQLStorageBackend {
263
337
  }
264
338
  async deleteAuthCodeFlow(internalState) {
265
339
  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
- }
340
+ const result = (await prisma.authCodeFlowState.deleteMany({
341
+ where: { internalState },
342
+ }));
343
+ return result.count === 1;
275
344
  }
276
345
  rowToAuthCodeFlow(row) {
277
346
  return {
347
+ requestedGitlabScopes: storedGitlabScopes(row.requestedGitlabScopes),
278
348
  clientId: row.clientId,
279
349
  codeChallenge: row.codeChallenge,
280
350
  codeChallengeMethod: row.codeChallengeMethod,
@@ -283,6 +353,11 @@ class PostgreSQLStorageBackend {
283
353
  clientRedirectUri: row.clientRedirectUri,
284
354
  callbackUri: row.callbackUri,
285
355
  expiresAt: Number(row.expiresAt),
356
+ selectedInstance: optional(row.selectedInstance),
357
+ selectedInstanceLabel: optional(row.selectedInstanceLabel),
358
+ scopes: storedMcpScopes(row.mcpScopes),
359
+ resource: optional(row.resource),
360
+ gitlabTokens: storedGitlabTokens(row.gitlabTokens),
286
361
  };
287
362
  }
288
363
  async storeAuthCode(code) {
@@ -310,15 +385,10 @@ class PostgreSQLStorageBackend {
310
385
  }
311
386
  async deleteAuthCode(code) {
312
387
  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
- }
388
+ const result = (await prisma.authorizationCode.deleteMany({
389
+ where: { code },
390
+ }));
391
+ return result.count === 1;
322
392
  }
323
393
  rowToAuthCode(row) {
324
394
  return {
@@ -349,15 +419,168 @@ class PostgreSQLStorageBackend {
349
419
  }
350
420
  async removeMcpSessionAssociation(mcpSessionId) {
351
421
  const prisma = this.getPrisma();
352
- try {
353
- await prisma.mcpSessionMapping.delete({
354
- where: { mcpSessionId },
355
- });
356
- return true;
422
+ const result = (await prisma.mcpSessionMapping.deleteMany({
423
+ where: { mcpSessionId },
424
+ }));
425
+ return result.count === 1;
426
+ }
427
+ async consumeAuthCode(code) {
428
+ const prisma = this.getPrisma();
429
+ const row = (await prisma.authorizationCode.findUnique({
430
+ where: { code },
431
+ }));
432
+ if (!row)
433
+ return undefined;
434
+ const removed = (await prisma.authorizationCode.deleteMany({
435
+ where: { code },
436
+ }));
437
+ return removed.count === 1 ? this.rowToAuthCode(row) : undefined;
438
+ }
439
+ async consumeAuthCodeFlow(internalState) {
440
+ const prisma = this.getPrisma();
441
+ const row = (await prisma.authCodeFlowState.findUnique({
442
+ where: { internalState },
443
+ }));
444
+ if (!row)
445
+ return undefined;
446
+ const removed = (await prisma.authCodeFlowState.deleteMany({
447
+ where: { internalState },
448
+ }));
449
+ return removed.count === 1 ? this.rowToAuthCodeFlow(row) : undefined;
450
+ }
451
+ async consumeDeviceFlow(state) {
452
+ const prisma = this.getPrisma();
453
+ const row = (await prisma.deviceFlowState.findUnique({
454
+ where: { state },
455
+ }));
456
+ if (!row)
457
+ return undefined;
458
+ const removed = (await prisma.deviceFlowState.deleteMany({
459
+ where: { state },
460
+ }));
461
+ return removed.count === 1 ? this.rowToDeviceFlow(row) : undefined;
462
+ }
463
+ async claimGitLabRefresh(sessionId, expectedRefreshToken, now, leaseUntil) {
464
+ const prisma = this.getPrisma();
465
+ const claimed = (await prisma.oAuthSession.updateMany({
466
+ where: {
467
+ id: sessionId,
468
+ gitlabRefreshToken: expectedRefreshToken,
469
+ OR: [{ gitlabRefreshLeaseUntil: null }, { gitlabRefreshLeaseUntil: { lte: BigInt(now) } }],
470
+ },
471
+ data: { gitlabRefreshLeaseUntil: BigInt(leaseUntil) },
472
+ }));
473
+ return claimed.count === 1;
474
+ }
475
+ async releaseGitLabRefresh(sessionId, leaseUntil) {
476
+ const prisma = this.getPrisma();
477
+ await prisma.oAuthSession.updateMany({
478
+ where: { id: sessionId, gitlabRefreshLeaseUntil: BigInt(leaseUntil) },
479
+ data: { gitlabRefreshLeaseUntil: null },
480
+ });
481
+ }
482
+ async claimDevicePoll(state, now, nextPollAt) {
483
+ const prisma = this.getPrisma();
484
+ const claimed = (await prisma.deviceFlowState.updateMany({
485
+ where: {
486
+ state,
487
+ OR: [{ nextPollAt: null }, { nextPollAt: { lte: BigInt(now) } }],
488
+ },
489
+ data: { nextPollAt: BigInt(nextPollAt) },
490
+ }));
491
+ if (claimed.count !== 1)
492
+ return undefined;
493
+ return this.getDeviceFlow(state);
494
+ }
495
+ async storeClient(client) {
496
+ const prisma = this.getPrisma();
497
+ await prisma.oAuthClient.create({
498
+ data: {
499
+ clientId: client.clientId,
500
+ clientSecret: client.clientSecret ?? null,
501
+ redirectUris: client.redirectUris,
502
+ clientName: client.clientName ?? null,
503
+ tokenEndpointAuthMethod: client.tokenEndpointAuthMethod,
504
+ grantTypes: client.grantTypes,
505
+ responseTypes: client.responseTypes,
506
+ createdAt: BigInt(client.createdAt),
507
+ registeredFrom: client.registeredFrom ?? null,
508
+ expiresAt: client.expiresAt === undefined ? null : BigInt(client.expiresAt),
509
+ },
510
+ });
511
+ }
512
+ async markClientUsed(clientId) {
513
+ const prisma = this.getPrisma();
514
+ await prisma.oAuthClient.updateMany({
515
+ where: { clientId },
516
+ data: { expiresAt: null },
517
+ });
518
+ }
519
+ async countClientsRegisteredSince(registeredFrom, since) {
520
+ const prisma = this.getPrisma();
521
+ return prisma.oAuthClient.count({
522
+ where: { registeredFrom, createdAt: { gte: BigInt(since) } },
523
+ });
524
+ }
525
+ async getClient(clientId) {
526
+ const prisma = this.getPrisma();
527
+ const row = (await prisma.oAuthClient.findUnique({
528
+ where: { clientId },
529
+ }));
530
+ if (!row)
531
+ return undefined;
532
+ return {
533
+ clientId: row.clientId,
534
+ clientSecret: optional(row.clientSecret),
535
+ redirectUris: row.redirectUris,
536
+ clientName: optional(row.clientName),
537
+ tokenEndpointAuthMethod: row.tokenEndpointAuthMethod,
538
+ grantTypes: row.grantTypes,
539
+ responseTypes: row.responseTypes,
540
+ createdAt: Number(row.createdAt),
541
+ registeredFrom: optional(row.registeredFrom),
542
+ expiresAt: row.expiresAt == null ? undefined : Number(row.expiresAt),
543
+ };
544
+ }
545
+ async getAccountSettings(accountKey) {
546
+ const prisma = this.getPrisma();
547
+ const row = (await prisma.accountSettings.findUnique({
548
+ where: { accountKey },
549
+ }));
550
+ if (!row)
551
+ return undefined;
552
+ return {
553
+ accountKey: row.accountKey,
554
+ settings: row.settings,
555
+ version: row.version,
556
+ updatedAt: Number(row.updatedAt),
557
+ };
558
+ }
559
+ async putAccountSettings(accountKey, settings, expectedVersion) {
560
+ const prisma = this.getPrisma();
561
+ const version = expectedVersion + 1;
562
+ const updatedAt = Date.now();
563
+ if (expectedVersion === 0) {
564
+ try {
565
+ await prisma.accountSettings.create({
566
+ data: { accountKey, settings, version, updatedAt: BigInt(updatedAt) },
567
+ });
568
+ }
569
+ catch (error) {
570
+ if (error.code === 'P2002')
571
+ return undefined;
572
+ throw error;
573
+ }
357
574
  }
358
- catch {
359
- return false;
575
+ else {
576
+ const result = (await prisma.accountSettings.updateMany({
577
+ where: { accountKey, version: expectedVersion },
578
+ data: { settings, version, updatedAt: BigInt(updatedAt) },
579
+ }));
580
+ if (result.count !== 1)
581
+ return undefined;
360
582
  }
583
+ return { accountKey, settings, version, updatedAt };
361
584
  }
362
585
  async cleanup() {
363
586
  const prisma = this.getPrisma();
@@ -379,6 +602,9 @@ class PostgreSQLStorageBackend {
379
602
  prisma.authorizationCode.deleteMany({
380
603
  where: { expiresAt: { lt: now } },
381
604
  }),
605
+ prisma.oAuthClient.deleteMany({
606
+ where: { expiresAt: { lt: now } },
607
+ }),
382
608
  ]));
383
609
  const expiredSessions = results[0].count;
384
610
  const expiredDeviceFlows = results[1].count;