All files / src/accounts link.ts

99.55% Statements 225/226
94.57% Branches 122/129
100% Functions 30/30
99.52% Lines 210/211

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726                          230x   230x   230x 230x 230x 230x   230x           230x 230x 230x         230x 230x           230x 230x 230x 230x     230x     230x   230x   230x         230x             17x                                   264x       190x         105x         42x                       42x 42x   49x 44x 42x 40x 40x 40x       101x                               101x 101x                               101x 100x               230x       61x 61x 1x       60x 1x       59x 59x 59x 1x   58x 58x 1x       57x 57x 2x 1x       56x             56x       56x                                           56x     56x                                               230x 25x               59x 59x   1x                           49x 49x 49x 1x 1x   48x 47x 47x 2x 2x 2x 1x 1x   1x     1x         1x         45x 45x         44x       44x 44x 2x 2x 2x   42x 42x 40x 40x         2x                                                                                             54x   38x                   16x 16x     16x                                     13x                       38x 38x 38x           38x   20x   18x 18x                 4x       14x 14x                   14x   18x                               54x 54x     51x 29x 24x 20x 1x   19x 19x                                             44x 44x 44x 1x 1x   43x 43x 43x 35x       31x 9x 4x   22x   22x 1x 1x   21x   43x                     37x 44x 40x 35x 4x 4x 4x 1x 1x         3x         2x   1x                                   42x 2x     2x 2x       2x   40x 40x 1x 1x   39x 38x 38x 38x 38x 1x 1x 1x         1x     37x                                 31x 10x   31x 2x 2x 2x   29x 8x 8x   21x 21x 21x 21x           21x                 21x 2x 4x 2x     1x         230x             96x 96x 3x 3x 3x   93x 93x 93x 2x 2x 2x   91x 49x   42x     9x 9x 1x       1x     8x                
/**
 * Linking another GitLab account to a signed-in session, from a chat.
 *
 * The chat receives a sign-in link. The browser first signs in with the session's own
 * account and continues only when GitLab reports that same user: otherwise a link opened by
 * another person would attach their GitLab account to this session. Then it signs in with
 * the account to link, and the callback stores that account with the session. That second
 * step completes only in the browser that passed the first (a cookie it was given there):
 * its sign-in URL forwarded to someone else would otherwise link their account. Every step
 * is a stored, single-use, expiring flow, so it works when requests land on different
 * replicas.
 */
 
import { createHash, timingSafeEqual } from 'node:crypto';
import type { Response } from 'express';
import { GITLAB_BASE_URL } from '../config';
import type { OAuthConfig } from '../oauth/config';
import { isOAuthEnabled, loadOAuthConfig } from '../oauth/config';
import { sessionStore } from '../oauth/session-store';
import { getTokenContext } from '../oauth/token-context';
import { oauthAppFor, selectableOAuthApps } from '../oauth/instance-app';
import type { GitLabOAuthApp } from '../oauth/oauth-app';
import {
  buildGitLabAuthUrl,
  getGitLabUser,
  revokeGitLabToken,
  GitLabOAuthHttpError,
} from '../oauth/gitlab-device-flow';
import { AccountLinkFlowUnavailableError, exchangeFlowCode } from '../oauth/code-exchange';
import { discardAuthCodeFlow } from '../oauth/grant-revocation';
import {
  claimSessionLease,
  withFreshGitLabToken,
  GitLabGrantRevokedError,
} from '../oauth/gitlab-token-refresh';
import { grantedGitlabScopes } from '../oauth/granted-scopes';
import {
  calculateTokenExpiry,
  generateRandomString,
  isTokenExpiringSoon,
} from '../oauth/token-utils';
import type { AccountLinkStep, AuthCodeFlowState, OAuthSession } from '../oauth/types';
import { normalizeInstanceUrl } from '../utils/url';
import { escapeHtml } from '../utils/html';
import { logInfo, logWarn, truncateId } from '../logger';
import { AccountUnavailableError } from './chat-accounts';
 
/** How long a link stays usable; long enough to sign in, short enough not to linger. */
const LINK_TTL_MS = 10 * 60 * 1000;
 
