@inixiative/integrations 0.2.1 → 0.4.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.
Files changed (212) hide show
  1. package/README.md +21 -13
  2. package/package.json +4 -3
  3. package/src/catalog/acceptedCredentialMethods.ts +17 -0
  4. package/src/catalog/catalogOperationMeta.ts +4 -0
  5. package/src/catalog/catalogOperations.ts +10 -0
  6. package/src/catalog/integrationFamilies.ts +12 -0
  7. package/src/catalog/integrationFamilyDefinition.ts +6 -0
  8. package/src/catalog/isAccountSuppliedByHost.ts +2 -2
  9. package/src/catalog/providerAuthenticatesThroughIntegrationFamily.ts +6 -0
  10. package/src/catalog/providerModel.ts +0 -1
  11. package/src/catalog/providers.ts +0 -4
  12. package/src/catalog/providersInIntegrationFamily.ts +5 -0
  13. package/src/contracts.ts +36 -25
  14. package/src/credentials/credentialAuth.ts +38 -0
  15. package/src/credentials/credentialClient.ts +2 -2
  16. package/src/credentials/exchangeOauthCode.ts +41 -41
  17. package/src/credentials/mintProviderCredential.ts +26 -40
  18. package/src/credentials/providerExchangeTimeoutMs.ts +1 -1
  19. package/src/credentials/refreshProviderCredential.ts +102 -83
  20. package/src/credentials/renewalError.ts +11 -0
  21. package/src/credentials/renewalOwner.ts +3 -0
  22. package/src/credentials/requestOauthToken.ts +28 -0
  23. package/src/credentials/validateCredentialSecret.ts +5 -5
  24. package/src/index.ts +0 -1
  25. package/src/integrationFamilies/atlassianIntegrationFamily.ts +12 -0
  26. package/src/{providers/github/githubProvider.ts → integrationFamilies/githubIntegrationFamily.ts} +2 -3
  27. package/src/{providers/google/googleProvider.ts → integrationFamilies/googleIntegrationFamily.ts} +2 -3
  28. package/src/integrationFamilies/inixiativeIntegrationFamily.ts +8 -0
  29. package/src/operations/providerOperationInput.ts +6 -0
  30. package/src/operations/providerOperationInputSchema.ts +36 -0
  31. package/src/operations/providerOperationOrThrow.ts +23 -0
  32. package/src/operations/providerOperationSet.ts +7 -0
  33. package/src/operations/providerOperations.ts +38 -0
  34. package/src/providers/chorus/chorusProvider.ts +1 -0
  35. package/src/providers/confluence/confluenceApiBaseUrl.ts +1 -0
  36. package/src/providers/confluence/confluenceOperations.ts +4 -0
  37. package/src/providers/confluence/confluenceProvider.ts +6 -8
  38. package/src/providers/confluence/models/page/fetchConfluencePage.ts +23 -0
  39. package/src/providers/discord/discordApiBaseUrl.ts +1 -0
  40. package/src/providers/discord/discordOperations.ts +8 -0
  41. package/src/providers/discord/discordProvider.ts +5 -14
  42. package/src/providers/discord/models/channel/discordChannelKind.ts +1 -0
  43. package/src/providers/discord/models/channel/fetchDiscordChannel.ts +25 -0
  44. package/src/providers/discord/models/channel/fetchDiscordChannelMessages.ts +37 -0
  45. package/src/providers/drive/driveApiBaseUrl.ts +1 -0
  46. package/src/providers/drive/driveOperations.ts +4 -0
  47. package/src/providers/drive/driveProvider.ts +7 -10
  48. package/src/providers/drive/models/file/fetchDriveFile.ts +27 -0
  49. package/src/providers/github/auth/createGithubInstallationToken.ts +19 -0
  50. package/src/providers/github/auth/fetchGithubAppInstallUrl.ts +21 -0
  51. package/src/providers/github/auth/fetchGithubAppInstallation.ts +16 -19
  52. package/src/providers/github/auth/fetchGithubOrganizationRole.ts +22 -22
  53. package/src/providers/github/auth/fetchGithubUser.ts +10 -4
  54. package/src/providers/github/auth/githubAppAuth.ts +6 -0
  55. package/src/providers/github/auth/githubUserAuthorizeUrl.ts +2 -2
  56. package/src/providers/github/auth/listGithubUserInstallationPage.ts +18 -0
  57. package/src/providers/github/events/listGithubNotificationPage.ts +18 -0
  58. package/src/providers/github/githubApiBaseUrl.ts +1 -0
  59. package/src/providers/github/githubOrganizationProvider.ts +6 -2
  60. package/src/providers/github/githubPagination.ts +2 -2
  61. package/src/providers/github/githubRequestHeaders.ts +4 -6
  62. package/src/providers/github/githubUserProvider.ts +7 -4
  63. package/src/providers/github/models/account/githubAccount.ts +0 -1
  64. package/src/providers/github/models/repository/fetchGithubBlob.ts +59 -0
  65. package/src/providers/github/models/repository/fetchGithubCommit.ts +38 -0
  66. package/src/providers/github/models/repository/fetchGithubTree.ts +74 -0
  67. package/src/providers/github/models/repository/githubObjectRequest.ts +15 -0
  68. package/src/providers/github/models/repository/githubRepository.ts +1 -11
  69. package/src/providers/github/models/repository/githubRepositoryOperations.ts +10 -0
  70. package/src/providers/github/models/repository/listGithubInstallationRepositoryPage.ts +18 -0
  71. package/src/providers/github/models/repository/listGithubUserInstallationRepositoryPage.ts +22 -0
  72. package/src/providers/github/models/repository/readGithubObjectIdentity.ts +9 -0
  73. package/src/providers/github/services/fetchGithubUserInstallation.ts +25 -0
  74. package/src/providers/github/services/listGithubNotifications.ts +27 -0
  75. package/src/providers/github/services/listInstallationRepositories.ts +34 -0
  76. package/src/providers/github/services/listUserRepositories.ts +43 -0
  77. package/src/providers/gmail/gmailApiBaseUrl.ts +1 -0
  78. package/src/providers/gmail/gmailOperations.ts +10 -0
  79. package/src/providers/gmail/gmailProvider.ts +8 -11
  80. package/src/providers/gmail/models/label/listGmailLabelMessages.ts +45 -0
  81. package/src/providers/gmail/models/message/fetchGmailMessage.ts +19 -0
  82. package/src/providers/gmail/models/message/fetchGmailMessageBatch.ts +20 -0
  83. package/src/providers/gmail/models/message/gmailMessageKind.ts +1 -0
  84. package/src/providers/gmail/models/message/gmailMessageRequest.ts +9 -0
  85. package/src/providers/gmail/models/message/readGmailMessage.ts +26 -0
  86. package/src/providers/google/auth/buildGoogleAuthorizationUrl.ts +2 -1
  87. package/src/providers/google/auth/verifyGoogleIdToken.ts +3 -3
  88. package/src/providers/jira/jiraApiBaseUrl.ts +1 -0
  89. package/src/providers/jira/jiraOperations.ts +4 -0
  90. package/src/providers/jira/jiraProvider.ts +6 -8
  91. package/src/providers/jira/models/issue/fetchJiraIssue.ts +22 -0
  92. package/src/providers/linear/events/createLinearWebhook.ts +29 -20
  93. package/src/providers/linear/events/deleteLinearWebhook.ts +16 -9
  94. package/src/providers/linear/events/linearWebhook.ts +1 -1
  95. package/src/providers/linear/events/listLinearWebhookPage.ts +23 -0
  96. package/src/providers/linear/events/repairLinearWebhook.ts +17 -13
  97. package/src/providers/linear/linearApiBaseUrl.ts +1 -0
  98. package/src/providers/linear/linearGraphqlErrorCode.ts +8 -0
  99. package/src/providers/linear/linearOperations.ts +4 -0
  100. package/src/providers/linear/linearPagination.ts +3 -9
  101. package/src/providers/linear/linearProvider.ts +5 -2
  102. package/src/providers/linear/models/issue/fetchLinearIssue.ts +32 -0
  103. package/src/providers/linear/models/team/fetchLinearWorkspace.ts +23 -13
  104. package/src/providers/linear/models/team/linearTeam.ts +0 -1
  105. package/src/providers/linear/services/listLinearWebhooks.ts +45 -0
  106. package/src/providers/notion/models/page/fetchNotionPage.ts +32 -0
  107. package/src/providers/notion/models/page/fetchNotionPageBlocks.ts +39 -0
  108. package/src/providers/notion/models/page/notionPageKind.ts +1 -0
  109. package/src/providers/notion/notionApiBaseUrl.ts +1 -0
  110. package/src/providers/notion/notionOperations.ts +8 -0
  111. package/src/providers/notion/notionProvider.ts +5 -14
  112. package/src/providers/notion/notionVersion.ts +1 -0
  113. package/src/providers/oracle/oracleProvider.ts +1 -0
  114. package/src/providers/slack/auth/fetchSlackIdentity.ts +14 -6
  115. package/src/providers/slack/models/account/slackAccount.ts +0 -1
  116. package/src/providers/slack/models/channel/fetchSlackChannel.ts +32 -0
  117. package/src/providers/slack/models/channel/fetchSlackChannelMessages.ts +34 -0
  118. package/src/providers/slack/models/channel/listSlackUserConversations.ts +19 -0
  119. package/src/providers/slack/models/channel/slackChannel.ts +0 -14
  120. package/src/providers/slack/readSlackBody.ts +10 -0
  121. package/src/providers/slack/services/listSlackChannels.ts +23 -0
  122. package/src/providers/slack/slackApiBaseUrl.ts +1 -0
  123. package/src/providers/slack/slackOperations.ts +8 -0
  124. package/src/providers/slack/slackPagination.ts +2 -2
  125. package/src/providers/slack/slackProvider.ts +9 -1
  126. package/src/providers/slack/slackProviderError.ts +2 -2
  127. package/src/providers/teams/models/channel/fetchTeamsChannelMessages.ts +36 -0
  128. package/src/providers/teams/teamsApiBaseUrl.ts +1 -0
  129. package/src/providers/teams/teamsOperations.ts +6 -0
  130. package/src/providers/teams/teamsProvider.ts +5 -8
  131. package/src/utils/acceptJsonHeaders.ts +1 -0
  132. package/src/utils/pageQuerySchema.ts +13 -0
  133. package/src/utils/readProviderLimits.ts +1 -2
  134. package/src/catalog/familyProducts.ts +0 -5
  135. package/src/catalog/isFamilyManaged.ts +0 -7
  136. package/src/catalog/providerFamily.ts +0 -4
  137. package/src/credentials/fetchRenewalResponse.ts +0 -41
  138. package/src/credentials/renewalRequest.ts +0 -1
  139. package/src/operations/buildProviderRequest.ts +0 -54
  140. package/src/operations/executeProvider.ts +0 -26
  141. package/src/operations/findOperationHandler.ts +0 -6
  142. package/src/operations/operationHandler.ts +0 -8
  143. package/src/operations/operationHandlers.ts +0 -41
  144. package/src/operations/operationRequestInput.ts +0 -12
  145. package/src/operations/providerRequestSpec.ts +0 -1
  146. package/src/providers/confluence/confluenceOperationHandler.ts +0 -14
  147. package/src/providers/discord/discordOperationHandler.ts +0 -30
  148. package/src/providers/drive/driveOperationHandler.ts +0 -21
  149. package/src/providers/github/auth/fetchGithubUserInstallation.ts +0 -21
  150. package/src/providers/github/auth/githubAppClient.ts +0 -4
  151. package/src/providers/github/auth/githubAppInstallUrl.ts +0 -20
  152. package/src/providers/github/auth/githubClientForApp.ts +0 -11
  153. package/src/providers/github/events/listGithubNotifications.ts +0 -27
  154. package/src/providers/github/fetchAllGithubPages.ts +0 -12
  155. package/src/providers/github/iterateGithubPages.ts +0 -12
  156. package/src/providers/github/models/repository/githubOperationHandler.ts +0 -36
  157. package/src/providers/github/models/repository/listInstallationRepositories.ts +0 -31
  158. package/src/providers/github/models/repository/listUserRepositories.ts +0 -36
  159. package/src/providers/github/models/repository/readGithubObject.ts +0 -85
  160. package/src/providers/github/requestGithub.ts +0 -18
  161. package/src/providers/gmail/buildGmailMessageRequest.ts +0 -22
  162. package/src/providers/gmail/fetchGmailMessages.ts +0 -81
  163. package/src/providers/gmail/gmailOperationHandler.ts +0 -12
  164. package/src/providers/jira/jiraOperationHandler.ts +0 -14
  165. package/src/providers/linear/events/listLinearWebhooks.ts +0 -44
  166. package/src/providers/linear/fetchAllLinearPages.ts +0 -40
  167. package/src/providers/linear/linearClient.ts +0 -5
  168. package/src/providers/linear/linearRequestInput.ts +0 -1
  169. package/src/providers/linear/models/issue/linearIssue.ts +0 -11
  170. package/src/providers/linear/models/issue/linearOperationHandler.ts +0 -30
  171. package/src/providers/linear/requestLinear.ts +0 -51
  172. package/src/providers/notion/notionOperationHandler.ts +0 -32
  173. package/src/providers/slack/fetchAllSlackPages.ts +0 -12
  174. package/src/providers/slack/models/channel/listSlackChannels.ts +0 -26
  175. package/src/providers/slack/models/channel/slackOperationHandler.ts +0 -30
  176. package/src/providers/slack/requestSlack.ts +0 -22
  177. package/src/providers/teams/teamsOperationHandler.ts +0 -24
  178. package/src/utils/headerNumber.ts +0 -6
  179. package/src/utils/pagination/applyCaps.ts +0 -18
  180. package/src/utils/pagination/byCursorKeys.ts +0 -7
  181. package/src/utils/pagination/byCursorOptions.ts +0 -7
  182. package/src/utils/pagination/byPageKeys.ts +0 -7
  183. package/src/utils/pagination/byPageOptions.ts +0 -8
  184. package/src/utils/pagination/collectPages.ts +0 -27
  185. package/src/utils/pagination/compactRequest.ts +0 -4
  186. package/src/utils/pagination/fetchAllByCursor.ts +0 -6
  187. package/src/utils/pagination/fetchAllByPage.ts +0 -6
  188. package/src/utils/pagination/fetchAllRequestPages.ts +0 -16
  189. package/src/utils/pagination/incompletePageWalkError.ts +0 -8
  190. package/src/utils/pagination/isAnotherPage.ts +0 -20
  191. package/src/utils/pagination/iterateByCursor.ts +0 -49
  192. package/src/utils/pagination/iterateByPage.ts +0 -59
  193. package/src/utils/pagination/iterateProviderPages.ts +0 -27
  194. package/src/utils/pagination/iterateRequestPages.ts +0 -18
  195. package/src/utils/pagination/pageWalkError.ts +0 -6
  196. package/src/utils/pagination/paginationOptions.ts +0 -9
  197. package/src/utils/pagination/providerPagesOptions.ts +0 -8
  198. package/src/utils/pagination/providerPagination.ts +0 -6
  199. package/src/utils/pagination/readPage.ts +0 -29
  200. package/src/utils/pagination/readPath.ts +0 -12
  201. package/src/utils/pagination/repeatedCursorError.ts +0 -10
  202. package/src/utils/providerClient.ts +0 -3
  203. package/src/utils/providerError.ts +0 -10
  204. package/src/utils/providerRequest.ts +0 -22
  205. package/src/utils/providerRequestInput.ts +0 -7
  206. package/src/utils/providerResponseLimit.ts +0 -1
  207. package/src/utils/providerSend.ts +0 -1
  208. package/src/utils/readProviderJson.ts +0 -38
  209. package/src/utils/readRateLimit.ts +0 -29
  210. package/src/utils/requestProviderJson.ts +0 -13
  211. package/src/utils/responseBudget.ts +0 -1
  212. package/src/utils/sendProviderRequest.ts +0 -33
