@catamorphic/github 0.0.0-stage → 0.1.0-alpha.31

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/src/oauth.ts ADDED
@@ -0,0 +1,272 @@
1
+ import {
2
+ type DeviceCodeGrant,
3
+ type FetchLike,
4
+ GithubApiError,
5
+ type GithubAppConfig,
6
+ GithubAuthError,
7
+ type GithubTokenSet,
8
+ } from "./types.js";
9
+
10
+ const GITHUB_BASE = "https://github.com";
11
+
12
+ interface OAuthTokenResponse {
13
+ access_token?: string;
14
+ expires_in?: number;
15
+ refresh_token?: string;
16
+ refresh_token_expires_in?: number;
17
+ error?: string;
18
+ error_description?: string;
19
+ interval?: number;
20
+ }
21
+
22
+ async function postForm(
23
+ fetchImpl: FetchLike,
24
+ url: string,
25
+ params: Record<string, string>,
26
+ signal?: AbortSignal,
27
+ ): Promise<OAuthTokenResponse> {
28
+ const response = await fetchImpl(url, {
29
+ ...(signal ? { signal } : {}),
30
+ method: "POST",
31
+ headers: {
32
+ Accept: "application/json",
33
+ "Content-Type": "application/x-www-form-urlencoded",
34
+ },
35
+ body: new URLSearchParams(params).toString(),
36
+ });
37
+ if (!response.ok) {
38
+ // GitHub failing says nothing of the grant: only a refusal is one.
39
+ if (response.status >= 500)
40
+ throw new GithubApiError(
41
+ response.status,
42
+ `GitHub OAuth endpoint returned ${response.status}`,
43
+ );
44
+ throw new GithubAuthError(
45
+ "http_error",
46
+ `GitHub OAuth endpoint returned ${response.status}`,
47
+ );
48
+ }
49
+ return (await response.json()) as OAuthTokenResponse;
50
+ }
51
+
52
+ function toTokenSet(data: OAuthTokenResponse, now: number): GithubTokenSet {
53
+ if (!data.access_token) {
54
+ throw new GithubAuthError(
55
+ data.error ?? "unknown",
56
+ data.error_description ?? "GitHub returned no access token",
57
+ );
58
+ }
59
+ return {
60
+ accessToken: data.access_token,
61
+ expiresAt: data.expires_in ? now + data.expires_in * 1000 : null,
62
+ refreshToken: data.refresh_token ?? null,
63
+ refreshTokenExpiresAt: data.refresh_token_expires_in
64
+ ? now + data.refresh_token_expires_in * 1000
65
+ : null,
66
+ };
67
+ }
68
+
69
+ /**
70
+ * Start the device flow: GitHub hands back a short user code to display and
71
+ * a verification URL to open in a browser. Requires "Enable Device Flow" on
72
+ * the GitHub App; needs only the client id, so it is safe in public clients.
73
+ */
74
+ export async function requestDeviceCode(
75
+ app: GithubAppConfig,
76
+ opts?: { fetch?: FetchLike; baseUrl?: string },
77
+ ): Promise<DeviceCodeGrant> {
78
+ const data = await postForm(
79
+ opts?.fetch ?? fetch,
80
+ `${opts?.baseUrl ?? GITHUB_BASE}/login/device/code`,
81
+ { client_id: app.clientId },
82
+ );
83
+ const raw = data as unknown as {
84
+ device_code?: string;
85
+ user_code?: string;
86
+ verification_uri?: string;
87
+ expires_in?: number;
88
+ interval?: number;
89
+ error?: string;
90
+ error_description?: string;
91
+ };
92
+ if (!raw.device_code || !raw.user_code || !raw.verification_uri) {
93
+ throw new GithubAuthError(
94
+ raw.error ?? "unknown",
95
+ raw.error_description ?? "GitHub returned an incomplete device grant",
96
+ );
97
+ }
98
+ return {
99
+ deviceCode: raw.device_code,
100
+ userCode: raw.user_code,
101
+ verificationUri: raw.verification_uri,
102
+ expiresIn: raw.expires_in ?? 900,
103
+ interval: raw.interval ?? 5,
104
+ };
105
+ }
106
+
107
+ /**
108
+ * Poll once for the device-flow result. Returns null while the user has not
109
+ * finished authorizing (`authorization_pending` / `slow_down` — on
110
+ * `slow_down` wait the returned `retryAfter` seconds before the next poll).
111
+ * Throws {@link GithubAuthError} on terminal failures (denied, expired).
112
+ */
113
+ export async function pollDeviceToken(
114
+ app: GithubAppConfig,
115
+ deviceCode: string,
116
+ opts?: { fetch?: FetchLike; baseUrl?: string; now?: number },
117
+ ): Promise<{ tokens: GithubTokenSet } | { tokens: null; retryAfter: number }> {
118
+ const data = await postForm(
119
+ opts?.fetch ?? fetch,
120
+ `${opts?.baseUrl ?? GITHUB_BASE}/login/oauth/access_token`,
121
+ {
122
+ client_id: app.clientId,
123
+ device_code: deviceCode,
124
+ grant_type: "urn:ietf:params:oauth:grant-type:device_code",
125
+ },
126
+ );
127
+ if (data.error === "authorization_pending") {
128
+ return { tokens: null, retryAfter: 0 };
129
+ }
130
+ if (data.error === "slow_down") {
131
+ return { tokens: null, retryAfter: data.interval ?? 5 };
132
+ }
133
+ return { tokens: toTokenSet(data, opts?.now ?? Date.now()) };
134
+ }
135
+
136
+ /** Build the browser URL for the web (authorization-code) flow. */
137
+ export function buildAuthorizeUrl(
138
+ app: GithubAppConfig,
139
+ opts: { redirectUri: string; state: string; baseUrl?: string },
140
+ ): string {
141
+ const url = new URL(`${opts.baseUrl ?? GITHUB_BASE}/login/oauth/authorize`);
142
+ url.searchParams.set("client_id", app.clientId);
143
+ url.searchParams.set("redirect_uri", opts.redirectUri);
144
+ url.searchParams.set("state", opts.state);
145
+ return url.toString();
146
+ }
147
+
148
+ /**
149
+ * Exchange the authorization code from the web-flow callback for tokens.
150
+ * Server-side only: requires the app's client secret.
151
+ */
152
+ export async function exchangeCode(
153
+ app: GithubAppConfig,
154
+ args: { code: string; redirectUri?: string },
155
+ opts?: { fetch?: FetchLike; baseUrl?: string; now?: number },
156
+ ): Promise<GithubTokenSet> {
157
+ if (!app.clientSecret) {
158
+ throw new GithubAuthError(
159
+ "missing_client_secret",
160
+ "The web OAuth flow requires a client secret; use the device flow for public clients",
161
+ );
162
+ }
163
+ const data = await postForm(
164
+ opts?.fetch ?? fetch,
165
+ `${opts?.baseUrl ?? GITHUB_BASE}/login/oauth/access_token`,
166
+ {
167
+ client_id: app.clientId,
168
+ client_secret: app.clientSecret,
169
+ code: args.code,
170
+ ...(args.redirectUri ? { redirect_uri: args.redirectUri } : {}),
171
+ },
172
+ );
173
+ return toTokenSet(data, opts?.now ?? Date.now());
174
+ }
175
+
176
+ /**
177
+ * Refresh an expiring user token. Works with only the client id for
178
+ * device-flow apps; include the secret when the app has one.
179
+ */
180
+ export async function refreshAccessToken(
181
+ app: GithubAppConfig,
182
+ refreshToken: string,
183
+ opts?: {
184
+ fetch?: FetchLike;
185
+ baseUrl?: string;
186
+ now?: number;
187
+ signal?: AbortSignal;
188
+ },
189
+ ): Promise<GithubTokenSet> {
190
+ const data = await postForm(
191
+ opts?.fetch ?? fetch,
192
+ `${opts?.baseUrl ?? GITHUB_BASE}/login/oauth/access_token`,
193
+ {
194
+ client_id: app.clientId,
195
+ ...(app.clientSecret ? { client_secret: app.clientSecret } : {}),
196
+ grant_type: "refresh_token",
197
+ refresh_token: refreshToken,
198
+ },
199
+ opts?.signal,
200
+ );
201
+ return toTokenSet(data, opts?.now ?? Date.now());
202
+ }
203
+
204
+ /**
205
+ * Where users install the app / edit which repositories it can access.
206
+ * GitHub shows the picker and redirects into the existing installation when
207
+ * one already exists.
208
+ */
209
+ export function buildInstallationUrl(app: GithubAppConfig): string {
210
+ if (!app.appSlug) {
211
+ throw new GithubAuthError(
212
+ "missing_app_slug",
213
+ "GithubAppConfig.appSlug is required to build the installation URL",
214
+ );
215
+ }
216
+ return `https://github.com/apps/${app.appSlug}/installations/new`;
217
+ }
218
+
219
+ /** True when the token should be refreshed before use. */
220
+ export function isTokenStale(
221
+ tokens: Pick<GithubTokenSet, "expiresAt">,
222
+ now = Date.now(),
223
+ skewMs = 60_000,
224
+ ): boolean {
225
+ return tokens.expiresAt !== null && tokens.expiresAt - skewMs <= now;
226
+ }
227
+
228
+ /**
229
+ * Revoke a user access token (and its refresh token). Needs the app's client
230
+ * secret: GitHub authenticates this call with the OAuth client itself.
231
+ */
232
+ export async function revokeUserToken(args: {
233
+ app: GithubAppConfig;
234
+ accessToken: string;
235
+ fetch?: FetchLike;
236
+ /** REST API base; GitHub Enterprise Server uses `https://HOST/api/v3`. */
237
+ apiBaseUrl?: string;
238
+ }): Promise<void> {
239
+ if (!args.app.clientSecret) {
240
+ throw new GithubAuthError(
241
+ "missing_client_secret",
242
+ "Revoking a user token requires the app's client secret",
243
+ );
244
+ }
245
+ const base = (args.apiBaseUrl ?? "https://api.github.com").replace(
246
+ /\/+$/,
247
+ "",
248
+ );
249
+ const basic = Buffer.from(
250
+ `${args.app.clientId}:${args.app.clientSecret}`,
251
+ ).toString("base64");
252
+ const response = await (args.fetch ?? fetch)(
253
+ `${base}/applications/${encodeURIComponent(args.app.clientId)}/token`,
254
+ {
255
+ method: "DELETE",
256
+ headers: {
257
+ Accept: "application/vnd.github+json",
258
+ Authorization: `Basic ${basic}`,
259
+ "Content-Type": "application/json",
260
+ "X-GitHub-Api-Version": "2022-11-28",
261
+ },
262
+ body: JSON.stringify({ access_token: args.accessToken }),
263
+ },
264
+ );
265
+ // 404: the token was already revoked or had expired.
266
+ if (!response.ok && response.status !== 404) {
267
+ throw new GithubAuthError(
268
+ "http_error",
269
+ `GitHub token revocation returned ${response.status}`,
270
+ );
271
+ }
272
+ }
package/src/rest.ts ADDED
@@ -0,0 +1,170 @@
1
+ import type { FetchLike, GithubJson } from "./types.js";
2
+
3
+ const API_BASE = "https://api.github.com";
4
+ const DEFAULT_MAX_RESPONSE_BYTES = 1024 * 1024;
5
+
6
+ export type GithubRestMethod = "GET" | "POST" | "PUT" | "PATCH" | "DELETE";
7
+
8
+ export interface GithubRestRequest {
9
+ /** Installation or user access token. */
10
+ token: string;
11
+ method: GithubRestMethod;
12
+ /** Path below the API base, e.g. `/repos/octo/hello/pulls`. */
13
+ path: string;
14
+ query?: Readonly<Record<string, string>>;
15
+ body?: unknown;
16
+ /**
17
+ * A GitHub media type, e.g. `application/vnd.github.diff`. Default
18
+ * `application/vnd.github+json`.
19
+ */
20
+ accept?: string;
21
+ /** Byte offset into the response body, to read large bodies in ranges. */
22
+ offset?: number;
23
+ /** Largest slice of the body returned. Default 1 MiB. */
24
+ maxResponseBytes?: number;
25
+ /** REST API base; GitHub Enterprise Server uses `https://HOST/api/v3`. */
26
+ apiBaseUrl?: string;
27
+ fetch?: FetchLike;
28
+ signal?: AbortSignal;
29
+ }
30
+
31
+ export interface GithubRestResponse {
32
+ status: number;
33
+ contentType: string;
34
+ /** Parsed JSON when the whole body was returned; text otherwise. */
35
+ body: GithubJson;
36
+ location?: string;
37
+ /** Set when the body did not fit: read on from `nextOffset`. */
38
+ truncated?: true;
39
+ nextOffset?: number;
40
+ totalBytes: number;
41
+ }
42
+
43
+ /**
44
+ * One GitHub REST call on behalf of a brokered connection. The path must stay
45
+ * below the API base (no `..`, encoded separators, or query in the path),
46
+ * redirects are returned instead of followed so the token never travels
47
+ * elsewhere, and large bodies are returned in byte ranges.
48
+ */
49
+ export async function githubRestRequest(
50
+ request: GithubRestRequest,
51
+ ): Promise<GithubRestResponse> {
52
+ const target = githubRestUrl({
53
+ path: request.path,
54
+ query: request.query,
55
+ apiBaseUrl: request.apiBaseUrl,
56
+ });
57
+ const accept = request.accept ?? "application/vnd.github+json";
58
+ if (!/^application\/(vnd\.github[\w.+-]*|json)$/.test(accept)) {
59
+ throw new Error(`Unsupported media type '${accept}'`);
60
+ }
61
+ const offset = request.offset ?? 0;
62
+ if (!Number.isSafeInteger(offset) || offset < 0) {
63
+ throw new Error("offset must be a non-negative integer");
64
+ }
65
+ const hasBody = request.body !== undefined && request.method !== "GET";
66
+ const response = await (request.fetch ?? fetch)(target, {
67
+ method: request.method,
68
+ headers: {
69
+ Accept: accept,
70
+ Authorization: `Bearer ${request.token}`,
71
+ "X-GitHub-Api-Version": "2022-11-28",
72
+ ...(hasBody ? { "Content-Type": "application/json" } : {}),
73
+ },
74
+ redirect: "manual",
75
+ ...(request.signal ? { signal: request.signal } : {}),
76
+ ...(hasBody ? { body: JSON.stringify(request.body) } : {}),
77
+ });
78
+ const bytes = new Uint8Array(await response.arrayBuffer());
79
+ const maxBytes = request.maxResponseBytes ?? DEFAULT_MAX_RESPONSE_BYTES;
80
+ const end = utf8Boundary({
81
+ bytes,
82
+ start: offset,
83
+ end: Math.min(bytes.byteLength, offset + maxBytes),
84
+ });
85
+ const whole = offset === 0 && end === bytes.byteLength;
86
+ const text = new TextDecoder().decode(bytes.slice(offset, end));
87
+ const contentType = response.headers.get("content-type") ?? "";
88
+ const location = response.headers.get("location");
89
+ return {
90
+ status: response.status,
91
+ contentType,
92
+ body: whole && contentType.includes("json") ? parseJson(text) : text,
93
+ ...(location ? { location } : {}),
94
+ ...(end < bytes.byteLength
95
+ ? { truncated: true as const, nextOffset: end }
96
+ : {}),
97
+ totalBytes: bytes.byteLength,
98
+ };
99
+ }
100
+
101
+ /** Resolve a caller path against the API base, refusing anything outside it. */
102
+ export function githubRestUrl(args: {
103
+ path: string;
104
+ query?: Readonly<Record<string, string>>;
105
+ apiBaseUrl?: string;
106
+ }): string {
107
+ const base = new URL(args.apiBaseUrl ?? API_BASE);
108
+ const basePath = base.pathname.replace(/\/+$/, "");
109
+ const path = args.path.startsWith("/") ? args.path : `/${args.path}`;
110
+ if (
111
+ path.includes("..") ||
112
+ path.split("/").includes(".") ||
113
+ path.includes("\\") ||
114
+ path.includes("//") ||
115
+ /[?#]/.test(path) ||
116
+ /%(2e|2f|5c)/i.test(path)
117
+ ) {
118
+ throw new Error(
119
+ "Paths may not contain '.' or '..' segments, '//', '?', '#', backslashes, or encoded dots and slashes",
120
+ );
121
+ }
122
+ const target = new URL(`${basePath}${path}`, base.origin);
123
+ if (
124
+ target.origin !== base.origin ||
125
+ (basePath &&
126
+ target.pathname !== basePath &&
127
+ !target.pathname.startsWith(`${basePath}/`))
128
+ ) {
129
+ throw new Error("Requests must stay on the GitHub API");
130
+ }
131
+ for (const [key, value] of Object.entries(args.query ?? {})) {
132
+ target.searchParams.set(key, value);
133
+ }
134
+ return target.toString();
135
+ }
136
+
137
+ /**
138
+ * The repository a REST path addresses (`/repos/{owner}/{repo}/...`), so a
139
+ * minted token can be narrowed to it. Null for paths outside one repository.
140
+ */
141
+ export function repositoryFromRestPath(
142
+ path: string,
143
+ ): { owner: string; name: string } | null {
144
+ const match = /^\/?repos\/([\w.-]+)\/([\w.-]+)(?:\/|$)/.exec(path);
145
+ if (!match?.[1] || !match[2]) return null;
146
+ return { owner: match[1], name: match[2] };
147
+ }
148
+
149
+ /** Move a range end back so a slice never splits a UTF-8 character. */
150
+ function utf8Boundary(args: {
151
+ bytes: Uint8Array;
152
+ start: number;
153
+ end: number;
154
+ }): number {
155
+ if (args.end >= args.bytes.byteLength) return args.end;
156
+ for (let end = args.end; end > args.start; end--) {
157
+ // Continuation bytes look like 0b10xxxxxx.
158
+ if (((args.bytes[end] ?? 0) & 0xc0) !== 0x80) return end;
159
+ }
160
+ return args.end;
161
+ }
162
+
163
+ function parseJson(text: string): GithubJson {
164
+ try {
165
+ const parsed: GithubJson = JSON.parse(text);
166
+ return parsed;
167
+ } catch {
168
+ return text;
169
+ }
170
+ }