/** Passes over the stored account before a link gives up and asks for a reload. */
const STORE_ATTEMPTS = 20;
/** Wait between passes while another link or a token refresh holds the account's lease. */
const STORE_RETRY_MS = 100;
/** How long a replacement holds the account: a lookup and one write. */
const REPLACE_LEASE_MS = 15_000;
/**
 * How long a link holds its session while it completes: the check, the store (with the
 * account's own lease and its passes) and spending the link.
 */
const LINK_COMPLETION_LEASE_MS = REPLACE_LEASE_MS + STORE_ATTEMPTS * STORE_RETRY_MS + 5_000;
 
/**
 * Storage id of an account linked to a session: one per session, instance and user. The
 * session id holds no colon and the user id is numeric, so the parts never run together.
 */
function linkedAccountId(sessionId: string, instance: string, userId: number): string {
  return `linked:${sessionId}:${userId}@${instance}`;
}
 
/** The URL elicitation through which a chat's client opened a link. */
export interface LinkElicitation {
  mcpSessionId: string;
  elicitationId: string;
}
 
export interface AccountLinkStart {
  /** Where the user signs in; opened in the browser, never shown to anyone else. */
  url: string;
  instanceUrl: string;
  instanceLabel?: string;
  expiresAt: number;
}
 
function callbackUri(config: OAuthConfig): string {
  return `${config.issuer}/oauth/callback`;
}
 
function sha256Hex(value: string): string {
  return createHash('sha256').update(value).digest('hex');
}
 
/** Cookie of one link's connect step, named after its state so parallel links coexist. */
function bindingCookieName(state: string): string {
  return `gitlab_mcp_link_${sha256Hex(state).slice(0, 16)}`;
}
 
/** Hand the browser that passed `verify` the nonce its connect step checks. */
function bindBrowser(res: Response, config: OAuthConfig, state: string, nonce: string): void {
  res.cookie(bindingCookieName(state), nonce, {
    httpOnly: true,
    // Sent on GitLab's top-level redirect back to the callback, never on cross-site requests.
    sameSite: 'lax',
    secure: new URL(config.issuer).protocol === 'https:',
    path: new URL(callbackUri(config)).pathname,
    maxAge: LINK_TTL_MS,
  });
}
 
/** Whether the request completing a connect step comes from the browser bound to it. */
function fromBoundBrowser(res: Response, state: string, link: AccountLinkStep): boolean {
  const name = bindingCookieName(state);
  const nonce = (res.req?.headers.cookie ?? '')
    .split(';')
    .map((pair) => pair.trim().split('='))
    .find(([key]) => key === name)?.[1];
  if (!nonce || !link.browserBinding) return false;
  const expected = Buffer.from(link.browserBinding, 'hex');
  const actual = Buffer.from(sha256Hex(nonce), 'hex');
  return expected.length === actual.length && timingSafeEqual(expected, actual);
}
 
function requestedScopes(app: GitLabOAuthApp): string[] {
  return app.scopes.split(/[,\s]+/).filter(Boolean);
}
 
/** A stored step of a link: its state and the GitLab sign-in URL that continues it. */
interface StoredLinkStep {
  state: string;
  url: string;
}
 
/** Store one step of a link. */
async function storeLinkStep(
  config: OAuthConfig,
  session: OAuthSession,
  app: GitLabOAuthApp,
  link: AccountLinkStep,
): Promise<StoredLinkStep> {
  const state = generateRandomString(32);
  const flow: AuthCodeFlowState = {
    requestedGitlabScopes: requestedScopes(app),
    selectedInstance: app.baseUrl,
    selectedInstanceLabel: app.label,
    clientId: session.clientId,
    // A link signs no MCP client in: no client PKCE, state or redirect.
    codeChallenge: '',
    codeChallengeMethod: 'S256',
    clientState: '',
    internalState: state,
    clientRedirectUri: '',
    callbackUri: callbackUri(config),
    expiresAt: Date.now() + LINK_TTL_MS,
    scopes: [],
    link,
  };
  await sessionStore.storeAuthCodeFlow(state, flow);
  return { state, url: buildGitLabAuthUrl(config, callbackUri(config), state, app) };
}
 
/**
 * Start linking an account on `instance` (default: the session's own instance) to the
 * connection's session; returns the sign-in link for the user. With `elicitation`, the chat
 * whose client opens the link is told when the account is linked.
 */
