@effected/github 0.29.0 → 0.30.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.
package/GitHubClient.js CHANGED
@@ -1,7 +1,8 @@
1
1
  import { GitHubError } from "./GitHubError.js";
2
2
  import { GitHubGraphQLError } from "./GraphQL.js";
3
+ import { API_VERSION_PATTERN, DEFAULT_API_VERSION } from "./internal/apiVersion.js";
3
4
  import { rawRequestRefusal, refusedRequest } from "./internal/confinement.js";
4
- import { DEFAULT_API_VERSION, expandOnDotcom, makeTransport } from "./internal/octokit.js";
5
+ import { expandOnDotcom, makeTransport } from "./internal/octokit.js";
5
6
  import { fromArray, paginate } from "./internal/paginate.js";
6
7
  import { unstubbed } from "./internal/unstubbed.js";
7
8
  import { DOTCOM_API_BASE_URL, originOf, uploadsBaseUrlFor, withUploadChannel } from "./internal/uploads.js";
@@ -233,8 +234,6 @@ var GitHubClient = class GitHubClient extends Context.Service()("@effected/githu
233
234
  */
234
235
  static layerFixture = (fixtures) => Layer.succeed(GitHubClient, confineDouble(makeFixture(fixtures)));
235
236
  };
236
- /** A calendar api-version: `YYYY-MM-DD`. */
237
- const API_VERSION_PATTERN = /^\d{4}-\d{2}-\d{2}$/;
238
237
  /**
239
238
  * The api-version a client pins: the option when it is a calendar version,
240
239
  * the default when it is absent, and a defect naming the option otherwise.
@@ -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/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).
package/index.d.ts CHANGED
@@ -4141,6 +4141,383 @@ export declare class GitHubRepository extends GitHubRepository_base {
4141
4141
  /** {@link GitHubRepository.makeTest} behind a `Layer`. */
4142
4142
  static readonly layerTest: (overrides?: Partial<GitHubRepositoryShape>) => Layer.Layer<GitHubRepository>;
4143
4143
  }