package/README.md CHANGED
@@ -24,27 +24,35 @@ operationLeaves('githubOrganization', 'repository');
24
24
 
25
25
  ## Shape
26
26
 
27
- Each provider has a folder under `src/providers/`, with `auth/`, `events/` and `models/<model>/` inside it where it has that code, and a `<provider>Provider.ts` definition that `src/catalog/providers.ts` lists.
27
+ Each provider has a folder under `src/providers/`, with `auth/`, `events/`, `models/<model>/` and `services/` inside it where it has that code, a `<provider>Operations.ts` of its catalog operations and a `<provider>Provider.ts` definition that `src/catalog/providers.ts` lists. The definition's `operations` are generated from the operations.
28
28
 
29
- A call that reaches a provider takes the client first, then the request, then anything that is not part of the request:
29
+ Every call is an atomic operation from `@inixiative/api-client`, called `(client, input, options?)`:
30
30
 
31
31
  ```ts
32
- import { fetchAllGithubPages } from '@inixiative/integrations/providers/github/fetchAllGithubPages';
33
-
34
- await fetchAllGithubPages(
35
- { token, send },
36
- { path: '/notifications', query: { since, per_page: 50 } },
37
- { maxPages: 10 },
38
- );
32
+ import { findProvider } from '@inixiative/integrations/catalog/findProvider';
33
+ import { credentialAuth } from '@inixiative/integrations/credentials/credentialAuth';
34
+ import { providerOperationOrThrow } from '@inixiative/integrations/operations/providerOperationOrThrow';
35
+
36
+ const client = {
37
+ baseUrl: findProvider('slack')?.apiBaseUrl ?? '',
38
+ auth: credentialAuth({ provider: 'slack', method: 'bearer', token: async () => secret.token }),
39
+ send,
40
+ };
41
+ await providerOperationOrThrow('slack', 'messages.read')(client, {
42
+ resource: { kind: 'channel', externalId: 'C123', metadata: {} },
43
+ configuration: {},
44
+ limit: 15,
45
+ input: {},
46
+ });
39
47
  ```
