@inixiative/integrations 0.3.0 → 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 (193) hide show
  1. package/README.md +21 -13
  2. package/package.json +3 -2
  3. package/src/catalog/catalogOperationMeta.ts +4 -0
  4. package/src/catalog/catalogOperations.ts +10 -0
  5. package/src/catalog/providerModel.ts +0 -1
  6. package/src/contracts.ts +1 -10
  7. package/src/credentials/credentialAuth.ts +38 -0
  8. package/src/credentials/credentialClient.ts +2 -2
  9. package/src/credentials/exchangeOauthCode.ts +30 -36
  10. package/src/credentials/mintProviderCredential.ts +26 -40
  11. package/src/credentials/providerExchangeTimeoutMs.ts +1 -1
  12. package/src/credentials/refreshProviderCredential.ts +62 -65
  13. package/src/credentials/renewalError.ts +11 -0
  14. package/src/credentials/requestOauthToken.ts +28 -0
  15. package/src/credentials/validateCredentialSecret.ts +5 -5
  16. package/src/index.ts +0 -1
  17. package/src/operations/providerOperationInput.ts +6 -0
  18. package/src/operations/providerOperationInputSchema.ts +36 -0
  19. package/src/operations/providerOperationOrThrow.ts +23 -0
  20. package/src/operations/providerOperationSet.ts +7 -0
  21. package/src/operations/providerOperations.ts +38 -0
  22. package/src/providers/confluence/confluenceApiBaseUrl.ts +1 -0
  23. package/src/providers/confluence/confluenceOperations.ts +4 -0
  24. package/src/providers/confluence/confluenceProvider.ts +5 -8
  25. package/src/providers/confluence/models/page/fetchConfluencePage.ts +23 -0
  26. package/src/providers/discord/discordApiBaseUrl.ts +1 -0
  27. package/src/providers/discord/discordOperations.ts +8 -0
  28. package/src/providers/discord/discordProvider.ts +5 -14
  29. package/src/providers/discord/models/channel/discordChannelKind.ts +1 -0
  30. package/src/providers/discord/models/channel/fetchDiscordChannel.ts +25 -0
  31. package/src/providers/discord/models/channel/fetchDiscordChannelMessages.ts +37 -0
  32. package/src/providers/drive/driveApiBaseUrl.ts +1 -0
  33. package/src/providers/drive/driveOperations.ts +4 -0
  34. package/src/providers/drive/driveProvider.ts +5 -8
  35. package/src/providers/drive/models/file/fetchDriveFile.ts +27 -0
  36. package/src/providers/github/auth/createGithubInstallationToken.ts +19 -0
  37. package/src/providers/github/auth/fetchGithubAppInstallUrl.ts +21 -0
  38. package/src/providers/github/auth/fetchGithubAppInstallation.ts +16 -19
  39. package/src/providers/github/auth/fetchGithubOrganizationRole.ts +22 -22
  40. package/src/providers/github/auth/fetchGithubUser.ts +10 -4
  41. package/src/providers/github/auth/githubAppAuth.ts +6 -0
  42. package/src/providers/github/auth/listGithubUserInstallationPage.ts +18 -0
  43. package/src/providers/github/events/listGithubNotificationPage.ts +18 -0
  44. package/src/providers/github/githubApiBaseUrl.ts +1 -0
  45. package/src/providers/github/githubOrganizationProvider.ts +5 -1
  46. package/src/providers/github/githubPagination.ts +2 -2
  47. package/src/providers/github/githubRequestHeaders.ts +4 -6
  48. package/src/providers/github/githubUserProvider.ts +5 -2
  49. package/src/providers/github/models/account/githubAccount.ts +0 -1
  50. package/src/providers/github/models/repository/fetchGithubBlob.ts +59 -0
  51. package/src/providers/github/models/repository/fetchGithubCommit.ts +38 -0
  52. package/src/providers/github/models/repository/fetchGithubTree.ts +74 -0
  53. package/src/providers/github/models/repository/githubObjectRequest.ts +15 -0
  54. package/src/providers/github/models/repository/githubRepository.ts +1 -11
  55. package/src/providers/github/models/repository/githubRepositoryOperations.ts +10 -0
  56. package/src/providers/github/models/repository/listGithubInstallationRepositoryPage.ts +18 -0
  57. package/src/providers/github/models/repository/listGithubUserInstallationRepositoryPage.ts +22 -0
  58. package/src/providers/github/models/repository/readGithubObjectIdentity.ts +9 -0
  59. package/src/providers/github/services/fetchGithubUserInstallation.ts +25 -0
  60. package/src/providers/github/services/listGithubNotifications.ts +27 -0
  61. package/src/providers/github/services/listInstallationRepositories.ts +34 -0
  62. package/src/providers/github/services/listUserRepositories.ts +43 -0
  63. package/src/providers/gmail/gmailApiBaseUrl.ts +1 -0
  64. package/src/providers/gmail/gmailOperations.ts +10 -0
  65. package/src/providers/gmail/gmailProvider.ts +6 -9
  66. package/src/providers/gmail/models/label/listGmailLabelMessages.ts +45 -0
  67. package/src/providers/gmail/models/message/fetchGmailMessage.ts +19 -0
  68. package/src/providers/gmail/models/message/fetchGmailMessageBatch.ts +20 -0
  69. package/src/providers/gmail/models/message/gmailMessageKind.ts +1 -0
  70. package/src/providers/gmail/models/message/gmailMessageRequest.ts +9 -0
  71. package/src/providers/gmail/models/message/readGmailMessage.ts +26 -0
  72. package/src/providers/google/auth/verifyGoogleIdToken.ts +3 -3
  73. package/src/providers/jira/jiraApiBaseUrl.ts +1 -0
  74. package/src/providers/jira/jiraOperations.ts +4 -0
  75. package/src/providers/jira/jiraProvider.ts +5 -8
  76. package/src/providers/jira/models/issue/fetchJiraIssue.ts +22 -0
  77. package/src/providers/linear/events/createLinearWebhook.ts +29 -20
  78. package/src/providers/linear/events/deleteLinearWebhook.ts +16 -9
  79. package/src/providers/linear/events/linearWebhook.ts +1 -1
  80. package/src/providers/linear/events/listLinearWebhookPage.ts +23 -0
  81. package/src/providers/linear/events/repairLinearWebhook.ts +17 -13
  82. package/src/providers/linear/linearApiBaseUrl.ts +1 -0
  83. package/src/providers/linear/linearGraphqlErrorCode.ts +8 -0
  84. package/src/providers/linear/linearOperations.ts +4 -0
  85. package/src/providers/linear/linearPagination.ts +3 -9
  86. package/src/providers/linear/linearProvider.ts +5 -2
  87. package/src/providers/linear/models/issue/fetchLinearIssue.ts +32 -0
  88. package/src/providers/linear/models/team/fetchLinearWorkspace.ts +23 -13
  89. package/src/providers/linear/models/team/linearTeam.ts +0 -1
  90. package/src/providers/linear/services/listLinearWebhooks.ts +45 -0
  91. package/src/providers/notion/models/page/fetchNotionPage.ts +32 -0
  92. package/src/providers/notion/models/page/fetchNotionPageBlocks.ts +39 -0
  93. package/src/providers/notion/models/page/notionPageKind.ts +1 -0
  94. package/src/providers/notion/notionApiBaseUrl.ts +1 -0
  95. package/src/providers/notion/notionOperations.ts +8 -0
  96. package/src/providers/notion/notionProvider.ts +5 -14
  97. package/src/providers/notion/notionVersion.ts +1 -0
  98. package/src/providers/slack/auth/fetchSlackIdentity.ts +14 -6
  99. package/src/providers/slack/models/account/slackAccount.ts +0 -1
  100. package/src/providers/slack/models/channel/fetchSlackChannel.ts +32 -0
  101. package/src/providers/slack/models/channel/fetchSlackChannelMessages.ts +34 -0
  102. package/src/providers/slack/models/channel/listSlackUserConversations.ts +19 -0
  103. package/src/providers/slack/models/channel/slackChannel.ts +0 -14
  104. package/src/providers/slack/readSlackBody.ts +10 -0
  105. package/src/providers/slack/services/listSlackChannels.ts +23 -0
  106. package/src/providers/slack/slackApiBaseUrl.ts +1 -0
  107. package/src/providers/slack/slackOperations.ts +8 -0
  108. package/src/providers/slack/slackPagination.ts +2 -2
  109. package/src/providers/slack/slackProvider.ts +9 -1
  110. package/src/providers/slack/slackProviderError.ts +2 -2
  111. package/src/providers/teams/models/channel/fetchTeamsChannelMessages.ts +36 -0
  112. package/src/providers/teams/teamsApiBaseUrl.ts +1 -0
  113. package/src/providers/teams/teamsOperations.ts +6 -0
  114. package/src/providers/teams/teamsProvider.ts +5 -8
  115. package/src/utils/acceptJsonHeaders.ts +1 -0
  116. package/src/utils/pageQuerySchema.ts +13 -0
  117. package/src/utils/readProviderLimits.ts +1 -2
  118. package/src/credentials/fetchRenewalResponse.ts +0 -41
  119. package/src/credentials/renewalRequest.ts +0 -1
  120. package/src/operations/buildProviderRequest.ts +0 -55
  121. package/src/operations/executeProvider.ts +0 -26
  122. package/src/operations/findOperationHandler.ts +0 -6
  123. package/src/operations/operationHandler.ts +0 -8
  124. package/src/operations/operationHandlers.ts +0 -39
  125. package/src/operations/operationRequestInput.ts +0 -12
  126. package/src/operations/providerRequestSpec.ts +0 -1
  127. package/src/providers/confluence/confluenceOperationHandler.ts +0 -14
  128. package/src/providers/discord/discordOperationHandler.ts +0 -30
  129. package/src/providers/drive/driveOperationHandler.ts +0 -21
  130. package/src/providers/github/auth/fetchGithubUserInstallation.ts +0 -21
  131. package/src/providers/github/auth/githubAppClient.ts +0 -4
  132. package/src/providers/github/auth/githubAppInstallUrl.ts +0 -20
  133. package/src/providers/github/auth/githubClientForApp.ts +0 -11
  134. package/src/providers/github/events/listGithubNotifications.ts +0 -27
  135. package/src/providers/github/fetchAllGithubPages.ts +0 -12
  136. package/src/providers/github/iterateGithubPages.ts +0 -12
  137. package/src/providers/github/models/repository/githubOperationHandler.ts +0 -36
  138. package/src/providers/github/models/repository/listInstallationRepositories.ts +0 -31
  139. package/src/providers/github/models/repository/listUserRepositories.ts +0 -36
  140. package/src/providers/github/models/repository/readGithubObject.ts +0 -85
  141. package/src/providers/github/requestGithub.ts +0 -18
  142. package/src/providers/gmail/buildGmailMessageRequest.ts +0 -22
  143. package/src/providers/gmail/fetchGmailMessages.ts +0 -81
  144. package/src/providers/gmail/gmailOperationHandler.ts +0 -12
  145. package/src/providers/jira/jiraOperationHandler.ts +0 -14
  146. package/src/providers/linear/events/listLinearWebhooks.ts +0 -44
  147. package/src/providers/linear/fetchAllLinearPages.ts +0 -40
  148. package/src/providers/linear/linearClient.ts +0 -5
  149. package/src/providers/linear/linearRequestInput.ts +0 -1
  150. package/src/providers/linear/models/issue/linearIssue.ts +0 -11
  151. package/src/providers/linear/models/issue/linearOperationHandler.ts +0 -30
  152. package/src/providers/linear/requestLinear.ts +0 -51
  153. package/src/providers/notion/notionOperationHandler.ts +0 -32
  154. package/src/providers/slack/fetchAllSlackPages.ts +0 -12
  155. package/src/providers/slack/models/channel/listSlackChannels.ts +0 -26
  156. package/src/providers/slack/models/channel/slackOperationHandler.ts +0 -30
  157. package/src/providers/slack/requestSlack.ts +0 -22
  158. package/src/providers/teams/teamsOperationHandler.ts +0 -24
  159. package/src/utils/headerNumber.ts +0 -6
  160. package/src/utils/pagination/applyCaps.ts +0 -18
  161. package/src/utils/pagination/byCursorKeys.ts +0 -7
  162. package/src/utils/pagination/byCursorOptions.ts +0 -7
  163. package/src/utils/pagination/byPageKeys.ts +0 -7
  164. package/src/utils/pagination/byPageOptions.ts +0 -8
  165. package/src/utils/pagination/collectPages.ts +0 -27
  166. package/src/utils/pagination/compactRequest.ts +0 -4
  167. package/src/utils/pagination/fetchAllByCursor.ts +0 -6
  168. package/src/utils/pagination/fetchAllByPage.ts +0 -6
  169. package/src/utils/pagination/fetchAllRequestPages.ts +0 -16
  170. package/src/utils/pagination/incompletePageWalkError.ts +0 -8
  171. package/src/utils/pagination/isAnotherPage.ts +0 -20
  172. package/src/utils/pagination/iterateByCursor.ts +0 -49
  173. package/src/utils/pagination/iterateByPage.ts +0 -59
  174. package/src/utils/pagination/iterateProviderPages.ts +0 -27
  175. package/src/utils/pagination/iterateRequestPages.ts +0 -18
  176. package/src/utils/pagination/pageWalkError.ts +0 -6
  177. package/src/utils/pagination/paginationOptions.ts +0 -9
  178. package/src/utils/pagination/providerPagesOptions.ts +0 -8
  179. package/src/utils/pagination/providerPagination.ts +0 -6
  180. package/src/utils/pagination/readPage.ts +0 -29
  181. package/src/utils/pagination/readPath.ts +0 -12
  182. package/src/utils/pagination/repeatedCursorError.ts +0 -10
  183. package/src/utils/providerClient.ts +0 -3
  184. package/src/utils/providerError.ts +0 -10
  185. package/src/utils/providerRequest.ts +0 -22
  186. package/src/utils/providerRequestInput.ts +0 -7
  187. package/src/utils/providerResponseLimit.ts +0 -1
  188. package/src/utils/providerSend.ts +0 -1
  189. package/src/utils/readProviderJson.ts +0 -38
  190. package/src/utils/readRateLimit.ts +0 -29
  191. package/src/utils/requestProviderJson.ts +0 -13
  192. package/src/utils/responseBudget.ts +0 -1
  193. 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.3.0",
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/api-client": "^0.2.4",
33
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.254",
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,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
+ });
@@ -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
  };
