| 1 | import type { Request, Response } from 'express'; |
| 2 | |
| 3 | /** GitHub answers its OAuth endpoints form-encoded unless the client asks for JSON; gh's client reads either. */ |
| 4 | export function sendOAuth( |
| 5 | req: Request |
| 6 | res: Response |
| 7 | { status, body |
| 8 | ) { |
| 9 | res.status(status |
| 10 | if (/application\/json |
| 11 | res |
| 12 | .type('application/x-www-form-urlencoded') |
| 13 | .send( |
| 14 | new URLSearchParams( |
| 15 | Object.entries(body |
| 16 | ).toString(), |
| 17 | ); |
| 18 | } |
| 19 | |
| 20 | /** What each OAuth error Ghost answers itself means, in GitHub's wording where GitHub has one, so a client that shows `error_description` tells its user what went wrong. */ |
| 21 | const OAUTH_ERROR_DESCRIPTIONS = { |
| 22 | incorrect_client_credentials: |
| 23 | 'The client_id and/or client_secret passed are incorrect.', |
| 24 | redirect_uri_mismatch: |
| 25 | 'The redirect_uri MUST match the registered callback URL for this application.', |
| 26 | bad_verification_code: 'The code passed is incorrect or expired.', |
| 27 | bad_refresh_token: 'The refresh token passed is incorrect or expired.', |
| 28 | unsupported_grant_type: |
| 29 | 'Send a code, a device_code with the device grant_type, or a refresh_token with grant_type=refresh_token.', |
| 30 | invalid_client: 'No OAuth app is registered with this client_id.', |
| 31 | unauthorized_client: |
| 32 | 'No OAuth app with device flow enabled is registered with this client_id.', |
| 33 | invalid_grant: 'The device code is incorrect or expired.', |
| 34 | } as const; |
| 35 | |
| 36 | export type OAuthError |
| 37 | |
| 38 | /** What an OAuth endpoint answers, whichever encoding the client asked for. */ |
| 39 | export type OAuthReply |
| 40 | status: number |
| 41 | body: Record |
| 42 | }; |
| 43 | |
| 44 | export function oauthError(status |
| 45 | return { |
| 46 | status, |
| 47 | body: { error, |
| 48 | }; |
| 49 | } |