@cepharum/mcp-gitlab 0.0.0-stage → 0.1.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 (44) hide show
  1. package/CHANGELOG.md +16 -0
  2. package/LICENSE +21 -0
  3. package/README.md +170 -2
  4. package/package.json +50 -5
  5. package/src/audit.js +185 -0
  6. package/src/cli.js +411 -0
  7. package/src/connect.js +335 -0
  8. package/src/consent.js +115 -0
  9. package/src/downloads.js +94 -0
  10. package/src/errors.js +13 -0
  11. package/src/git.js +94 -0
  12. package/src/gitlab/client.js +406 -0
  13. package/src/gitlab/diff.js +79 -0
  14. package/src/hosts.js +228 -0
  15. package/src/paths.js +71 -0
  16. package/src/permissions/catalog.js +75 -0
  17. package/src/permissions/policy.js +230 -0
  18. package/src/permissions/profiles.js +66 -0
  19. package/src/pins.js +36 -0
  20. package/src/platform/index.js +76 -0
  21. package/src/platform/macos.js +129 -0
  22. package/src/platform/service.js +2 -0
  23. package/src/process.js +56 -0
  24. package/src/refs.js +146 -0
  25. package/src/secrets.js +51 -0
  26. package/src/server.js +146 -0
  27. package/src/session.js +140 -0
  28. package/src/text.js +68 -0
  29. package/src/tools/artifacts.js +288 -0
  30. package/src/tools/audit.js +53 -0
  31. package/src/tools/environments.js +147 -0
  32. package/src/tools/files.js +101 -0
  33. package/src/tools/index.js +33 -0
  34. package/src/tools/issues.js +465 -0
  35. package/src/tools/merge-requests.js +698 -0
  36. package/src/tools/packages.js +322 -0
  37. package/src/tools/pipelines.js +415 -0
  38. package/src/tools/registry.js +107 -0
  39. package/src/tools/repositories.js +174 -0
  40. package/src/tools/schedules.js +521 -0
  41. package/src/tools/shared.js +93 -0
  42. package/src/tools/variables.js +294 -0
  43. package/src/tools/wikis.js +168 -0
  44. package/src/zip.js +178 -0
