| 1 | import { Injectable, type NestMiddleware } from '@nestjs/common'; |
| 2 | import { AuthService } |
| 3 | import { fromNodeHeaders } |
| 4 | import type { NextFunction, |
| 5 | |
| 6 | import type { Auth |
| 7 | import { KNOWN_SCOPES, scopesOfKey |
| 8 | import type { GithubRequest, |
| 9 | |
| 10 | const TOKEN = / |
| 11 | const GITHUB_MEDIA_TYPE = / |
| 12 | /** `gh pr diff` asks for the raw diff or patch, which is not JSON and which the pulls controller answers by this header. */ |
| 13 | const RAW_MEDIA_TYPE = / |
| 14 | |
| 15 | /** Resolves `Authorization: token|Bearer <key>` (what gh sends) or a session cookie (GraphiQL in a browser) to a viewer, and sets the headers gh reads on every compat response. */ |
| 16 | @Injectable() |
| 17 | export class GithubAuthMiddleware |
| 18 | constructor(private readonly |
| 19 | |
| 20 | async use(req |
| 21 | res.setHeader('X-GitHub-Media-Type |
| 22 | // gh asks for GitHub's preview media types, which Apollo answers 406 because they do not name JSON; they are JSON. |
| 23 | const accept = |
| 24 | if (GITHUB_MEDIA_TYPE.test |
| 25 | req.headers.accept |
| 26 | const header = |
| 27 | const token = |
| 28 | |
| 29 | if (header && |
| 30 | const viewer = |
| 31 | ? await this. |
| 32 | : await this. |
| 33 | if (token && |
| 34 | |
| 35 | req.githubViewer = |
| 36 | res.setHeader('X-OAuth-Scopes |
| 37 | next(); |
| 38 | } |
| 39 | |
| 40 | private async fromKey |
| 41 | const { valid, |
| 42 | body: { key |
| 43 | }); |
| 44 | return valid && |
| 45 | ? { |
| 46 | userId: apiKey.referenceId |
| 47 | scopes: scopesOfKey(apiKey |
| 48 | oauthClientId: |
| 49 | (apiKey.metadata as |
| 50 | ?.oauthClientId ?? null, |
| 51 | } |
| 52 | : null; |
| 53 | } |
| 54 | |
| 55 | private async fromSession |
| 56 | const session = |
| 57 | headers: fromNodeHeaders(req |
| 58 | }); |
| 59 | return session |
| 60 | ? { userId: session |
| 61 | : null; |
| 62 | } |
| 63 | |
| 64 | private badCredentials(res |
| 65 | res.status(401) |
| 66 | message: 'Bad credentials', |
| 67 | documentation_url: 'https://docs.github.com/rest', |
| 68 | }); |
| 69 | } |
| 70 | } |