export async function startAccountLink(
  instance: string | undefined,
  elicitation?: LinkElicitation,
): Promise<AccountLinkStart> {
  const config = loadOAuthConfig();
  if (!isOAuthEnabled() || !config) {
    throw new AccountUnavailableError(
      'Linking accounts needs a server that signs users in with GitLab; with a static token, configure the instance with a token instead.',
    );
  }
  if (!sessionStore.linksAccounts()) {
    throw new AccountUnavailableError(
      'The session storage of this server cannot keep linked accounts; update the database package.',
    );
  }
  const context = getTokenContext();
  const session = context ? await sessionStore.getSession(context.sessionId) : undefined;
  if (!session) {
    throw new AccountUnavailableError('This connection is not signed in to GitLab.');
  }
  const own = await oauthAppFor(config, session.gitlabApiUrl);
  if (!own) {
    throw new AccountUnavailableError(
      'The instance this connection signed in with is no longer configured; sign in again.',
    );
  }
  const target = instance ? await oauthAppFor(config, normalizeInstanceUrl(instance)) : own;
  if (!target) {
    const known = (await selectableOAuthApps(config)).map((app) => app.baseUrl).join(', ');
    throw new AccountUnavailableError(
      `No GitLab instance ${instance} is configured for sign-in; configured: ${known}.`,
    );
  }
  const { url } = await storeLinkStep(config, session, own, {
    sessionId: session.id,
    stage: 'verify',
    instance: target.baseUrl,
    instanceLabel: target.label,
    ...elicitation,
  });
  logInfo('Account link started', {
    sessionId: truncateId(session.id),
    instance: target.baseUrl,
  });
  return {
    url,
    instanceUrl: target.baseUrl,
    instanceLabel: target.label,
    expiresAt: Date.now() + LINK_TTL_MS,
  };
}
 
/** A button on a link page that continues to `href`. */
interface LinkPageAction {
  href: string;
  label: string;
}
 
/** Page the browser ends on; `message` is plain text. */
function linkPage(
  res: Response,
  status: number,
  title: string,
  message: string,
  action?: LinkPageAction,
): void {
  const button = action
    ? `\n    <p><a class="button" href="${escapeHtml(action.href)}">${escapeHtml(action.label)}</a></p>`
    : '';
  res.status(status).type('html').send(`<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>GitLab MCP - ${escapeHtml(title)}</title>
  <style>
    body { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; max-width: 600px; margin: 0 auto; padding: 40px 20px; background: #f5f5f5; }
    .container { background: white; padding: 40px; border-radius: 12px; box-shadow: 0 2px 10px rgba(0,0,0,0.1); }
    h1 { color: #333; font-size: 24px; margin: 0 0 16px; }
    p { color: #555; line-height: 1.5; }
    .button { display: inline-block; padding: 10px 20px; background: #6b4fbb; color: white; border-radius: 6px; text-decoration: none; }
  </style>
</head>
<body>
  <div class="container">
    <h1>${escapeHtml(title)}</h1>
    <p>${escapeHtml(message)}</p>${button}
  </div>
</body>
</html>`);
}
 
/** End a link the browser cannot complete. */
export function failAccountLink(res: Response, message: string): void {
  linkPage(res, 400, 'Account not linked', message);
}
 
async function revokeQuietly(
  token: string,
  config: OAuthConfig,
  app: GitLabOAuthApp,
): Promise<void> {
  try {
    await revokeGitLabToken(token, config, app);
  } catch (error: unknown) {
    logWarn('Failed to revoke a GitLab token of an account link', { err: error as Error });
  }
}
 
