| 1 | import { AsyncLocalStorage } from 'node:async_hooks'; |
| 2 | |
| 3 | import { type Database, |
| 4 | import { and, eq |
| 5 | |
| 6 | export type OauthApp |
| 7 | clientId: string |
| 8 | name: string |
| 9 | redirectUris: string |
| 10 | deviceFlowEnabled: boolean |
| 11 | /** GitHub's "Expire user authorization tokens": keys last 8 hours and come with a refresh token. */ |
| 12 | expireUserTokens: boolean |
| 13 | /** Built into the instance, such as gh: no owner, and no one can edit or delete it. */ |
| 14 | builtIn: boolean |
| 15 | ownerId: string |
| 16 | /** Slug of the organization that owns the app, null for a user's app. */ |
| 17 | organization: string |
| 18 | }; |
| 19 | |
| 20 | /** The organization a call into the oauth-provider plugin acts for. The plugin's `clientReference` reads it, so an org's app is created with it as `referenceId` and only calls made for that org may change it. Outside a call it is unset, and apps belong to users. */ |
| 21 | export const oauthAppOrganization = |
| 22 | |
| 23 | /** Columns of an OAuth app as Ghost names them, shared by every query that reads one. */ |
| 24 | export const oauthAppColumns = |
| 25 | clientId: schema.oauthClient |
| 26 | name: sql<string |
| 27 | description: sql< |
| 28 | string | null |
| 29 | >`${schema.oauthClient |
| 30 | logoUrl: schema.oauthClient |
| 31 | homepageUrl: sql<string |
| 32 | deviceFlowEnabled: sql<boolean |
| 33 | expireUserTokens: sql<boolean |
| 34 | }; |
| 35 | |
| 36 | /** Vouched for by the instance. Only an operator sets it, in the database or the seed; no API writes it. */ |
| 37 | export const oauthAppVerified = |
| 38 | |
| 39 | /** The OAuth app an API key was minted for, null for keys made in Ghost. */ |
| 40 | export const keyOauthClientId = |
| 41 | string | null |
| 42 | >`${schema.apikey. |
| 43 | |
| 44 | /** The plugin leaves `disabled` null on apps it never touched. */ |
| 45 | export const oauthAppEnabled = |
| 46 | |
| 47 | /** An enabled OAuth app from the oauth-provider plugin's registry, or null. */ |
| 48 | export async function findOauthApp |
| 49 | db: Database |
| 50 | clientId: string, |
| 51 | ): Promise<OauthApp |
| 52 | const [app] |
| 53 | .select({ |
| 54 | clientId: oauthAppColumns.clientId |
| 55 | name: oauthAppColumns.name |
| 56 | deviceFlowEnabled: oauthAppColumns.deviceFlowEnabled |
| 57 | expireUserTokens: oauthAppColumns.expireUserTokens |
| 58 | redirectUris: schema.oauthClient |
| 59 | builtIn: sql<boolean |
| 60 | ownerId: schema.oauthClient |
| 61 | organization: schema.organization |
| 62 | }) |
| 63 | .from(schema.oauthClient |
| 64 | .leftJoin( |
| 65 | schema.organization, |
| 66 | eq(schema.organization |
| 67 | ) |
| 68 | .where(and(eq |
| 69 | return app ?? |
| 70 | } |