package/src/contracts.ts CHANGED
@@ -95,6 +95,7 @@ export const providerDefinitionSchema = z
95
95
  name: z.string(),
96
96
  documentationUrl: z.url(),
97
97
  authMethods: z.array(authMethodSchema),
98
+ apiBaseUrl: z.url({ protocol: /^https$/ }).optional(),
98
99
  operations: z.array(catalogOperationSchema),
99
100
  inbound: z.boolean().optional(),
100
101
  delivery: z.literal('installationSocket').optional(),
@@ -115,13 +116,3 @@ export type ProviderDefinition = z.infer<typeof providerDefinitionSchema> & {
115
116
  syncedResourceKinds?: string[];
116
117
  holderHandleKinds?: string[];
117
118
  };
118
- export type ProviderContext = {
119
- provider: Provider;
120
- configuration: unknown;
121
- resource: { kind: string; externalId: string; metadata: unknown };
122
- operation: string;
123
- input: Record<string, unknown>;
124
- limit: number;
125
- method: z.infer<typeof credentialMethodSchema>;
126
- secret: z.infer<typeof credentialSecretSchema>;
127
- };
@@ -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
4
  import { integrationFamilyDefinition } from '../catalog/integrationFamilyDefinition';
3
5
  import type { IntegrationFamily, OAuthClient } from '../contracts';
