@sentry/junior-github 0.311.0 → 0.312.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.
@@ -2,7 +2,7 @@ import * as z from "zod";
2
2
  import pLimit from "p-limit";
3
3
  import { PluginToolInputError, eventMatchFieldsSchema, mergeEventMatchFields } from "@sentry/junior-plugin-api";
4
4
  import { lexer } from "marked";
5
- import { createPrivateKey, createSign } from "node:crypto";
5
+ import { createHash, createPrivateKey, createSign } from "node:crypto";
6
6
  // src/tool-support/github-api.ts
7
7
  const GITHUB_API_BASE = "https://api.github.com";
8
8
  const MAX_REDIRECTS = 3;
@@ -679,7 +679,7 @@ function gitHubPullRequestSubscription(config) {
679
679
  * Each passing suite wakes the Watch, so a suite that leaves the required
680
680
  * checks unfinished must stay silent, or every suite posts.
681
681
  */
682
- const DRAFT_CHECKS_RECOVERED_GUIDANCE = "If the pull request is still a draft, call github_getPullRequest and read its `checks`, `code_owners`, and `agents_md`. When `checks.required` is `passing` and no decision is open, in the pull request body or in an open review item that waits on the person who asked for it: mark it ready with github_updatePullRequest and draft false, when the person who asked for it said to mark it ready, or when `code_owners` is empty and `agents_md` does not ask for draft pull requests or say that a person marks them ready. Otherwise keep it a draft: marking it ready would ask the code owners to review, or break the AGENTS.md rule. Tell the person who asked for it in the originating thread that the checks pass and the draft waits for their review, and name why: the code owners that marking it ready asks, or the AGENTS.md rule. If you already told them for this head commit, stay silent. When it is `failing`, fix the failing checks like a failed check. When it is `pending` or `not_reported`, stay silent: a later passing suite wakes you again. `not_reported` means the required checks may not have started on the latest commit yet, not that none are required.";
682
+ const DRAFT_CHECKS_RECOVERED_GUIDANCE = "If the pull request is still a draft, call github_getPullRequest and read its `checks`, `code_owners`, and `agents_md`. When `checks.required` is `passing` and no decision is open, in the pull request body or in an open inbox item that waits on the person who asked for it: mark it ready with github_updatePullRequest and draft false, when the person who asked for it said to mark it ready, or when `code_owners` is empty and `agents_md` does not ask for draft pull requests or say that a person marks them ready. Otherwise keep it a draft: marking it ready would ask the code owners to review, or break the AGENTS.md rule. Tell the person who asked for it in the originating thread that the checks pass and the draft waits for their review, and name why: the code owners that marking it ready asks, or the AGENTS.md rule. If you already told them for this head commit, stay silent. When it is `failing`, fix the failing checks like a failed check. When it is `pending` or `not_reported`, stay silent: a later passing suite wakes you again. `not_reported` means the required checks may not have started on the latest commit yet, not that none are required.";
683
683
  /**
684
684
  * State changes that need no action but that a later Turn must know, so that
685
685
  * it does not call an approved pull request unreviewed, or a merged or
@@ -1020,6 +1020,124 @@ function mentionsBotLogin(text, botEmail) {
1020
1020
  const escaped = slug.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
1021
1021
  return new RegExp(`(?:^|[^\\w-])@${escaped}(?![\\w-])`, "i").test(splitCommentText(text, { withoutCode: true }).own ?? "");
1022
1022
  }
1023
+ // src/conditional-requests.ts
1024
+ /**
1025
+ * Conditional GitHub reads. GitHub does not count a `304 Not Modified`
1026
+ * answer against the rate limit, so a repeat read of an unchanged resource,
1027
+ * such as a pull request that every check suite webhook reads, is free.
1028
+ *
1029
+ * Saved bodies are plaintext in plugin state. A breach of that store exposes
1030
+ * up to 6 hours of webhook reads: pull requests, their commits with author
1031
+ * names and emails, and collaborator roles. It exposes no token.
1032
+ */
1033
+ /**
1034
+ * How long a saved response stays. Webhooks for one pull request come in
1035
+ * bursts, such as one for each check suite, so most repeat reads are minutes
1036
+ * apart.
1037
+ */
1038
+ const SAVED_RESPONSE_TTL_MS = 216e5;
1039
+ /** Larger bodies, such as long commit lists, are not saved. */
1040
+ const MAX_SAVED_BODY_LENGTH = 262144;
1041
+ const savedResponseSchema = z.object({
1042
+ body: z.string(),
1043
+ etag: z.string().min(1)
1044
+ });
1045
+ /**
1046
+ * The state key of a saved response. It has no token: GitHub answers 304
1047
+ * only to a request that it authorized, and only when the response to that
1048
+ * request did not change, so a saved body never reaches a token that cannot
1049
+ * read it.
1050
+ */
1051
+ function savedResponseKey(url) {
1052
+ return `github-response:${createHash("sha256").update(url).digest("hex")}`;
1053
+ }
1054
+ /**
1055
+ * Send one GitHub GET with the ETag of its saved response. On 304, return
1056
+ * the saved body as a 200 response. On a 200 with an ETag, save the body.
1057
+ * Without `responses`, send the request as it is.
1058
+ *
1059
+ * Saved responses only save rate limit. A read or write failure of plugin
1060
+ * state is a cache miss, so it never fails the GitHub read.
1061
+ */
1062
+ async function sendConditionalRequest(responses, url, send) {
1063
+ if (!responses) return await send({});
1064
+ const key = savedResponseKey(url);
1065
+ const saved = savedResponseSchema.safeParse(await responses.get(key).catch(() => void 0));
1066
+ const response = await send(saved.success ? { "If-None-Match": saved.data.etag } : {});
1067
+ if (response.status === 304 && saved.success) {
1068
+ await response.body?.cancel();
1069
+ return new Response(saved.data.body, {
1070
+ headers: { etag: saved.data.etag },
1071
+ status: 200
1072
+ });
1073
+ }
1074
+ const etag = response.headers.get("etag");
1075
+ if (!response.ok || !etag) return response;
1076
+ const body = await response.text();
1077
+ if (body.length <= MAX_SAVED_BODY_LENGTH) await responses.set(key, {
1078
+ body,
1079
+ etag
1080
+ }, SAVED_RESPONSE_TTL_MS).catch(() => void 0);
1081
+ return new Response(body, {
1082
+ headers: response.headers,
1083
+ status: response.status,
1084
+ statusText: response.statusText
1085
+ });
1086
+ }
1087
+ // src/installation-responses.ts
1088
+ /** Parsers for GitHub App installation API responses. */
1089
+ const installationTokenResponseSchema = z.object({
1090
+ expires_at: z.unknown().optional(),
1091
+ token: z.unknown().optional()
1092
+ });
1093
+ const installationPermissionsSchema = z.object({ permissions: z.record(z.string(), z.unknown()) });
1094
+ /** Read the token and its expiry from an installation token response. */
1095
+ function parseInstallationTokenResponse(value) {
1096
+ const parsed = installationTokenResponseSchema.safeParse(value);
1097
+ if (!parsed.success) throw new Error("GitHub installation token response is invalid");
1098
+ const data = parsed.data;
1099
+ const token = data["token"];
1100
+ if (typeof token !== "string" || !token.trim()) throw new Error("GitHub installation token response missing token");
1101
+ const expiresAt = data["expires_at"];
1102
+ const expiresAtMs = typeof expiresAt === "string" ? Date.parse(expiresAt) : NaN;
1103
+ if (!Number.isFinite(expiresAtMs) || expiresAtMs <= Date.now()) throw new Error("GitHub installation token response returned invalid expires_at");
1104
+ return {
1105
+ token,
1106
+ expiresAtMs
1107
+ };
1108
+ }
1109
+ /** Read the read permissions that an installation was granted. */
1110
+ function readInstallationPermissions(installation) {
1111
+ const parsed = installationPermissionsSchema.safeParse(installation);
1112
+ if (!parsed.success) throw new Error("GitHub installation response missing permissions");
1113
+ return readGrantPermissions(parsed.data.permissions);
1114
+ }
1115
+ // src/installation-tokens.ts
1116
+ /** A token this close to its expiry is minted again. */
1117
+ const REUSE_BUFFER_MS = 3e5;
1118
+ /**
1119
+ * Return the token of the same permissions and repositories while it has
1120
+ * time left, or mint one. Concurrent callers share one mint. A failed mint
1121
+ * is not kept.
1122
+ */
1123
+ async function reuseInstallationToken(tokens, scope, mint) {
1124
+ const key = JSON.stringify([
1125
+ scope.permissions ?? null,
1126
+ scope.repositories ?? null,
1127
+ scope.repositoryIds ?? null
1128
+ ]);
1129
+ const pending = tokens.get(key);
1130
+ const reused = pending && await pending.catch(() => void 0);
1131
+ if (reused && reused.expiresAtMs - REUSE_BUFFER_MS > Date.now()) return reused;
1132
+ const minted = mint();
1133
+ tokens.set(key, minted);
1134
+ try {
1135
+ return await minted;
1136
+ } catch (error) {
1137
+ if (tokens.get(key) === minted) tokens.delete(key);
1138
+ throw error;
1139
+ }
1140
+ }
1023
1141
  // src/credential-support.ts
1024
1142
  /**
1025
1143
  * GitHub credential issuance and provider request support.
@@ -1077,11 +1195,6 @@ const oauthTokenResponseSchema = z.object({
1077
1195
  refresh_token_expires_in: z.unknown().optional(),
1078
1196
  scope: z.unknown().optional()
1079
1197
  });
1080
- const installationTokenResponseSchema = z.object({
1081
- expires_at: z.unknown().optional(),
1082
- token: z.unknown().optional()
1083
- });
1084
- const installationPermissionsSchema = z.object({ permissions: z.record(z.string(), z.unknown()) });
1085
1198
  const userAccountSchema = z.object({
1086
1199
  html_url: z.unknown().optional(),
1087
1200
  id: z.unknown().optional(),
@@ -1158,16 +1271,19 @@ function createAppJwt(appId, privateKeyEnv) {
1158
1271
  }
1159
1272
  /** Send an authenticated request to the GitHub API. */
1160
1273
  async function githubRequest(apiBase, path, params) {
1161
- const response = await fetch(`${apiBase}${path}`, {
1162
- method: params.method ?? "GET",
1274
+ const method = params.method ?? "GET";
1275
+ const url = `${apiBase}${path}`;
1276
+ const response = await sendConditionalRequest(method === "GET" ? params.responses : void 0, url, (headers) => fetch(url, {
1277
+ method,
1163
1278
  headers: {
1279
+ ...headers,
1164
1280
  Accept: "application/vnd.github+json",
1165
1281
  Authorization: `Bearer ${params.token}`,
1166
1282
  "X-GitHub-Api-Version": "2022-11-28",
1167
1283
  ...params.body ? { "Content-Type": "application/json" } : void 0
1168
1284
  },
1169
1285
  ...params.body ? { body: JSON.stringify(params.body) } : void 0
1170
- });
1286
+ }));
1171
1287
  const text = await response.text();
1172
1288
  let parsed;
1173
1289
  if (text) try {
@@ -1307,25 +1423,6 @@ function credentialUnavailable(message) {
1307
1423
  message
1308
1424
  };
1309
1425
  }
1310
- function parseInstallationTokenResponse(value) {
1311
- const parsed = installationTokenResponseSchema.safeParse(value);
1312
- if (!parsed.success) throw new Error("GitHub installation token response is invalid");
1313
- const data = parsed.data;
1314
- const token = data["token"];
1315
- if (typeof token !== "string" || !token.trim()) throw new Error("GitHub installation token response missing token");
1316
- const expiresAt = data["expires_at"];
1317
- const expiresAtMs = typeof expiresAt === "string" ? Date.parse(expiresAt) : NaN;
1318
- if (!Number.isFinite(expiresAtMs) || expiresAtMs <= Date.now()) throw new Error("GitHub installation token response returned invalid expires_at");
1319
- return {
1320
- token,
1321
- expiresAtMs
1322
- };
1323
- }
1324
- function readInstallationPermissions(installation) {
1325
- const parsed = installationPermissionsSchema.safeParse(installation);
1326
- if (!parsed.success) throw new Error("GitHub installation response missing permissions");
1327
- return readGrantPermissions(parsed.data.permissions);
1328
- }
1329
1426
  function decodeGitHubPathSegment(value) {
1330
1427
  try {
1331
1428
  const decoded = decodeURIComponent(value).trim();
@@ -1502,8 +1599,15 @@ async function issueUserCredential(ctx, options) {
1502
1599
  }
1503
1600
  return credentialNeeded("Your GitHub authorization has expired.", scope);
1504
1601
  }
1505
- /** Issue a bounded raw token for plugin-owned GitHub API calls. */
1602
+ /**
1603
+ * Issue a bounded raw token for plugin-owned GitHub API calls. With
1604
+ * `tokens`, reuse a token of the same scope.
1605
+ */
1506
1606
  async function issueInstallationToken(options) {
1607
+ if (!options.tokens || options.loadPermissions) return await mintInstallationToken(options);
1608
+ return await reuseInstallationToken(options.tokens, options, () => mintInstallationToken(options));
1609
+ }
1610
+ async function mintInstallationToken(options) {
1507
1611
  const appId = requireEnv(options.appIdEnv);
1508
1612
  const installationIdRaw = requireEnv(options.installationIdEnv);
1509
1613
  const installationId = Number(installationIdRaw);
@@ -2119,7 +2223,8 @@ async function loadCheckSuiteFacts(args) {
2119
2223
  installationIdEnv: args.installationIdEnv,
2120
2224
  permissions: { checks: "read" },
2121
2225
  privateKeyEnv: args.privateKeyEnv,
2122
- repositories: [target.repoName]
2226
+ repositories: [target.repoName],
2227
+ tokens: args.tokens
2123
2228
  });
2124
2229
  const failing = selectFailingChecks(checkRunsFromResponse(await githubRequest("https://api.github.com", `/repos/${encodeURIComponent(target.owner)}/${encodeURIComponent(target.repoName)}/check-suites/${target.checkSuiteId}/check-runs?filter=latest&per_page=100`, { token: token.token })), { checkSuiteId: target.checkSuiteId });
2125
2230
  if (failing.length > 0) facts.failingChecks = failing;
@@ -2135,7 +2240,8 @@ async function loadCheckSuiteFacts(args) {
2135
2240
  installationIdEnv: args.installationIdEnv,
2136
2241
  permissions: { checks: "read" },
2137
2242
  privateKeyEnv: args.privateKeyEnv,
2138
- repositories: [target.repoName]
2243
+ repositories: [target.repoName],
2244
+ tokens: args.tokens
2139
2245
  });
2140
2246
  if (await loadAllCheckSuitesPassed({
2141
2247
  checkSuiteId: target.checkSuiteId,
@@ -2162,11 +2268,15 @@ async function loadCheckSuiteFacts(args) {
2162
2268
  installationIdEnv: args.installationIdEnv,
2163
2269
  permissions: { pull_requests: "read" },
2164
2270
  privateKeyEnv: args.privateKeyEnv,
2165
- repositories: [target.repoName]
2271
+ repositories: [target.repoName],
2272
+ tokens: args.tokens
2166
2273
  });
2167
2274
  const loaded = await pLimit(PULL_REQUEST_LOAD_CONCURRENCY).map(target.pullRequestNumbers, async (number) => {
2168
2275
  try {
2169
- const loadedFacts = pullRequestFactsFromResponse(await githubRequest("https://api.github.com", `/repos/${encodeURIComponent(target.owner)}/${encodeURIComponent(target.repoName)}/pulls/${number}`, { token: token.token }));
2276
+ const loadedFacts = pullRequestFactsFromResponse(await githubRequest("https://api.github.com", `/repos/${encodeURIComponent(target.owner)}/${encodeURIComponent(target.repoName)}/pulls/${number}`, {
2277
+ responses: args.responses,
2278
+ token: token.token
2279
+ }));
2170
2280
  return loadedFacts ? [number, loadedFacts] : void 0;
2171
2281
  } catch (error) {
2172
2282
  if (!isGitHubNotFoundError(error)) logFailOpenFailure(args.log, "GitHub pull request data load failed", error, {