51 lines · 2.1 KB
import { TOKEN_AREAS } from "../token-scope";
import type { AreaAccess, TokenArea, TokenPermissions } from "../token-scope";

/** Agents get read access everywhere they are granted unless they ask for more. */
const DEFAULT_PERMISSIONS: TokenPermissions = { contents: "read", issues: "read", pulls: "read", actions: "read" };
const MAX_REPO_SCOPES = 50;
const REPO_SCOPE = /^repo:([A-Za-z0-9_.-]+)\/([A-Za-z0-9_.-]+)$/;

export const SCOPES_SUPPORTED = [
  ...TOKEN_AREAS.flatMap((area) => [`${area}:read`, `${area}:write`]),
  "repo:{owner}/{name}",
];

export type RequestedScope = { permissions: TokenPermissions; repos: Array<{ owner: string; name: string }> };

function isArea(value: string): value is TokenArea {
  return (TOKEN_AREAS as readonly string[]).includes(value);
}

/**
 * Scope grammar: `<area>:read|write` for each fine-grained token area and `repo:owner/name` to pin
 * the grant to specific repositories. No repo scopes means "all repositories", which the consent
 * screen calls out explicitly.
 */
export function parseScope(raw: string | null): RequestedScope {
  const permissions: TokenPermissions = {};
  const repos: RequestedScope["repos"] = [];
  let sawArea = false;
  for (const item of (raw ?? "").split(/\s+/).filter(Boolean)) {
    const repo = REPO_SCOPE.exec(item);
    if (repo) {
      if (repos.length < MAX_REPO_SCOPES && !repos.some((r) => r.owner === repo[1] && r.name === repo[2]))
        repos.push({ owner: repo[1], name: repo[2] });
      continue;
    }
    const [area, access] = item.split(":");
    if (!isArea(area) || (access !== "read" && access !== "write")) continue;
    sawArea = true;
    if (permissions[area] !== "write") permissions[area] = access;
  }