DevelopForge
@holtkeeper/forge-gitlab
GitLab adapter: a GitForge over the GitLab REST API v4 and token rotation for @holtkeeper/credentials.
import { env } from '@holtkeeper/forge'import { gitlab } from '@holtkeeper/forge-gitlab'
const definition = gitlab({ url: 'https://gitlab.example.com', token: env('GITLAB_TOKEN') })const forge = definition.create()The server builds it for every GitLab forge added in the panel, with the token of the forge’s credential (gitlabForgeFactory of @holtkeeper/managed-config).
Options: url (base URL, with or without a trailing slash, including the path prefix of a self-managed instance such as https://example.com/gitlab), token (Secret, resolved when create() is called), fetch?, perPage? (1 to 100, default 100) and retries? (how often a 429 is retried after waiting for Retry-After, capped at 60 s; default 1).
The token needs the api scope (code review writes — draft notes, publishing, approving, replying, resolving — need it too); read_api is enough when only listRepositories, listMemberRepositories, getRepository, readFile, readFileBytes, listFiles, getMergeRequest, getMergeRequestDiff, compareCommits, listDiscussions, listApprovals, listNoteReactions, findMergeRequest, listPipelines, listJobs and the insight reads (listMergeRequests, listPipelineRuns, listJobRuns, listProjectJobRuns, listPipelineJobs, listDeployments, listEnvironments, listTags, listBranches, listCiVariables, listImageTags, getPushRules) are used. For the insight reads on private projects, give the user behind the token at least Reporter access; Guests may not see jobs and deployments. listCiVariables needs Maintainer on the project or group; without it the variables stay unknown. git clone over HTTPS with gitCredentials() needs read_repository (or api). Personal, project, group and service-account tokens work alike; the user behind the token needs Developer access to push, open merge requests and run jobs, and Maintainer access on protected branches and tags.
Repositories are projects addressed by URL-encoded full path (games/app-x → projects/games%2Fapp-x); merge request ids are GitLab iids.
| Method | Request |
|---|---|
listRepositories |
GET /groups/:ns/projects?include_subgroups=true&with_shared=false, paginated; on 404 GET /users/:ns/projects |
getRepository |
GET /projects/:id |
readFile |
GET /projects/:id/repository/files/:path/raw?ref= (no ref: project HEAD) |
readFileBytes |
Same endpoint as readFile, body returned as bytes |
listFiles |
GET /projects/:id/repository/tree?path=&ref=&recursive=&pagination=keyset, following Link: rel="next" up to limit (default 10 000) |
createBranch |
POST /projects/:id/repository/branches |
deleteBranch |
DELETE /projects/:id/repository/branches/:branch |
commit |
GET /projects/:id/repository/branches/:branch (only with startBranch), POST /projects/:id/repository/commits |
findMergeRequest |
GET /projects/:id/merge_requests?source_branch=&target_branch=&state= (newest first) |
createMergeRequest |
GET /users?username= per reviewer, POST /projects/:id/merge_requests |
updateMergeRequest |
GET /projects/:id/merge_requests/:iid (when the draft flag or title needs the current value), PUT /projects/:id/merge_requests/:iid |
mergeMergeRequest |
PUT /projects/:id/merge_requests/:iid/merge |
commentOnMergeRequest |
POST /projects/:id/merge_requests/:iid/notes |
listPipelines |
GET /projects/:id/pipelines?ref=&sha= (newest page only, perPage entries) |
listJobs |
GET /projects/:id/pipelines/:pipeline_id/jobs, all pages |
playJob, retryJob |
POST /projects/:id/jobs/:job_id/play, POST /projects/:id/jobs/:job_id/retry |
createTag |
POST /projects/:id/repository/tags |
listCommits |
GET /projects/:id/repository/commits?ref_name=<since>..<ref> (or ref alone) with since=<after>, paginated up to limit |
listMergeRequestCommits |
GET /projects/:id/merge_requests/:iid/commits, all pages |
getPushRules |
GET /projects/:id/push_rule (Premium and Ultimate); empty regexes are dropped, and 401, 403, 404 or no rule answer undefined |
getRelease |
GET /projects/:id/releases/:tag_name; 404 answers undefined |
createRelease |
POST /projects/:id/releases with tag_name, name, description |
updateRelease |
PUT /projects/:id/releases/:tag_name |
listMergeRequests |
GET /projects/:id/merge_requests?state=&updated_after=&target_branch=&order_by=updated_at&sort=desc, paginated up to limit |
listPipelineRuns |
GET /projects/:id/pipelines?ref=&created_after=&order_by=id&sort=desc up to limit, then GET /projects/:id/pipelines/:pipeline_id for each (8 at a time) |
listJobRuns |
GET /projects/:id/pipelines/:pipeline_id/jobs?include_retried=true, all pages |
listPipelineJobs |
GET /projects/:id/pipelines/latest?ref= (default branch without ref; 404 answers []), then GET /projects/:id/pipelines/:pipeline_id/jobs, all pages, sorted by id and cut to limit |
listProjectJobRuns |
GET /projects/:id/jobs newest first, page by page until the first job created before after or limit |
listMemberRepositories |
GET /projects?membership=true&archived=false&order_by=last_activity_at&sort=desc, with search and search_namespaces=true when searching; stops at limit (default 50) |
getRepositoryAvatar |
GET /projects/:id/avatar, then GET /groups/:id/avatar up the namespace; 404s move on, the bytes’ signature gives the type |
listDeployments |
GET /projects/:id/deployments?environment=&status=&sort=desc with updated_after=&order_by=updated_at when after is set, order_by=id otherwise; up to limit |
listEnvironments |
GET /projects/:id/environments?states=available, up to limit (default 100) |
listTags |
GET /projects/:id/repository/tags?order_by=updated&sort=desc, up to limit |
listBranches |
GET /projects/:id/repository/branches, every page |
listCiVariables |
GET /projects/:id/variables or GET /groups/:id/variables, every page; masked, hidden and file variables are dropped; 401, 403 and 404 answer undefined (reading variables needs Maintainer) |
listImageTags |
GET /projects/:id/registry/repositories?tags=true for each project path the image path starts with, longest first, until one lists a repository whose location is the image; denied or missing projects move on |
npmRegistry |
<url>/api/v4/projects/:id/packages/npm/, the project-level npm endpoint; reading packages needs read_api (or api) |
getMergeRequest |
GET /projects/:id/merge_requests/:iid |
getMergeRequestDiff |
GET /projects/:id/merge_requests/:iid/versions (all pages), then GET .../versions/:version_id of the latest; without versions diff_refs and paginated GET .../diffs |
compareCommits |
GET /projects/:id/repository/compare?from=&to=&straight=true |
listDiscussions |
GET /projects/:id/merge_requests/:iid/discussions, all pages |
listApprovals |
GET /projects/:id/merge_requests/:iid/approvals; user.username of each approved_by entry |
listNoteReactions |
GET /projects/:id/merge_requests/:iid/notes/:note_id/award_emoji, all pages; name and user.username of each award |
noteMarks, addNoteMark, removeNoteMark |
award emoji of the token’s own account (GET /user once): seen is eyes, done is white_check_mark; POST .../notes/:note_id/award_emoji, DELETE .../award_emoji/:award_id |
submitReview |
POST .../approve (only approve), GET .../versions + GET .../versions/:version_id, POST .../draft_notes per comment, POST .../draft_notes/bulk_publish; on failure PUT .../draft_notes/:id/publish and DELETE .../draft_notes/:id |
replyToDiscussion |
POST /projects/:id/merge_requests/:iid/discussions/:discussion_id/notes |
postMergeRequestNote |
POST /projects/:id/merge_requests/:iid/notes (a standalone note), or POST .../discussions/:discussion_id/notes with discussionId |
updateMergeRequestNote |
PUT /projects/:id/merge_requests/:iid/notes/:note_id |
deleteMergeRequestNote |
DELETE /projects/:id/merge_requests/:iid/notes/:note_id (404 ignored) |
resolveDiscussion |
PUT /projects/:id/merge_requests/:iid/discussions/:discussion_id?resolved=true|false |
getCurrentUser |
GET /user; email is commit_email, else email; avatarUrl and webUrl from avatar_url and web_url; name and username cannot be changed with the account’s own token (PUT /users/:id needs an admin token). For a group’s service account (bot: true) manageUrl is <url>/groups/<top-level group>/-/settings/service_accounts, the top-level group of the first group the account is a member of (GET /groups), else of its first project’s namespace (GET /projects?membership=true), where the group’s owners change them |
setCurrentUserAvatar |
PUT /user/avatar as multipart/form-data with the file in the avatar field (GitLab 17.0+; GitLab itself caps it at 200 KB and checks the extension) |
registerSshKey |
POST /user/keys with usage_type (scope.kind: user, the token’s own user); POST /projects/:id/deploy_keys with can_push (deploy keys accept only usage auth) |
listSshKeys |
GET /user/keys or GET /projects/:id/deploy_keys, all pages; user keys without usage_type (pre-15.7) report auth_and_signing |
removeSshKey |
DELETE /user/keys/:key_id or DELETE /projects/:id/deploy_keys/:key_id (the key stays on other projects) |
enableDeployKey |
POST /projects/:id/deploy_keys/:key_id/enable, then PUT /projects/:id/deploy_keys/:key_id with can_push: true when asked (enabling never grants write access) |
Behavior worth knowing:
listRepositoriesyields lazily, includes archived projects (archivedis set) and leaves out projects only shared with the group. Pages follow theLink: rel="next"header, orX-Next-Pagewhen it is missing; a next link outside the configured API root is refused, because the token would be sent there.listFilesmapstree→dirandblob→fileand skips submodules (commit). A 404 for the path or ref gives[]; a missing project still rejects.readFilereturnsundefinedfor 404 (missing file or ref) but rejects when the project itself is not found.commitsends all changes as one Commits API call withcreate/update/deleteactions.start_branchis sent only whenstartBranchis given andbranchdoes not exist yet.- Merge request states map
opened/locked→open,merged→merged,closed→closed. Draft is theDraft:title prefix:drafton create and update adds or strips it, and an update that changes only the title keeps the current draft state. Labels are sent as a comma-separated list, reviewers are looked up by username (an unknown username rejects before the merge request is created).state: 'closed' | 'open'sendsstate_event: close | reopen. mergeMergeRequestsendssquash,should_remove_source_branchand, forwhenPipelineSucceeds, bothmerge_when_pipeline_succeedsand its replacementauto_merge(GitLab 17.11+), so old and new instances behave the same.- Pipeline and job statuses:
created,waiting_for_resource,preparing,pending,scheduled→pending;canceling,canceled→canceled;running,success,failed,skipped,manualas is; unknown statuses →pending. gitCredentials()returns{ username: 'oauth2', password: <token> }, the form GitLab accepts for HTTPS git with personal, project, group and OAuth tokens. The token is resolved on each call.- Insight reads:
listMergeRequestsmapscreated_at,updated_at,merged_at, (closed merge requests only)closed_at,merge_commit_shaandsquash_commit_sha.firstCommitAtandchangesCountare left out: the list endpoint has neither, and fetching them costs one request per merge request.listPipelineRunsneeds one extra request per pipeline because only the single-pipeline endpoint returnsstarted_at,finished_at,durationandqueued_duration; keeplimitsmall on busy projects.aftermaps tocreated_after.listJobRunssendsinclude_retried=true. GitLab’s job objects carry no documented retried flag, so an attempt isretriedwhen the same pipeline has a newer job (higher id) with the same name; aretriedfield in the response wins when present.allowFailureisallow_failure.listProjectJobRunshas no time filter on GitLab’s side, so it stops reading pages at the first job created beforeafter.retriedis derived per pipeline as inlistJobRuns;refandshacome from the job’spipelineobject,tagfrom the job’stagflag.listPipelineJobsreturns the latest attempt of each job.manualis set when the job’s status ismanualor itswhenismanual(GitLab sendswhenonly on some versions, so a manual job someone already started may read as not manual);environmentisenvironment.namewhen the job object carries it, absent otherwise.listDeploymentsstatuses:created→pending,running,success,failed,canceled,skipped,blockedas is.finishedAtis the deployment job’sdeployable.finished_at. GitLab rejectsupdated_afterwithoutorder_by=updated_at(400), so results withafterare newest update first.listTagsreturnscommittedAtfromcommit.committed_dateandcreatedAtfrom the tag’s owncreated_at(annotated tags only).
createTagreturns the commit SHA the tag points to, also for annotated tags.commitsendsencoding: base64for changes withencoding: 'base64'(binary files); text changes carry noencoding.readFileBytesreturns the raw bytes with the same 404 rules asreadFile.
Code review
Section titled “Code review”getMergeRequestaddsheadShafromsha(falling back todiff_refs.head_sha).getMergeRequestDiffuses the newest merge request version, sorefs(base_commit_sha,start_commit_sha,head_commit_sha) and files always belong together. Right after a merge request is created GitLab has no version yet; thendiff_refsand the paginated/diffsendpoint are used. Status:new_file→added,deleted_file→deleted,renamed_file→renamed, elsemodified.binaryis set when the diff isBinary files … differor aGIT binary patch;collapsedis set when GitLab sendscollapsedortoo_large(GitLab 18.4+ on the versions endpoint), anddiffis then empty.compareCommitscompares the two commits directly (straight=true,from..to), not from their merge base. When GitLab hits its compare limits (compare_timeout) the list may be incomplete.listDiscussionsmaps each note’sauthor.username,body,created_atandsystem. A discussion isresolvablewhen any note is,resolvedwhen all resolvable notes are.positioncomes from the first diff note:new_lineandnew_pathwhen set (side: 'new'), otherwiseold_lineandold_path(side: 'old'); image and file positions have no line and are left out.submitReview:event: 'approve'approves first withsha: refs.headSha. A refused approval (401/403 not an eligible approver, 409 the head moved, 401 when re-authentication is required) rejects withGitLabApiErrorbefore anything is posted.- Comments are checked locally:
startLineafterline, a suggestion onside: 'old', or a suggestion over more than 101 lines (GitLab allows 100 above the commented line) go tofailedwithout a request; so do paths that are not in the diff. - The diff of the version whose shas equal
refs(else the newest) is read to place each line. Positions areposition_type: textwithbase_sha,start_sha,head_sha,old_path,new_pathand, per GitLab’s rules,new_linefor an added line,old_linefor a removed one and both for an unchanged one (also outside the hunks, shifted by the hunks above). WithstartLine < linealine_rangeis added whosestartandendcarryline_code(<sha1(new_path)>_<old>_<new>, using GitLab’s line counters, so an added line has the old number of the line after it),type(newfor an added line, otherwiseold) and the line numbers; the note itself sits online. Without a diff body (collapsed) the line is sent on its side only. summarybecomes a general draft note created before the comment drafts, then one draft per comment. A draft GitLab refuses (for example 400 for a line outside the diff) goes tofailedwith GitLab’s message.POST .../draft_notes/bulk_publishpublishes everything at once, so the author gets one notification;request_changessendsreviewer_state: requested_changes, which sets the reviewer state on GitLab versions that support it and is harmless otherwise.approveandcommentsend no reviewer state.request_changeswith no comments and no summary still callsbulk_publishto set the state.- When
bulk_publishfails, each draft is published on its own (PUT .../publish, a 404 counts as already published); a draft GitLab rejects then is deleted and reported infailed. The summary is published last;reviewer_stateis retried once with a finalbulk_publish, ignoring its failure.bulk_publishpublishes all pending drafts of the token’s user, so leftovers from another tool would go out with the review; use a dedicated bot token.postedcounts published comments, not the summary.
- Suggestions render as GitLab expects: the comment body, a blank line, then a fence,
suggestion:-N+0withN = line - startLine(lines above the commented line that the replacement covers,0for a single line), the replacement and the closing fence. The fence is three backticks, or one more than the longest backtick run in the replacement, so code blocks inside survive (GitLab 17.7+ renders them). An empty replacement deletes the lines; one trailing newline of the replacement is dropped. replyToDiscussionadds a note to the thread;resolveDiscussionsendsresolvedas a query parameter. Resolving needs the Developer role or authorship of the merge request.
Failures are GitLabApiError with status and a message like GitLab POST /api/v4/projects/g%2Fa/repository/commits failed with 400: A file with this name already exists; the token is redacted, malformed bodies are reported by field names, and redirects are refused as for rotation.
Webhooks
Section titled “Webhooks”ensureWebhook uses /groups/:id/hooks for group targets and /projects/:id/hooks for projects, finding an existing hook by URL (then PUT, else POST) and setting every event flag explicitly plus enable_ssl_verification: true; the secret goes into token. Group hooks need GitLab Premium: when GitLab answers 404 or 403 for them, it registers a project hook on every non-archived project of the group (subgroups included) and says so in fallback. removeWebhook deletes hooks and ignores 404. webhookStatus reads GET .../hooks/:hook_id (on 404 or another URL it looks through GET .../hooks for the URL): alert_status disabled is disabled, temporarily_disabled is temporarily_disabled with disabled_until, anything else enabled; GitLab versions without alert_status count a future disabled_until as temporarily disabled. GitLab disables a hook after 4 failed deliveries in a row (for a minute, growing up to a day) and for good after 40, and only a successful test delivery turns it back on, so enableWebhook sends POST .../hooks/:hook_id/test/:trigger: GitLab answers 201 and re-enables the hook when the delivery gets a 2xx, 422 otherwise (thrown as GitLabApiError). It tries resource_access_token_events, then releases_events: GitLab builds both without real activity of the project and Holtkeeper’s receiver answers their events 200 without dispatching anything. Only when GitLab cannot build either (400 for a trigger it does not know, 422 “Ensure the project has …”) does it send push_events, a push of the default branch’s last commits sent as the token’s user, which the server’s receiver ignores while the re-enable runs. Any other failure is thrown at once, so a hook GitLab cannot deliver to gets one test delivery per attempt. The token needs the api scope and Maintainer (project hooks) or Owner (group hooks). withFetch(wrap) returns gitlab({ ...options, fetch: wrap(fetch) }).
Package registries
Section titled “Package registries”gitlabPackageRegistry(url) returns { host, paths }: the host of the instance and a regular expression for its package registry endpoints (/api/v4/packages/…, /api/v4/groups/:id/-/packages/…, /api/v4/projects/:id/packages/…; npm, Maven, PyPI, generic and the rest), keeping an instance’s sub-path. The server builds egress proxy rules from it for panel forges (“Packages for jobs”, on by default), so a GitLab token reads packages for jobs without them seeing it. GitLab accepts personal, group and project access tokens there as Authorization: Bearer.
gitlabPackageFiles(url) returns the same shape for the registry files that do not change once published, for caching proxies: npm tarballs (…/npm/<name>/-/<file>.tgz), Maven files of release versions (not maven-metadata.xml, not -SNAPSHOT), PyPI files (…/pypi/files/<sha256>/<file>) and generic package files (…/generic/<name>/<version>/<file>), on instance, group and project level. Package metadata, /simple indexes and version lists never match. GitLab lets generic files be uploaded again under the same version unless duplicates are turned off for the project; a cache keeps the copy it has. The server serves these as private cache rules for forges with Cache packages.
gitlabGitRead(url) returns two { host, paths, methods } locations for fetching private Go modules and git repositories through such a proxy: GET/HEAD of go get discovery (<project>?go-get=1, exactly that query) and of <project>[.git]/info/refs?service=git-upload-pack, and POST of <project>[.git]/git-upload-pack. Projects need at least two path segments under the instance’s sub-path; /api/, .., - (GitLab’s web routes such as /-/blob/) and percent-encoded segments never match, and neither does git-receive-pack, so a token added there can fetch but never push. gitlabGitAuthorization(token) is the header value GitLab accepts for those requests: Basic with oauth2 as user and the token as password (personal, group and project access tokens).
Token rotation
Section titled “Token rotation”import { gitlabTokenRotator } from '@holtkeeper/forge-gitlab'
const rotator = gitlabTokenRotator() // options: { fetch?, now? }A TokenRotator with kind gitlab. url is the GitLab base URL, with or without a trailing slash, including the path prefix of a self-managed instance (https://example.com/gitlab). Requests authenticate with the PRIVATE-TOKEN header and use the token’s own self endpoints, so no admin token is needed:
| Method | Request | Result |
|---|---|---|
inspect |
GET /api/v4/personal_access_tokens/self |
name, scopes, expiresAt |
rotate |
POST /api/v4/personal_access_tokens/self/rotate with expires_at (date) |
new token and expiresAt from GitLab |
expires_at is today (UTC) plus lifetimeDays, as YYYY-MM-DD. GitLab tokens stop working at 00:00 UTC on that date, so expiresAt is reported as that instant. The instance’s maximum token lifetime still applies; a longer request fails with 400.
Responses are validated; failures are GitLabApiError with status and a message like GitLab POST /api/v4/personal_access_tokens/self/rotate failed with 401: 401 Unauthorized. The token is never part of a message, and a malformed success body is reported by field names only, since it may contain the new token. signal is passed to fetch. Redirects are refused, because fetch would forward the PRIVATE-TOKEN header to another origin.
GitLab facts (checked against the REST API docs, October 2026)
Section titled “GitLab facts (checked against the REST API docs, October 2026)”-
Merge request versions are listed newest first;
GET .../versions/:version_idreturns all diffs of that version without pagination,GET .../diffsis paginated (page,per_page)./changesis deprecated since 15.7. -
Draft notes:
POST .../draft_notestakesnoteandposition(same fields as discussions, includingline_range);bulk_publishtakes optionalnote,internalandreviewer_state(requested_changesorreviewed, not an approval). -
Approve:
POST .../approvewith optionalsha(409 when it is not the head) andapproval_password. -
Self-rotation needs the
apiorself_rotatescope on the token itself. -
Rotation immediately revokes the old token and returns
200with the newtoken. Withoutexpires_atthe new token expires in one week when expiry is enforced. -
If an already revoked token is used to rotate, GitLab revokes every active token of that token family (automatic reuse detection). Never rotate the same token from two places, and store the new token before anything else.
-
Status codes:
400not rotated,401token missing, expired, revoked or no access,403token may not rotate itself,405not a personal access token. -
Project and group access tokens have their own self-rotation endpoints:
POST /projects/:id/access_tokens/self/rotateandPOST /groups/:id/access_tokens/self/rotate(same scopes, sameexpires_at). The docs do not say that the personal access token endpoint accepts them, and this rotator does not call the project or group endpoints yet. Use a personal access token (for example of a service account) for rotated credentials; a405error says so.