@bli-cockpit/telemetry-core 0.1.83 → 0.1.84
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.
- package/dist/github-app-token.d.ts +47 -0
- package/dist/github-app-token.js +141 -0
- package/package.json +6 -1
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
/** Log the remaining quota once it drops below this. */
|
|
2
|
+
export declare const LOW_QUOTA = 500;
|
|
3
|
+
export type Via = "app" | "user";
|
|
4
|
+
export interface ResolvedToken {
|
|
5
|
+
token: string;
|
|
6
|
+
via: Via;
|
|
7
|
+
}
|
|
8
|
+
export type TokenProvider = () => Promise<ResolvedToken>;
|
|
9
|
+
/** A fixed token (tests, the personal-token path) or a provider that mints and caches. */
|
|
10
|
+
export type GithubToken = string | TokenProvider;
|
|
11
|
+
export declare function resolveToken(source: GithubToken): Promise<ResolvedToken>;
|
|
12
|
+
/** An RS256 JWT for the App: issued a minute in the past (clock skew), valid for nine minutes. */
|
|
13
|
+
export declare function signAppJwt(appId: string, privateKey: string, nowSeconds?: number): string;
|
|
14
|
+
/** Where the installation token reaches: one repository, or every repository of the org's installation. */
|
|
15
|
+
export type TokenScope = {
|
|
16
|
+
repo: string;
|
|
17
|
+
owner?: never;
|
|
18
|
+
} | {
|
|
19
|
+
owner: string;
|
|
20
|
+
repo?: never;
|
|
21
|
+
};
|
|
22
|
+
export type TokenSourceOptions = TokenScope & {
|
|
23
|
+
appId?: string;
|
|
24
|
+
privateKey?: string;
|
|
25
|
+
/** The personal token, used only when the App token cannot be minted. */
|
|
26
|
+
userToken?: string;
|
|
27
|
+
/** Log tag; the runner keeps `[runner github token]`. */
|
|
28
|
+
tag?: string;
|
|
29
|
+
fetchImpl?: typeof fetch;
|
|
30
|
+
now?: () => number;
|
|
31
|
+
};
|
|
32
|
+
/** Returns a provider: the cached App token, a fresh mint when near expiry, else the personal token (reason logged). Never throws unless no token exists at all. */
|
|
33
|
+
export declare function createTokenSource(opts: TokenSourceOptions): TokenProvider;
|
|
34
|
+
/** The provider for this env: App first, `GITHUB_TOKEN` (else `GH_TOKEN`) as the fallback. */
|
|
35
|
+
export declare function tokenSourceFromEnv(scope: TokenScope, env?: Record<string, string | undefined>, opts?: {
|
|
36
|
+
fetchImpl?: typeof fetch;
|
|
37
|
+
tag?: string;
|
|
38
|
+
}): TokenProvider;
|
|
39
|
+
/** True when this env can produce any GitHub token at all (the App pair, or a personal token). */
|
|
40
|
+
export declare function hasGithubCredentials(env?: Record<string, string | undefined>): boolean;
|
|
41
|
+
/** One log line per GitHub call: which token carried it, plus the remaining quota once it is low. Metadata only: the host and the query string are dropped. */
|
|
42
|
+
export declare function logGithubCall(tag: string, fields: {
|
|
43
|
+
path: string;
|
|
44
|
+
status: number;
|
|
45
|
+
via: Via;
|
|
46
|
+
headers?: Pick<Headers, "get"> | null;
|
|
47
|
+
}): void;
|
|
@@ -0,0 +1,141 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The one GitHub App READ token source for Tower's server code (ticket 22427 for the runner, BLI-23182 for the dashboard).
|
|
3
|
+
*
|
|
4
|
+
* `GITHUB_TOKEN` is a fine-grained personal token, and a fine-grained token cannot read check runs, commit status or
|
|
5
|
+
* Actions runs at all (403). So server readers mint an installation token from the `BLI Cloud Agents` App instead (its own
|
|
6
|
+
* rate-limit bucket, Checks / Commit statuses / Actions read), the same App the Agent Batch uses (`scripts/agent-token.mjs`):
|
|
7
|
+
* an RS256 JWT from the App key, the installation (one repo's, or the whole org's), an installation token, cached until five
|
|
8
|
+
* minutes before it expires. Only when minting fails does a call use the personal token, with the reason logged once, and
|
|
9
|
+
* every call logs `via: app|user`. The key and the tokens are never logged.
|
|
10
|
+
*
|
|
11
|
+
* Two scopes: `repo` mints a token limited to that one repository (the runner); `owner` mints one for every repository the
|
|
12
|
+
* org's installation covers (the dashboard's readers, which read many BLI-INC repos).
|
|
13
|
+
*
|
|
14
|
+
* Env: AGENT_APP_ID, AGENT_APP_PRIVATE_KEY (the same names as the repo secrets), GITHUB_TOKEN, else GH_TOKEN (fallback).
|
|
15
|
+
* Docs: docs/runbooks/cloud-agent-lanes.md, "The runner's GitHub token".
|
|
16
|
+
*/
|
|
17
|
+
import { createSign } from "node:crypto";
|
|
18
|
+
const API = "https://api.github.com";
|
|
19
|
+
/** Mint again this long before the hour is up. */
|
|
20
|
+
const REFRESH_BEFORE_MS = 5 * 60_000;
|
|
21
|
+
/** Log the remaining quota once it drops below this. */
|
|
22
|
+
export const LOW_QUOTA = 500;
|
|
23
|
+
const DEFAULT_TAG = "[github token]";
|
|
24
|
+
export async function resolveToken(source) {
|
|
25
|
+
return typeof source === "string" ? { token: source, via: "user" } : source();
|
|
26
|
+
}
|
|
27
|
+
const b64url = (input) => Buffer.from(input).toString("base64url");
|
|
28
|
+
/** An RS256 JWT for the App: issued a minute in the past (clock skew), valid for nine minutes. */
|
|
29
|
+
export function signAppJwt(appId, privateKey, nowSeconds = Math.floor(Date.now() / 1000)) {
|
|
30
|
+
const unsigned = `${b64url(JSON.stringify({ alg: "RS256", typ: "JWT" }))}.${b64url(JSON.stringify({ iat: nowSeconds - 60, exp: nowSeconds + 540, iss: String(appId) }))}`;
|
|
31
|
+
const signature = createSign("RSA-SHA256").update(unsigned).sign(privateKey.replaceAll("\\n", "\n"));
|
|
32
|
+
return `${unsigned}.${signature.toString("base64url")}`;
|
|
33
|
+
}
|
|
34
|
+
class MintError extends Error {
|
|
35
|
+
}
|
|
36
|
+
async function appCall(doFetch, method, path, jwt, expected, body) {
|
|
37
|
+
let response;
|
|
38
|
+
try {
|
|
39
|
+
response = await doFetch(`${API}${path}`, {
|
|
40
|
+
method,
|
|
41
|
+
headers: {
|
|
42
|
+
Authorization: `Bearer ${jwt}`,
|
|
43
|
+
Accept: "application/vnd.github+json",
|
|
44
|
+
"X-GitHub-Api-Version": "2022-11-28",
|
|
45
|
+
"User-Agent": "bli-cockpit-github-app",
|
|
46
|
+
},
|
|
47
|
+
body: body ? JSON.stringify(body) : undefined,
|
|
48
|
+
signal: AbortSignal.timeout(30_000),
|
|
49
|
+
});
|
|
50
|
+
}
|
|
51
|
+
catch {
|
|
52
|
+
throw new MintError("network");
|
|
53
|
+
}
|
|
54
|
+
if (response.status !== expected)
|
|
55
|
+
throw new MintError(String(response.status));
|
|
56
|
+
return (await response.json().catch(() => ({})));
|
|
57
|
+
}
|
|
58
|
+
/** Returns a provider: the cached App token, a fresh mint when near expiry, else the personal token (reason logged). Never throws unless no token exists at all. */
|
|
59
|
+
export function createTokenSource(opts) {
|
|
60
|
+
const now = opts.now ?? Date.now;
|
|
61
|
+
const doFetch = opts.fetchImpl ?? fetch;
|
|
62
|
+
const tag = opts.tag ?? DEFAULT_TAG;
|
|
63
|
+
let cached = null;
|
|
64
|
+
let loggedFallback = false;
|
|
65
|
+
const [owner, name] = opts.repo ? opts.repo.split("/") : [opts.owner, undefined];
|
|
66
|
+
const scope = name ? "repo" : "org";
|
|
67
|
+
const mint = async () => {
|
|
68
|
+
let jwt;
|
|
69
|
+
try {
|
|
70
|
+
jwt = signAppJwt(opts.appId, opts.privateKey, Math.floor(now() / 1000));
|
|
71
|
+
}
|
|
72
|
+
catch {
|
|
73
|
+
throw new MintError("key_invalid");
|
|
74
|
+
}
|
|
75
|
+
const installation = await appCall(doFetch, "GET", name ? `/repos/${owner}/${name}/installation` : `/orgs/${owner}/installation`, jwt, 200);
|
|
76
|
+
const minted = await appCall(doFetch, "POST", `/app/installations/${String(installation["id"])}/access_tokens`, jwt, 201, name ? { repositories: [name] } : undefined);
|
|
77
|
+
const token = typeof minted["token"] === "string" ? minted["token"] : "";
|
|
78
|
+
if (!token)
|
|
79
|
+
throw new MintError("no_token");
|
|
80
|
+
const expires = Date.parse(String(minted["expires_at"] ?? ""));
|
|
81
|
+
return { token, expiresMs: Number.isFinite(expires) ? expires : now() + 55 * 60_000 };
|
|
82
|
+
};
|
|
83
|
+
const fallback = (reason) => {
|
|
84
|
+
if (!opts.userToken) {
|
|
85
|
+
console.error(`${tag} no token`, JSON.stringify({ reason: `${reason}_and_user_token_missing`, scope }));
|
|
86
|
+
throw new Error("github_token_missing");
|
|
87
|
+
}
|
|
88
|
+
if (!loggedFallback) {
|
|
89
|
+
console.warn(`${tag} using the personal token`, JSON.stringify({ reason, scope }));
|
|
90
|
+
loggedFallback = true;
|
|
91
|
+
}
|
|
92
|
+
return { token: opts.userToken, via: "user" };
|
|
93
|
+
};
|
|
94
|
+
const refresh = async () => {
|
|
95
|
+
try {
|
|
96
|
+
cached = await mint();
|
|
97
|
+
loggedFallback = false;
|
|
98
|
+
console.info(`${tag} minted`, JSON.stringify({ via: "app", scope, valid_min: Math.round((cached.expiresMs - now()) / 60_000) }));
|
|
99
|
+
return { token: cached.token, via: "app" };
|
|
100
|
+
}
|
|
101
|
+
catch (error) {
|
|
102
|
+
cached = null;
|
|
103
|
+
return fallback(`app_mint_failed:${error instanceof MintError ? error.message : "unexpected"}`);
|
|
104
|
+
}
|
|
105
|
+
};
|
|
106
|
+
// Concurrent callers (a reader's pool) share one mint instead of each minting their own.
|
|
107
|
+
let inflight = null;
|
|
108
|
+
return async () => {
|
|
109
|
+
if (!opts.appId || !opts.privateKey)
|
|
110
|
+
return fallback("app_secrets_absent");
|
|
111
|
+
if (cached && cached.expiresMs - REFRESH_BEFORE_MS > now())
|
|
112
|
+
return { token: cached.token, via: "app" };
|
|
113
|
+
inflight ??= refresh().finally(() => { inflight = null; });
|
|
114
|
+
return inflight;
|
|
115
|
+
};
|
|
116
|
+
}
|
|
117
|
+
/** The provider for this env: App first, `GITHUB_TOKEN` (else `GH_TOKEN`) as the fallback. */
|
|
118
|
+
export function tokenSourceFromEnv(scope, env = process.env, opts = {}) {
|
|
119
|
+
return createTokenSource({
|
|
120
|
+
...scope,
|
|
121
|
+
appId: env["AGENT_APP_ID"]?.trim() || undefined,
|
|
122
|
+
privateKey: env["AGENT_APP_PRIVATE_KEY"]?.trim() || undefined,
|
|
123
|
+
userToken: env["GITHUB_TOKEN"]?.trim() || env["GH_TOKEN"]?.trim() || undefined,
|
|
124
|
+
...opts,
|
|
125
|
+
});
|
|
126
|
+
}
|
|
127
|
+
/** True when this env can produce any GitHub token at all (the App pair, or a personal token). */
|
|
128
|
+
export function hasGithubCredentials(env = process.env) {
|
|
129
|
+
return Boolean((env["AGENT_APP_ID"]?.trim() && env["AGENT_APP_PRIVATE_KEY"]?.trim()) || env["GITHUB_TOKEN"]?.trim() || env["GH_TOKEN"]?.trim());
|
|
130
|
+
}
|
|
131
|
+
/** One log line per GitHub call: which token carried it, plus the remaining quota once it is low. Metadata only: the host and the query string are dropped. */
|
|
132
|
+
export function logGithubCall(tag, fields) {
|
|
133
|
+
// A response without headers (a test double, an odd proxy) still gets its line; logging never breaks a read.
|
|
134
|
+
const remaining = typeof fields.headers?.get === "function" ? fields.headers.get("x-ratelimit-remaining") : null;
|
|
135
|
+
const base = { path: fields.path.replace(API, "").split("?")[0], status: fields.status, via: fields.via };
|
|
136
|
+
console.info(`${tag} github call`, JSON.stringify(base));
|
|
137
|
+
const left = remaining === null ? NaN : Number(remaining);
|
|
138
|
+
if (Number.isFinite(left) && left < LOW_QUOTA) {
|
|
139
|
+
console.warn(`${tag} github quota low`, JSON.stringify({ ...base, ratelimit_remaining: left, ratelimit_reset: fields.headers?.get("x-ratelimit-reset") ?? null }));
|
|
140
|
+
}
|
|
141
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@bli-cockpit/telemetry-core",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.84",
|
|
4
4
|
"private": false,
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./dist/index.js",
|
|
@@ -44,6 +44,11 @@
|
|
|
44
44
|
"types": "./dist/node-read-cache.d.ts",
|
|
45
45
|
"import": "./dist/node-read-cache.js",
|
|
46
46
|
"default": "./dist/node-read-cache.js"
|
|
47
|
+
},
|
|
48
|
+
"./github-app-token": {
|
|
49
|
+
"types": "./dist/github-app-token.d.ts",
|
|
50
|
+
"import": "./dist/github-app-token.js",
|
|
51
|
+
"default": "./dist/github-app-token.js"
|
|
47
52
|
}
|
|
48
53
|
},
|
|
49
54
|
"publishConfig": {
|