@effected/github 0.29.0 → 0.31.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.
@@ -0,0 +1,581 @@
1
+ import { API_VERSION_PATTERN, DEFAULT_API_VERSION } from "./internal/apiVersion.js";
2
+ import { unstubbed } from "./internal/unstubbed.js";
3
+ import { Clock, Context, DateTime, Duration, Effect, Layer, Option, Redacted, Schema } from "effect";
4
+ import { HttpRedaction } from "@effected/crypto";
5
+ import { Base64 } from "effect/encoding";
6
+
7
+ // src/GitHubUserAuth.ts
8
+ /**
9
+ * Which `GitHubUserAuth` operation a failure came from.
10
+ *
11
+ * @public
12
+ */
13
+ const GitHubUserAuthOperation = Schema.Literals([
14
+ "exchange",
15
+ "refresh",
16
+ "revokeGrant"
17
+ ]);
18
+ /**
19
+ * A user-to-server token pair that expires: what GitHub issues to a GitHub
20
+ * App with "Expire user authorization tokens" turned on, which is the default.
21
+ *
22
+ * @remarks
23
+ * Times are absolute instants, computed from GitHub's `expires_in` and
24
+ * `refresh_token_expires_in` against `Clock` when the reply arrived, the same
25
+ * way `InstallationToken.expiresAt` is.
26
+ *
27
+ * Encodable, like `InstallationToken`: `Schema.encodeUnknownEffect` over
28
+ * {@link (GitHubUserTokens:variable)} produces JSON with both tokens as plain
29
+ * strings and both times as ISO instants, which is how a caller persists a
30
+ * user's grant. Encrypting it at rest is the caller's job.
31
+ *
32
+ * @public
33
+ */
34
+ var ExpiringUserTokens = class extends Schema.Class("ExpiringUserTokens")({
35
+ /** The discriminant: these tokens expire, and the refresh token renews them. */
36
+ expiry: Schema.tag("expiring"),
37
+ /** The user access token. Decodes to `Redacted`, encodes back to the raw string. */
38
+ accessToken: Schema.RedactedFromValue(Schema.String),
39
+ /** GitHub's `token_type`, `bearer` in practice. */
40
+ tokenType: Schema.String,
41
+ /**
42
+ * GitHub's `scope`, as sent: a comma-separated list for an OAuth App and
43
+ * the empty string for a GitHub App, whose user tokens carry the app's
44
+ * permissions instead of scopes.
45
+ */
46
+ scope: Schema.String,
47
+ /** When GitHub stops accepting the access token — eight hours out by default. */
48
+ expiresAt: Schema.DateTimeUtcFromString,
49
+ /** The refresh token. Decodes to `Redacted`, encodes back to the raw string. */
50
+ refreshToken: Schema.RedactedFromValue(Schema.String),
51
+ /** When GitHub stops accepting the refresh token — six months out by default. */
52
+ refreshTokenExpiresAt: Schema.DateTimeUtcFromString
53
+ }) {
54
+ /**
55
+ * Whether the access token is spent, `skew` before its stated expiry.
56
+ *
57
+ * @remarks
58
+ * `skew` defaults to one minute, so a token is treated as spent slightly
59
+ * early rather than answering 401 mid-request.
60
+ */
61
+ isExpired(nowMillis, skew = DEFAULT_SKEW) {
62
+ return isSpent(DateTime.toEpochMillis(this.expiresAt), nowMillis, skew);
63
+ }
64
+ /**
65
+ * Whether the refresh token is spent, `skew` before its stated expiry. A
66
+ * spent refresh token cannot renew the grant: the user has to authorize
67
+ * again.
68
+ */
69
+ isRefreshExpired(nowMillis, skew = DEFAULT_SKEW) {
70
+ return isSpent(DateTime.toEpochMillis(this.refreshTokenExpiresAt), nowMillis, skew);
71
+ }
72
+ };
73
+ /**
74
+ * A user access token that does not expire: what GitHub issues to an OAuth
75
+ * App, or to a GitHub App with "Expire user authorization tokens" turned off.
76
+ * It carries no refresh token and no expiry.
77
+ *
78
+ * @public
79
+ */
80
+ var NonExpiringUserTokens = class extends Schema.Class("NonExpiringUserTokens")({
81
+ /** The discriminant: this token does not expire and cannot be refreshed. */
82
+ expiry: Schema.tag("non-expiring"),
83
+ /** The user access token. Decodes to `Redacted`, encodes back to the raw string. */
84
+ accessToken: Schema.RedactedFromValue(Schema.String),
85
+ /** GitHub's `token_type`, `bearer` in practice. */
86
+ tokenType: Schema.String,
87
+ /** GitHub's `scope`, as sent; see `ExpiringUserTokens.scope`. */
88
+ scope: Schema.String
89
+ }) {};
90
+ /**
91
+ * What a code exchange answers, discriminated by `expiry`: `expiring` carries
92
+ * a refresh token and both expiry instants, `non-expiring` carries neither.
93
+ *
94
+ * @remarks
95
+ * **Construct the variant classes, never the union.** The union's inherited
96
+ * `make` typechecks against both variants at once and reports a wrong field
97
+ * as a two-branch error; {@link ExpiringUserTokens}`.make` and
98
+ * {@link NonExpiringUserTokens}`.make` fill `expiry` themselves. The union is
99
+ * a `Schema` so a stored grant decodes back into the right variant.
100
+ *
101
+ * @public
102
+ */
103
+ const GitHubUserTokens = Schema.Union([ExpiringUserTokens, NonExpiringUserTokens]);
104
+ /**
105
+ * GitHub refused the call, and repeating it will not change the answer.
106
+ *
107
+ * @remarks
108
+ * `remedy` says what has to change, and it is the field to branch on:
109
+ *
110
+ * - `"reconnect"` — the user's side is dead: the authorization code was
111
+ * wrong, expired or already used (`bad_verification_code`), the refresh
112
+ * token was revoked or expired (`bad_refresh_token`), or the grant is
113
+ * already gone. Send the user through the authorization flow again, and
114
+ * drop the tokens you hold for them.
115
+ * - `"reconfigure"` — the app's side is wrong: its client id or secret
116
+ * (`incorrect_client_credentials`), its callback URL
117
+ * (`redirect_uri_mismatch`), refresh tokens being turned off for it
118
+ * (`unsupported_grant_type`), or a code GitHub sent that this package does
119
+ * not know. Nothing about the user's grant is learned, and reconnecting the
120
+ * user does not help; an operator has to fix the app. A 401, 403 or 404
121
+ * with no `error` code lands here too — but never a 403 whose message
122
+ * names a rate limit (or GitHub's older "abuse detection" wording), which
123
+ * is a {@link GitHubUserAuthTemporary}.
124
+ *
125
+ * **Never wipe a user's tokens on `GitHubUserAuthFinal` alone.** The obvious
126
+ * handler, `Effect.catchTag("GitHubUserAuthFinal", () => forgetUser(id))`,
127
+ * typechecks, runs and reports success, and on a rotated or mistyped client
128
+ * secret it signs every user out at once, because every refresh then answers
129
+ * `incorrect_client_credentials`. silk-app's hand-rolled flow carried this
130
+ * exact rule as a comment before the kit had this error. Match on
131
+ * `remedy === "reconnect"`.
132
+ *
133
+ * GitHub answers the token endpoint with HTTP 200 and an `error` body when it
134
+ * refuses a code or a refresh token, so `status` is usually 200. `code` is
135
+ * GitHub's `error` code when it sent one (an unrecognisable one reads
136
+ * `unknown_error`), and `http_<status>` when GitHub answered a non-success
137
+ * status with no error code. `description` is GitHub's `error_description`
138
+ * (or the REST `message`), with any credential this call carried replaced by
139
+ * `REDACTED`.
140
+ *
141
+ * @public
142
+ */
143
+ var GitHubUserAuthFinal = class extends Schema.TaggedError()("GitHubUserAuthFinal", {
144
+ /** The operation GitHub refused. */
145
+ operation: GitHubUserAuthOperation,
146
+ /** What has to change before the call can succeed. */
147
+ remedy: Schema.Literals(["reconnect", "reconfigure"]),
148
+ /** GitHub's `error` code, or `http_<status>`. */
149
+ code: Schema.String,
150
+ /** GitHub's own explanation, scrubbed of this call's credentials. */
151
+ description: Schema.optionalKey(Schema.String),
152
+ /** The HTTP status GitHub answered with. */
153
+ status: Schema.Int
154
+ }) {
155
+ get message() {
156
+ return `GitHub user auth ${this.operation} refused (${this.code}, HTTP ${this.status})${this.description === void 0 ? "" : `: ${this.description}`} — ${this.remedy === "reconnect" ? "the user must authorize again" : "the app's configuration must be fixed"}`;
157
+ }
158
+ };
159
+ /**
160
+ * The call did not get an answer GitHub meant: try it again later.
161
+ *
162
+ * @remarks
163
+ * `kind` is the reason:
164
+ *
165
+ * - `"network"` — `fetch` threw, or the body could not be read;
166
+ * - `"timeout"` — no complete answer within the layer's `timeout`;
167
+ * - `"status"` — GitHub answered 5xx, 429 or 408, or a 403 whose message
168
+ * names a rate limit or "abuse detection" (GitHub's primary REST rate
169
+ * limit answers 403, and its secondary limits answer 403 or 429);
170
+ * - `"malformed"` — a success status whose body is not a token reply, or a
171
+ * refresh that answered a token with no refresh token.
172
+ *
173
+ * None of these is a refusal of the user's grant, so a caller keeps the
174
+ * tokens it holds and retries later.
175
+ *
176
+ * One case does not leave the grant as it was. GitHub refresh tokens are
177
+ * single-use and rotate when a refresh succeeds, so a refresh GitHub
178
+ * processed has already spent the refresh token the caller sent: a
179
+ * `"malformed"` with a 2xx `status` (GitHub answered, the reply was
180
+ * rejected), or a `"network"` or `"timeout"` that ended after the request
181
+ * reached GitHub. Retrying such a refresh with the same refresh token answers
182
+ * `bad_refresh_token`, a {@link GitHubUserAuthFinal} with
183
+ * `remedy: "reconnect"`. That is the expected consequence, not a second
184
+ * fault: the user authorizes again.
185
+ *
186
+ * `cause` is a copy of what `fetch` threw, rebuilt with its message, stack
187
+ * and primitive fields scrubbed of this call's credentials, never the
188
+ * original: a custom `fetch` can put the request (and so the client secret)
189
+ * in its error.
190
+ *
191
+ * @public
192
+ */
193
+ var GitHubUserAuthTemporary = class extends Schema.TaggedError()("GitHubUserAuthTemporary", {
194
+ /** The operation that did not complete. */
195
+ operation: GitHubUserAuthOperation,
196
+ /** Why it did not complete. */
197
+ kind: Schema.Literals([
198
+ "network",
199
+ "timeout",
200
+ "status",
201
+ "malformed"
202
+ ]),
203
+ /** The HTTP status, when a response arrived. */
204
+ status: Schema.optionalKey(Schema.Int),
205
+ /** A credential-free copy of what `fetch` threw, for `network`. */
206
+ cause: Schema.optionalKey(Schema.Defect())
207
+ }) {
208
+ get message() {
209
+ const status = this.status === void 0 ? "" : ` (HTTP ${this.status})`;
210
+ const what = this.kind === "network" ? "the request could not be sent or its reply read" : this.kind === "timeout" ? "GitHub did not answer in time" : this.kind === "status" ? "GitHub answered with a server error or a rate limit" : "GitHub answered with a body that is not a token reply";
211
+ return `GitHub user auth ${this.operation} failed temporarily${status}: ${what}`;
212
+ }
213
+ };
214
+ /**
215
+ * The OAuth web flow a GitHub App (or an OAuth App) uses to act as a user:
216
+ * PKCE code exchange, refresh, and grant revoke.
217
+ *
218
+ * @remarks
219
+ * None of these calls go through `GitHubClient`: the token endpoint lives on
220
+ * the web host rather than the REST host, and the revoke authenticates as the
221
+ * app's OAuth client with HTTP Basic rather than with a bearer token. So the
222
+ * service speaks to `fetch` directly, and this module imports neither octokit
223
+ * nor the JWT signer — a Worker that only signs users in links neither.
224
+ *
225
+ * Every failure is one of two errors, and the split is the point:
226
+ * {@link GitHubUserAuthFinal} when GitHub refused (read its `remedy` before
227
+ * dropping anything), {@link GitHubUserAuthTemporary} when no real answer
228
+ * arrived. GitHub answers a refused code or refresh token with HTTP 200 and an
229
+ * `error` body, which is read as the refusal it is.
230
+ *
231
+ * The client secret, the code, the verifier and both tokens appear in no
232
+ * error message, no span annotation and no kept cause.
233
+ *
234
+ * @example
235
+ * ```ts
236
+ * import { GitHubUserAuth } from "@effected/github";
237
+ * import { Effect, Redacted } from "effect";
238
+ *
239
+ * const UserAuth = GitHubUserAuth.layer({
240
+ * clientId: "Iv23liExample",
241
+ * clientSecret: Redacted.make("app-client-secret"),
242
+ * });
243
+ *
244
+ * const signIn = (code: string, codeVerifier: string) =>
245
+ * Effect.gen(function* () {
246
+ * const auth = yield* GitHubUserAuth;
247
+ * return yield* auth.exchange({ code, codeVerifier, redirectUri: "https://app.example/callback" });
248
+ * });
249
+ *
250
+ * Effect.runPromise(signIn("code-from-query", "verifier").pipe(Effect.provide(UserAuth)));
251
+ * ```
252
+ *
253
+ * @public
254
+ */
255
+ var GitHubUserAuth = class GitHubUserAuth extends Context.Service()("@effected/github/GitHubUserAuth") {
256
+ /**
257
+ * The live service over `fetch`.
258
+ *
259
+ * @remarks
260
+ * Parameterized, so **bind the result to a `const`** and reuse it: each
261
+ * call mints a fresh layer, and layers are memoized by reference.
262
+ *
263
+ * Bad wiring — an empty client id, a URL that does not parse or is not
264
+ * `http(s)`, an api-version that is not `YYYY-MM-DD`, a timeout that is not
265
+ * finite and positive — dies while the layer builds, with a defect naming
266
+ * the option.
267
+ */
268
+ static layer = (options) => Layer.effect(GitHubUserAuth, makeUserAuth(options));
269
+ /** An in-memory double; an unstubbed member dies when run, naming itself. */
270
+ static makeTest = (overrides = {}) => ({
271
+ exchange: overrides.exchange ?? (() => dies("exchange")),
272
+ refresh: overrides.refresh ?? (() => dies("refresh")),
273
+ revokeGrant: overrides.revokeGrant ?? (() => dies("revokeGrant"))
274
+ });
275
+ /** {@link GitHubUserAuth.makeTest} behind a `Layer`. */
276
+ static layerTest = (overrides = {}) => Layer.succeed(GitHubUserAuth, GitHubUserAuth.makeTest(overrides));
277
+ };
278
+ const dies = unstubbed("GitHubUserAuth.makeTest");
279
+ const DEFAULT_TOKEN_URL = "https://github.com/login/oauth/access_token";
280
+ const DEFAULT_API_URL = "https://api.github.com";
281
+ const DEFAULT_USER_AGENT = "@effected/github";
282
+ const DEFAULT_TIMEOUT = Duration.seconds(10);
283
+ const DEFAULT_SKEW = Duration.seconds(60);
284
+ const REDACTED = "REDACTED";
285
+ const MAX_DESCRIPTION = 500;
286
+ const MAX_CAUSE_DEPTH = 4;
287
+ const isSpent = (expiresAtMillis, nowMillis, skew) => expiresAtMillis - Duration.toMillis(skew) <= nowMillis;
288
+ /** GitHub `error` codes meaning the user's code, refresh token or grant is dead. */
289
+ const RECONNECT_CODES = /* @__PURE__ */ new Set([
290
+ "bad_verification_code",
291
+ "bad_refresh_token",
292
+ "expired_token",
293
+ "invalid_grant",
294
+ "access_denied",
295
+ "unverified_user_email"
296
+ ]);
297
+ const ERROR_CODE = /^[a-z0-9_]{1,64}$/;
298
+ /** GitHub's prefixed token shapes (`ghu_`, `ghr_`, `gho_`, `ghp_`, `ghs_`, `github_pat_`), whoever sent them. */
299
+ const GITHUB_TOKEN = /\b(?:gh[pousr]_[A-Za-z0-9]{16,}|github_pat_[A-Za-z0-9_]{16,})/g;
300
+ /**
301
+ * Replace every credential this call carried, then any GitHub token shape,
302
+ * then anything else that reads as a credential.
303
+ */
304
+ const scrub = (text, secrets) => {
305
+ let out = text;
306
+ for (const secret of secrets) if (secret.length >= 4) out = out.split(secret).join(REDACTED);
307
+ return HttpRedaction.text(out.replace(GITHUB_TOKEN, REDACTED));
308
+ };
309
+ /** A copy of a thrown value with nothing a credential could hide in left unscrubbed. */
310
+ const scrubCause = (thrown, secrets, depth = 0) => {
311
+ if (!(thrown instanceof Error)) return new Error(scrub(typeof thrown === "string" ? thrown : Object.prototype.toString.call(thrown), secrets));
312
+ const copy = new Error(scrub(thrown.message, secrets));
313
+ copy.name = scrub(thrown.name, secrets);
314
+ if (thrown.stack !== void 0) copy.stack = scrub(thrown.stack, secrets);
315
+ for (const [key, value] of Object.entries(thrown)) {
316
+ if (key === "message" || key === "stack" || key === "cause" || key === "name") continue;
317
+ const kept = typeof value === "string" ? scrub(value, secrets) : typeof value === "number" || typeof value === "boolean" ? value : void 0;
318
+ if (kept !== void 0) Object.defineProperty(copy, key, {
319
+ value: kept,
320
+ enumerable: true,
321
+ writable: true,
322
+ configurable: true
323
+ });
324
+ }
325
+ if (thrown.cause !== void 0 && depth < MAX_CAUSE_DEPTH) Object.defineProperty(copy, "cause", {
326
+ value: scrubCause(thrown.cause, secrets, depth + 1),
327
+ enumerable: false,
328
+ writable: true,
329
+ configurable: true
330
+ });
331
+ return copy;
332
+ };
333
+ /** `JSON.parse` that answers `undefined` rather than throwing. */
334
+ const parseJson = (text) => {
335
+ try {
336
+ return JSON.parse(text);
337
+ } catch {
338
+ return;
339
+ }
340
+ };
341
+ const ErrorReply = Schema.Struct({
342
+ error: Schema.String,
343
+ error_description: Schema.optionalKey(Schema.String)
344
+ });
345
+ const RestMessage = Schema.Struct({ message: Schema.String });
346
+ const TokenReply = Schema.Struct({
347
+ access_token: Schema.NonEmptyString,
348
+ token_type: Schema.optionalKey(Schema.String),
349
+ scope: Schema.optionalKey(Schema.String),
350
+ expires_in: Schema.optionalKey(Schema.Number),
351
+ refresh_token: Schema.optionalKey(Schema.String),
352
+ refresh_token_expires_in: Schema.optionalKey(Schema.Number)
353
+ });
354
+ const decodeErrorReply = Schema.decodeUnknownOption(ErrorReply);
355
+ const decodeRestMessage = Schema.decodeUnknownOption(RestMessage);
356
+ const decodeTokenReply = Schema.decodeUnknownOption(TokenReply);
357
+ /** 5xx, a rate limit or a request timeout: GitHub meant "later", not "no". */
358
+ const isRetryableStatus = (status) => status >= 500 || status === 429 || status === 408;
359
+ const isSuccess = (status) => status >= 200 && status < 300;
360
+ /**
361
+ * GitHub's rate-limit wording: "rate limit" in its current bodies, "abuse
362
+ * detection" in the older secondary-limit body ("You have triggered an abuse
363
+ * detection mechanism …"). The match follows GitHub's English wording; a
364
+ * reworded body falls back to the plain 403 classification.
365
+ */
366
+ const RATE_LIMIT_MESSAGE = /rate limit|abuse detection/i;
367
+ /**
368
+ * A 403 whose decoded REST `message` names a rate limit. GitHub's primary
369
+ * REST rate limit answers 403, and its secondary limits answer 403 or 429;
370
+ * the reply's headers are not kept, so the body's message ("API rate limit
371
+ * exceeded for …", "You have exceeded a secondary rate limit …") is what tells
372
+ * it from a 403 refusal of the app's credentials. Takes the already-decoded
373
+ * message so a classifier reads the body through one decode.
374
+ */
375
+ const isRateLimited403 = (status, message) => status === 403 && Option.isSome(message) && RATE_LIMIT_MESSAGE.test(message.value.message);
376
+ const final = (operation, status, code, remedy, description, secrets) => new GitHubUserAuthFinal({
377
+ operation,
378
+ remedy,
379
+ code,
380
+ status,
381
+ ...description === void 0 ? {} : { description: scrub(description, secrets).slice(0, MAX_DESCRIPTION) }
382
+ });
383
+ const temporary = (operation, kind, extra = {}) => new GitHubUserAuthTemporary({
384
+ operation,
385
+ kind,
386
+ ...extra
387
+ });
388
+ /**
389
+ * What a token-endpoint reply means: the token fields, or the failure.
390
+ *
391
+ * @remarks
392
+ * The order is load-bearing. A retryable status wins over its body (a 503
393
+ * page is never a refusal); an `error` body wins over the status (GitHub
394
+ * refuses with 200); a 403 with no `error` whose message names a rate limit
395
+ * is temporary; any other non-success status with no `error` is a refusal of
396
+ * the app's request; only then is a success read as tokens.
397
+ */
398
+ const classifyTokenReply = (operation, status, text, secrets) => {
399
+ if (isRetryableStatus(status)) return temporary(operation, "status", { status });
400
+ const json = parseJson(text);
401
+ const refusal = decodeErrorReply(json);
402
+ if (Option.isSome(refusal)) {
403
+ const raw = refusal.value.error;
404
+ const code = ERROR_CODE.test(raw) ? raw : "unknown_error";
405
+ const remedy = RECONNECT_CODES.has(code) ? "reconnect" : "reconfigure";
406
+ return final(operation, status, code, remedy, refusal.value.error_description, secrets);
407
+ }
408
+ if (isRateLimited403(status, decodeRestMessage(json))) return temporary(operation, "status", { status });
409
+ if (!isSuccess(status)) return final(operation, status, `http_${status}`, "reconfigure", void 0, secrets);
410
+ const reply = decodeTokenReply(json);
411
+ return Option.isSome(reply) ? reply.value : temporary(operation, "malformed", { status });
412
+ };
413
+ const isPositiveInteger = (value) => value !== void 0 && Number.isInteger(value) && value > 0;
414
+ /** The tokens a reply carries at `nowMillis`, or `undefined` when its expiring fields are partial or invalid. */
415
+ const toTokens = (reply, nowMillis) => {
416
+ const base = {
417
+ accessToken: Redacted.make(reply.access_token),
418
+ tokenType: reply.token_type ?? "bearer",
419
+ scope: reply.scope ?? ""
420
+ };
421
+ const { expires_in, refresh_token, refresh_token_expires_in } = reply;
422
+ if (expires_in === void 0 && refresh_token === void 0 && refresh_token_expires_in === void 0) return NonExpiringUserTokens.make(base);
423
+ if (!isPositiveInteger(expires_in) || !isPositiveInteger(refresh_token_expires_in) || refresh_token === void 0 || refresh_token.length === 0) return;
424
+ return ExpiringUserTokens.make({
425
+ ...base,
426
+ expiresAt: DateTime.makeUnsafe(nowMillis + expires_in * 1e3),
427
+ refreshToken: Redacted.make(refresh_token),
428
+ refreshTokenExpiresAt: DateTime.makeUnsafe(nowMillis + refresh_token_expires_in * 1e3)
429
+ });
430
+ };
431
+ /**
432
+ * What a grant-revoke reply means.
433
+ *
434
+ * @remarks
435
+ * 204 is success. 422 is GitHub's documented answer for an access token that
436
+ * is not a live token of this app, so the grant is already gone. 401, 403 and
437
+ * 404 are what GitHub answers a wrong client id or secret with — except a 403
438
+ * whose message names a rate limit, which is GitHub's primary (or a
439
+ * secondary) rate limit and so temporary.
440
+ *
441
+ * GitHub documents 422 as "Validation failed, or the endpoint has been
442
+ * spammed", so a 422 can also be an abuse refusal of a grant that still
443
+ * exists. It maps to `reconnect` all the same: a caller revoking is already
444
+ * discarding the grant on its side, and the mapping has not been checked
445
+ * against a live spam refusal.
446
+ */
447
+ const classifyRevokeReply = (status, text, secrets) => {
448
+ if (isSuccess(status)) return void 0;
449
+ if (isRetryableStatus(status)) return temporary("revokeGrant", "status", { status });
450
+ const message = decodeRestMessage(parseJson(text));
451
+ if (isRateLimited403(status, message)) return temporary("revokeGrant", "status", { status });
452
+ const description = Option.isSome(message) ? message.value.message : void 0;
453
+ return status === 422 ? final("revokeGrant", status, "validation_failed", "reconnect", description, secrets) : final("revokeGrant", status, `http_${status}`, "reconfigure", description, secrets);
454
+ };
455
+ const wiring = (message) => Effect.die(/* @__PURE__ */ new Error(`GitHubUserAuth: ${message}`));
456
+ const validUrl = (name, value) => {
457
+ let parsed;
458
+ try {
459
+ parsed = new URL(value);
460
+ } catch {
461
+ return wiring(`the ${name} option must be an absolute URL, got ${JSON.stringify(value)}`);
462
+ }
463
+ return parsed.protocol === "https:" || parsed.protocol === "http:" ? Effect.succeed(trimTrailingSlashes(value)) : wiring(`the ${name} option must be an http(s) URL, got ${JSON.stringify(value)}`);
464
+ };
465
+ /** A linear trim: a `/+$` regex backtracks quadratically on a long run of slashes. */
466
+ const trimTrailingSlashes = (value) => {
467
+ let end = value.length;
468
+ while (end > 0 && value[end - 1] === "/") end--;
469
+ return value.slice(0, end);
470
+ };
471
+ const makeUserAuth = (options) => Effect.gen(function* () {
472
+ if (options.clientId.length === 0) return yield* wiring("the clientId option must not be empty");
473
+ const tokenUrl = yield* validUrl("tokenUrl", options.tokenUrl ?? DEFAULT_TOKEN_URL);
474
+ const apiUrl = yield* validUrl("apiUrl", options.apiUrl ?? DEFAULT_API_URL);
475
+ const apiVersion = options.apiVersion ?? "2026-03-10";
476
+ if (!API_VERSION_PATTERN.test(apiVersion)) return yield* wiring(`the apiVersion option must be a calendar version like "${DEFAULT_API_VERSION}" (YYYY-MM-DD), got ${JSON.stringify(apiVersion)}`);
477
+ const timeout = options.timeout === void 0 ? Option.some(DEFAULT_TIMEOUT) : Duration.fromInput(options.timeout);
478
+ if (Option.isNone(timeout) || !Duration.isFinite(timeout.value) || Duration.toMillis(timeout.value) <= 0) return yield* wiring("the timeout option must be a finite, positive duration");
479
+ const ceiling = timeout.value;
480
+ const { clientId, clientSecret } = options;
481
+ const userAgent = options.userAgent ?? DEFAULT_USER_AGENT;
482
+ const doFetch = options.fetch ?? ((input, init) => globalThis.fetch(input, init));
483
+ const send = (operation, url, init, secrets) => Effect.gen(function* () {
484
+ let status;
485
+ const reply = yield* Effect.tryPromise({
486
+ try: async (signal) => {
487
+ const response = await doFetch(url, {
488
+ ...init,
489
+ signal
490
+ });
491
+ status = response.status;
492
+ return {
493
+ status: response.status,
494
+ text: await response.text()
495
+ };
496
+ },
497
+ catch: (thrown) => temporary(operation, "network", {
498
+ ...status === void 0 ? {} : { status },
499
+ cause: scrubCause(thrown, secrets)
500
+ })
501
+ });
502
+ yield* Effect.annotateCurrentSpan({ status: reply.status });
503
+ return reply;
504
+ }).pipe(Effect.timeoutOrElse({
505
+ duration: ceiling,
506
+ orElse: () => Effect.fail(temporary(operation, "timeout"))
507
+ }));
508
+ const postToken = (operation, fields, secrets) => send(operation, tokenUrl, {
509
+ method: "POST",
510
+ headers: {
511
+ accept: "application/json",
512
+ "content-type": "application/x-www-form-urlencoded",
513
+ "user-agent": userAgent
514
+ },
515
+ body: new URLSearchParams(fields).toString()
516
+ }, secrets).pipe(Effect.flatMap((reply) => {
517
+ const outcome = classifyTokenReply(operation, reply.status, reply.text, secrets);
518
+ return outcome instanceof GitHubUserAuthFinal || outcome instanceof GitHubUserAuthTemporary ? Effect.fail(outcome) : Effect.succeed(outcome);
519
+ }));
520
+ return {
521
+ exchange: Effect.fn("GitHubUserAuth.exchange")(function* (request) {
522
+ const secret = Redacted.value(clientSecret);
523
+ const secrets = [
524
+ secret,
525
+ request.code,
526
+ ...request.codeVerifier === void 0 ? [] : [request.codeVerifier]
527
+ ];
528
+ const reply = yield* postToken("exchange", {
529
+ client_id: clientId,
530
+ client_secret: secret,
531
+ code: request.code,
532
+ ...request.codeVerifier === void 0 ? {} : { code_verifier: request.codeVerifier },
533
+ ...request.redirectUri === void 0 ? {} : { redirect_uri: request.redirectUri }
534
+ }, secrets);
535
+ const tokens = toTokens(reply, yield* Clock.currentTimeMillis);
536
+ if (tokens === void 0) return yield* temporary("exchange", "malformed", { status: 200 });
537
+ return tokens;
538
+ }),
539
+ refresh: Effect.fn("GitHubUserAuth.refresh")(function* (request) {
540
+ const secret = Redacted.value(clientSecret);
541
+ const refreshToken = Redacted.value(request.refreshToken);
542
+ const reply = yield* postToken("refresh", {
543
+ client_id: clientId,
544
+ client_secret: secret,
545
+ grant_type: "refresh_token",
546
+ refresh_token: refreshToken
547
+ }, [secret, refreshToken]);
548
+ const tokens = toTokens(reply, yield* Clock.currentTimeMillis);
549
+ if (tokens === void 0 || tokens.expiry !== "expiring") return yield* temporary("refresh", "malformed", { status: 200 });
550
+ return tokens;
551
+ }),
552
+ revokeGrant: Effect.fn("GitHubUserAuth.revokeGrant")(function* (request) {
553
+ const secret = Redacted.value(clientSecret);
554
+ const accessToken = Redacted.value(request.accessToken);
555
+ const basic = Base64.encode(`${clientId}:${secret}`);
556
+ const reply = yield* send("revokeGrant", `${apiUrl}/applications/${encodeURIComponent(clientId)}/grant`, {
557
+ method: "DELETE",
558
+ headers: {
559
+ authorization: `Basic ${basic}`,
560
+ accept: "application/vnd.github+json",
561
+ "content-type": "application/json",
562
+ "x-github-api-version": apiVersion,
563
+ "user-agent": userAgent
564
+ },
565
+ body: JSON.stringify({ access_token: accessToken })
566
+ }, [
567
+ secret,
568
+ accessToken,
569
+ basic
570
+ ]);
571
+ const failure = classifyRevokeReply(reply.status, reply.text, [
572
+ secret,
573
+ accessToken,
574
+ basic
575
+ ]);
576
+ if (failure !== void 0) return yield* Effect.fail(failure);
577
+ })
578
+ };
579
+ });
580
+
581
+ export { ExpiringUserTokens, GitHubUserAuth, GitHubUserAuthFinal, GitHubUserAuthOperation, GitHubUserAuthTemporary, GitHubUserTokens, NonExpiringUserTokens };
package/GraphQL.js CHANGED
@@ -12,7 +12,17 @@ var GraphQLErrorEntry = class extends Schema.Class("GraphQLErrorEntry")({
12
12
  /** GitHub's prose. */
13
13
  message: Schema.String,
14
14
  /** GitHub's own classification, e.g. `"NOT_FOUND"` or `"FORBIDDEN"`. */
15
- type: Schema.optionalKey(Schema.String)
15
+ type: Schema.optionalKey(Schema.String),
16
+ /**
17
+ * Where in the response the entry applies: field names (aliases, when the
18
+ * document aliases) and list indexes, outermost first.
19
+ *
20
+ * @remarks
21
+ * This is what tells a batched document which aliased lookup GitHub could
22
+ * not resolve: a missing pull request in a batch reports
23
+ * `["repo__0", "pull__42"]`, a missing repository `["repo__0"]`.
24
+ */
25
+ path: Schema.optionalKey(Schema.Array(Schema.Union([Schema.String, Schema.Number])))
16
26
  }) {};