4
- import { ProviderError } from '../utils/providerError';
5
- import type { ProviderSend } from '../utils/providerSend';
6
- import { readProviderJson } from '../utils/readProviderJson';
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,50 +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 },
23
+ { app, send }: { app: OAuthClient; send?: ApiSend },
18
24
  input: {
19
25
  integrationFamily: IntegrationFamily;
20
26
  code: string;
21
27
  codeVerifier?: string;
22
28
  redirectUri?: string;
23
29
  },
30
+ options?: ApiOperationOptions,
24
31
  ) => {
25
32
  const tokenUrl = z
26
33
  .url()
27
34
  .parse(integrationFamilyDefinition(input.integrationFamily)?.oauth?.tokenUrl);
28
- let response: Response;
29
- try {
30
- response = await send(
31
- new Request(tokenUrl, {
32
- method: 'POST',
33
- headers: {
34
- Accept: 'application/json',
35
- 'Content-Type': 'application/x-www-form-urlencoded',
36
- },
37
- body: new URLSearchParams({
38
- grant_type: 'authorization_code',
39
- code: input.code,
40
- client_id: app.clientId,
41
- client_secret: app.clientSecret,
42
- ...(input.redirectUri ? { redirect_uri: input.redirectUri } : {}),
43
- ...(input.codeVerifier ? { code_verifier: input.codeVerifier } : {}),
44
- }).toString(),
45
- redirect: 'error',
46
- signal: AbortSignal.timeout(15000),
47
- }),
48
- );
49
- } catch {
50
- throw new ProviderError('provider_unreachable', 502);
51
- }
52
- if (!response.ok) {
53
- await response.body?.cancel();
54
- throw new ProviderError('code_exchange_failed', 502);
55
- }
56
- const parsed = tokenResponseSchema.safeParse(
57
- await readProviderJson(response, { remainingBytes: 128 * 1024 }).catch(() => null),
58
- );
59
- if (!parsed.success) throw new ProviderError('code_exchange_failed', 502);
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);
60
54
  return {
61
55
  accessToken: parsed.data.access_token,
62
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;
@@ -1,4 +1,10 @@
1
1
  import { Buffer } from 'node:buffer';
2
+ import { ApiError } from '@inixiative/api-client';
3
+ import {
4
+ type ApiAuth,
5
+ type ApiOperationOptions,
6
+ headerAuth,
7
+ } from '@inixiative/api-client/operation';
2
8
  import { z } from 'zod';
3
9
  import { findProvider } from '../catalog/findProvider';
4
10
  import { integrationFamilyDefinition } from '../catalog/integrationFamilyDefinition';
@@ -9,18 +15,19 @@ import {
9
15
  type OAuthClient,
10
16
  type Provider,
11
17
  } from '../contracts';
18
+ import { notionVersion } from '../providers/notion/notionVersion';
12
19
  import { jwtClaims } from '../utils/jwtClaims';
13
- import { ProviderError } from '../utils/providerError';
14
20
  import { CODEX_TOKEN_URL } from './codexTokenUrl';
15
21
  import type { CredentialClient } from './credentialClient';
16
- import { fetchRenewalResponse } from './fetchRenewalResponse';
17
22
  import { mintProviderCredential } from './mintProviderCredential';
23
+ import { providerExchangeTimeoutMs } from './providerExchangeTimeoutMs';
24
+ import { renewalError } from './renewalError';
18
25
  import type { RenewalOwner } from './renewalOwner';
19
- import type { RenewalRequest } from './renewalRequest';
26
+ import { requestOauthToken } from './requestOauthToken';
20
27
 
21
28
  const secondsUntilJwtExpiry = (token: string) => {
22
29
  const exp = z.number().int().positive().safeParse(jwtClaims(token)?.exp);
23
- if (!exp.success) throw new ProviderError('renewal_outcome_unknown', 409);
30
+ if (!exp.success) throw new ApiError('renewal_outcome_unknown', 409);
24
31
  return z
25
32
  .number()
26
33
  .int()
@@ -42,87 +49,72 @@ const renewalEndpointKey = (owner: RenewalOwner): Provider | IntegrationFamily =
42
49
  const familyTokenUrl = (integrationFamily: IntegrationFamily) =>
43
50
  z.url().parse(integrationFamilyDefinition(integrationFamily)?.oauth?.tokenUrl);
44
51
 
52
+ type RefreshRequest = {
53
+ tokenUrl: string;
54
+ encoding: 'form' | 'json';
55
+ fields: Record<string, string>;
56
+ headers?: Record<string, string>;
57
+ auth?: ApiAuth;
58
+ };
59
+
45
60
  const refreshRequest = (
46
61
  provider: Provider | IntegrationFamily,
47
62
  secret: CredentialSecret,
48
63
  client?: OAuthClient,
49
- ): RenewalRequest => {
50
- if (!secret.oauth) throw new ProviderError('renewal_unsupported', 409);
64
+ ): RefreshRequest => {
65
+ if (!secret.oauth) throw new ApiError('renewal_unsupported', 409);
51
66
  const { refreshToken, tenantId } = secret.oauth;
52
67
  const clientId = client?.clientId ?? secret.oauth.clientId;
53
68
  const clientSecret = client?.clientSecret ?? secret.oauth.clientSecret;
54
69
  const publicClient = provider === 'codex';
55
- if (!clientId || (!clientSecret && !publicClient))
56
- throw new ProviderError('renewal_unsupported', 409);
70
+ if (!clientId || (!clientSecret && !publicClient)) throw new ApiError('renewal_unsupported', 409);
57
71
  const fields = {
58
72
  grant_type: 'refresh_token',
59
73
  refresh_token: refreshToken,
60
74
  client_id: clientId,
61
75
  client_secret: clientSecret ?? '',
62
76
  };
63
- const headers = new Headers({
64
- Accept: 'application/json',
65
- 'Content-Type': 'application/x-www-form-urlencoded',
66
- });
67
77
  switch (provider) {
68
78
  case 'slack':
69
- return {
70
- url: 'https://slack.com/api/oauth.v2.access',
71
- headers,
72
- body: new URLSearchParams(fields).toString(),
73
- };
79
+ return { tokenUrl: 'https://slack.com/api/oauth.v2.access', encoding: 'form', fields };
74
80
  case 'github':
75
81
  case 'google':
76
- return {
77
- url: familyTokenUrl(provider),
78
- headers,
79
- body: new URLSearchParams(fields).toString(),
80
- };
82
+ return { tokenUrl: familyTokenUrl(provider), encoding: 'form', fields };
81
83
  case 'linear':
82
- return {
83
- url: 'https://api.linear.app/oauth/token',
84
- headers,
85
- body: new URLSearchParams(fields).toString(),
86
- };
84
+ return { tokenUrl: 'https://api.linear.app/oauth/token', encoding: 'form', fields };
87
85
  case 'teams':
88
86
  return {
89
- url: `https://login.microsoftonline.com/${z.uuid().parse(tenantId)}/oauth2/v2.0/token`,
90
- headers,
91
- body: new URLSearchParams(fields).toString(),
87
+ tokenUrl: `https://login.microsoftonline.com/${z.uuid().parse(tenantId)}/oauth2/v2.0/token`,
88
+ encoding: 'form',
89
+ fields,
92
90
  };
93
91
  case 'atlassian':
94
- headers.set('Content-Type', 'application/json');
95
- return {
96
- url: familyTokenUrl(provider),
97
- headers,
98
- body: JSON.stringify(fields),
99
- };
92
+ return { tokenUrl: familyTokenUrl(provider), encoding: 'json', fields };
100
93
  case 'notion':
101
- headers.set('Content-Type', 'application/json');
102
- headers.set('Notion-Version', '2026-03-11');
103
- headers.set(
104
- 'Authorization',
105
- `Basic ${Buffer.from(`${clientId}:${clientSecret}`).toString('base64')}`,
106
- );
107
94
  return {
108
- url: 'https://api.notion.com/v1/oauth/token',
109
- headers,
110
- body: JSON.stringify({ grant_type: 'refresh_token', refresh_token: refreshToken }),
95
+ tokenUrl: 'https://api.notion.com/v1/oauth/token',
96
+ encoding: 'json',
97
+ fields: { grant_type: 'refresh_token', refresh_token: refreshToken },
98
+ headers: { 'Notion-Version': notionVersion },
99
+ auth: headerAuth(
100
+ 'Authorization',
101
+ async () => Buffer.from(`${clientId}:${clientSecret}`).toString('base64'),
102
+ { prefix: 'Basic ' },
103
+ ),
111
104
  };
112
105
  case 'codex':
113
- headers.set('Content-Type', 'application/json');
114
106
  return {
115
- url: CODEX_TOKEN_URL,
116
- headers,
117
- body: JSON.stringify({
107
+ tokenUrl: CODEX_TOKEN_URL,
108
+ encoding: 'json',
109
+ fields: {
118
110
  client_id: clientId,
119
111
  grant_type: 'refresh_token',
120
112
  refresh_token: refreshToken,
121
113
  scope: 'openid profile email',
122
- }),
114
+ },
123
115
  };
124
116
  default:
125
- throw new ProviderError('renewal_unsupported', 409);
117
+ throw new ApiError('renewal_unsupported', 409);
126
118
  }
127
119
  };
128
120
 
@@ -132,7 +124,7 @@ const refreshedSecret = (
132
124
  data: Record<string, unknown>,
133
125
  ) => {
134
126
  if (data.error || (provider === 'slack' && data.ok !== true))
135
- throw new ProviderError(
127
+ throw new ApiError(
136
128
  data.error === 'ratelimited' ? 'renewal_temporarily_unavailable' : 'renewal_rejected',
137
129
  data.error === 'ratelimited' ? 503 : 409,
138
130
  );
@@ -145,7 +137,7 @@ const refreshedSecret = (
145
137
  ...(typeof data.id_token === 'string' ? { idToken: data.id_token } : {}),
146
138
  },
147
139
  });
148
- if (!refreshed.success) throw new ProviderError('renewal_outcome_unknown', 409);
140
+ if (!refreshed.success) throw new ApiError('renewal_outcome_unknown', 409);
149
141
  if (
150
142
  [
151
143
  'slack',
@@ -159,36 +151,41 @@ const refreshedSecret = (
159
151
  ].includes(provider) &&
160
152
  !data.refresh_token
161
153
  )
162
- throw new ProviderError('renewal_outcome_unknown', 409);
154
+ throw new ApiError('renewal_outcome_unknown', 409);
163
155
  const expiresIn =
164
156
  provider === 'notion' && data.expires_in === undefined
165
157
  ? null
166
158
  : provider === 'codex' && data.expires_in === undefined
167
159
  ? secondsUntilJwtExpiry(refreshed.data.token)
168
160
  : z.number().int().positive().max(31536000).safeParse(data.expires_in).data;
169
- if (expiresIn === undefined) throw new ProviderError('renewal_outcome_unknown', 409);
161
+ if (expiresIn === undefined) throw new ApiError('renewal_outcome_unknown', 409);
170
162
  return { secret: refreshed.data, expiresIn };
171
163
  };
172
164
 
173
165
  export const refreshProviderCredential = async (
174
166
  client: CredentialClient,
175
167
  { secret: value, ...owner }: RenewalOwner & { secret: unknown },
168
+ options?: ApiOperationOptions,
176
169
  ) => {
177
170
  const secret = credentialSecretSchema.parse(value);
178
171
  const provider = renewalEndpointKey(owner);
179
172
  if (secret.clientCredentials)
180
- return await mintProviderCredential(client, {
181
- provider,
182
- clientCredentials: secret.clientCredentials,
183
- });
184
- const data = await fetchRenewalResponse(
185
- client.send ?? fetch,
186
- refreshRequest(provider, secret, client.app),
187
- );
173
+ return await mintProviderCredential(
174
+ client,
175
+ { provider, clientCredentials: secret.clientCredentials },
176
+ options,
177
+ );
178
+ const { tokenUrl, auth, ...request } = refreshRequest(provider, secret, client.app);
179
+ const data = await requestOauthToken({ baseUrl: tokenUrl, auth, send: client.send }, request, {
180
+ timeoutMs: providerExchangeTimeoutMs,
181
+ ...options,
182
+ }).catch((error: unknown) => {
183
+ throw renewalError(error);
184
+ });
188
185
  try {
189
186
  return refreshedSecret(provider, secret, data);
190
187
  } catch (error) {
191
- if (error instanceof ProviderError) throw error;
192
- throw new ProviderError('renewal_outcome_unknown', 409);
188
+ if (error instanceof ApiError) throw error;
189
+ throw new ApiError('renewal_outcome_unknown', 409);
193
190
  }
194
191
  };
@@ -0,0 +1,11 @@
1
+ import { ApiError } from '@inixiative/api-client';
2
+
3
+ export const renewalError = (error: unknown) => {
4
+ if (!(error instanceof ApiError)) return error;
5
+ if (error.code === 'provider_unreachable') return new ApiError('renewal_outcome_unknown', 409);
6
+ const status = error.providerStatus ?? 0;
7
+ if (error.code === 'provider_rate_limited' || status >= 500)
8
+ return new ApiError('renewal_temporarily_unavailable', 503);
9
+ if (status >= 400) return new ApiError('renewal_rejected', 409);
10
+ return new ApiError('renewal_outcome_unknown', 409);
11
+ };
@@ -0,0 +1,28 @@
1
+ import { makeApiOperation } from '@inixiative/api-client/operation';
2
+ import { z } from 'zod';
3
+
4
+ const inputSchema = z.strictObject({
5
+ encoding: z.enum(['form', 'json']),
6
+ fields: z.record(z.string(), z.string()),
7
+ headers: z.record(z.string(), z.string()).optional(),
8
+ });
9
+
10
+ export const requestOauthToken = makeApiOperation({
11
+ key: 'oauth.token',
12
+ idempotent: false,
13
+ response: 'json',
14
+ responseLimitBytes: 128 * 1024,
15
+ input: inputSchema,
16
+ toRequest: ({ encoding, fields, headers }) => ({
17
+ path: '',
18
+ method: 'POST',
19
+ headers: {
20
+ Accept: 'application/json',
21
+ 'Content-Type':
22
+ encoding === 'form' ? 'application/x-www-form-urlencoded' : 'application/json',
23
+ ...headers,
24
+ },
25
+ body: encoding === 'form' ? new URLSearchParams(fields).toString() : fields,
26
+ }),
27
+ parse: ({ body }) => z.record(z.string(), z.unknown()).parse(body),
28
+ });
@@ -1,18 +1,18 @@
1
+ import { ApiError } from '@inixiative/api-client';
1
2
  import { credentialSecretSchema } from '../contracts';
2
- import { ProviderError } from '../utils/providerError';
3
3
 
4
4
  export const validateCredentialSecret = (method: string, secret: unknown, provider: string) => {
5
5
  const parsed = credentialSecretSchema.parse(secret);
6
6
  if ((method === 'oauth2') !== Boolean(parsed.oauth))
7
- throw new ProviderError('Credential method and OAuth bundle must match', 400);
7
+ throw new ApiError('Credential method and OAuth bundle must match', 400);
8
8
  if ((method === 'clientCredentials') !== Boolean(parsed.clientCredentials))
9
- throw new ProviderError('Credential method and client credentials must match', 400);
9
+ throw new ApiError('Credential method and client credentials must match', 400);
10
10
  if (
11
11
  method === 'oauth2' &&
12
12
  (!parsed.oauth?.clientId || (!parsed.oauth.clientSecret && provider !== 'codex'))
13
13
  )
14
- throw new ProviderError('OAuth requires the application client ID and secret', 400);
14
+ throw new ApiError('OAuth requires the application client ID and secret', 400);
15
15
  if (method === 'oauth2' && provider === 'teams' && !parsed.oauth?.tenantId)
16
- throw new ProviderError('Microsoft OAuth requires a tenant UUID', 400);
16
+ throw new ApiError('Microsoft OAuth requires a tenant UUID', 400);
17
17
  return parsed;
18
18
  };