4144
+ /**
4145
+ * Which `GitHubUserAuth` operation a failure came from.
4146
+ *
4147
+ * @public
4148
+ */
4149
+ export declare const GitHubUserAuthOperation: Schema.Literals<readonly ["exchange", "refresh", "revokeGrant"]>;
4150
+ /**
4151
+ * The decoded type of {@link (GitHubUserAuthOperation:variable)}.
4152
+ *
4153
+ * @public
4154
+ */
4155
+ export type GitHubUserAuthOperation = typeof GitHubUserAuthOperation.Type;
4156
+ declare const ExpiringUserTokens_base: Schema.Class<ExpiringUserTokens, Schema.Struct<{
4157
+ /** The discriminant: these tokens expire, and the refresh token renews them. */
4158
+ readonly expiry: Schema.tag<"expiring">;
4159
+ /** The user access token. Decodes to `Redacted`, encodes back to the raw string. */
4160
+ readonly accessToken: Schema.RedactedFromValue<Schema.String>;
4161
+ /** GitHub's `token_type`, `bearer` in practice. */
4162
+ readonly tokenType: Schema.String;
4163
+ /**
4164
+ * GitHub's `scope`, as sent: a comma-separated list for an OAuth App and
4165
+ * the empty string for a GitHub App, whose user tokens carry the app's
4166
+ * permissions instead of scopes.
4167
+ */
4168
+ readonly scope: Schema.String;
4169
+ /** When GitHub stops accepting the access token — eight hours out by default. */
4170
+ readonly expiresAt: Schema.DateTimeUtcFromString;
4171
+ /** The refresh token. Decodes to `Redacted`, encodes back to the raw string. */
4172
+ readonly refreshToken: Schema.RedactedFromValue<Schema.String>;
4173
+ /** When GitHub stops accepting the refresh token — six months out by default. */
4174
+ readonly refreshTokenExpiresAt: Schema.DateTimeUtcFromString;
4175
+ }>, {}>;
4176
+ /**
4177
+ * A user-to-server token pair that expires: what GitHub issues to a GitHub
4178
+ * App with "Expire user authorization tokens" turned on, which is the default.
4179
+ *
4180
+ * @remarks
4181
+ * Times are absolute instants, computed from GitHub's `expires_in` and
4182
+ * `refresh_token_expires_in` against `Clock` when the reply arrived, the same
4183
+ * way `InstallationToken.expiresAt` is.
4184
+ *
4185
+ * Encodable, like `InstallationToken`: `Schema.encodeUnknownEffect` over
4186
+ * {@link (GitHubUserTokens:variable)} produces JSON with both tokens as plain
4187
+ * strings and both times as ISO instants, which is how a caller persists a
4188
+ * user's grant. Encrypting it at rest is the caller's job.
4189
+ *
4190
+ * @public
4191
+ */
4192
+ export declare class ExpiringUserTokens extends ExpiringUserTokens_base {
4193
+ /**
4194
+ * Whether the access token is spent, `skew` before its stated expiry.
4195
+ *
4196
+ * @remarks
4197
+ * `skew` defaults to one minute, so a token is treated as spent slightly
4198
+ * early rather than answering 401 mid-request.
4199
+ */
4200
+ isExpired(nowMillis: number, skew?: Duration.Duration): boolean;
4201
+ /**
4202
+ * Whether the refresh token is spent, `skew` before its stated expiry. A
4203
+ * spent refresh token cannot renew the grant: the user has to authorize
4204
+ * again.
4205
+ */
4206
+ isRefreshExpired(nowMillis: number, skew?: Duration.Duration): boolean;
4207
+ }
4208
+ declare const NonExpiringUserTokens_base: Schema.Class<NonExpiringUserTokens, Schema.Struct<{
4209
+ /** The discriminant: this token does not expire and cannot be refreshed. */
4210
+ readonly expiry: Schema.tag<"non-expiring">;
4211
+ /** The user access token. Decodes to `Redacted`, encodes back to the raw string. */
4212
+ readonly accessToken: Schema.RedactedFromValue<Schema.String>;
4213
+ /** GitHub's `token_type`, `bearer` in practice. */
4214
+ readonly tokenType: Schema.String;
4215
+ /** GitHub's `scope`, as sent; see `ExpiringUserTokens.scope`. */
4216
+ readonly scope: Schema.String;
4217
+ }>, {}>;
4218
+ /**
4219
+ * A user access token that does not expire: what GitHub issues to an OAuth
4220
+ * App, or to a GitHub App with "Expire user authorization tokens" turned off.
4221
+ * It carries no refresh token and no expiry.
4222
+ *
4223
+ * @public
4224
+ */
4225
+ export declare class NonExpiringUserTokens extends NonExpiringUserTokens_base {}
4226
+ /**
4227
+ * What a code exchange answers, discriminated by `expiry`: `expiring` carries
4228
+ * a refresh token and both expiry instants, `non-expiring` carries neither.
4229
+ *
4230
+ * @remarks
4231
+ * **Construct the variant classes, never the union.** The union's inherited
4232
+ * `make` typechecks against both variants at once and reports a wrong field
4233
+ * as a two-branch error; {@link ExpiringUserTokens}`.make` and
4234
+ * {@link NonExpiringUserTokens}`.make` fill `expiry` themselves. The union is
4235
+ * a `Schema` so a stored grant decodes back into the right variant.
4236
+ *
4237
+ * @public
4238
+ */
4239
+ export declare const GitHubUserTokens: Schema.Union<readonly [typeof ExpiringUserTokens, typeof NonExpiringUserTokens]>;
4240
+ /**
4241
+ * The decoded type of {@link (GitHubUserTokens:variable)}:
4242
+ * {@link ExpiringUserTokens} `|` {@link NonExpiringUserTokens}.
4243
+ *
4244
+ * @public
4245
+ */
4246
+ export type GitHubUserTokens = typeof GitHubUserTokens.Type;
4247
+ declare const GitHubUserAuthFinal_base: Schema.Class<GitHubUserAuthFinal, Schema.TaggedStruct<"GitHubUserAuthFinal", {
4248
+ /** The operation GitHub refused. */
4249
+ readonly operation: Schema.Literals<readonly ["exchange", "refresh", "revokeGrant"]>;
4250
+ /** What has to change before the call can succeed. */
4251
+ readonly remedy: Schema.Literals<readonly ["reconnect", "reconfigure"]>;
4252
+ /** GitHub's `error` code, or `http_<status>`. */
4253
+ readonly code: Schema.String;
4254
+ /** GitHub's own explanation, scrubbed of this call's credentials. */
4255
+ readonly description: Schema.optionalKey<Schema.String>;
4256
+ /** The HTTP status GitHub answered with. */
4257
+ readonly status: Schema.Int;
4258
+ }>, import("effect/Cause").YieldableError>;
4259
+ /**
4260
+ * GitHub refused the call, and repeating it will not change the answer.
4261
+ *
4262
+ * @remarks
4263
+ * `remedy` says what has to change, and it is the field to branch on:
4264
+ *
4265
+ * - `"reconnect"` — the user's side is dead: the authorization code was
4266
+ * wrong, expired or already used (`bad_verification_code`), the refresh
4267
+ * token was revoked or expired (`bad_refresh_token`), or the grant is
4268
+ * already gone. Send the user through the authorization flow again, and
4269
+ * drop the tokens you hold for them.
4270
+ * - `"reconfigure"` — the app's side is wrong: its client id or secret
4271
+ * (`incorrect_client_credentials`), its callback URL
4272
+ * (`redirect_uri_mismatch`), refresh tokens being turned off for it
4273
+ * (`unsupported_grant_type`), or a code GitHub sent that this package does
4274
+ * not know. Nothing about the user's grant is learned, and reconnecting the
4275
+ * user does not help; an operator has to fix the app. A 401, 403 or 404
4276
+ * with no `error` code lands here too — but never a 403 whose message
4277
+ * names a rate limit (or GitHub's older "abuse detection" wording), which
4278
+ * is a {@link GitHubUserAuthTemporary}.
4279
+ *
4280
+ * **Never wipe a user's tokens on `GitHubUserAuthFinal` alone.** The obvious
4281
+ * handler, `Effect.catchTag("GitHubUserAuthFinal", () => forgetUser(id))`,
4282
+ * typechecks, runs and reports success, and on a rotated or mistyped client
4283
+ * secret it signs every user out at once, because every refresh then answers
4284
+ * `incorrect_client_credentials`. silk-app's hand-rolled flow carried this
4285
+ * exact rule as a comment before the kit had this error. Match on
4286
+ * `remedy === "reconnect"`.
4287
+ *
4288
+ * GitHub answers the token endpoint with HTTP 200 and an `error` body when it
4289
+ * refuses a code or a refresh token, so `status` is usually 200. `code` is
4290
+ * GitHub's `error` code when it sent one (an unrecognisable one reads
4291
+ * `unknown_error`), and `http_<status>` when GitHub answered a non-success
4292
+ * status with no error code. `description` is GitHub's `error_description`
4293
+ * (or the REST `message`), with any credential this call carried replaced by
4294
+ * `REDACTED`.
4295
+ *
4296
+ * @public
4297
+ */
4298
+ export declare class GitHubUserAuthFinal extends GitHubUserAuthFinal_base {
4299
+ get message(): string;
4300
+ }
4301
+ declare const GitHubUserAuthTemporary_base: Schema.Class<GitHubUserAuthTemporary, Schema.TaggedStruct<"GitHubUserAuthTemporary", {
4302
+ /** The operation that did not complete. */
4303
+ readonly operation: Schema.Literals<readonly ["exchange", "refresh", "revokeGrant"]>;
4304
+ /** Why it did not complete. */
4305
+ readonly kind: Schema.Literals<readonly ["network", "timeout", "status", "malformed"]>;
4306
+ /** The HTTP status, when a response arrived. */
4307
+ readonly status: Schema.optionalKey<Schema.Int>;
4308
+ /** A credential-free copy of what `fetch` threw, for `network`. */
4309
+ readonly cause: Schema.optionalKey<Schema.Defect>;
4310
+ }>, import("effect/Cause").YieldableError>;
4311
+ /**
4312
+ * The call did not get an answer GitHub meant: try it again later.
4313
+ *
4314
+ * @remarks
4315
+ * `kind` is the reason:
4316
+ *
4317
+ * - `"network"` — `fetch` threw, or the body could not be read;
4318
+ * - `"timeout"` — no complete answer within the layer's `timeout`;
4319
+ * - `"status"` — GitHub answered 5xx, 429 or 408, or a 403 whose message
4320
+ * names a rate limit or "abuse detection" (GitHub's primary REST rate
4321
+ * limit answers 403, and its secondary limits answer 403 or 429);
4322
+ * - `"malformed"` — a success status whose body is not a token reply, or a
4323
+ * refresh that answered a token with no refresh token.
4324
+ *
4325
+ * None of these is a refusal of the user's grant, so a caller keeps the
4326
+ * tokens it holds and retries later.
4327
+ *
4328
+ * One case does not leave the grant as it was. GitHub refresh tokens are
4329
+ * single-use and rotate when a refresh succeeds, so a refresh GitHub
4330
+ * processed has already spent the refresh token the caller sent: a
4331
+ * `"malformed"` with a 2xx `status` (GitHub answered, the reply was
4332
+ * rejected), or a `"network"` or `"timeout"` that ended after the request
4333
+ * reached GitHub. Retrying such a refresh with the same refresh token answers
4334
+ * `bad_refresh_token`, a {@link GitHubUserAuthFinal} with
4335
+ * `remedy: "reconnect"`. That is the expected consequence, not a second
4336
+ * fault: the user authorizes again.
4337
+ *
4338
+ * `cause` is a copy of what `fetch` threw, rebuilt with its message, stack
4339
+ * and primitive fields scrubbed of this call's credentials, never the
4340
+ * original: a custom `fetch` can put the request (and so the client secret)
4341
+ * in its error.
4342
+ *
4343
+ * @public
4344
+ */
4345
+ export declare class GitHubUserAuthTemporary extends GitHubUserAuthTemporary_base {
4346
+ get message(): string;
4347
+ }
4348
+ /**
4349
+ * Every failure of a `GitHubUserAuth` operation: final (reconnect or
4350
+ * reconfigure) or temporary (retry later).
4351
+ *
4352
+ * @public
4353
+ */
4354
+ type GitHubUserAuthError = GitHubUserAuthFinal | GitHubUserAuthTemporary;
4355
+ /**
4356
+ * How a {@link GitHubUserAuth} layer is built.
4357
+ *
4358
+ * @public
4359
+ */
4360
+ interface GitHubUserAuthOptions {
4361
+ /** The app's OAuth client id (`Iv1.…` or `Iv23…` for a GitHub App). */
4362
+ readonly clientId: string;
4363
+ /** The app's OAuth client secret. */
4364
+ readonly clientSecret: Redacted.Redacted<string>;
4365
+ /**
4366
+ * A replacement for the global `fetch`, for Workers, proxies and tests —
4367
+ * the same shape as `GitHubClientOptions.fetch`.
4368
+ *
4369
+ * @remarks
4370
+ * It receives an `AbortSignal` on every call, aborted when the call times
4371
+ * out or the caller is interrupted.
4372
+ */
4373
+ readonly fetch?: typeof globalThis.fetch | undefined;
4374
+ /**
4375
+ * The token endpoint. Defaults to
4376
+ * `https://github.com/login/oauth/access_token`; a GitHub Enterprise Server
4377
+ * app uses `https://<host>/login/oauth/access_token`.
4378
+ */
4379
+ readonly tokenUrl?: string | undefined;
4380
+ /**
4381
+ * The REST API root the grant revoke goes to. Defaults to
4382
+ * `https://api.github.com`; a GitHub Enterprise Server app uses
4383
+ * `https://<host>/api/v3`.
4384
+ */
4385
+ readonly apiUrl?: string | undefined;
4386
+ /**
4387
+ * The REST api-version the grant revoke pins, sent as
4388
+ * `x-github-api-version`. Defaults to the same version `GitHubClient`
4389
+ * pins; must be `YYYY-MM-DD`.
4390
+ */
4391
+ readonly apiVersion?: string | undefined;
4392
+ /** The `user-agent` every request sends. Defaults to `@effected/github`. */
4393
+ readonly userAgent?: string | undefined;
4394
+ /**
4395
+ * How long one call may take, request and body together, before it fails
4396
+ * as `GitHubUserAuthTemporary` with `kind: "timeout"`. Defaults to ten
4397
+ * seconds; must be finite and positive.
4398
+ */
4399
+ readonly timeout?: Duration.Input | undefined;
4400
+ }
4401
+ /**
4402
+ * The code a user brought back from GitHub's authorize page.
4403
+ *
4404
+ * @public
4405
+ */
4406
+ interface UserAuthExchangeRequest {
4407
+ /** The `code` query parameter GitHub redirected back with. */
4408
+ readonly code: string;
4409
+ /** The PKCE `code_verifier` whose S256 challenge the authorize URL carried. */
4410
+ readonly codeVerifier?: string | undefined;
4411
+ /** The `redirect_uri` the authorize URL carried, when it carried one. */
4412
+ readonly redirectUri?: string | undefined;
4413
+ }
4414
+ /**
4415
+ * A refresh token to renew.
4416
+ *
4417
+ * @public
4418
+ */
4419
+ interface UserAuthRefreshRequest {
4420
+ /** The refresh token from the last exchange or refresh. */
4421
+ readonly refreshToken: Redacted.Redacted<string>;
4422
+ }
4423
+ /**
4424
+ * A user's grant to revoke.
4425
+ *
4426
+ * @public
4427
+ */
4428
+ interface UserAuthRevokeRequest {
4429
+ /** Any live access token from the grant. */
4430
+ readonly accessToken: Redacted.Redacted<string>;
4431
+ }
4432
+ /**
4433
+ * The operations of {@link GitHubUserAuth}.
4434
+ *
4435
+ * @public
4436
+ */
4437
+ interface GitHubUserAuthShape {
4438
+ /**
4439
+ * Trade an authorization code (and its PKCE verifier) for the user's
4440
+ * tokens.
4441
+ */
4442
+ readonly exchange: (request: UserAuthExchangeRequest) => Effect.Effect<GitHubUserTokens, GitHubUserAuthError>;
4443
+ /**
4444
+ * Renew an expiring grant. GitHub rotates the refresh token, so store the
4445
+ * answer's `refreshToken` in place of the one you sent.
4446
+ */
4447
+ readonly refresh: (request: UserAuthRefreshRequest) => Effect.Effect<ExpiringUserTokens, GitHubUserAuthError>;
4448
+ /**
4449
+ * Revoke the user's whole grant to the app, every token it issued included:
4450
+ * `DELETE /applications/{client_id}/grant` with HTTP Basic client
4451
+ * authentication.
4452
+ *
4453
+ * @remarks
4454
+ * A grant that is already gone answers 422, which fails as
4455
+ * `GitHubUserAuthFinal` with `remedy: "reconnect"`; a caller that treats
4456
+ * revocation as idempotent recovers that case.
4457
+ */
4458
+ readonly revokeGrant: (request: UserAuthRevokeRequest) => Effect.Effect<void, GitHubUserAuthError>;
4459
+ }
4460
+ declare const GitHubUserAuth_base: Context.ServiceClass<GitHubUserAuth, "@effected/github/GitHubUserAuth", GitHubUserAuthShape>;
4461
+ /**
4462
+ * The OAuth web flow a GitHub App (or an OAuth App) uses to act as a user:
4463
+ * PKCE code exchange, refresh, and grant revoke.
4464
+ *
4465
+ * @remarks
4466
+ * None of these calls go through `GitHubClient`: the token endpoint lives on
4467
+ * the web host rather than the REST host, and the revoke authenticates as the
4468
+ * app's OAuth client with HTTP Basic rather than with a bearer token. So the
4469
+ * service speaks to `fetch` directly, and this module imports neither octokit
4470
+ * nor the JWT signer — a Worker that only signs users in links neither.
4471
+ *
4472
+ * Every failure is one of two errors, and the split is the point:
4473
+ * {@link GitHubUserAuthFinal} when GitHub refused (read its `remedy` before
4474
+ * dropping anything), {@link GitHubUserAuthTemporary} when no real answer
4475
+ * arrived. GitHub answers a refused code or refresh token with HTTP 200 and an
4476
+ * `error` body, which is read as the refusal it is.
4477
+ *
4478
+ * The client secret, the code, the verifier and both tokens appear in no
4479
+ * error message, no span annotation and no kept cause.
4480
+ *
4481
+ * @example
4482
+ * ```ts
4483
+ * import { GitHubUserAuth } from "@effected/github";
4484
+ * import { Effect, Redacted } from "effect";
4485
+ *
4486
+ * const UserAuth = GitHubUserAuth.layer({
4487
+ * clientId: "Iv23liExample",
4488
+ * clientSecret: Redacted.make("app-client-secret"),
4489
+ * });
4490
+ *
4491
+ * const signIn = (code: string, codeVerifier: string) =>
4492
+ * Effect.gen(function* () {
4493
+ * const auth = yield* GitHubUserAuth;
4494
+ * return yield* auth.exchange({ code, codeVerifier, redirectUri: "https://app.example/callback" });
4495
+ * });
4496
+ *
4497
+ * Effect.runPromise(signIn("code-from-query", "verifier").pipe(Effect.provide(UserAuth)));
4498
+ * ```
4499
+ *
4500
+ * @public
4501
+ */
4502
+ export declare class GitHubUserAuth extends GitHubUserAuth_base {
4503
+ /**
4504
+ * The live service over `fetch`.
4505
+ *
4506
+ * @remarks
4507
+ * Parameterized, so **bind the result to a `const`** and reuse it: each
4508
+ * call mints a fresh layer, and layers are memoized by reference.
4509
+ *
4510
+ * Bad wiring — an empty client id, a URL that does not parse or is not
4511
+ * `http(s)`, an api-version that is not `YYYY-MM-DD`, a timeout that is not
4512
+ * finite and positive — dies while the layer builds, with a defect naming
4513
+ * the option.
4514
+ */
4515
+ static readonly layer: (options: GitHubUserAuthOptions) => Layer.Layer<GitHubUserAuth>;
4516
+ /** An in-memory double; an unstubbed member dies when run, naming itself. */
4517
+ static readonly makeTest: (overrides?: Partial<GitHubUserAuthShape>) => GitHubUserAuthShape;
4518
+ /** {@link GitHubUserAuth.makeTest} behind a `Layer`. */
4519
+ static readonly layerTest: (overrides?: Partial<GitHubUserAuthShape>) => Layer.Layer<GitHubUserAuth>;
4520
+ }
4144
4521
  declare const TagRef_base: Schema.Class<TagRef, Schema.Struct<{
4145
4522
  /** The tag name, without `refs/tags/`. */
4146
4523
  readonly tag: Schema.NonEmptyString;
@@ -5232,5 +5609,5 @@ export declare class WorkflowDispatch extends WorkflowDispatch_base {
5232
5609
  /** {@link WorkflowDispatch.makeTest} behind a `Layer`. */
5233
5610
  static readonly layerTest: (overrides?: Partial<WorkflowDispatchShape>) => Layer.Layer<WorkflowDispatch>;
5234
5611
  }
5235
- export { type ActionsOidcVerifyOptions, type AppCredentials, type AppliedSettings, type ApplySettingsOptions, type ArtifactMetadataShape, type AttestationShape, type AuthenticatedAppShape, type BareLineReference, type BotUserRequest, type BranchOutcome, CLOSING_KEYWORDS, type CachedToken, type CachedTokenRequest, type CheckRunShape, type ClosingKeyword, type CodeScanningSetup, type CodeScanningShape, type CompleteCheckRunOptions, type ConcludeCheckRun, type CreateCheckRunOptions, type DeliveriesOptions, type DeploymentEnvironmentInfo, type DeploymentEnvironmentShape, type GitBranchShape, type GitCommitShape, type GitHubAppOptions, type GitHubAppShape, type GitHubClientOptions, type GitHubClientShape, type GitHubCommitShape, type GitHubContentShape, type GitHubIssueShape, type GitHubReleaseShape, type GitHubRepositoryShape, type GitTagShape, type InstallationTokenStoreShape, type IssueReference, type LatestSemverOptions, type ListCheckRunsOptions, type OwnerType, type PollOptions, type PullRequestCommentShape, type PullRequestShape, type RecordedCall, type RepositoryPatch, type RepositoryPatchDraft, type RepositoryPatchExtra, type RepositoryPatchOptions, type RepositoryPatchReservedKey, type RepositorySecretShape, type RepositorySecurityShape, type RepositorySettings, type RepositoryVariableShape, type Data as RestData, type RequestExtras as RestExtras, type Item as RestItem, type PaginatingRoute as RestPaginatingRoute, type Params as RestParams, type Response as RestResponse, type Route as RestRoute, type RetryableFailure, type RulesetInfo, type RulesetPayload, type RulesetShape, type SecretInfo, type SecretScope, type TokenRequest, type UpdateCheckRunOptions, type UpsertedPullRequest, type VariableInfo, type VersionFromTag, type WorkflowDispatchShape, type WorkflowInfo, harvestIssueReferences, parseBareLineReference };
5612
+ export { type ActionsOidcVerifyOptions, type AppCredentials, type AppliedSettings, type ApplySettingsOptions, type ArtifactMetadataShape, type AttestationShape, type AuthenticatedAppShape, type BareLineReference, type BotUserRequest, type BranchOutcome, CLOSING_KEYWORDS, type CachedToken, type CachedTokenRequest, type CheckRunShape, type ClosingKeyword, type CodeScanningSetup, type CodeScanningShape, type CompleteCheckRunOptions, type ConcludeCheckRun, type CreateCheckRunOptions, type DeliveriesOptions, type DeploymentEnvironmentInfo, type DeploymentEnvironmentShape, type GitBranchShape, type GitCommitShape, type GitHubAppOptions, type GitHubAppShape, type GitHubClientOptions, type GitHubClientShape, type GitHubCommitShape, type GitHubContentShape, type GitHubIssueShape, type GitHubReleaseShape, type GitHubRepositoryShape, type GitHubUserAuthError, type GitHubUserAuthOptions, type GitHubUserAuthShape, type GitTagShape, type InstallationTokenStoreShape, type IssueReference, type LatestSemverOptions, type ListCheckRunsOptions, type OwnerType, type PollOptions, type PullRequestCommentShape, type PullRequestShape, type RecordedCall, type RepositoryPatch, type RepositoryPatchDraft, type RepositoryPatchExtra, type RepositoryPatchOptions, type RepositoryPatchReservedKey, type RepositorySecretShape, type RepositorySecurityShape, type RepositorySettings, type RepositoryVariableShape, type Data as RestData, type RequestExtras as RestExtras, type Item as RestItem, type PaginatingRoute as RestPaginatingRoute, type Params as RestParams, type Response as RestResponse, type Route as RestRoute, type RetryableFailure, type RulesetInfo, type RulesetPayload, type RulesetShape, type SecretInfo, type SecretScope, type TokenRequest, type UpdateCheckRunOptions, type UpsertedPullRequest, type UserAuthExchangeRequest, type UserAuthRefreshRequest, type UserAuthRevokeRequest, type VariableInfo, type VersionFromTag, type WorkflowDispatchShape, type WorkflowInfo, harvestIssueReferences, parseBareLineReference };
5236
5613
  //# sourceMappingURL=index.d.ts.map
package/index.js CHANGED
@@ -15,6 +15,7 @@ import { GitHubError, GitHubErrorKind, GitHubValidationCode, GitHubValidationEnt
15
15
  import { CommentOnceResult, GitHubIssue, IssueInfo, LinkedIssue } from "./GitHubIssue.js";
16
16
  import { GitHubRelease, ReleaseAsset, ReleaseInfo } from "./GitHubRelease.js";
17
17
  import { GRAPHQL_ONLY_SETTINGS, GitHubRepository, SECURITY_ANALYSIS_STATUS_FIELDS, repositoryPatch, transformSecurityAndAnalysis } from "./GitHubRepository.js";
18
+ import { ExpiringUserTokens, GitHubUserAuth, GitHubUserAuthFinal, GitHubUserAuthOperation, GitHubUserAuthTemporary, GitHubUserTokens, NonExpiringUserTokens } from "./GitHubUserAuth.js";
18
19
  import { GitTag, SemverTag, TagRef, versionFromTag } from "./GitTag.js";
19
20
  import { GitHubGraphQLError, GraphQLDocument, GraphQLErrorEntry } from "./GraphQL.js";
20
21
  import { InstallationTokenStore } from "./InstallationTokenStore.js";
@@ -31,4 +32,4 @@ import { ExtraPermission, PermissionGap, PermissionLevel, PermissionResult, Toke
31
32
  import { DispatchedRun, WorkflowDispatch, WorkflowRunStatus } from "./WorkflowDispatch.js";
32
33
  import { CLOSING_KEYWORDS, harvestIssueReferences, parseBareLineReference } from "@effected/github-references";
33
34
 
34
- export { ActionsOidc, ActionsOidcClaims, ActionsOidcClaimsFromWire, Annotation, AnnotationLevel, AppIdentity, AppInfo, ArtifactMetadata, Attestation, AttestationListEntry, AttestationRecord, AuthenticatedApp, BotIdentity, BotUser, CLOSING_KEYWORDS, CheckConclusion, CheckRun, CheckRunOutput, CheckRunRef, CheckRunStatus, CodeScanning, CommentMarker, CommentOnceResult, CommentRecord, CommitComparison, CommitFile, CommitRef, CommitSummary, CreatedCommit, DeliveryAttempt, DeploymentEnvironment, DispatchedRun, ExtraPermission, FileChange, FileContent, FileDeletion, FileMode, FileStatus, GRAPHQL_ONLY_SETTINGS, GitBranch, GitCommit, GitHubApp, GitHubAppError, GitHubClient, GitHubCommit, GitHubContent, GitHubError, GitHubErrorKind, GitHubFixtures, GitHubGraphQLError, GitHubIssue, GitHubRelease, GitHubRepository, GitHubValidationCode, GitHubValidationEntry, GitTag, GraphQLDocument, GraphQLErrorEntry, Installation, InstallationToken, InstallationTokenStore, InvalidRepoRefError, IssueInfo, LinkedIssue, MergeMethod, PageOptions, PermissionGap, PermissionLevel, PermissionResult, PullRequest, PullRequestComment, PullRequestInfo, RateLimitSnapshot, RawFailure, ReleaseAsset, ReleaseInfo, Repo, RepoRef, ReportedCheckConclusion, ReportedCheckRunOutput, RepositorySecret, RepositorySecurity, RepositoryVariable, RetryPolicy, Ruleset, SECURITY_ANALYSIS_STATUS_FIELDS, SemverTag, StorageRecordInput, TagRef, TokenPermissionError, TokenPermissions, WorkflowDispatch, WorkflowRunStatus, harvestIssueReferences, parseBareLineReference, repositoryPatch, transformSecurityAndAnalysis, versionFromTag };
35
+ export { ActionsOidc, ActionsOidcClaims, ActionsOidcClaimsFromWire, Annotation, AnnotationLevel, AppIdentity, AppInfo, ArtifactMetadata, Attestation, AttestationListEntry, AttestationRecord, AuthenticatedApp, BotIdentity, BotUser, CLOSING_KEYWORDS, CheckConclusion, CheckRun, CheckRunOutput, CheckRunRef, CheckRunStatus, CodeScanning, CommentMarker, CommentOnceResult, CommentRecord, CommitComparison, CommitFile, CommitRef, CommitSummary, CreatedCommit, DeliveryAttempt, DeploymentEnvironment, DispatchedRun, ExpiringUserTokens, ExtraPermission, FileChange, FileContent, FileDeletion, FileMode, FileStatus, GRAPHQL_ONLY_SETTINGS, GitBranch, GitCommit, GitHubApp, GitHubAppError, GitHubClient, GitHubCommit, GitHubContent, GitHubError, GitHubErrorKind, GitHubFixtures, GitHubGraphQLError, GitHubIssue, GitHubRelease, GitHubRepository, GitHubUserAuth, GitHubUserAuthFinal, GitHubUserAuthOperation, GitHubUserAuthTemporary, GitHubUserTokens, GitHubValidationCode, GitHubValidationEntry, GitTag, GraphQLDocument, GraphQLErrorEntry, Installation, InstallationToken, InstallationTokenStore, InvalidRepoRefError, IssueInfo, LinkedIssue, MergeMethod, NonExpiringUserTokens, PageOptions, PermissionGap, PermissionLevel, PermissionResult, PullRequest, PullRequestComment, PullRequestInfo, RateLimitSnapshot, RawFailure, ReleaseAsset, ReleaseInfo, Repo, RepoRef, ReportedCheckConclusion, ReportedCheckRunOutput, RepositorySecret, RepositorySecurity, RepositoryVariable, RetryPolicy, Ruleset, SECURITY_ANALYSIS_STATUS_FIELDS, SemverTag, StorageRecordInput, TagRef, TokenPermissionError, TokenPermissions, WorkflowDispatch, WorkflowRunStatus, harvestIssueReferences, parseBareLineReference, repositoryPatch, transformSecurityAndAnalysis, versionFromTag };
@@ -0,0 +1,15 @@
1
+ // src/internal/apiVersion.ts
2
+ /**
3
+ * The REST api-version a client pins when its options name none.
4
+ *
5
+ * @internal
6
+ */
7
+ const DEFAULT_API_VERSION = "2026-03-10";
8
+ /**
9
+ * A calendar api-version: `YYYY-MM-DD`.
10
+ *
11
+ * @internal
12
+ */
13
+ const API_VERSION_PATTERN = /^\d{4}-\d{2}-\d{2}$/;
14
+
15
+ export { API_VERSION_PATTERN, DEFAULT_API_VERSION };
@@ -8,8 +8,6 @@ import { Octokit } from "@octokit/core";
8
8
  import { composePaginateRest } from "@octokit/plugin-paginate-rest";
9
9
 
10
10
  // src/internal/octokit.ts
11
- /** The REST api-version a client pins when its options name none. */
12
- const DEFAULT_API_VERSION = "2026-03-10";
13
11
  const SILENT_LOG = {
14
12
  debug: () => {},
15
13
  info: () => {},
@@ -203,4 +201,4 @@ const readThrownHeaders = (error) => {
203
201
  return typeof headers === "object" && headers !== null ? headers : void 0;
204
202
  };
205
203
 
206
- export { DEFAULT_API_VERSION, expandOnDotcom, makeTransport };
204
+ export { expandOnDotcom, makeTransport };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@effected/github",
3
- "version": "0.29.0",
3
+ "version": "0.30.0",
4
4
  "private": false,
5
5
  "description": "Typed GitHub REST and GraphQL services over the octokit core request surface, with app auth and resource helpers.",
6
6
  "keywords": [
@@ -38,9 +38,9 @@
38
38
  "./package.json": "./package.json"
39
39
  },
40
40
  "dependencies": {
41
- "@effected/crypto": "^0.5.0",
41
+ "@effected/crypto": "^0.6.0",
42
42
  "@effected/github-references": "^0.14.0",
43
- "@effected/jwt": "^0.9.0",
43
+ "@effected/jwt": "^0.9.1",
44
44
  "@effected/oidc": "^0.4.0",
45
45
  "@effected/semver": "^0.22.0",
46
46
  "@octokit/core": "^7.0.6",