40
48
 
41
- - **Client:** `{ token, send? }`. `send` is any `fetch`, so a recording or stubbed fetch drops in.
42
- - **Input:** `{ path, method?, query?, body?, headers? }`.
43
- - **Options:** pagination keys and caps.
49
+ - **Client:** `{ baseUrl, auth?, send? }`. `send` is any `fetch`, so a recording or stubbed fetch drops in.
50
+ - **Input:** a catalog operation takes the stored resource, the integration's configuration, a limit and the operation's own input.
51
+ - **Options:** `auth`, `logger`, `retry`, `signal`, `timeoutMs`.
44
52
 
45
53
  ## Pagination
46
54
 
47
- `src/utils/pagination/` reads page-numbered and cursor lists. A provider declares its strategy, its parameter names and where its responses keep the list (`githubPagination`, `slackPagination`, `linearPagination`); a call may replace any key in its options.
55
+ `@inixiative/api-client/http/pagination` reads page-numbered and cursor lists, and `@inixiative/api-client/graphql` walks a GraphQL connection. A provider declares its strategy, its parameter names and where its responses keep the list (`githubPagination`, `slackPagination`, `linearPagination`); a service walks a list by calling one list operation per page.
48
56
 
49
57
  ## License
50
58
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@inixiative/integrations",
3
- "version": "0.2.1",
3
+ "version": "0.4.0",
4
4
  "description": "The provider catalog behind Kingdom integrations: each provider's operations, events, resource kinds and scopes, with the request, webhook and credential code that reaches it.",
