@zereight/mcp-gitlab 2.3.26-next.227 → 2.3.26-next.228

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.
@@ -1,170 +1,292 @@
1
- function stripGraphQLCommentsAndStrings(source) {
2
- let result = "";
1
+ // The guards below need the structure of a GraphQL document, not text patterns. A regex
2
+ // over the raw query can take a field alias or argument named `mutation` for an operation
3
+ // keyword, and it misses operation headers that the spec allows to contain commas,
4
+ // directives or comments. The document is therefore tokenized the way the GraphQL spec
5
+ // defines it, and the definitions are walked by a small parser. Anything the parser does
6
+ // not recognize throws, and the public checks treat that as a match (fail closed).
7
+ const PUNCTUATORS = new Set(["!", "$", "&", "(", ")", ":", "=", "@", "[", "]", "{", "|", "}"]);
8
+ const NAME_PATTERN = /[_A-Za-z][_0-9A-Za-z]*/y;
9
+ const NUMBER_PATTERN = /-?(?:0|[1-9][0-9]*)(?:\.[0-9]+)?(?:[eE][+-]?[0-9]+)?/y;
10
+ // Index just past the regular string literal that starts at `start`.
11
+ function skipString(source, start) {
12
+ let i = start + 1;
13
+ while (i < source.length) {
14
+ const ch = source[i];
15
+ if (ch === '"') {
16
+ return i + 1;
17
+ }
18
+ if (ch === "\n" || ch === "\r") {
19
+ break;
20
+ }
21
+ i += ch === "\\" ? 2 : 1;
22
+ }
23
+ throw new Error("Unterminated GraphQL string");
24
+ }
25
+ // Index just past the block string that starts at `start`. Only `\"""` is an escape.
26
+ function skipBlockString(source, start) {
27
+ let i = start + 3;
28
+ while (i < source.length) {
29
+ if (source.startsWith('\\"""', i)) {
30
+ i += 4;
31
+ }
32
+ else if (source.startsWith('"""', i)) {
33
+ return i + 3;
34
+ }
35
+ else {
36
+ i++;
37
+ }
38
+ }
39
+ throw new Error("Unterminated GraphQL block string");
40
+ }
41
+ function tokenizeGraphQL(source) {
42
+ const tokens = [];
3
43
  let i = 0;
4
44
  while (i < source.length) {
5
45
  const ch = source[i];
6
- if (ch === "#") {
46
+ // Ignored tokens: whitespace, line terminators, commas, the BOM, and comments.
47
+ if (ch === " " || ch === "\t" || ch === "\n" || ch === "\r" || ch === "," || ch === "") {
48
+ i++;
49
+ }
50
+ else if (ch === "#") {
7
51
  while (i < source.length && source[i] !== "\n" && source[i] !== "\r") {
8
52
  i++;
9
53
  }
10
- result += " ";
11
- continue;
12
54
  }
13
- if (source.slice(i, i + 3) === '"""') {
55
+ else if (source.startsWith('"""', i)) {
56
+ i = skipBlockString(source, i);
57
+ tokens.push({ kind: "literal" });
58
+ }
59
+ else if (ch === '"') {
60
+ i = skipString(source, i);
61
+ tokens.push({ kind: "literal" });
62
+ }
63
+ else if (source.startsWith("...", i)) {
64
+ tokens.push({ kind: "punct", value: "..." });
14
65
  i += 3;
15
- while (i < source.length && source.slice(i, i + 3) !== '"""') {
16
- if (source[i] === "\\" && source.slice(i, i + 4) === '\\"""') {
17
- i += 4;
18
- continue;
19
- }
20
- i++;
66
+ }
67
+ else if (PUNCTUATORS.has(ch)) {
68
+ tokens.push({ kind: "punct", value: ch });
69
+ i++;
70
+ }
71
+ else if (ch === "-" || /[0-9]/.test(ch)) {
72
+ NUMBER_PATTERN.lastIndex = i;
73
+ const match = NUMBER_PATTERN.exec(source);
74
+ if (!match) {
75
+ throw new Error(`Invalid GraphQL number at ${i}`);
21
76
  }
22
- if (i < source.length) {
23
- i += 3;
77
+ i += match[0].length;
78
+ // A number cannot run into a name or a dot.
79
+ if (i < source.length && /[_.A-Za-z0-9]/.test(source[i])) {
80
+ throw new Error(`Invalid GraphQL number at ${i}`);
24
81
  }
25
- result += " ";
26
- continue;
82
+ tokens.push({ kind: "literal" });
27
83
  }
28
- if (ch === '"' || ch === "'") {
29
- const quote = ch;
30
- i++;
31
- while (i < source.length) {
32
- if (source[i] === "\\") {
33
- i = Math.min(i + 2, source.length);
34
- continue;
35
- }
36
- if (source[i] === quote) {
37
- i++;
38
- break;
39
- }
40
- i++;
84
+ else {
85
+ NAME_PATTERN.lastIndex = i;
86
+ const match = NAME_PATTERN.exec(source);
87
+ if (!match) {
88
+ throw new Error(`Unexpected character in GraphQL document at ${i}`);
41
89
  }
42
- result += " ";
43
- continue;
90
+ tokens.push({ kind: "name", value: match[0] });
91
+ i += match[0].length;
44
92
  }
45
- result += ch;
46
- i++;
47
93
  }
48
- return result;
94
+ return tokens;
49
95
  }
50
- export function graphqlQueryContainsWriteOperation(query) {
51
- const normalized = stripGraphQLCommentsAndStrings(query).trim();
52
- if (!normalized) {
53
- return false;
54
- }
55
- const operationTypePattern = /\s*(?:,\s*)?(query|mutation|subscription)\b/y;
56
- let depth = 0;
57
- let expectingOperationType = true;
58
- for (let i = 0; i < normalized.length; i++) {
59
- const ch = normalized[i];
60
- if (ch === "{") {
61
- depth++;
62
- expectingOperationType = false;
63
- continue;
64
- }
65
- if (ch === "}") {
66
- depth = Math.max(0, depth - 1);
67
- if (depth === 0) {
68
- expectingOperationType = true;
96
+ const OPERATION_TYPES = new Set(["query", "mutation", "subscription"]);
97
+ const CLOSING_BRACKET = new Map([
98
+ ["(", ")"],
99
+ ["[", "]"],
100
+ ["{", "}"],
101
+ ]);
102
+ // Parses the executable definitions of a document. Throws on anything else: type-system
103
+ // definitions, stray punctuation, unbalanced brackets, or an empty selection set.
104
+ function parseGraphQLOperations(source) {
105
+ const tokens = tokenizeGraphQL(source);
106
+ const operations = [];
107
+ let pos = 0;
108
+ function isPunct(value) {
109
+ const token = tokens[pos];
110
+ return token !== undefined && token.kind === "punct" && token.value === value;
111
+ }
112
+ function isName(value) {
113
+ const token = tokens[pos];
114
+ return (token !== undefined && token.kind === "name" && (value === undefined || token.value === value));
115
+ }
116
+ function expectPunct(value) {
117
+ if (!isPunct(value)) {
118
+ throw new Error(`Expected "${value}" at token ${pos}`);
119
+ }
120
+ pos++;
121
+ }
122
+ function expectName() {
123
+ const token = tokens[pos];
124
+ if (token === undefined || token.kind !== "name") {
125
+ throw new Error(`Expected a name at token ${pos}`);
126
+ }
127
+ pos++;
128
+ return token.value;
129
+ }
130
+ // Skips a balanced "(...)", "[...]" or "{...}" that starts at the current token.
131
+ function skipBalanced() {
132
+ if (!isPunct("(") && !isPunct("[") && !isPunct("{")) {
133
+ throw new Error(`Expected a bracket at token ${pos}`);
134
+ }
135
+ const closers = [];
136
+ do {
137
+ const token = tokens[pos];
138
+ if (token === undefined) {
139
+ throw new Error("Unclosed bracket in GraphQL document");
69
140
  }
70
- continue;
71
- }
72
- if (depth === 0 && (ch === ";" || ch === ",")) {
73
- expectingOperationType = true;
74
- continue;
75
- }
76
- if (depth === 0 && expectingOperationType) {
77
- operationTypePattern.lastIndex = i;
78
- const operationMatch = operationTypePattern.exec(normalized);
79
- if (operationMatch) {
80
- const operationType = operationMatch[1];
81
- expectingOperationType = false;
82
- if (operationType === "mutation" || operationType === "subscription") {
83
- return true;
141
+ if (token.kind === "punct") {
142
+ const closer = CLOSING_BRACKET.get(token.value);
143
+ if (closer !== undefined) {
144
+ closers.push(closer);
145
+ }
146
+ else if (token.value === ")" || token.value === "]" || token.value === "}") {
147
+ if (closers.pop() !== token.value) {
148
+ throw new Error("Mismatched bracket in GraphQL document");
149
+ }
84
150
  }
85
- i = operationTypePattern.lastIndex - 1;
86
151
  }
87
- }
152
+ pos++;
153
+ } while (closers.length > 0);
88
154
  }
89
- return false;
90
- }
91
- // Verbs that mark a mutation as destructive for GITLAB_PERMISSION_MODE=modify.
92
- // GitLab exposes many destructive mutations whose names do not contain "delete"
93
- // (environmentStop, pipelineCancel, clusterAgentTokenRevoke, jobUnschedule, ...), so
94
- // the ban covers teardown verbs as well as deletion verbs.
95
- const DESTRUCTIVE_FIELD_PATTERN = /delete|destroy|remove|prune|purge|erase|revoke|cancel|stop|terminate|unprotect|disable|deactivate|drop|unschedule/i;
96
- // GraphQL treats whitespace and commas as insignificant, including between an
97
- // alias and its colon (`stop : field` and `stop,: field` are both aliases).
98
- function skipInsignificantGraphQL(source, index) {
99
- while (index < source.length && /[\s,]/.test(source[index])) {
100
- index++;
155
+ function skipDirectives() {
156
+ while (isPunct("@")) {
157
+ pos++;
158
+ expectName();
159
+ if (isPunct("(")) {
160
+ skipBalanced();
161
+ }
162
+ }
101
163
  }
102
- return index;
103
- }
104
- // Collects top-level selection field names of every mutation operation. Aliases are
105
- // skipped: `stop: environmentStop(...)` must be judged by the field name, so a
106
- // harmless label on a harmless field (`stop : issueSetSeverity(...)`) is not mistaken
107
- // for a destructive mutation. Content inside parentheses (arguments) is skipped so
108
- // argument names like removeSourceBranch do not count as delete fields. Returns null
109
- // when a top-level fragment spread is present, since the spread could hide a delete
110
- // field. Commas between operations are insignificant in GraphQL, so they are accepted
111
- // as operation separators alongside `;` and `}`.
112
- function extractTopLevelMutationFields(normalized) {
113
- const fields = [];
114
- const mutationRegex = /(?:^|[;},]\s*)mutation\b[^({]*(?:\([^)]*\))?\s*\{/g;
115
- while (mutationRegex.exec(normalized) !== null) {
116
- let i = mutationRegex.lastIndex;
117
- let braceDepth = 1;
118
- let parenDepth = 0;
119
- let current = "";
120
- while (i < normalized.length && braceDepth > 0) {
121
- const ch = normalized[i];
122
- if (ch === "(")
123
- parenDepth++;
124
- else if (ch === ")")
125
- parenDepth = Math.max(0, parenDepth - 1);
126
- else if (ch === "{")
127
- braceDepth++;
128
- else if (ch === "}")
129
- braceDepth--;
130
- if (braceDepth === 1 && parenDepth === 0) {
131
- if (normalized.startsWith("...", i)) {
132
- return null;
164
+ // Parses a selection set and returns its root field names. Nested selection sets are
165
+ // parsed too, so a malformed body is rejected rather than skipped.
166
+ function parseSelectionSet() {
167
+ expectPunct("{");
168
+ const fields = [];
169
+ let hasSpread = false;
170
+ let selections = 0;
171
+ while (!isPunct("}")) {
172
+ selections++;
173
+ if (isPunct("...")) {
174
+ hasSpread = true;
175
+ pos++;
176
+ if (isName("on")) {
177
+ pos++;
178
+ expectName();
179
+ }
180
+ else if (isName()) {
181
+ // Named fragment spread.
182
+ pos++;
133
183
  }
134
- if (/[A-Za-z0-9_]/.test(ch)) {
135
- current += ch;
136
- i++;
137
- continue;
184
+ skipDirectives();
185
+ if (isPunct("{")) {
186
+ parseSelectionSet();
138
187
  }
139
188
  }
140
- if (current) {
141
- // Only the actual field name is tested. Skip insignificant tokens so a
142
- // teardown-verb alias does not look like a destructive mutation.
143
- if (normalized[skipInsignificantGraphQL(normalized, i)] !== ":") {
144
- fields.push(current);
189
+ else {
190
+ let field = expectName();
191
+ if (isPunct(":")) {
192
+ // An alias: the field name after the colon is what GitLab executes.
193
+ pos++;
194
+ field = expectName();
195
+ }
196
+ if (isPunct("(")) {
197
+ skipBalanced();
145
198
  }
146
- current = "";
199
+ skipDirectives();
200
+ if (isPunct("{")) {
201
+ parseSelectionSet();
202
+ }
203
+ fields.push(field);
147
204
  }
148
- i++;
149
205
  }
150
- if (current) {
151
- fields.push(current);
206
+ if (selections === 0) {
207
+ throw new Error("Empty selection set in GraphQL document");
152
208
  }
209
+ pos++;
210
+ return { fields, hasSpread };
153
211
  }
154
- return fields;
212
+ function parseDefinition() {
213
+ if (isName("fragment")) {
214
+ pos++;
215
+ if (isName("on")) {
216
+ throw new Error("A fragment cannot be named on");
217
+ }
218
+ expectName();
219
+ if (!isName("on")) {
220
+ throw new Error("Expected a type condition on the fragment");
221
+ }
222
+ pos++;
223
+ expectName();
224
+ skipDirectives();
225
+ parseSelectionSet();
226
+ return;
227
+ }
228
+ let type = "query";
229
+ if (!isPunct("{")) {
230
+ const keyword = expectName();
231
+ if (!OPERATION_TYPES.has(keyword)) {
232
+ throw new Error(`Unsupported GraphQL definition "${keyword}"`);
233
+ }
234
+ type = keyword;
235
+ if (isName()) {
236
+ // Operation name.
237
+ pos++;
238
+ }
239
+ if (isPunct("(")) {
240
+ skipBalanced();
241
+ }
242
+ skipDirectives();
243
+ }
244
+ const selection = parseSelectionSet();
245
+ operations.push({
246
+ type,
247
+ rootFields: selection.hasSpread ? null : selection.fields,
248
+ });
249
+ }
250
+ while (pos < tokens.length) {
251
+ parseDefinition();
252
+ }
253
+ return operations;
155
254
  }
255
+ // Returns true when the document contains a mutation or subscription. A document that
256
+ // cannot be parsed is treated as a write.
257
+ export function graphqlQueryContainsWriteOperation(query) {
258
+ let operations;
259
+ try {
260
+ operations = parseGraphQLOperations(query);
261
+ }
262
+ catch {
263
+ return true;
264
+ }
265
+ return operations.some(operation => operation.type !== "query");
266
+ }
267
+ // Verbs that mark a mutation as destructive for GITLAB_PERMISSION_MODE=modify.
268
+ // GitLab exposes many destructive mutations whose names do not contain "delete"
269
+ // (environmentStop, pipelineCancel, clusterAgentTokenRevoke, jobUnschedule, ...), so
270
+ // the ban covers teardown verbs as well as deletion verbs.
271
+ const DESTRUCTIVE_FIELD_PATTERN = /delete|destroy|remove|prune|purge|erase|revoke|cancel|stop|terminate|unprotect|disable|deactivate|drop|unschedule/i;
156
272
  // Kept as `...DeleteOperation` for callers, but the guard now covers every
157
- // destructive mutation verb, not only delete-named ones.
273
+ // destructive mutation verb, not only delete-named ones. Only the field name is tested,
274
+ // so an alias such as `stop: issueSetSeverity(...)` does not count as a destructive field.
158
275
  export function graphqlQueryContainsDeleteOperation(query) {
159
- const normalized = stripGraphQLCommentsAndStrings(query).trim();
160
- if (!normalized || !/(?:^|[;},]\s*)mutation\b/.test(normalized)) {
161
- return false;
162
- }
163
- const fields = extractTopLevelMutationFields(normalized);
164
- if (fields === null || fields.length === 0) {
165
- // Fragment spread at mutation top level, or a mutation whose selection set
166
- // could not be located (exotic syntax): be conservative and treat as delete
276
+ let operations;
277
+ try {
278
+ operations = parseGraphQLOperations(query);
279
+ }
280
+ catch {
281
+ // The document could hide a mutation, so it is blocked.
167
282
  return true;
168
283
  }
169
- return fields.some(field => DESTRUCTIVE_FIELD_PATTERN.test(field));
284
+ return operations.some(operation => {
285
+ if (operation.type !== "mutation") {
286
+ return false;
287
+ }
288
+ // A root fragment spread could hide any field, so it is blocked too.
289
+ return (operation.rootFields === null ||
290
+ operation.rootFields.some(field => DESTRUCTIVE_FIELD_PATTERN.test(field)));
291
+ });
170
292
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@zereight/mcp-gitlab",
3
- "version": "2.3.26-next.227",
3
+ "version": "2.3.26-next.228",
4
4
  "mcpName": "io.github.zereight/gitlab-mcp",
5
5
  "description": "GitLab MCP server for projects, merge requests, issues, pipelines, wiki, releases, and more",
6
6
  "keywords": [