17
27
  /**
18
28
  * A GraphQL call failed.
@@ -111,9 +121,11 @@ const readEntries = (value) => {
111
121
  if (record === void 0) continue;
112
122
  const message = typeof record.message === "string" ? record.message : String(raw);
113
123
  const type = typeof record.type === "string" ? record.type : void 0;
124
+ const path = Array.isArray(record.path) ? record.path.filter((step) => typeof step === "string" || typeof step === "number") : void 0;
114
125
  entries.push(GraphQLErrorEntry.make({
115
126
  message,
116
- ...type !== void 0 ? { type } : {}
127
+ ...type !== void 0 ? { type } : {},
128
+ ...path !== void 0 ? { path } : {}
117
129
  }));
118
130
  }
119
131
  return entries;
package/README.md CHANGED
@@ -227,9 +227,40 @@ const AppClient = GitHubApp.clientLayer({
227
227
 
228
228
  Only `GitHubApp` and its statics import the JWT signer — a consumer authenticating with a plain token never reaches it.
229
229
 
230
+ ## Acting as a user: the OAuth web flow
231
+
232
+ `GitHubUserAuth` runs the OAuth web flow a GitHub App (or an OAuth App) uses to act as a user: `exchange` trades the code GitHub redirected back with, and its PKCE verifier, for the user's tokens; `refresh` renews an expiring grant; `revokeGrant` deletes the user's whole grant with HTTP Basic client authentication. It speaks to `fetch` directly, never through `GitHubClient`, so a Worker that only signs users in links neither octokit nor the JWT signer:
233
+
234
+ ```ts
235
+ import { GitHubUserAuth } from "@effected/github";
236
+ import { Effect, Redacted } from "effect";
237
+
238
+ // bind once — layers memoize by reference
239
+ const UserAuth = GitHubUserAuth.layer({
240
+ clientId: "Iv23liExample",
241
+ clientSecret: Redacted.make(process.env.GITHUB_CLIENT_SECRET as string),
242
+ });
243
+
244
+ const renew = (refreshToken: Redacted.Redacted<string>) =>
245
+ Effect.gen(function* () {
246
+ const auth = yield* GitHubUserAuth;
247
+ return yield* auth.refresh({ refreshToken });
248
+ }).pipe(
249
+ // "reconnect": the user's grant is dead; "reconfigure": the app's secret or settings
250
+ // are wrong, so keep the tokens and let it fail on to an operator
251
+ Effect.catchTag("GitHubUserAuthFinal", (error) =>
252
+ error.remedy === "reconnect" ? Effect.succeed("sign-in-again" as const) : Effect.fail(error),
253
+ ),
254
+ );
255
+ ```
256
+
257
+ `exchange` answers `GitHubUserTokens`: `ExpiringUserTokens` (access token, refresh token, and the instants both expire, from `Clock`) or `NonExpiringUserTokens` when the app does not expire user tokens; `refresh` always answers the expiring pair, and GitHub rotates the refresh token on every refresh. Both are encodable, with the tokens as plain strings and the times as ISO instants.
258
+
259
+ Every failure is `GitHubUserAuthFinal` (GitHub refused; its `code`, `description` and `status` are kept) or `GitHubUserAuthTemporary` (network, timeout, 5xx or 429, or a body that is not a token reply — retry later and keep the tokens you hold). One temporary failure has already spent the refresh token: GitHub rotates it on every refresh it processes, so a refresh that failed after reaching GitHub (a 2xx `malformed`, or a `network` or `timeout` that ended mid-reply) answers `bad_refresh_token` when retried, and the user signs in again. GitHub refuses a bad code or refresh token with HTTP 200 and an `error` body, which is read as the refusal it is. **Branch on `remedy`, never on the tag alone:** `incorrect_client_credentials` is final too, and a handler that drops every user's tokens on any `GitHubUserAuthFinal` signs everyone out the moment the client secret is rotated. The client secret, the code, the verifier and the tokens appear in no error message and no kept cause. `tokenUrl`, `apiUrl`, `apiVersion`, `userAgent`, `timeout` (ten seconds) and `fetch` are options, for GitHub Enterprise Server, Workers and tests.
260
+
230
261
  ## Errors
231
262
 
232
- `GitHubError` covers REST, `GitHubGraphQLError` covers GraphQL, `GitHubAppError` covers app authentication, and `TokenPermissions` produces its own `TokenPermissionError` — four kinds, not one per resource:
263
+ `GitHubError` covers REST, `GitHubGraphQLError` covers GraphQL, `GitHubAppError` covers app authentication, `GitHubUserAuthFinal` / `GitHubUserAuthTemporary` cover the OAuth user flow, and `TokenPermissions` produces its own `TokenPermissionError` — five kinds, not one per resource:
233
264
 
234
265
  ```ts
235
266
  import { GitHubError } from "@effected/github";
@@ -304,6 +335,7 @@ const TestClient = GitHubClient.layerFixture(fixtures);
304
335
  - `GitHubError` / `GitHubGraphQLError` — one error per transport, `kind`-routed with `hasKind` for `Effect.catchIf`; a REST 422's validation entries ride on `validation`, matched with `hasValidationCode`.
305
336
  - `RetryPolicy` — the client's one retry policy: full-jitter backoff, server-advised delays honored up to a ceiling.
306
337
  - `GitHubApp` — App JWT signing, installation token minting/revocation, app and installation identity, and `clientLayer` for an App-authenticated `GitHubClient`.
338
+ - `GitHubUserAuth` — the OAuth web flow for acting as a user: PKCE code exchange, refresh, and grant revoke over a bare `fetch`, with failures split into final (`remedy: "reconnect"` or `"reconfigure"`) and temporary.
307
339
  - `GitBranch` / `GitTag` — Git Database API refs, with `upsert` collapsing the create-or-reset dance to one call and `GitTag.latestSemver` picking the newest version-shaped tag in one pass.
308
340
  - `CheckRun` — `withCheckRun` concludes on every exit path; `CheckRunOutput.truncated()` cuts rendered output to GitHub's byte limits.
309
341
  - `PullRequest` / `PullRequestComment` — upserts for both, `listFiles` answering with the same full `CommitFile` records a commit read returns, `headSha`/`baseSha` on `PullRequestInfo`, plus `CommentMarker` for finding a sticky comment again. `PullRequestInfo.mergeCommitSha` is read from GraphQL `mergeCommit.oid` for merged pull requests only, because the REST object no longer carries it: `get`, `update` and `upsert` always fill it, while `list` and `listAssociatedWithCommit` fill it only with `mergeCommits: true` (one GraphQL call per 100 merged pull requests).