5
5
  "type": "module",
6
6
  "main": "src/index.ts",
@@ -30,12 +30,13 @@
30
30
  ],
31
31
  "license": "MIT",
32
32
  "dependencies": {
33
- "@inixiative/signet": "^0.28.0",
33
+ "@inixiative/api-client": "^0.2.4",
34
+ "@inixiative/signet": "^0.29.0",
34
35
  "jose": "^6.2.3"
35
36
  },
36
37
  "devDependencies": {
37
38
  "@biomejs/biome": "2.5.2",
38
- "@inixiative/config": "^0.5.237",
39
+ "@inixiative/config": "^0.5.258",
39
40
  "@types/bun": "1.4.4",
40
41
  "lefthook": "2.1.9",
41
42
  "typescript": "6.0.3",
@@ -0,0 +1,17 @@
1
+ import { type CredentialMethod, credentialMethodSchema, type Provider } from '../contracts';
2
+ import { findProvider } from './findProvider';
3
+ import { integrationFamilyDefinition } from './integrationFamilyDefinition';
4
+
5
+ export const acceptedCredentialMethods = (
6
+ provider: Provider | null | undefined,
7
+ ): CredentialMethod[] => {
8
+ const definition = findProvider(provider);
9
+ if (!definition) return [];
10
+ const ownMethods = definition.authMethods.flatMap(
11
+ (method) => credentialMethodSchema.safeParse(method).data ?? [],
12
+ );
13
+ if (!definition.authMethods.includes('integrationFamily')) return ownMethods;
14
+ const familyMethods =
15
+ integrationFamilyDefinition(definition.integrationFamily)?.authMethods ?? [];
16
+ return [...new Set([...ownMethods, ...familyMethods])];
17
+ };
@@ -0,0 +1,4 @@
1
+ import type { z } from 'zod';
2
+ import type { catalogOperationSchema } from '../contracts';
3
+
4
+ export type CatalogOperationMeta = Omit<z.infer<typeof catalogOperationSchema>, 'key'>;
@@ -0,0 +1,10 @@
1
+ import type { ProviderDefinition } from '../contracts';
2
+ import type { ProviderOperationSet } from '../operations/providerOperationSet';
3
+
4
+ export const catalogOperations = (
5
+ operations: ProviderOperationSet,
6
+ ): ProviderDefinition['operations'] =>
7
+ Object.values(operations).map(({ definition: { key, meta } }) => {
8
+ if (!meta) throw new Error(`catalog operation ${key} declares no meta`);
9
+ return { key, ...meta };
10
+ });
@@ -0,0 +1,12 @@
1
+ import type { IntegrationFamilyDefinition } from '../contracts';
2
+ import { atlassianIntegrationFamily } from '../integrationFamilies/atlassianIntegrationFamily';
3
+ import { githubIntegrationFamily } from '../integrationFamilies/githubIntegrationFamily';
4
+ import { googleIntegrationFamily } from '../integrationFamilies/googleIntegrationFamily';
5
+ import { inixiativeIntegrationFamily } from '../integrationFamilies/inixiativeIntegrationFamily';
6
+
7
+ export const integrationFamilies: IntegrationFamilyDefinition[] = [
8
+ googleIntegrationFamily,
9
+ githubIntegrationFamily,
10
+ atlassianIntegrationFamily,
11
+ inixiativeIntegrationFamily,
12
+ ];
@@ -0,0 +1,6 @@
1
+ import type { IntegrationFamily } from '../contracts';
2
+ import { integrationFamilies } from './integrationFamilies';
3
+
4
+ export const integrationFamilyDefinition = (
5
+ integrationFamily: IntegrationFamily | null | undefined,
6
+ ) => integrationFamilies.find((definition) => definition.key === integrationFamily);
@@ -1,6 +1,6 @@
1
1
  import type { Provider } from '../contracts';
2
- import { isFamilyManaged } from './isFamilyManaged';
2
+ import { providerAuthenticatesThroughIntegrationFamily } from './providerAuthenticatesThroughIntegrationFamily';
3
3
  import { providerHasEvents } from './providerHasEvents';
4
4
 
5
5
  export const isAccountSuppliedByHost = (provider: Provider | null | undefined) =>
6
- isFamilyManaged(provider) || providerHasEvents(provider);
6
+ providerAuthenticatesThroughIntegrationFamily(provider) || providerHasEvents(provider);
@@ -0,0 +1,6 @@
1
+ import type { Provider } from '../contracts';
2
+ import { findProvider } from './findProvider';
3
+
4
+ export const providerAuthenticatesThroughIntegrationFamily = (
5
+ provider: Provider | null | undefined,
6
+ ) => Boolean(findProvider(provider)?.authMethods.includes('integrationFamily'));
@@ -6,7 +6,6 @@ export type ProviderModel = {
6
6
  kind: string;
7
7
  externalIdSchema?: z.ZodType<string>;
8
8
  metadataSchema?: z.ZodType;
9
- operations: ProviderDefinition['operations'];
10
9
  events: ProviderDefinition['operations'];
11
10
  externalIdOfEvent?: (event: Pick<IntegrationEvent, 'scope' | 'payload'>) => string | null;
12
11
  };
@@ -10,10 +10,8 @@ import { driveProvider } from '../providers/drive/driveProvider';
10
10
  import { foundryProvider } from '../providers/foundry/foundryProvider';
11
11
  import { geminiApiProvider } from '../providers/geminiApi/geminiApiProvider';
12
12
  import { githubOrganizationProvider } from '../providers/github/githubOrganizationProvider';
13
- import { githubProvider } from '../providers/github/githubProvider';
14
13
  import { githubUserProvider } from '../providers/github/githubUserProvider';
15
14
  import { gmailProvider } from '../providers/gmail/gmailProvider';
16
- import { googleProvider } from '../providers/google/googleProvider';
17
15
  import { jiraProvider } from '../providers/jira/jiraProvider';
18
16
  import { linearProvider } from '../providers/linear/linearProvider';
19
17
  import { museProvider } from '../providers/muse/museProvider';
@@ -32,7 +30,6 @@ export const providers: ProviderDefinition[] = [
32
30
  linearProvider,
33
31
  notionProvider,
34
32
  jiraProvider,
35
- googleProvider,
36
33
  gmailProvider,
37
34
  driveProvider,
38
35
  confluenceProvider,
@@ -43,7 +40,6 @@ export const providers: ProviderDefinition[] = [
43
40
  foundryProvider,
44
41
  oracleProvider,
45
42
  chorusProvider,
46
- githubProvider,
47
43
  githubOrganizationProvider,
48
44
  githubUserProvider,
49
45
  railwayProvider,
@@ -0,0 +1,5 @@
1
+ import type { IntegrationFamily } from '../contracts';
2
+ import { providers } from './providers';
3
+
4
+ export const providersInIntegrationFamily = (integrationFamily: IntegrationFamily) =>
5
+ providers.filter((definition) => definition.integrationFamily === integrationFamily);
package/src/contracts.ts CHANGED
@@ -35,11 +35,14 @@ export const credentialSecretSchema = z.strictObject({
35
35
  });
36
36
  export type CredentialSecret = z.infer<typeof credentialSecretSchema>;
37
37
  export const credentialMethodSchema = z.enum(['bearer', 'apiKey', 'oauth2', 'clientCredentials']);
38
+ export type CredentialMethod = z.infer<typeof credentialMethodSchema>;
38
39
  export const renewableCredentialMethods: string[] = credentialMethodSchema.extract([
39
40
  'oauth2',
40
41
  'clientCredentials',
41
42
  ]).options;
42
43
  export const isRenewableMethod = (method: string) => renewableCredentialMethods.includes(method);
44
+ export const authMethodSchema = z.enum([...credentialMethodSchema.options, 'integrationFamily']);
45
+ export type AuthMethod = z.infer<typeof authMethodSchema>;
43
46
 
44
47
  export const catalogOperationSchema = z.object({
45
48
  key: operationKeySchema,
@@ -54,7 +57,6 @@ export const providerSchema = z.enum([
54
57
  'linear',
55
58
  'notion',
56
59
  'jira',
57
- 'google',
58
60
  'gmail',
59
61
  'drive',
60
62
  'confluence',
@@ -62,7 +64,6 @@ export const providerSchema = z.enum([
62
64
  'openai',
63
65
  'geminiApi',
64
66
  'archive',
65
- 'github',
66
67
  'githubOrganization',
67
68
  'githubUser',
68
69
  'foundry',
@@ -74,19 +75,39 @@ export const providerSchema = z.enum([
74
75
  'codex',
75
76
  'muse',
76
77
  ]);
77
- export const providerDefinitionSchema = z.object({
78
- key: providerSchema,
79
- name: z.string(),
80
- documentationUrl: z.url(),
81
- authMethods: z.array(credentialMethodSchema),
82
- operations: z.array(catalogOperationSchema),
83
- inbound: z.boolean().optional(),
84
- delivery: z.literal('installationSocket').optional(),
85
- subscription: z.boolean().optional(),
86
- family: providerSchema.optional(),
87
- oauthScopes: z.array(z.string()).optional(),
88
- oauth: z.object({ authorizeUrl: z.url(), tokenUrl: z.url() }).optional(),
89
- });
78
+ export const integrationFamilySchema = z.enum(['google', 'github', 'atlassian', 'inixiative']);
79
+ export type IntegrationFamily = z.infer<typeof integrationFamilySchema>;
80
+ export const integrationFamilyDefinitionSchema = z
81
+ .object({
82
+ key: integrationFamilySchema,
83
+ name: z.string(),
84
+ documentationUrl: z.url(),
85
+ authMethods: z.array(credentialMethodSchema),
86
+ oauth: z.object({ authorizeUrl: z.url(), tokenUrl: z.url() }).optional(),
87
+ })
88
+ .refine((definition) => !definition.authMethods.includes('oauth2') || definition.oauth, {
89
+ message: 'an integration family with oauth2 auth needs its OAuth endpoints',
90
+ });
91
+ export type IntegrationFamilyDefinition = z.infer<typeof integrationFamilyDefinitionSchema>;
92
+ export const providerDefinitionSchema = z
93
+ .object({
94
+ key: providerSchema,
95
+ name: z.string(),
96
+ documentationUrl: z.url(),
97
+ authMethods: z.array(authMethodSchema),
98
+ apiBaseUrl: z.url({ protocol: /^https$/ }).optional(),
99
+ operations: z.array(catalogOperationSchema),
100
+ inbound: z.boolean().optional(),
101
+ delivery: z.literal('installationSocket').optional(),
102
+ subscription: z.boolean().optional(),
103
+ integrationFamily: integrationFamilySchema.optional(),
104
+ oauthScopes: z.array(z.string()).optional(),
105
+ })
106
+ .refine(
107
+ (definition) =>
108
+ !definition.authMethods.includes('integrationFamily') || definition.integrationFamily,
109
+ { message: 'integrationFamily auth needs the provider to name its integrationFamily' },
110
+ );
90
111
  export type Provider = z.infer<typeof providerSchema>;
91
112
  export type OAuthClient = { clientId: string; clientSecret: string };
92
113
  export type SigningClient = OAuthClient & { appId: string; privateKey: string };
@@ -95,13 +116,3 @@ export type ProviderDefinition = z.infer<typeof providerDefinitionSchema> & {
95
116
  syncedResourceKinds?: string[];
96
117
  holderHandleKinds?: string[];
97
118
  };
98
- export type ProviderContext = {
99
- provider: Provider;
100
- configuration: unknown;
101
- resource: { kind: string; externalId: string; metadata: unknown };
102
- operation: string;
103
- input: Record<string, unknown>;
104
- limit: number;
105
- method: z.infer<typeof credentialMethodSchema>;
106
- secret: z.infer<typeof credentialSecretSchema>;
107
- };
@@ -0,0 +1,38 @@
1
+ import { ApiError } from '@inixiative/api-client';
2
+ import {
3
+ type ApiAuth,
4
+ type ApiTokenSource,
5
+ bearerAuth,
6
+ headerAuth,
7
+ } from '@inixiative/api-client/operation';
8
+ import { acceptedCredentialMethods } from '../catalog/acceptedCredentialMethods';
9
+ import { type CredentialMethod, credentialSecretSchema, type Provider } from '../contracts';
10
+
11
+ const apiKeyHeaders: Partial<Record<Provider, { name: string; prefix?: string }>> = {
12
+ discord: { name: 'Authorization', prefix: 'Bot ' },
13
+ anthropic: { name: 'x-api-key' },
14
+ geminiApi: { name: 'x-goog-api-key' },
15
+ openai: { name: 'Authorization', prefix: 'Bearer ' },
16
+ };
17
+
18
+ export const credentialAuth = ({
19
+ provider,
20
+ method,
21
+ token,
22
+ }: {
23
+ provider: Provider;
24
+ method: CredentialMethod;
25
+ token: ApiTokenSource;
26
+ }): ApiAuth => {
27
+ if (!acceptedCredentialMethods(provider).includes(method))
28
+ throw new ApiError('unsupported_authentication', 400);
29
+ // why: the token becomes a header value, so a line break in it would add a header of its own.
30
+ const checked = async () => {
31
+ const parsed = credentialSecretSchema.shape.token.safeParse(await token());
32
+ if (!parsed.success) throw new ApiError('unsupported_authentication', 400);
33
+ return parsed.data;
34
+ };
35
+ if (method !== 'apiKey') return bearerAuth(checked);
36
+ const header = apiKeyHeaders[provider] ?? { name: 'Authorization' };
37
+ return headerAuth(header.name, checked, { prefix: header.prefix });
38
+ };
@@ -1,4 +1,4 @@
1
+ import type { ApiSend } from '@inixiative/api-client';
1
2
  import type { OAuthClient, SigningClient } from '../contracts';
2
- import type { ProviderSend } from '../utils/providerSend';
3
3
 
4
- export type CredentialClient = { app?: OAuthClient | SigningClient; send?: ProviderSend };
4
+ export type CredentialClient = { app?: OAuthClient | SigningClient; send?: ApiSend };
@@ -1,9 +1,10 @@
1
+ import { ApiError, type ApiSend } from '@inixiative/api-client';
2
+ import type { ApiOperationOptions } from '@inixiative/api-client/operation';
1
3
  import { z } from 'zod';
2
- import { findProvider } from '../catalog/findProvider';
3
- import type { OAuthClient, Provider } from '../contracts';
4
- import { ProviderError } from '../utils/providerError';
5
- import type { ProviderSend } from '../utils/providerSend';
6
- import { readProviderJson } from '../utils/readProviderJson';
4
+ import { integrationFamilyDefinition } from '../catalog/integrationFamilyDefinition';
5
+ import type { IntegrationFamily, OAuthClient } from '../contracts';
6
+ import { providerExchangeTimeoutMs } from './providerExchangeTimeoutMs';
7
+ import { requestOauthToken } from './requestOauthToken';
7
8
 
8
9
  const tokenResponseSchema = z.object({
9
10
  access_token: z.string().min(1).max(16000),
@@ -13,44 +14,43 @@ const tokenResponseSchema = z.object({
13
14
  id_token: z.string().min(1).optional(),
14
15
  });
15
16
 
17
+ const exchangeError = (error: unknown) =>
18
+ error instanceof ApiError && error.code === 'provider_unreachable'
19
+ ? new ApiError('provider_unreachable', 502)
20
+ : new ApiError('code_exchange_failed', 502);
21
+
16
22
  export const exchangeOauthCode = async (
17
- { app, send = fetch }: { app: OAuthClient; send?: ProviderSend },
18
- input: { family: Provider; code: string; codeVerifier?: string; redirectUri?: string },
23
+ { app, send }: { app: OAuthClient; send?: ApiSend },
24
+ input: {
25
+ integrationFamily: IntegrationFamily;
26
+ code: string;
27
+ codeVerifier?: string;
28
+ redirectUri?: string;
29
+ },
30
+ options?: ApiOperationOptions,
19
31
  ) => {
20
- const { family } = input;
21
- const tokenUrl = z.url().parse(findProvider(family)?.oauth?.tokenUrl);
22
- let response: Response;
23
- try {
24
- response = await send(
25
- new Request(tokenUrl, {
26
- method: 'POST',
27
- headers: {
28
- Accept: 'application/json',
29
- 'Content-Type': 'application/x-www-form-urlencoded',
30
- },
31
- body: new URLSearchParams({
32
- grant_type: 'authorization_code',
33
- code: input.code,
34
- client_id: app.clientId,
35
- client_secret: app.clientSecret,
36
- ...(input.redirectUri ? { redirect_uri: input.redirectUri } : {}),
37
- ...(input.codeVerifier ? { code_verifier: input.codeVerifier } : {}),
38
- }).toString(),
39
- redirect: 'error',
40
- signal: AbortSignal.timeout(15000),
41
- }),
42
- );
43
- } catch {
44
- throw new ProviderError('provider_unreachable', 502);
45
- }
46
- if (!response.ok) {
47
- await response.body?.cancel();
48
- throw new ProviderError('code_exchange_failed', 502);
49
- }
50
- const parsed = tokenResponseSchema.safeParse(
51
- await readProviderJson(response, { remainingBytes: 128 * 1024 }).catch(() => null),
52
- );
53
- if (!parsed.success) throw new ProviderError('code_exchange_failed', 502);
32
+ const tokenUrl = z
33
+ .url()
34
+ .parse(integrationFamilyDefinition(input.integrationFamily)?.oauth?.tokenUrl);
35
+ const answer = await requestOauthToken(
36
+ { baseUrl: tokenUrl, send },
37
+ {
38
+ encoding: 'form',
39
+ fields: {
40
+ grant_type: 'authorization_code',
41
+ code: input.code,
42
+ client_id: app.clientId,
43
+ client_secret: app.clientSecret,
44
+ ...(input.redirectUri ? { redirect_uri: input.redirectUri } : {}),
45
+ ...(input.codeVerifier ? { code_verifier: input.codeVerifier } : {}),
46
+ },
47
+ },
48
+ { timeoutMs: providerExchangeTimeoutMs, ...options },
49
+ ).catch((error: unknown) => {
50
+ throw exchangeError(error);
51
+ });
52
+ const parsed = tokenResponseSchema.safeParse(answer);
53
+ if (!parsed.success) throw new ApiError('code_exchange_failed', 502);
54
54
  return {
55
55
  accessToken: parsed.data.access_token,
56
56
  refreshToken: parsed.data.refresh_token ?? null,
@@ -1,37 +1,17 @@
1
+ import { ApiError } from '@inixiative/api-client';
2
+ import type { ApiOperationOptions } from '@inixiative/api-client/operation';
1
3
  import { z } from 'zod';
2
- import {
3
- type CredentialSecret,
4
- credentialSecretSchema,
5
- type OAuthClient,
6
- type SigningClient,
7
- } from '../contracts';
8
- import { githubAppJwt } from '../providers/github/auth/githubAppJwt';
4
+ import { type CredentialSecret, credentialSecretSchema } from '../contracts';
5
+ import { createGithubInstallationToken } from '../providers/github/auth/createGithubInstallationToken';
6
+ import { githubAppAuth } from '../providers/github/auth/githubAppAuth';
9
7
  import { githubPermissionScopes } from '../providers/github/auth/githubPermissionScopes';
10
- import { githubRequestHeaders } from '../providers/github/githubRequestHeaders';
11
- import { ProviderError } from '../utils/providerError';
8
+ import { githubApiBaseUrl } from '../providers/github/githubApiBaseUrl';
12
9
  import type { CredentialClient } from './credentialClient';
13
- import { fetchRenewalResponse } from './fetchRenewalResponse';
14
- import type { RenewalRequest } from './renewalRequest';
10
+ import { providerExchangeTimeoutMs } from './providerExchangeTimeoutMs';
11
+ import { renewalError } from './renewalError';
15
12
 
16
13
  type ClientCredentials = NonNullable<CredentialSecret['clientCredentials']>;
17
14
 
18
- const mintRequest = async (
19
- provider: string,
20
- clientCredentials: ClientCredentials,
21
- client?: OAuthClient | SigningClient,
22
- ): Promise<RenewalRequest> => {
23
- const subjectId = clientCredentials.subjectId;
24
- if (provider !== 'githubOrganization' || !subjectId || !client || !('privateKey' in client))
25
- throw new ProviderError('renewal_unsupported', 409);
26
- const headers = githubRequestHeaders(new Headers(), await githubAppJwt(client));
27
- headers.set('Content-Type', 'application/json');
28
- return {
29
- url: `https://api.github.com/app/installations/${encodeURIComponent(subjectId)}/access_tokens`,
30
- headers,
31
- body: JSON.stringify({ permissions: { contents: 'read' } }),
32
- };
33
- };
34
-
35
15
  const mintedSecret = (clientCredentials: ClientCredentials, data: Record<string, unknown>) => {
36
16
  const minted = z
37
17
  .object({
@@ -40,29 +20,35 @@ const mintedSecret = (clientCredentials: ClientCredentials, data: Record<string,
40
20
  permissions: z.record(z.string(), z.string()).default({}),
41
21
  })
42
22
  .safeParse(data);
43
- if (!minted.success) throw new ProviderError('renewal_outcome_unknown', 409);
23
+ if (!minted.success) throw new ApiError('renewal_outcome_unknown', 409);
44
24
  const expiresIn = z
45
25
  .number()
46
26
  .int()
47
27
  .positive()
48
28
  .max(31536000)
49
29
  .safeParse(Math.floor((Date.parse(minted.data.expires_at) - Date.now()) / 1000));
50
- if (!expiresIn.success) throw new ProviderError('renewal_outcome_unknown', 409);
30
+ if (!expiresIn.success) throw new ApiError('renewal_outcome_unknown', 409);
51
31
  return {
52
- secret: credentialSecretSchema.parse({
53
- token: minted.data.token,
54
- clientCredentials,
55
- }),
32
+ secret: credentialSecretSchema.parse({ token: minted.data.token, clientCredentials }),
56
33
  expiresIn: expiresIn.data,
57
34
  scopes: githubPermissionScopes(minted.data.permissions),
58
35
  };
59
36
  };
60
37
 
61
38
  export const mintProviderCredential = async (
62
- { app, send = fetch }: CredentialClient,
39
+ { app, send }: CredentialClient,
63
40
  { provider, clientCredentials }: { provider: string; clientCredentials: ClientCredentials },
64
- ) =>
65
- mintedSecret(
66
- clientCredentials,
67
- await fetchRenewalResponse(send, await mintRequest(provider, clientCredentials, app)),
68
- );
41
+ options?: ApiOperationOptions,
42
+ ) => {
43
+ const installationId = clientCredentials.subjectId;
44
+ if (provider !== 'githubOrganization' || !installationId || !app || !('privateKey' in app))
45
+ throw new ApiError('renewal_unsupported', 409);
46
+ const data = await createGithubInstallationToken(
47
+ { baseUrl: githubApiBaseUrl, auth: githubAppAuth(app), send },
48
+ { installationId },
49
+ { timeoutMs: providerExchangeTimeoutMs, ...options },
50
+ ).catch((error: unknown) => {
51
+ throw renewalError(error);
52
+ });
53
+ return mintedSecret(clientCredentials, data);
54
+ };
@@ -1 +1 @@
1
- export const PROVIDER_EXCHANGE_TIMEOUT_MS = 15_000;
1
+ export const providerExchangeTimeoutMs = 15_000;