/** First step: the browser proves it belongs to the session's own user, then goes on. */
async function verifyOwnAccount(
  res: Response,
  state: string,
  flow: AuthCodeFlowState,
  link: AccountLinkStep,
  code: string,
  config: OAuthConfig,
  session: OAuthSession,
): Promise<void> {
  const own = await oauthAppFor(config, flow.selectedInstance);
  const target = await oauthAppFor(config, link.instance);
  if (!own || !target) {
    failAccountLink(res, 'A GitLab instance of this link is no longer configured.');
    return;
  }
  const tokens = flow.gitlabTokens ?? (await exchangeFlowCode(state, flow, code, config, own));
  const user = await getGitLabUser(tokens.access_token, own.baseUrl);
  if (user.id !== session.gitlabUserId) {
    const consumed = await sessionStore.consumeAuthCodeFlow(state);
    await revokeQuietly(tokens.access_token, config, own);
    if (!consumed) {
      failAccountLink(res, 'This link was already used. Ask for a new one in the chat.');
      return;
    }
    logWarn('Account link refused: the browser signed in as another user', {
      sessionId: truncateId(session.id),
    });
    failAccountLink(
      res,
      `This link belongs to ${session.gitlabUsername}, but GitLab signed you in as ${user.username}. ` +
        'Only the person who asked for the link can complete it.',
    );
    return;
  }
  // The next step is stored before this one is spent: a failed write leaves this step and
  // its tokens in place, so reloading the page retries it. It keeps only a digest of the
  // nonce this browser receives below.
  const nonce = generateRandomString(32);
  const next = await storeLinkStep(config, session, target, {
    ...link,
    stage: 'connect',
    browserBinding: sha256Hex(nonce),
  });
  const consumed = await sessionStore.consumeAuthCodeFlow(state);
  // Only the identity was needed; this grant must not outlive the check. It is a grant of its
  // own, never the session's: GitLab leaves Doorkeeper's reuse_access_token off (and hashes
  // token secrets, which rules it out), so every code exchange issues a new token.
  await revokeQuietly(tokens.access_token, config, own);
  if (!consumed) {
    await sessionStore.deleteAuthCodeFlow(next.state);
    failAccountLink(res, 'This link was already used. Ask for a new one in the chat.');
    return;
  }
  bindBrowser(res, config, next.state, nonce);
  if (normalizeInstanceUrl(target.baseUrl) !== normalizeInstanceUrl(own.baseUrl)) {
    res.redirect(next.url);
    return;
  }
  // On its own instance the browser is still signed in to GitLab as the account just
  // verified, which GitLab would authorize again; the user signs in with the other one first,
  // in this browser (another one, a private window included, lacks the cookie of this step).
  linkPage(
    res,
    200,
    'Sign in with the account to link',
    `GitLab confirmed you as ${user.username}. To link another account on ${target.label ?? new URL(target.baseUrl).host}, ` +
      'sign out of GitLab in this browser (or switch to that account there), then continue here.',
    { href: next.url, label: 'Continue to GitLab sign-in' },
  );
}
 
type LinkedGrant = Pick<
  OAuthSession,
  'gitlabAccessToken' | 'gitlabRefreshToken' | 'gitlabTokenExpiry' | 'gitlabScopes'
>;
 
/** The account a link stores with a session, and the grant it stores. */
interface LinkedAccountWrite {
  session: OAuthSession;
  link: AccountLinkStep;
  user: { id: number; username: string };
  instance: string;
  grant: LinkedGrant;
}
 
/** Ownership evidence checked by storage in the same commit that spends the flow. */
interface LinkFence {
  internalState: string;
  primaryLeaseUntil: number;
}
 
/** What one pass over the stored account achieved; `wait` asks for a pause before the next. */
type StorePass =
  | { done: true; displaced: string | undefined }
  | { done: false; wait: boolean; refresh?: OAuthSession; retry?: true };
 
type StoreResult =
  | { done: true; displaced: string | undefined }
  | { done: false; refresh: OAuthSession }
  | { done: false; retry: true };
 
/** The exact refresh credential prepared by this completion's preceding refresh attempt. */
interface PreparedGrant {
  refreshToken: string;
  unusable: boolean;
}
 
async function findLinkedAccount(write: LinkedAccountWrite): Promise<OAuthSession | undefined> {
  return (await sessionStore.getLinkedSessions(write.session.id)).find(
    (row) =>
      normalizeInstanceUrl(row.gitlabApiUrl ?? GITLAB_BASE_URL) === write.instance &&
      row.gitlabUserId === write.user.id,
  );
}
 