package/src/paths.js ADDED
@@ -0,0 +1,71 @@
1
+ import { mkdir, readFile, rename, writeFile } from "node:fs/promises";
2
+ import { homedir } from "node:os";
3
+ import { join } from "node:path";
4
+
5
+ /**
6
+ * Folder holding hosts, settings, pins and the audit log of mcp-gitlab. It
7
+ * never holds access tokens, they are kept in the credential store of the
8
+ * operating system. `MCP_GITLAB_HOME` overrides it, e.g. for tests.
9
+ *
10
+ * @returns {string}
11
+ */
12
+ export function configDirectory() {
13
+ if ( process.env.MCP_GITLAB_HOME ) {
14
+ return process.env.MCP_GITLAB_HOME;
15
+ }
16
+
17
+ switch ( process.platform ) {
18
+ case "darwin" :
19
+ return join( homedir(), "Library", "Application Support", "mcp-gitlab" );
20
+ case "win32" :
21
+ return join( process.env.APPDATA ?? join( homedir(), "AppData", "Roaming" ), "mcp-gitlab" );
22
+ default :
23
+ return join( process.env.XDG_CONFIG_HOME ?? join( homedir(), ".config" ), "mcp-gitlab" );
24
+ }
25
+ }
26
+
27
+ /**
28
+ * Reads a JSON file of the configuration folder.
29
+ *
30
+ * @template T
31
+ * @param {string} name name of the file in the configuration folder
32
+ * @param {T} fallback returned if the file doesn't exist
33
+ * @returns {Promise<T|unknown>} parsed content, which callers have to validate
34
+ */
35
+ export async function readJsonFile( name, fallback ) {
36
+ let text;
37
+
38
+ try {
39
+ text = await readFile( join( configDirectory(), name ), "utf8" );
40
+ } catch ( error ) {
41
+ if ( error.code === "ENOENT" ) {
42
+ return fallback;
43
+ }
44
+
45
+ throw error;
46
+ }
47
+
48
+ try {
49
+ return JSON.parse( text );
50
+ } catch ( cause ) {
51
+ throw new Error( `${join( configDirectory(), name )} isn't valid JSON: ${cause.message}` );
52
+ }
53
+ }
54
+
55
+ /**
56
+ * Writes a JSON file of the configuration folder. The file is replaced as a
57
+ * whole, so a crash can't leave a partially written file behind.
58
+ *
59
+ * @param {string} name name of the file in the configuration folder
60
+ * @param {unknown} data
61
+ * @returns {Promise<void>}
62
+ */
63
+ export async function writeJsonFile( name, data ) {
64
+ const folder = configDirectory();
65
+ const target = join( folder, name );
66
+ const temporary = `${target}.${process.pid}.tmp`;
67
+
68
+ await mkdir( folder, { recursive: true, mode: 0o700 } );
69
+ await writeFile( temporary, `${JSON.stringify( data, null, "\t" )}\n`, { mode: 0o600 } );
70
+ await rename( temporary, target );
71
+ }
@@ -0,0 +1,75 @@
1
+ /**
2
+ * Every permission a tool can require, with what it allows. Profiles grant
3
+ * them by name or by pattern such as "mr.*" or "*.read".
4
+ *
5
+ * @type {Readonly<Record<string, string>>}
6
+ */
7
+ export const PERMISSIONS = Object.freeze( {
8
+ "repo.read": "list repositories",
9
+ "code.read": "read files and folders of repositories",
10
+ "pins.change": "pin and unpin repositories locally",
11
+ "mr.read": "read merge requests, their changes and comments",
12
+ "mr.create": "create merge requests",
13
+ "mr.update": "change title, description and draft state of merge requests",
14
+ "mr.close": "close and reopen merge requests",
15
+ "mr.comment": "comment on merge requests, resolve and reopen threads",
16
+ "mr.vote": "approve merge requests and revoke approvals",
17
+ "mr.merge": "merge merge requests or have them merged when the pipeline succeeds",
18
+ "issue.read": "read issues, their comments and milestones",
19
+ "issue.create": "create issues",
20
+ "issue.update": "change issues",
21
+ "issue.comment": "comment on issues",
22
+ "issue.link": "link issues",
23
+ "pipeline.read": "read pipelines, jobs and job logs",
24
+ "pipeline.run": "start pipelines",
25
+ "pipeline.retry": "retry jobs and pipelines",
26
+ "pipeline.cancel": "cancel pipelines",
27
+ "artifact.read": "read files of job artifacts",
28
+ "artifact.download": "save files of job artifacts on this computer",
29
+ "package.read": "read packages and files of generic packages",
30
+ "package.upload": "upload files of local clones to generic packages, confirmed every time",
31
+ "package.delete": "delete versions and files of packages",
32
+ "registry.read": "read images and tags of container registries",
33
+ "deployment.read": "read environments and deployments",
34
+ "runner.read": "read the runners available to repositories",
35
+ "variable.read": "list CI/CD variables of repositories and read values of those that aren't sensitive; sensitive ones only after confirmation every time",
36
+ "variable.update": "create and change CI/CD variables; the user enters values of sensitive ones",
37
+ "variable.delete": "delete CI/CD variables",
38
+ "schedule.read": "read pipeline schedules and values of their variables that aren't sensitive; sensitive ones only after confirmation every time",
39
+ "schedule.update": "create and change pipeline schedules and their variables; the user enters values of sensitive ones and confirms taking over schedules of others every time",
40
+ "schedule.delete": "delete pipeline schedules",
41
+ "schedule.run": "run pipeline schedules now, with the permissions of their owners",
42
+ "wiki.read": "read wiki pages",
43
+ "wiki.create": "create wiki pages",
44
+ "wiki.update": "change wiki pages",
45
+ "audit.read": "read the audit log of this server",
46
+ } );
47
+
48
+ /**
49
+ * Converts a permission pattern into a regular expression: `*` matches one
50
+ * part of a name.
51
+ *
52
+ * @param {string} pattern e.g. "mr.*"
53
+ * @returns {RegExp}
54
+ */
55
+ function permissionPattern( pattern ) {
56
+ return new RegExp( `^${pattern.split( "*" ).map( part => part.replace( /[.+?^${}()|[\]\\]/g, "\\$&" ) ).join( "[a-z]+" )}$` );
57
+ }
58
+
59
+ /**
60
+ * Lists the permissions matching a pattern.
61
+ *
62
+ * @param {string} pattern
63
+ * @returns {string[]}
64
+ * @throws {Error} if nothing matches, so a typo doesn't silently grant or deny nothing
65
+ */
66
+ export function expandPermission( pattern ) {
67
+ const matcher = permissionPattern( pattern );
68
+ const matches = Object.keys( PERMISSIONS ).filter( name => matcher.test( name ) );
69
+
70
+ if ( matches.length === 0 ) {
71
+ throw new Error( `"${pattern}" doesn't match any permission` );
72
+ }
73
+
74
+ return matches;
75
+ }
@@ -0,0 +1,230 @@
1
+ import { readJsonFile, writeJsonFile } from "../paths.js";
2
+ import { expandPermission } from "./catalog.js";
3
+ import { BUILT_IN_PROFILES, DEFAULT_PROFILE } from "./profiles.js";
4
+
5
+ /**
6
+ * Content of settings.json.
7
+ *
8
+ * @typedef {object} Settings
9
+ * @property {string} [profile] profile used unless MCP_GITLAB_PROFILE selects another one
10
+ * @property {Record<string, import("./profiles.js").ProfileDefinition>} [profiles] custom profiles
11
+ * @property {string[]} [deny] permissions taken away from every profile
12
+ * @property {string[]} [repos] reference patterns limiting the repositories of every profile, in addition to those of the profile
13
+ */
14
+
15
+ /**
16
+ * A profile with its inheritance resolved.
17
+ *
18
+ * @typedef {object} Profile
19
+ * @property {string} name
20
+ * @property {string} [description]
21
+ * @property {Set<string>} permissions
22
+ * @property {Map<string, "session"|"always">} confirm
23
+ * @property {string[][]} scopes lists of reference patterns, each of which has to allow a repository, empty for no limit
24
+ */
25
+
26
+ const FILE = "settings.json";
27
+
28
+ const CONFIRM_MODES = [ "never", "session", "always" ];
29
+
30
+ /**
31
+ * @returns {Promise<Settings>}
32
+ */
33
+ export async function loadSettings() {
34
+ const settings = await readJsonFile( FILE, {} );
35
+
36
+ if ( !settings || typeof settings !== "object" || Array.isArray( settings ) ) {
37
+ throw new Error( "settings.json has to contain an object" );
38
+ }
39
+
40
+ return /** @type {Settings} */ settings;
41
+ }
42
+
43
+ /**
44
+ * @param {Settings} settings
45
+ * @returns {Promise<void>}
46
+ */
47
+ export function saveSettings( settings ) {
48
+ return writeJsonFile( FILE, settings );
49
+ }
50
+
51
+ /**
52
+ * Lists the profiles available, built-in and custom ones.
53
+ *
54
+ * @param {Settings} settings
55
+ * @returns {Record<string, import("./profiles.js").ProfileDefinition>}
56
+ */
57
+ export function availableProfiles( settings ) {
58
+ return { ...BUILT_IN_PROFILES, ...settings.profiles ?? {} };
59
+ }
60
+
61
+ /**
62
+ * Names the profile to use: MCP_GITLAB_PROFILE, else the one in the settings, else the default.
63
+ *
64
+ * @param {Settings} settings
65
+ * @param {NodeJS.ProcessEnv} [env]
66
+ * @returns {string}
67
+ */
68
+ export function selectedProfileName( settings, env = process.env ) {
69
+ return env.MCP_GITLAB_PROFILE?.trim() || settings.profile || DEFAULT_PROFILE;
70
+ }
71
+
72
+ /**
73
+ * Resolves a profile, including the profiles it extends and the global denials.
74
+ *
75
+ * @param {string} name
76
+ * @param {Settings} settings
77
+ * @returns {Profile}
78
+ */
79
+ export function resolveProfile( name, settings ) {
80
+ const definitions = availableProfiles( settings );
81
+
82
+ /**
83
+ * @param {string} current
84
+ * @param {string[]} chain names already visited, to detect cycles
85
+ * @returns {Omit<Profile, "scopes"> & { repos: string[]|undefined }}
86
+ */
87
+ const resolve = ( current, chain ) => {
88
+ const definition = definitions[current];
89
+
90
+ if ( !definition || typeof definition !== "object" ) {
91
+ throw new Error( `there is no profile "${current}", available are ${Object.keys( definitions ).join( ", " )}` );
92
+ }
93
+
94
+ if ( chain.includes( current ) ) {
95
+ throw new Error( `profile "${current}" extends itself via ${chain.join( " → " )}` );
96
+ }
97
+
98
+ const base = definition.extends ?
99
+ resolve( definition.extends, [ ...chain, current ] ) :
100
+ { name: current, permissions: new Set(), confirm: new Map(), repos: undefined };
101
+
102
+ const permissions = new Set( base.permissions );
103
+
104
+ for ( const pattern of list( definition.allow, current, "allow" ) ) {
105
+ expandPermission( pattern ).forEach( permission => permissions.add( permission ) );
106
+ }
107
+
108
+ for ( const pattern of list( definition.deny, current, "deny" ) ) {
109
+ expandPermission( pattern ).forEach( permission => permissions.delete( permission ) );
110
+ }
111
+
112
+ const confirm = new Map( base.confirm );
113
+
114
+ for ( const [ pattern, mode ] of Object.entries( definition.confirm ?? {} ) ) {
115
+ if ( !CONFIRM_MODES.includes( mode ) ) {
116
+ throw new Error( `profile "${current}" confirms "${pattern}" with "${mode}", expected one of ${CONFIRM_MODES.join( ", " )}` );
117
+ }
118
+
119
+ for ( const permission of expandPermission( pattern ) ) {
120
+ if ( mode === "never" ) {
121
+ confirm.delete( permission );
122
+ } else {
123
+ confirm.set( permission, mode );
124
+ }
125
+ }
126
+ }
127
+
128
+ const repos = definition.repos === undefined ? base.repos : scope( definition.repos, current );
129
+
130
+ return { name: current, description: definition.description, permissions, confirm, repos };
131
+ };
132
+
133
+ const { repos, ...resolved } = resolve( name, [] );
134
+ const global = settings.repos === undefined ? undefined : scope( settings.repos, "settings" );
135
+
136
+ /** @type {Profile} */
137
+ const profile = { ...resolved, scopes: [ global, repos ].filter( patterns => patterns !== undefined ) };
138
+
139
+ for ( const pattern of list( settings.deny, "settings", "deny" ) ) {
140
+ expandPermission( pattern ).forEach( permission => profile.permissions.delete( permission ) );
141
+ }
142
+
143
+ return profile;
144
+ }
145
+
146
+ /**
147
+ * @param {unknown} value
148
+ * @param {string} profile
149
+ * @param {string} property
150
+ * @returns {string[]}
151
+ */
152
+ function list( value, profile, property ) {
153
+ if ( value === undefined ) {
154
+ return [];
155
+ }
156
+
157
+ if ( !Array.isArray( value ) || !value.every( item => typeof item === "string" ) ) {
158
+ throw new Error( `"${property}" of "${profile}" has to be a list of strings` );
159
+ }
160
+
161
+ return value;
162
+ }
163
+
164
+ /**
165
+ * Validates a list of reference patterns.
166
+ *
167
+ * @param {unknown} value
168
+ * @param {string} profile
169
+ * @returns {string[]}
170
+ */
171
+ function scope( value, profile ) {
172
+ const patterns = list( value, profile, "repos" );
173
+
174
+ for ( const pattern of patterns ) {
175
+ if ( !pattern.replace( /^!/, "" ).trim() ) {
176
+ throw new Error( `"repos" of "${profile}" contains an empty pattern` );
177
+ }
178
+ }
179
+
180
+ return patterns;
181
+ }
182
+
183
+ /**
184
+ * Converts a reference pattern into a regular expression: `*` matches within
185
+ * one segment of a path, `**` across segments. Matching ignores case like GitLab does.
186
+ *
187
+ * @param {string} pattern e.g. "gitlab.com:my-group/**"
188
+ * @returns {RegExp}
189
+ */
190
+ export function refPattern( pattern ) {
191
+ const source = pattern
192
+ .split( /(\*\*|\*)/ )
193
+ .map( part => ( part === "**" ? ".*" : part === "*" ? "[^/]*" : part.replace( /[.+?^${}()|[\]\\]/g, "\\$&" ) ) )
194
+ .join( "" );
195
+
196
+ return new RegExp( `^${source}$`, "i" );
197
+ }
198
+
199
+ /**
200
+ * Tells whether a list of reference patterns allows a repository: it has to
201
+ * match one of the patterns and none of those excluding repositories with a
202
+ * leading "!". A list of exclusions only allows all other repositories, an
203
+ * empty list none.
204
+ *
205
+ * @param {string[]} patterns e.g. [ "gitlab.com:my-group/**", "!gitlab.com:my-group/secret" ]
206
+ * @param {string} ref formatted reference, e.g. "gitlab.com:group/project"
207
+ * @returns {boolean}
208
+ */
209
+ export function scopeAllows( patterns, ref ) {
210
+ const included = patterns.filter( pattern => !pattern.startsWith( "!" ) );
211
+ const excluded = patterns.filter( pattern => pattern.startsWith( "!" ) ).map( pattern => pattern.slice( 1 ) );
212
+
213
+ if ( excluded.some( pattern => refPattern( pattern ).test( ref ) ) ) {
214
+ return false;
215
+ }
216
+
217
+ return included.length > 0 ? included.some( pattern => refPattern( pattern ).test( ref ) ) : excluded.length > 0;
218
+ }
219
+
220
+ /**
221
+ * Tells whether a profile may access a repository: every scope, the global
222
+ * one of the settings and the one of the profile, has to allow it.
223
+ *
224
+ * @param {Profile} profile
225
+ * @param {string} ref formatted reference, e.g. "gitlab.com:group/project"
226
+ * @returns {boolean}
227
+ */
228
+ export function allowsRepo( profile, ref ) {
229
+ return profile.scopes.every( patterns => scopeAllows( patterns, ref ) );
230
+ }
@@ -0,0 +1,66 @@
1
+ /**
2
+ * A set of permissions, selected per agent. Custom profiles in settings.json
3
+ * have the same structure.
4
+ *
5
+ * @typedef {object} ProfileDefinition
6
+ * @property {string} [description]
7
+ * @property {string} [extends] name of a profile whose permissions, confirmations and scopes are taken over
8
+ * @property {string[]} [allow] permissions or patterns granted
9
+ * @property {string[]} [deny] permissions or patterns taken away, which wins over `allow`
10
+ * @property {Record<string, "never"|"session"|"always">} [confirm] permissions the user has to confirm in a dialog
11
+ * @property {string[]} [repos] reference patterns of the only repositories the profile may access, e.g. "gitlab.com:my-group/**"
12
+ */
13
+
14
+ /** @type {Readonly<Record<string, ProfileDefinition>>} */
15
+ export const BUILT_IN_PROFILES = Object.freeze( {
16
+ readonly: {
17
+ description: "reads everything, changes nothing at GitLab (default)",
18
+ allow: [ "*.read", "pins.change" ],
19
+ },
20
+ developer: {
21
+ description: "works on merge requests, issues, pipelines and wikis, uploads packages, but doesn't approve or merge",
22
+ extends: "readonly",
23
+ allow: [
24
+ "mr.create", "mr.update", "mr.close", "mr.comment",
25
+ "issue.create", "issue.update", "issue.comment", "issue.link",
26
+ "pipeline.run", "pipeline.retry", "pipeline.cancel", "schedule.run",
27
+ "artifact.download", "package.upload",
28
+ "wiki.create", "wiki.update",
29
+ ],
30
+ confirm: { "artifact.download": "session", "mr.close": "always", "schedule.run": "session", "package.upload": "always" },
31
+ },
32
+ devops: {
33
+ description: "watches pipelines and infrastructure: runs, retries and cancels pipelines, manages CI/CD variables, pipeline schedules and packages, reports and updates issues and runbooks, comments on merge requests",
34
+ extends: "readonly",
35
+ allow: [
36
+ "pipeline.run", "pipeline.retry", "pipeline.cancel",
37
+ "artifact.download",
38
+ "issue.create", "issue.update", "issue.comment", "issue.link",
39
+ "wiki.create", "wiki.update",
40
+ "mr.comment",
41
+ "variable.update", "variable.delete",
42
+ "schedule.update", "schedule.delete", "schedule.run",
43
+ "package.upload", "package.delete",
44
+ ],
45
+ confirm: {
46
+ "pipeline.run": "session", "pipeline.cancel": "always", "artifact.download": "session",
47
+ "variable.update": "session", "variable.delete": "always",
48
+ "schedule.update": "session", "schedule.delete": "always", "schedule.run": "session",
49
+ "package.upload": "always", "package.delete": "always",
50
+ },
51
+ },
52
+ maintainer: {
53
+ description: "like developer, also approves and merges merge requests and manages CI/CD variables, pipeline schedules and packages after confirmation",
54
+ extends: "developer",
55
+ allow: [ "mr.vote", "mr.merge", "variable.update", "variable.delete", "schedule.update", "schedule.delete", "package.delete" ],
56
+ confirm: {
57
+ "mr.vote": "session", "mr.merge": "always",
58
+ "variable.update": "session", "variable.delete": "always",
59
+ "schedule.update": "session", "schedule.delete": "always",
60
+ "package.delete": "always",
61
+ },
62
+ },
63
+ } );
64
+
65
+ /** Profile used if neither the environment nor the settings select one. */
66
+ export const DEFAULT_PROFILE = "readonly";
package/src/pins.js ADDED
@@ -0,0 +1,36 @@
1
+ import { readJsonFile, writeJsonFile } from "./paths.js";
2
+
3
+ const FILE = "pins.json";
4
+
5
+ /**
6
+ * References of the repositories the user pinned, so `repo_list` shows them
7
+ * by default.
8
+ *
9
+ * @returns {Promise<string[]>}
10
+ */
11
+ export async function loadPins() {
12
+ const entries = await readJsonFile( FILE, [] );
13
+
14
+ return Array.isArray( entries ) ? entries.filter( entry => typeof entry === "string" && entry.length <= 300 ) : [];
15
+ }
16
+
17
+ /**
18
+ * Pins or unpins a repository.
19
+ *
20
+ * @param {string} ref formatted reference of the repository
21
+ * @param {boolean} pinned
22
+ * @returns {Promise<boolean>} true if the pins changed
23
+ */
24
+ export async function setPinned( ref, pinned ) {
25
+ const pins = await loadPins();
26
+ const key = ref.toLowerCase();
27
+ const has = pins.some( pin => pin.toLowerCase() === key );
28
+
29
+ if ( has === pinned ) {
30
+ return false;
31
+ }
32
+
33
+ await writeJsonFile( FILE, pinned ? [ ...pins, ref ].sort() : pins.filter( pin => pin.toLowerCase() !== key ) );
34
+
35
+ return true;
36
+ }
@@ -0,0 +1,76 @@
1
+ import { createMacOSPlatform } from "./macos.js";
2
+
3
+ /**
4
+ * Everything mcp-gitlab needs from the operating system. Supporting another
5
+ * operating system means writing one module implementing this interface and
6
+ * selecting it in `selectPlatform()`; nothing else depends on the platform.
7
+ * See docs/ARCHITECTURE.md for the requirements an implementation has to meet.
8
+ *
9
+ * @typedef {object} Platform
10
+ * @property {string} name human readable name of the platform, used in messages
11
+ * @property {(account: string) => Promise<string|null>} readSecret
12
+ * returns the secret stored for an account, null if there is none
13
+ * @property {(account: string) => Promise<boolean>} storeSecretInteractively
14
+ * has the user enter the secret for an account in the terminal and stores it,
15
+ * ideally without the secret passing through this process; false if the user aborted
16
+ * @property {(account: string) => Promise<boolean>} deleteSecret
17
+ * removes the secret of an account, false if there was none
18
+ * @property {(request: ConfirmRequest) => Promise<ConfirmAnswer>} confirm
19
+ * asks the user in a dialog of the desktop, independent of the agent
20
+ * @property {(request: { message: string }) => Promise<string|null>} promptSecret
21
+ * has the user enter a secret value in a dialog of the desktop with hidden input,
22
+ * independent of the agent; null if the user cancelled or entered nothing
23
+ */
24
+
25
+ /**
26
+ * @typedef {object} ConfirmRequest
27
+ * @property {string} message what is about to happen, in plain text
28
+ * @property {boolean} [allowSession] offer to allow for the rest of the session as well
29
+ * @property {string} [sessionLabel] text of the button allowing for the session, if it differs
30
+ * from "Allow for this session", e.g. "Allow until 18:30" while a session started by the user runs
31
+ */
32
+
33
+ /**
34
+ * - `once`: allowed this time
35
+ * - `session`: allowed for the session: until the server stops, or until the session started by the user ends
36
+ * - `deny`: denied, also when the dialog timed out or couldn't be shown
37
+ *
38
+ * @typedef {"once"|"session"|"deny"} ConfirmAnswer
39
+ */
40
+
41
+ /**
42
+ * Picks the implementation for the operating system running the server.
43
+ *
44
+ * @param {NodeJS.Platform} [platform]
45
+ * @returns {Platform}
46
+ */
47
+ export function selectPlatform( platform = process.platform ) {
48
+ switch ( platform ) {
49
+ case "darwin" :
50
+ return createMacOSPlatform();
51
+ default :
52
+ return createUnsupportedPlatform( platform );
53
+ }
54
+ }
55
+
56
+ /**
57
+ * Stands in on operating systems that aren't supported yet, so the server
58
+ * starts and explains instead of crashing.
59
+ *
60
+ * @param {string} platform
61
+ * @returns {Platform}
62
+ */
63
+ function createUnsupportedPlatform( platform ) {
64
+ const fail = async() => {
65
+ throw new Error( `mcp-gitlab doesn't support ${platform} yet: it needs a credential store and a confirmation dialog, see docs/ARCHITECTURE.md` );
66
+ };
67
+
68
+ return {
69
+ name: platform,
70
+ readSecret: fail,
71
+ storeSecretInteractively: fail,
72
+ deleteSecret: fail,
73
+ confirm: async() => "deny",
74
+ promptSecret: async() => null,
75
+ };
76
+ }
@@ -0,0 +1,129 @@
1
+ import { run, runInteractive } from "../process.js";
2
+ import { SECRET_SERVICE } from "./service.js";
3
+
4
+ /** Seconds a confirmation dialog waits for an answer before it counts as denied. */
5
+ const DIALOG_TIMEOUT = 120;
6
+
7
+ /**
8
+ * Shows a dialog whose texts are passed as arguments, so nothing in them can
9
+ * be interpreted as AppleScript. The first button denies: it is the default
10
+ * button, the cancel button (Escape) and what a timeout or error results in.
11
+ */
12
+ const DIALOG_SCRIPT = `
13
+ on run argv
14
+ set theMessage to item 1 of argv
15
+ set theButtons to items 2 thru -1 of argv
16
+ try
17
+ set theResult to display dialog theMessage with title "mcp-gitlab" buttons theButtons default button 1 cancel button 1 with icon caution giving up after ${DIALOG_TIMEOUT}
18
+ if gave up of theResult then return ""
19
+ return button returned of theResult
20
+ on error
21
+ return ""
22
+ end try
23
+ end run`;
24
+
25
+ /** Seconds a dialog asking for a secret waits for it, longer than for a decision. */
26
+ const PROMPT_TIMEOUT = 300;
27
+
28
+ /**
29
+ * Asks for a secret with hidden input. The secret is written to stdout only,
30
+ * prefixed, so an empty result means cancelled, timed out or failed. Unlike
31
+ * confirmations, "Set" is the default button, so Enter submits what was typed;
32
+ * Escape cancels, and nothing typed counts as cancelled.
33
+ */
34
+ const PROMPT_SCRIPT = `
35
+ on run argv
36
+ try
37
+ set theResult to display dialog (item 1 of argv) with title "mcp-gitlab" default answer "" with hidden answer buttons {"Cancel", "Set"} default button 2 cancel button 1 with icon caution giving up after ${PROMPT_TIMEOUT}
38
+ if gave up of theResult then return ""
39
+ if button returned of theResult is not "Set" then return ""
40
+ return "value:" & text returned of theResult
41
+ on error
42
+ return ""
43
+ end try
44
+ end run`;
45
+
46
+ /** Default text of the button allowing for the rest of the session. */
47
+ const SESSION_LABEL = "Allow for this session";
48
+
49
+ /** Exit code of `security` for an item that doesn't exist. */
50
+ const NOT_FOUND = 44;
51
+
52
+ /**
53
+ * Credentials in the login keychain via `security`, dialogs via `osascript`.
54
+ * Both ship with macOS.
55
+ *
56
+ * @returns {import("./index.js").Platform}
57
+ */
58
+ export function createMacOSPlatform() {
59
+ return {
60
+ name: "macOS",
61
+
62
+ async readSecret( account ) {
63
+ try {
64
+ return ( await run( "security", [ "find-generic-password", "-s", SECRET_SERVICE, "-a", account, "-w" ] ) ).trim() || null;
65
+ } catch ( error ) {
66
+ if ( error.exitCode === NOT_FOUND ) {
67
+ return null;
68
+ }
69
+
70
+ throw new Error( `reading the keychain failed: ${error.message}` );
71
+ }
72
+ },
73
+
74
+ async storeSecretInteractively( account ) {
75
+ // "-w" as last option has security prompt for the secret, so it never shows up in a process list or passes this process
76
+ const code = await runInteractive( "security", [ "add-generic-password", "-U", "-s", SECRET_SERVICE, "-a", account, "-l", `${SECRET_SERVICE}: ${account}`, "-w" ] );
77
+
78
+ return code === 0;
79
+ },
80
+
81
+ async deleteSecret( account ) {
82
+ try {
83
+ await run( "security", [ "delete-generic-password", "-s", SECRET_SERVICE, "-a", account ] );
84
+
85
+ return true;
86
+ } catch ( error ) {
87
+ if ( error.exitCode === NOT_FOUND ) {
88
+ return false;
89
+ }
90
+
91
+ throw new Error( `removing from the keychain failed: ${error.message}` );
92
+ }
93
+ },
94
+
95
+ async confirm( { message, allowSession = false, sessionLabel = SESSION_LABEL } ) {
96
+ const buttons = allowSession ? [ "Deny", "Allow once", sessionLabel ] : [ "Deny", "Allow" ];
97
+ let answer;
98
+
99
+ try {
100
+ answer = ( await run( "osascript", [ "-e", DIALOG_SCRIPT, message, ...buttons ], { timeoutMs: ( DIALOG_TIMEOUT + 10 ) * 1000 } ) ).trim();
101
+ } catch {
102
+ return "deny";
103
+ }
104
+
105
+ switch ( answer ) {
106
+ case "Allow" :
107
+ case "Allow once" :
108
+ return "once";
109
+ default :
110
+ return allowSession && answer === sessionLabel ? "session" : "deny";
111
+ }
112
+ },
113
+
114
+ async promptSecret( { message } ) {
115
+ let output;
116
+
117
+ try {
118
+ output = await run( "osascript", [ "-e", PROMPT_SCRIPT, message ], { timeoutMs: ( PROMPT_TIMEOUT + 10 ) * 1000 } );
119
+ } catch {
120
+ return null;
121
+ }
122
+
123
+ // osascript ends its output with a line break, which isn't part of the value
124
+ const value = output.replace( /\n$/, "" );
125
+
126
+ return value.startsWith( "value:" ) && value.length > 6 ? value.slice( 6 ) : null;
127
+ },
128
+ };
129
+ }
@@ -0,0 +1,2 @@
1
+ /** Name of the service under which secrets are kept in credential stores. */
2
+ export const SECRET_SERVICE = "mcp-gitlab";