@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
@@ -0,0 +1,294 @@
1
+ import { z } from "zod";
2
+ import { DeniedError } from "../errors.js";
3
+ import { GitLabError, projectId } from "../gitlab/client.js";
4
+ import { formatRef } from "../refs.js";
5
+ import { PAGE_INPUT, pick } from "./shared.js";
6
+
7
+ /** Names of variables whose values are treated as secrets, whatever GitLab knows about them. */
8
+ const SENSITIVE_NAME = /token|secret|password|passwort|key/i;
9
+
10
+ const KEY_INPUT = z.string().min( 1 ).max( 255 ).regex( /^\w+$/ ).describe( "Name of the variable, e.g. \"DEPLOY_HOST\"" );
11
+
12
+ const ENVIRONMENT_INPUT = z.string().min( 1 ).max( 255 ).optional()
13
+ .describe( "Environment scope of the variable, e.g. \"*\" or \"production\", as variable_list returns it; needed if the name is used in several scopes" );
14
+
15
+ /**
16
+ * Tells why a variable's value is treated as a secret, if it is.
17
+ *
18
+ * @param {{ key: string, masked?: boolean, hidden?: boolean }} variable
19
+ * @returns {string|null} e.g. "masked", null if it isn't sensitive
20
+ */
21
+ export function sensitivity( { key, masked, hidden } ) {
22
+ if ( hidden ) {
23
+ return "hidden";
24
+ }
25
+
26
+ if ( masked ) {
27
+ return "masked";
28
+ }
29
+
30
+ return SENSITIVE_NAME.test( key ) ? "sensitive" : null;
31
+ }
32
+
33
+ /**
34
+ * @param {import("../refs.js").RepoRef} repo
35
+ * @param {string} [key]
36
+ * @returns {string}
37
+ */
38
+ function endpoint( repo, key ) {
39
+ return `projects/${projectId( repo )}/variables${key ? `/${encodeURIComponent( key )}` : ""}`;
40
+ }
41
+
42
+ /**
43
+ * @param {string|undefined} environment
44
+ * @returns {Record<string, string>|undefined}
45
+ */
46
+ function scopeFilter( environment ) {
47
+ return environment ? { "filter[environment_scope]": environment } : undefined;
48
+ }
49
+
50
+ /**
51
+ * @param {string} key
52
+ * @param {string|undefined} environment
53
+ * @returns {string}
54
+ */
55
+ function describeVariable( key, environment ) {
56
+ return `"${key}"${environment ? ` (environment ${environment})` : ""}`;
57
+ }
58
+
59
+ /**
60
+ * Reads a variable including its value, null if it doesn't exist.
61
+ *
62
+ * @param {import("./shared.js").ToolContext} context
63
+ * @param {string} key
64
+ * @param {string} [environment]
65
+ * @returns {Promise<any>}
66
+ */
67
+ async function readVariable( { gitlab, repo }, key, environment ) {
68
+ try {
69
+ return await gitlab.get( repo.host, endpoint( repo, key ), scopeFilter( environment ) );
70
+ } catch ( error ) {
71
+ if ( error.status === 404 ) {
72
+ return null;
73
+ }
74
+
75
+ if ( error.status === 409 ) {
76
+ throw new GitLabError( `"${key}" is defined for several environments in ${formatRef( repo )}, name one as "environment", see variable_list`, 409 );
77
+ }
78
+
79
+ throw error;
80
+ }
81
+ }
82
+
83
+ /**
84
+ * Properties of a variable agents get, never its value.
85
+ *
86
+ * @param {any} variable as GitLab returns it
87
+ * @returns {Record<string, unknown>}
88
+ */
89
+ function describe( variable ) {
90
+ return {
91
+ ...pick( variable, {
92
+ key: "key",
93
+ type: "variable_type",
94
+ environment: "environment_scope",
95
+ protected: source => source.protected || undefined,
96
+ masked: source => source.masked || undefined,
97
+ hidden: source => source.hidden || undefined,
98
+ raw: source => source.raw || undefined,
99
+ description: "description",
100
+ } ),
101
+ ...sensitivity( variable ) ? { sensitive: true } : {},
102
+ };
103
+ }
104
+
105
+ /**
106
+ * What variable_set is about to do, found out once before the user is asked.
107
+ *
108
+ * @type {WeakMap<object, { existing: any, sensitive: string|null }>}
109
+ */
110
+ const plans = new WeakMap();
111
+
112
+ /**
113
+ * @param {any} args
114
+ * @param {import("./shared.js").ToolContext} context
115
+ * @returns {Promise<{ existing: any, sensitive: string|null }>}
116
+ */
117
+ async function planSet( args, context ) {
118
+ if ( !plans.has( args ) ) {
119
+ const { key, value, environment = "*", masked, hidden } = args;
120
+ const existing = await readVariable( context, key, environment );
121
+
122
+ if ( existing && hidden && !existing.hidden ) {
123
+ throw new Error( `${describeVariable( key, environment )} exists and isn't hidden, which GitLab can't change: delete it and create it again` );
124
+ }
125
+
126
+ const sensitive = sensitivity( { key, masked: masked ?? existing?.masked, hidden: hidden ?? existing?.hidden } );
127
+
128
+ if ( sensitive && value !== undefined ) {
129
+ throw new DeniedError( `${describeVariable( key, environment )} is ${sensitive}: its value is entered by the user in a dialog, so call variable_set again without "value"` );
130
+ }
131
+
132
+ if ( !sensitive && value === undefined && !existing ) {
133
+ throw new Error( `${describeVariable( key, environment )} doesn't exist yet, give it a "value"` );
134
+ }
135
+
136
+ plans.set( args, { existing, sensitive } );
137
+ }
138
+
139
+ return /** @type {{ existing: any, sensitive: string|null }} */ ( plans.get( args ) );
140
+ }
141
+
142
+ /**
143
+ * Lists flags of a variable for dialogs, e.g. "masked, protected".
144
+ *
145
+ * @param {any} existing the variable as GitLab returns it, if it exists
146
+ * @param {Record<string, unknown>} args flags given, which win over those of the existing variable
147
+ * @returns {string}
148
+ */
149
+ function flagsOf( existing, args ) {
150
+ const set = [ "masked", "hidden", "protected", "raw" ].filter( flag => args[flag] ?? existing?.[flag] );
151
+
152
+ return set.length > 0 ? `, ${set.join( ", " )}` : "";
153
+ }
154
+
155
+ /** @type {import("./shared.js").ToolDefinition[]} */
156
+ export const variableTools = [
157
+ {
158
+ name: "variable_list",
159
+ title: "List CI/CD variables",
160
+ description: "Lists the CI/CD variables of a repository with type, environment scope and flags, never their values. Variables marked \"sensitive\" (masked, hidden, or named like a token, secret, password or key) can be read only after the user confirms it.",
161
+ permission: "variable.read",
162
+ usesRepo: true,
163
+ input: {
164
+ page: PAGE_INPUT,
165
+ },
166
+ async handler( { page = 1 }, { repo, gitlab } ) {
167
+ const { items, nextPage } = await gitlab.list( repo.host, endpoint( repo ), { page, perPage: 100 } );
168
+
169
+ return {
170
+ repo: formatRef( repo ),
171
+ variables: items.map( describe ),
172
+ ...nextPage ? { nextPage } : {},
173
+ };
174
+ },
175
+ },
176
+ {
177
+ name: "variable_get",
178
+ title: "Read a CI/CD variable",
179
+ description: "Returns the value of a CI/CD variable of a repository. Values of sensitive variables (masked, or named like a token, secret, password or key) are returned only if the user allows it in a dialog, every time; GitLab never returns values of hidden variables.",
180
+ permission: "variable.read",
181
+ usesRepo: true,
182
+ input: {
183
+ key: KEY_INPUT,
184
+ environment: ENVIRONMENT_INPUT,
185
+ },
186
+ async handler( { key, environment }, context ) {
187
+ const variable = await readVariable( context, key, environment );
188
+
189
+ if ( !variable ) {
190
+ throw new GitLabError( `there is no variable ${describeVariable( key, environment )} in ${formatRef( context.repo )}, see variable_list`, 404 );
191
+ }
192
+
193
+ const sensitive = sensitivity( variable );
194
+
195
+ if ( variable.hidden || typeof variable.value !== "string" ) {
196
+ throw new DeniedError( `${describeVariable( key, variable.environment_scope )} is hidden: GitLab doesn't reveal its value to anyone` );
197
+ }
198
+
199
+ if ( sensitive ) {
200
+ await context.consent.confirm(
201
+ "variable.read",
202
+ `An agent wants to read the value of the ${sensitive} CI/CD variable ${describeVariable( key, variable.environment_scope )} of ${formatRef( context.repo )}. The agent will see the value.`,
203
+ "always",
204
+ );
205
+ }
206
+
207
+ return { repo: formatRef( context.repo ), ...describe( variable ), value: variable.value };
208
+ },
209
+ },
210
+ {
211
+ name: "variable_set",
212
+ title: "Create or change a CI/CD variable",
213
+ description: "Creates a CI/CD variable of a repository or changes it. Values of sensitive variables (masked, hidden, or named like a token, secret, password or key) are entered by the user in a dialog and never pass the agent: leave out \"value\" for them. Without \"value\", a variable that isn't sensitive keeps its value.",
214
+ permission: "variable.update",
215
+ usesRepo: true,
216
+ mutates: true,
217
+ input: {
218
+ key: KEY_INPUT,
219
+ value: z.string().max( 10_000 ).optional().describe( "New value, only for variables that aren't sensitive" ),
220
+ environment: z.string().min( 1 ).max( 255 ).optional().describe( "Environment scope, default: \"*\" (all environments)" ),
221
+ type: z.enum( [ "env_var", "file" ] ).optional().describe( "Default: env_var, or the type of the existing variable" ),
222
+ protected: z.boolean().optional().describe( "Only for protected branches and tags" ),
223
+ masked: z.boolean().optional().describe( "Masked in job logs; makes the variable sensitive" ),
224
+ hidden: z.boolean().optional().describe( "Masked and never shown again, not even in GitLab; only when creating a variable" ),
225
+ raw: z.boolean().optional().describe( "Don't expand variables referenced in the value" ),
226
+ description: z.string().max( 255 ).optional(),
227
+ },
228
+ precheck: async( args, context ) => {
229
+ await planSet( args, context );
230
+ },
231
+ asksUser: async( args, context ) => Boolean( ( await planSet( args, context ) ).sensitive ),
232
+ async confirmMessage( args, context ) {
233
+ const { existing } = await planSet( args, context );
234
+ const { key, environment = "*" } = args;
235
+
236
+ return `An agent wants to ${existing ? "change" : "create"} the CI/CD variable ${describeVariable( key, environment )}${flagsOf( existing, args )} of ${formatRef( context.repo )}${args.value === undefined ? "" : ` with a value of ${args.value.length} characters`}.`;
237
+ },
238
+ async handler( args, context ) {
239
+ const { key, environment = "*", type, description, raw } = args;
240
+ const { existing, sensitive } = await planSet( args, context );
241
+ const { repo, gitlab, consent } = context;
242
+ const flags = { masked: args.masked, protected: args.protected, raw };
243
+ let { value } = args;
244
+
245
+ if ( sensitive ) {
246
+ value = await consent.enterSecret( `Enter the value of the ${sensitive} CI/CD variable ${describeVariable( key, environment )}${flagsOf( existing, args )} of ${formatRef( repo )}. An agent asked to ${existing ? "change" : "create"} it; the agent won't see the value. Cancel to deny.` );
247
+ }
248
+
249
+ const body = {
250
+ value: value ?? existing.value,
251
+ variable_type: type,
252
+ ...flags,
253
+ description,
254
+ };
255
+
256
+ if ( existing ) {
257
+ await gitlab.request( repo.host, "PUT", endpoint( repo, key ), { query: scopeFilter( environment ), body } );
258
+ } else {
259
+ await gitlab.post( repo.host, endpoint( repo ), {
260
+ ...body,
261
+ key,
262
+ environment_scope: environment,
263
+ ...args.hidden ? { masked_and_hidden: true, masked: true } : {},
264
+ } );
265
+ }
266
+
267
+ return { repo: formatRef( repo ), key, environment, [existing ? "updated" : "created"]: true, ...sensitive ? { valueEnteredByUser: true } : {} };
268
+ },
269
+ },
270
+ {
271
+ name: "variable_delete",
272
+ title: "Delete a CI/CD variable",
273
+ description: "Deletes a CI/CD variable of a repository.",
274
+ permission: "variable.delete",
275
+ usesRepo: true,
276
+ mutates: true,
277
+ destructive: true,
278
+ input: {
279
+ key: KEY_INPUT,
280
+ environment: ENVIRONMENT_INPUT,
281
+ },
282
+ precheck: async( { key, environment }, context ) => {
283
+ if ( !await readVariable( context, key, environment ) ) {
284
+ throw new GitLabError( `there is no variable ${describeVariable( key, environment )} in ${formatRef( context.repo )}, see variable_list`, 404 );
285
+ }
286
+ },
287
+ confirmMessage: ( { key, environment }, { repo } ) => `An agent wants to delete the CI/CD variable ${describeVariable( key, environment )} of ${formatRef( repo )}. Its value can't be restored.`,
288
+ async handler( { key, environment }, { repo, gitlab } ) {
289
+ await gitlab.request( repo.host, "DELETE", endpoint( repo, key ), { query: scopeFilter( environment ) } );
290
+
291
+ return { repo: formatRef( repo ), key, ...environment ? { environment } : {}, deleted: true };
292
+ },
293
+ },
294
+ ];
@@ -0,0 +1,168 @@
1
+ import { createHash } from "node:crypto";
2
+ import { z } from "zod";
3
+ import { projectId } from "../gitlab/client.js";
4
+ import { formatRef } from "../refs.js";
5
+ import { UNTRUSTED } from "./shared.js";
6
+
7
+ /** Characters of a page wiki_get returns. Longer pages can only be appended to. */
8
+ const MAX_PAGE_CHARS = 50_000;
9
+
10
+ const PAGE_INPUT = z.string().min( 1 ).max( 255 ).describe( "Slug of the page as wiki_list returns it, e.g. \"setup/install\"" );
11
+
12
+ /**
13
+ * @param {import("../refs.js").RepoRef} repo
14
+ * @param {string} [slug]
15
+ * @returns {string}
16
+ */
17
+ function wikiEndpoint( repo, slug ) {
18
+ return `projects/${projectId( repo )}/wikis${slug ? `/${encodeURIComponent( slug.replace( /^\/+|\/+$/g, "" ) )}` : ""}`;
19
+ }
20
+
21
+ /**
22
+ * Identifies a version of a page, so changes made meanwhile aren't overwritten.
23
+ *
24
+ * @param {string} content
25
+ * @returns {string}
26
+ */
27
+ function versionOf( content ) {
28
+ return createHash( "sha256" ).update( content, "utf8" ).digest( "hex" ).slice( 0, 16 );
29
+ }
30
+
31
+ /**
32
+ * Reads a page, null if it doesn't exist.
33
+ *
34
+ * @param {import("../gitlab/client.js").GitLabClient} gitlab
35
+ * @param {import("../refs.js").RepoRef} repo
36
+ * @param {string} slug
37
+ * @returns {Promise<any>}
38
+ */
39
+ async function readPage( gitlab, repo, slug ) {
40
+ try {
41
+ return await gitlab.get( repo.host, wikiEndpoint( repo, slug ) );
42
+ } catch ( error ) {
43
+ if ( error.status === 404 ) {
44
+ return null;
45
+ }
46
+
47
+ throw error;
48
+ }
49
+ }
50
+
51
+ /** @type {import("./shared.js").ToolDefinition[]} */
52
+ export const wikiTools = [
53
+ {
54
+ name: "wiki_list",
55
+ title: "List wiki pages",
56
+ description: "Lists the pages of a repository's wiki, optionally those below a path.",
57
+ permission: "wiki.read",
58
+ usesRepo: true,
59
+ input: {
60
+ path: z.string().max( 255 ).optional().describe( "Only pages whose slug starts with this path, e.g. \"runbooks/\"" ),
61
+ },
62
+ async handler( { path }, { repo, gitlab } ) {
63
+ const pages = await gitlab.get( repo.host, wikiEndpoint( repo ), { with_content: 0 } );
64
+ const prefix = path?.replace( /^\/+/, "" );
65
+
66
+ return {
67
+ repo: formatRef( repo ),
68
+ pages: ( Array.isArray( pages ) ? pages : [] )
69
+ .filter( page => !prefix || page.slug.startsWith( prefix ) )
70
+ .map( page => ( { page: page.slug, title: page.title, ...page.format !== "markdown" ? { format: page.format } : {} } ) ),
71
+ };
72
+ },
73
+ },
74
+ {
75
+ name: "wiki_get",
76
+ title: "Read a wiki page",
77
+ description: `Returns the content of a wiki page and its "version", which wiki_update needs to replace it. ${UNTRUSTED}`,
78
+ permission: "wiki.read",
79
+ usesRepo: true,
80
+ input: { page: PAGE_INPUT },
81
+ async handler( { page }, { repo, gitlab } ) {
82
+ const data = await readPage( gitlab, repo, page );
83
+
84
+ if ( !data ) {
85
+ throw new Error( `there is no wiki page "${page}" in ${formatRef( repo )}, see wiki_list` );
86
+ }
87
+
88
+ const content = String( data.content ?? "" );
89
+ const cut = content.length > MAX_PAGE_CHARS;
90
+
91
+ return {
92
+ repo: formatRef( repo ),
93
+ page: data.slug,
94
+ title: data.title,
95
+ format: data.format,
96
+ version: versionOf( content ),
97
+ content: cut ? content.slice( 0, MAX_PAGE_CHARS ) : content,
98
+ ...cut ? { cut: true, note: `the page has ${content.length} characters, only the first ${MAX_PAGE_CHARS} are shown; it can only be appended to` } : {},
99
+ };
100
+ },
101
+ },
102
+ {
103
+ name: "wiki_create",
104
+ title: "Create a wiki page",
105
+ description: "Creates a new wiki page; refuses if the page exists. Slashes in the title put the page into folders.",
106
+ permission: "wiki.create",
107
+ usesRepo: true,
108
+ mutates: true,
109
+ input: {
110
+ page: z.string().min( 1 ).max( 255 ).describe( "Title of the new page, e.g. \"runbooks/Restart the mail server\"" ),
111
+ content: z.string().min( 1 ).max( 500_000 ),
112
+ format: z.enum( [ "markdown", "asciidoc", "rdoc", "org" ] ).optional().describe( "Default: markdown" ),
113
+ },
114
+ async handler( { page, content, format = "markdown" }, { repo, gitlab } ) {
115
+ const slug = page.trim().replace( /\s+/g, "-" );
116
+
117
+ if ( await readPage( gitlab, repo, slug ) ) {
118
+ throw new Error( `the wiki page "${slug}" exists already, use wiki_update` );
119
+ }
120
+
121
+ const created = await gitlab.post( repo.host, wikiEndpoint( repo ), { title: page.trim(), content, format } );
122
+
123
+ return { repo: formatRef( repo ), page: created.slug, title: created.title, version: versionOf( content ) };
124
+ },
125
+ },
126
+ {
127
+ name: "wiki_update",
128
+ title: "Change a wiki page",
129
+ description: "Replaces the content of a wiki page, only if it is still in the \"version\" wiki_get returned, or appends to it. Pages too long for wiki_get can only be appended to.",
130
+ permission: "wiki.update",
131
+ usesRepo: true,
132
+ mutates: true,
133
+ input: {
134
+ page: PAGE_INPUT,
135
+ content: z.string().min( 1 ).max( 500_000 ),
136
+ mode: z.enum( [ "replace", "append" ] ).optional().describe( "Default: replace" ),
137
+ version: z.string().regex( /^[0-9a-f]{16}$/ ).optional().describe( "Version wiki_get returned, required for replacing" ),
138
+ },
139
+ async handler( { page, content, mode = "replace", version }, { repo, gitlab } ) {
140
+ const current = await readPage( gitlab, repo, page );
141
+
142
+ if ( !current ) {
143
+ throw new Error( `there is no wiki page "${page}" in ${formatRef( repo )}, use wiki_create` );
144
+ }
145
+
146
+ const existing = String( current.content ?? "" );
147
+
148
+ if ( mode === "replace" ) {
149
+ if ( !version ) {
150
+ throw new Error( "replacing a page needs the \"version\" wiki_get returned" );
151
+ }
152
+
153
+ if ( existing.length > MAX_PAGE_CHARS ) {
154
+ throw new Error( "the page is longer than wiki_get shows, it can only be appended to" );
155
+ }
156
+ }
157
+
158
+ if ( version && versionOf( existing ) !== version ) {
159
+ throw new Error( "the page has changed since it was read, read it again with wiki_get" );
160
+ }
161
+
162
+ const next = mode === "append" ? `${existing.replace( /\s+$/, "" )}\n\n${content}` : content;
163
+ const updated = await gitlab.put( repo.host, wikiEndpoint( repo, current.slug ), { title: current.title, content: next, format: current.format } );
164
+
165
+ return { repo: formatRef( repo ), page: updated.slug ?? current.slug, mode, version: versionOf( next ) };
166
+ },
167
+ },
168
+ ];
package/src/zip.js ADDED
@@ -0,0 +1,178 @@
1
+ /**
2
+ * Reads the list of files of a ZIP archive from its central directory, which
3
+ * is at the end of the archive. Only the parts needed are read, so the list
4
+ * of a large archive costs a few small requests where the server supports
5
+ * ranges. Contents aren't extracted here.
6
+ */
7
+
8
+ const END_SIGNATURE = 0x06054b50;
9
+ const END_SIZE = 22;
10
+ const ZIP64_LOCATOR_SIGNATURE = 0x07064b50;
11
+ const ZIP64_LOCATOR_SIZE = 20;
12
+ const ZIP64_END_SIGNATURE = 0x06064b50;
13
+ const ENTRY_SIGNATURE = 0x02014b50;
14
+ const MAX_COMMENT = 0xffff;
15
+
16
+ /** Largest central directory read, about 300,000 files. */
17
+ const MAX_DIRECTORY_BYTES = 32 * 1024 * 1024;
18
+
19
+ /**
20
+ * @typedef {object} ZipEntry
21
+ * @property {string} path
22
+ * @property {number} size uncompressed size in bytes
23
+ * @property {boolean} folder
24
+ */
25
+
26
+ /**
27
+ * @typedef {(start: number, end: number) => Promise<Buffer>} RangeReader
28
+ * reads the bytes from `start` up to, not including, `end`
29
+ */
30
+
31
+ /**
32
+ * Number of bytes at the end of an archive holding its end record for sure.
33
+ */
34
+ export const TAIL_BYTES = END_SIZE + MAX_COMMENT + ZIP64_LOCATOR_SIZE;
35
+
36
+ /**
37
+ * @param {string} message
38
+ * @returns {Error}
39
+ */
40
+ function invalid( message ) {
41
+ return new Error( `the artifacts archive can't be read: ${message}` );
42
+ }
43
+
44
+ /**
45
+ * @param {Buffer} buffer
46
+ * @param {number} offset
47
+ * @returns {number}
48
+ */
49
+ function uint64( buffer, offset ) {
50
+ const value = buffer.readBigUInt64LE( offset );
51
+
52
+ if ( value > BigInt( Number.MAX_SAFE_INTEGER ) ) {
53
+ throw invalid( "it is too large" );
54
+ }
55
+
56
+ return Number( value );
57
+ }
58
+
59
+ /**
60
+ * Lists the entries of a ZIP archive.
61
+ *
62
+ * @param {RangeReader} read
63
+ * @param {number} size size of the archive in bytes
64
+ * @returns {Promise<ZipEntry[]>}
65
+ */
66
+ export async function listZip( read, size ) {
67
+ if ( size < END_SIZE ) {
68
+ throw invalid( "it is empty or cut" );
69
+ }
70
+
71
+ const tailStart = Math.max( 0, size - TAIL_BYTES );
72
+ const tail = await read( tailStart, size );
73
+ let end = -1;
74
+
75
+ for ( let index = tail.length - END_SIZE; index >= 0; index-- ) {
76
+ if ( tail.readUInt32LE( index ) === END_SIGNATURE && index + END_SIZE + tail.readUInt16LE( index + 20 ) === tail.length ) {
77
+ end = index;
78
+ break;
79
+ }
80
+ }
81
+
82
+ if ( end < 0 ) {
83
+ throw invalid( "it isn't a ZIP archive" );
84
+ }
85
+
86
+ let count = tail.readUInt16LE( end + 10 );
87
+ let directorySize = tail.readUInt32LE( end + 12 );
88
+ let directoryOffset = tail.readUInt32LE( end + 16 );
89
+
90
+ if ( count === 0xffff || directorySize === 0xffffffff || directoryOffset === 0xffffffff ) {
91
+ const locator = end - ZIP64_LOCATOR_SIZE;
92
+
93
+ if ( locator < 0 || tail.readUInt32LE( locator ) !== ZIP64_LOCATOR_SIGNATURE ) {
94
+ throw invalid( "its ZIP64 directory is missing" );
95
+ }
96
+
97
+ const recordOffset = uint64( tail, locator + 8 );
98
+ const record = await read( recordOffset, recordOffset + 56 );
99
+
100
+ if ( record.length < 56 || record.readUInt32LE( 0 ) !== ZIP64_END_SIGNATURE ) {
101
+ throw invalid( "its ZIP64 directory is broken" );
102
+ }
103
+
104
+ count = uint64( record, 32 );
105
+ directorySize = uint64( record, 40 );
106
+ directoryOffset = uint64( record, 48 );
107
+ }
108
+
109
+ if ( directorySize > MAX_DIRECTORY_BYTES ) {
110
+ throw invalid( "it lists too many files" );
111
+ }
112
+
113
+ if ( directoryOffset + directorySize > size ) {
114
+ throw invalid( "it is cut" );
115
+ }
116
+
117
+ const directory = directoryOffset >= tailStart ?
118
+ tail.subarray( directoryOffset - tailStart, directoryOffset - tailStart + directorySize ) :
119
+ await read( directoryOffset, directoryOffset + directorySize );
120
+
121
+ return parseDirectory( directory, count );
122
+ }
123
+
124
+ /**
125
+ * @param {Buffer} directory
126
+ * @param {number} count
127
+ * @returns {ZipEntry[]}
128
+ */
129
+ function parseDirectory( directory, count ) {
130
+ const entries = [];
131
+ let offset = 0;
132
+
133
+ for ( let index = 0; index < count; index++ ) {
134
+ if ( offset + 46 > directory.length || directory.readUInt32LE( offset ) !== ENTRY_SIGNATURE ) {
135
+ throw invalid( "its directory is broken" );
136
+ }
137
+
138
+ const nameLength = directory.readUInt16LE( offset + 28 );
139
+ const extraLength = directory.readUInt16LE( offset + 30 );
140
+ const commentLength = directory.readUInt16LE( offset + 32 );
141
+ const name = directory.subarray( offset + 46, offset + 46 + nameLength );
142
+ const extra = directory.subarray( offset + 46 + nameLength, offset + 46 + nameLength + extraLength );
143
+ const utf8 = Boolean( directory.readUInt16LE( offset + 8 ) & 0x800 );
144
+ let size = directory.readUInt32LE( offset + 24 );
145
+
146
+ if ( size === 0xffffffff ) {
147
+ size = zip64Size( extra ) ?? size;
148
+ }
149
+
150
+ const path = name.toString( utf8 ? "utf8" : "latin1" );
151
+
152
+ entries.push( { path: path.replace( /\/$/, "" ), size, folder: path.endsWith( "/" ) } );
153
+ offset += 46 + nameLength + extraLength + commentLength;
154
+ }
155
+
156
+ return entries;
157
+ }
158
+
159
+ /**
160
+ * Reads the uncompressed size from the ZIP64 extra field of an entry.
161
+ *
162
+ * @param {Buffer} extra
163
+ * @returns {number|null}
164
+ */
165
+ function zip64Size( extra ) {
166
+ for ( let offset = 0; offset + 4 <= extra.length; ) {
167
+ const id = extra.readUInt16LE( offset );
168
+ const length = extra.readUInt16LE( offset + 2 );
169
+
170
+ if ( id === 0x0001 && length >= 8 ) {
171
+ return uint64( extra, offset + 4 );
172
+ }
173
+
174
+ offset += 4 + length;
175
+ }
176
+
177
+ return null;
178
+ }