/** Store the account's row; another pass is needed when another link stored it meanwhile. */
async function createLinkedAccount(
  write: LinkedAccountWrite,
  fence: LinkFence,
): Promise<StorePass> {
  const { session, link, user, instance, grant } = write;
  const now = Date.now();
  // The id follows from the session and the account, so a concurrent link of the same
  // account collides on it in storage instead of storing the account twice.
  const committed = await sessionStore.commitLinkedAccount({
    ...fence,
    account: {
      id: linkedAccountId(session.id, instance, user.id),
      mcpAccessToken: '',
      mcpRefreshToken: '',
      mcpTokenExpiry: 0,
      ...grant,
      gitlabUserId: user.id,
      gitlabUsername: user.username,
      gitlabApiUrl: instance,
      instanceLabel: link.instanceLabel,
      clientId: session.clientId,
      scopes: [],
      linkedToSessionId: session.id,
      createdAt: now,
      updatedAt: now,
    },
  });
  return committed
    ? { done: true, displaced: undefined }
    : { done: false, wait: false, retry: true };
}
 
/** Give the stored account the new grant while holding its lease. */
async function replaceLinkedGrant(
  write: LinkedAccountWrite,
  stored: OAuthSession,
  preparedGrant: PreparedGrant | undefined,
  fence: LinkFence,
): Promise<StorePass> {
  const now = Date.now();
  const leaseUntil = now + REPLACE_LEASE_MS;
  const claimed = await sessionStore.claimGitLabRefresh(
    stored.id,
    stored.gitlabRefreshToken,
    now,
    leaseUntil,
  );
  if (!claimed) {
    // Another link or a token refresh is changing the row: wait for its turn to end.
    return { done: false, wait: true };
  }
  try {
    if (
      stored.gitlabRefreshToken !== write.grant.gitlabRefreshToken &&
      isTokenExpiringSoon(stored.gitlabTokenExpiry) &&
      (preparedGrant?.refreshToken !== stored.gitlabRefreshToken ||
        (!preparedGrant.unusable && stored.gitlabTokenExpiry <= Date.now()))
    ) {
      // Doorkeeper 5.6.6 skips expired access tokens on revoke. Keep both credentials
      // until refreshed. A just-refreshed short-lived grant need not refresh again,
      // but recheck its actual expiry under the lease after waiting for the primary.
      return { done: false, wait: false, refresh: stored };
    }
    // Read before the update: a backend may hand out the stored record, which it changes.
    // A refused refresh does not prove this access token is unusable; still revoke it.
    const displaced = stored.gitlabAccessToken;
    const committed = await sessionStore.commitLinkedAccount({
      ...fence,
      account: {
        ...stored,
        ...write.grant,
        gitlabUsername: write.user.username,
        linkedToSessionId: write.session.id,
      },
      existing: { refreshToken: stored.gitlabRefreshToken, leaseUntil },
    });
    return committed ? { done: true, displaced } : { done: false, wait: false, retry: true };
  } finally {
    await sessionStore.releaseGitLabRefresh(stored.id, leaseUntil).catch(() => undefined);
  }
}
 
/**
 * Store the account with the session, or give an account linked before the new grant;
 * returns the access token of the grant it displaced, if any. Replacements of one account
 * take turns under the lease a GitLab token refresh holds (claimed only while the row still
 * holds the refresh token read), so each knows exactly which grant it displaced.
 */
async function storeLinkedAccount(
  write: LinkedAccountWrite,
  preparedGrant: PreparedGrant | undefined,
  fence: LinkFence,
  attempt = 1,
): Promise<StoreResult> {
  const stored = await findLinkedAccount(write);
  const pass = stored
    ? await replaceLinkedGrant(write, stored, preparedGrant, fence)
    : await createLinkedAccount(write, fence);
  if (pass.done) return pass;
  if (pass.retry) return { done: false, retry: true };
  if (pass.refresh) return { done: false, refresh: pass.refresh };
  if (attempt >= STORE_ATTEMPTS) {
    throw new Error('The linked account is being changed elsewhere');
  }
  Eif (pass.wait) await new Promise((resolve) => setTimeout(resolve, STORE_RETRY_MS));
  return storeLinkedAccount(write, preparedGrant, fence, attempt + 1);
}
 
/** How a link's completion ended, and the grant its store displaced, if any. */
interface LinkCompletion {
  outcome: 'completed' | 'spent' | 'signed-out';
  replacedToken?: string;
}
 
/**
 * Store the account and spend the link. The completions of the session's links take turns
 * under its lease, from the check that this link is still unspent until it is spent: a
 * delivery that lost to another delivery of the same callback stores nothing, so it cannot
 * put back a grant a later link replaced and ended, and a discard of the expired flow
 * decides whether its grant is the account's under the same lease. A revocation of the
 * session holds the lease from before it reads the linked accounts until it deletes them,
 * so it either sees this account or this link sees the session gone.
 */
async function completeUnderSessionLease(
  state: string,
  write: LinkedAccountWrite,
  preparedGrant: PreparedGrant | undefined,
): Promise<LinkCompletion | { outcome: 'refresh'; account: OAuthSession } | { outcome: 'retry' }> {
  const { session, instance, user } = write;
  const turn = await claimSessionLease(session.id, LINK_COMPLETION_LEASE_MS);
  if (turn === undefined) {
    await sessionStore.consumeAuthCodeFlow(state);
    return { outcome: 'signed-out' };
  }
  try {
    const flow = await sessionStore.getAuthCodeFlow(state);
    if (!flow || flow.expiresAt <= Date.now()) return { outcome: 'spent' };
    const result = await storeLinkedAccount(write, preparedGrant, {
      internalState: state,
      primaryLeaseUntil: turn,
    });
    if (!result.done) {
      if ('retry' in result) return { outcome: 'retry' };
      return { outcome: 'refresh', account: result.refresh };
    }
    const replacedToken = result.displaced;
    // A session removed without its lease (storage cleanup) leaves the row behind.
    if (!(await sessionStore.getSession(session.id))) {
      await sessionStore.deleteSession(linkedAccountId(session.id, instance, user.id));
      return { outcome: 'signed-out', replacedToken };
    }
    return { outcome: 'completed', replacedToken };
  } finally {
    await sessionStore.releaseGitLabRefresh(session.id, turn).catch(() => undefined);
  }
}
 
/** Refresh a displaced grant outside the primary lease, then retry the serialized store. */
async function completeWithLiveDisplacedGrant(
  state: string,
  write: LinkedAccountWrite,
  config: OAuthConfig,
): Promise<LinkCompletion> {
  let preparedGrant: PreparedGrant | undefined;
  for (let attempt = 0; attempt < STORE_ATTEMPTS; attempt++) {
    const result = await completeUnderSessionLease(state, write, preparedGrant);
    if (result.outcome === 'retry') continue;
    if (result.outcome !== 'refresh') return result;
    const spent = result.account.gitlabRefreshToken;
    try {
      const refreshed = await withFreshGitLabToken(result.account, config);
      Eif (refreshed) {
        preparedGrant = { refreshToken: refreshed.gitlabRefreshToken, unusable: false };
      }
    } catch (error: unknown) {
      // Only invalid_grant proves this particular credential is already unusable.
      // A missing application or a temporary failure must leave the old pair stored.
      if (
        !(error instanceof GitLabGrantRevokedError) ||
        !(error.cause instanceof GitLabOAuthHttpError) ||
        error.cause.oauthError !== 'invalid_grant'
      ) {
        throw error;
      }
      preparedGrant = { refreshToken: spent, unusable: true };
    }
  }
  throw new Error('The linked account is being changed elsewhere');
}
 
/** Second step: store the signed-in account with the session, or refresh it when linked. */
async function connectAccount(
  res: Response,
  state: string,
  flow: AuthCodeFlowState,
  link: AccountLinkStep,
  code: string,
  config: OAuthConfig,
  session: OAuthSession,
): Promise<void> {
  // Checked before the code is exchanged: a browser this step was forwarded to gets no
  // grant at all, and the step is spent so the forwarded link cannot be retried.
  if (!fromBoundBrowser(res, state, link)) {
    logWarn('Account link refused: continued in another browser', {
      sessionId: truncateId(session.id),
    });
    await discardAuthCodeFlow(state, flow, config);
    failAccountLink(
      res,
      'Continue the link in the browser where you confirmed your own account; a link cannot be passed on. Ask for a new one in the chat.',
    );
    return;
  }
  const app = await oauthAppFor(config, flow.selectedInstance);
  if (!app) {
    failAccountLink(res, 'The GitLab instance of this link is no longer configured.');
    return;
  }
  const tokens = flow.gitlabTokens ?? (await exchangeFlowCode(state, flow, code, config, app));
  const user = await getGitLabUser(tokens.access_token, app.baseUrl);
  const instance = normalizeInstanceUrl(app.baseUrl);
  const ownInstance = normalizeInstanceUrl(session.gitlabApiUrl ?? GITLAB_BASE_URL);
  if (instance === ownInstance && user.id === session.gitlabUserId) {
    await sessionStore.consumeAuthCodeFlow(state);
    await revokeQuietly(tokens.access_token, config, app);
    failAccountLink(
      res,
      `GitLab signed you in as ${user.username} again, the account this connection already uses. ` +
        'To link another account, sign out of GitLab or sign in with the other account first.',
    );
    return;
  }
 
  const { outcome, replacedToken } = await completeWithLiveDisplacedGrant(
    state,
    {
      session,
      link,
      user,
      instance,
      grant: {
        gitlabAccessToken: tokens.access_token,
        gitlabRefreshToken: tokens.refresh_token,
        gitlabTokenExpiry: calculateTokenExpiry(tokens.expires_in),
        gitlabScopes: grantedGitlabScopes(tokens.scope, flow.requestedGitlabScopes),
      },
    },
    config,
  );
  // The displaced grant is no longer stored. A grant this link already stored is not one.
  if (replacedToken && replacedToken !== tokens.access_token) {
    await revokeQuietly(replacedToken, config, app);
  }
  if (outcome === 'signed-out') {
    await revokeQuietly(tokens.access_token, config, app);
    failAccountLink(res, 'The connection that asked for this link has signed out.');
    return;
  }
  if (outcome === 'spent') {
    failAccountLink(res, 'This link was already completed or has expired.');
    return;
  }
  res.clearCookie(bindingCookieName(state), { path: new URL(callbackUri(config)).pathname });
  const label = `${user.username} @ ${link.instanceLabel ?? new URL(instance).host}`;
  logInfo('Account linked', { sessionId: truncateId(session.id), instance });
  linkPage(
    res,
    200,
    'Account linked',
    `${label} is linked to your GitLab MCP connection. Return to the chat and switch to it with manage_context switch_account.`,
  );
  await announceLinked(link);
}
 
/**
 * Tell the chat whose client opened the link (MCP URL elicitation) that it completed. The
 * client's answer to the elicitation only meant consent to open it; this is how it learns
 * the outcome. Best effort: the callback may reach a replica that does not hold the chat.
 */
async function announceLinked(link: AccountLinkStep): Promise<void> {
  if (!link.mcpSessionId || !link.elicitationId) return;
  try {
    const { getSessionManager } = await import('../session-manager');
    await getSessionManager().notifyElicitationComplete(link.mcpSessionId, link.elicitationId);
  } catch (error: unknown) {
    // The page is already sent: a failed announcement must not reach the error page.
    logWarn('Could not announce a completed account link', { err: error as Error });
  }
}
 
/** Complete a step of an account link from GitLab's callback. */
export async function completeAccountLink(
  res: Response,
  state: string,
  flow: AuthCodeFlowState,
  code: string,
  config: OAuthConfig,
): Promise<void> {
  const link = flow.link as AccountLinkStep;
  if (Date.now() > flow.expiresAt) {
    await discardAuthCodeFlow(state, flow, config);
    failAccountLink(res, 'This link expired. Ask for a new one in the chat.');
    return;
  }
  try {
    const session = await sessionStore.getSession(link.sessionId);
    if (!session) {
      await discardAuthCodeFlow(state, flow, config);
      failAccountLink(res, 'The connection that asked for this link has signed out.');
      return;
    }
    if (link.stage === 'verify') {
      await verifyOwnAccount(res, state, flow, link, code, config, session);
    } else {
      await connectAccount(res, state, flow, link, code, config, session);
    }
  } catch (error: unknown) {
    logWarn('Account link failed', { err: error as Error });
    if (error instanceof AccountLinkFlowUnavailableError) {
      failAccountLink(
        res,
        'This link was already used or has expired. Ask for a new one in the chat.',
      );
      return;
    }
    // The flow is kept unless it was completed, so reloading the page retries it.
    linkPage(
      res,
      500,
      'Account not linked',
      'Linking failed for a temporary reason; reload this page to try again.',
    );
  }
}