@inixiative/integrations 0.0.0-stage → 0.1.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 (210) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +50 -2
  3. package/package.json +56 -4
  4. package/src/archiveCandidate.ts +1 -0
  5. package/src/archiveConfigurationSchema.ts +3 -0
  6. package/src/buildProviderRequest.ts +54 -0
  7. package/src/catalog.ts +54 -0
  8. package/src/codexClientId.ts +2 -0
  9. package/src/codexTokenUrl.ts +1 -0
  10. package/src/consentReason.ts +4 -0
  11. package/src/consentReasonSchema.ts +21 -0
  12. package/src/contracts.ts +107 -0
  13. package/src/credentialClient.ts +4 -0
  14. package/src/declaredOperations.ts +9 -0
  15. package/src/eventLeaves.ts +5 -0
  16. package/src/exchangeOauthCode.ts +61 -0
  17. package/src/executeProvider.ts +26 -0
  18. package/src/familyProducts.ts +5 -0
  19. package/src/fetchRenewalResponse.ts +41 -0
  20. package/src/findOperationHandler.ts +6 -0
  21. package/src/findProvider.ts +5 -0
  22. package/src/index.ts +3 -0
  23. package/src/integrationConfigurationSchemas.ts +11 -0
  24. package/src/integrationEventResource.ts +20 -0
  25. package/src/integrationKeyedKinds.ts +4 -0
  26. package/src/isAccountSuppliedByHost.ts +6 -0
  27. package/src/isEventLeaf.ts +1 -0
  28. package/src/isFamilyManaged.ts +7 -0
  29. package/src/isLocalArchive.ts +5 -0
  30. package/src/isUncalledLeaf.ts +6 -0
  31. package/src/localArchiveConfigurationSchema.ts +5 -0
  32. package/src/localArchiveSourceId.ts +8 -0
  33. package/src/mintProviderCredential.ts +68 -0
  34. package/src/operationHandler.ts +8 -0
  35. package/src/operationHandlers.ts +41 -0
  36. package/src/operationLeaves.ts +6 -0
  37. package/src/operationRequestInput.ts +12 -0
  38. package/src/perProvider.ts +20 -0
  39. package/src/providerEvent.ts +3 -0
  40. package/src/providerEventSchema.ts +3 -0
  41. package/src/providerExchangeTimeoutMs.ts +1 -0
  42. package/src/providerFamily.ts +4 -0
  43. package/src/providerHasEvents.ts +8 -0
  44. package/src/providerModel.ts +12 -0
  45. package/src/providerRequestSpec.ts +1 -0
  46. package/src/providers/anthropic/anthropicProvider.ts +16 -0
  47. package/src/providers/archive/archiveProvider.ts +21 -0
  48. package/src/providers/chorus/chorusProvider.ts +22 -0
  49. package/src/providers/claude/claudeProvider.ts +17 -0
  50. package/src/providers/codex/codexProvider.ts +17 -0
  51. package/src/providers/confluence/confluenceOperationHandler.ts +14 -0
  52. package/src/providers/confluence/confluenceProvider.ts +16 -0
  53. package/src/providers/discord/discordOperationHandler.ts +30 -0
  54. package/src/providers/discord/discordProvider.ts +22 -0
  55. package/src/providers/drive/driveOperationHandler.ts +21 -0
  56. package/src/providers/drive/driveProvider.ts +18 -0
  57. package/src/providers/foundry/foundryProvider.ts +33 -0
  58. package/src/providers/geminiApi/geminiApiProvider.ts +16 -0
  59. package/src/providers/github/auth/fetchGithubAppInstallation.ts +21 -0
  60. package/src/providers/github/auth/fetchGithubOrganizationRole.ts +27 -0
  61. package/src/providers/github/auth/fetchGithubUser.ts +11 -0
  62. package/src/providers/github/auth/fetchGithubUserInstallation.ts +21 -0
  63. package/src/providers/github/auth/githubAppClient.ts +4 -0
  64. package/src/providers/github/auth/githubAppInstallUrl.ts +20 -0
  65. package/src/providers/github/auth/githubAppJwt.ts +16 -0
  66. package/src/providers/github/auth/githubClientForApp.ts +11 -0
  67. package/src/providers/github/auth/githubInstallation.ts +4 -0
  68. package/src/providers/github/auth/githubInstallationAccountId.ts +4 -0
  69. package/src/providers/github/auth/githubInstallationFromAccountId.ts +4 -0
  70. package/src/providers/github/auth/githubInstallationSchema.ts +12 -0
  71. package/src/providers/github/auth/githubPermissionCovers.ts +14 -0
  72. package/src/providers/github/auth/githubPermissionScopes.ts +4 -0
  73. package/src/providers/github/auth/githubProviderForOwner.ts +6 -0
  74. package/src/providers/github/auth/githubUserAuthorizeUrl.ts +10 -0
  75. package/src/providers/github/events/githubEventRepositoryId.ts +10 -0
  76. package/src/providers/github/events/githubNotification.ts +4 -0
  77. package/src/providers/github/events/githubNotificationSchema.ts +9 -0
  78. package/src/providers/github/events/listGithubNotifications.ts +27 -0
  79. package/src/providers/github/events/normalizeGithubEvent.ts +200 -0
  80. package/src/providers/github/events/normalizeGithubNotification.ts +56 -0
  81. package/src/providers/github/events/verifyGithubSignature.ts +7 -0
  82. package/src/providers/github/fetchAllGithubPages.ts +12 -0
  83. package/src/providers/github/githubApiVersion.ts +1 -0
  84. package/src/providers/github/githubOrganizationProvider.ts +13 -0
  85. package/src/providers/github/githubPagination.ts +7 -0
  86. package/src/providers/github/githubProvider.ts +13 -0
  87. package/src/providers/github/githubRequestHeaders.ts +9 -0
  88. package/src/providers/github/githubUserProvider.ts +13 -0
  89. package/src/providers/github/iterateGithubPages.ts +12 -0
  90. package/src/providers/github/models/account/githubAccount.ts +17 -0
  91. package/src/providers/github/models/repository/githubOperationHandler.ts +36 -0
  92. package/src/providers/github/models/repository/githubRepository.ts +40 -0
  93. package/src/providers/github/models/repository/githubRepositoryIdSchema.ts +3 -0
  94. package/src/providers/github/models/repository/githubRepositoryMetadataSchema.ts +6 -0
  95. package/src/providers/github/models/repository/githubRepositoryName.ts +4 -0
  96. package/src/providers/github/models/repository/githubRepositoryNameSchema.ts +9 -0
  97. package/src/providers/github/models/repository/githubTreeEntryModeSchema.ts +3 -0
  98. package/src/providers/github/models/repository/githubTreeEntryTypeForMode.ts +14 -0
  99. package/src/providers/github/models/repository/githubTreeEntryTypeSchema.ts +3 -0
  100. package/src/providers/github/models/repository/listInstallationRepositories.ts +31 -0
  101. package/src/providers/github/models/repository/listUserRepositories.ts +36 -0
  102. package/src/providers/github/models/repository/readGithubObject.ts +85 -0
  103. package/src/providers/github/models/repository/readGithubRepositoryName.ts +4 -0
  104. package/src/providers/github/requestGithub.ts +18 -0
  105. package/src/providers/gmail/buildGmailMessageRequest.ts +22 -0
  106. package/src/providers/gmail/fetchGmailMessages.ts +81 -0
  107. package/src/providers/gmail/gmailOperationHandler.ts +12 -0
  108. package/src/providers/gmail/gmailProvider.ts +19 -0
  109. package/src/providers/google/auth/buildGoogleAuthorizationUrl.ts +33 -0
  110. package/src/providers/google/auth/verifyGoogleIdToken.ts +22 -0
  111. package/src/providers/google/googleProvider.ts +13 -0
  112. package/src/providers/jira/jiraOperationHandler.ts +14 -0
  113. package/src/providers/jira/jiraProvider.ts +16 -0
  114. package/src/providers/linear/auth/linearIntegrationSecret.ts +6 -0
  115. package/src/providers/linear/events/createLinearWebhook.ts +30 -0
  116. package/src/providers/linear/events/deleteLinearWebhook.ts +13 -0
  117. package/src/providers/linear/events/linearUserSchema.ts +3 -0
  118. package/src/providers/linear/events/linearWebhook.ts +3 -0
  119. package/src/providers/linear/events/linearWebhookPayload.ts +4 -0
  120. package/src/providers/linear/events/linearWebhookPayloadSchema.ts +13 -0
  121. package/src/providers/linear/events/listLinearWebhooks.ts +44 -0
  122. package/src/providers/linear/events/normalizeLinearEvent.ts +127 -0
  123. package/src/providers/linear/events/repairLinearWebhook.ts +17 -0
  124. package/src/providers/linear/events/verifyLinearSignature.ts +25 -0
  125. package/src/providers/linear/fetchAllLinearPages.ts +40 -0
  126. package/src/providers/linear/linearClient.ts +5 -0
  127. package/src/providers/linear/linearPagination.ts +13 -0
  128. package/src/providers/linear/linearProvider.ts +25 -0
  129. package/src/providers/linear/linearRequestInput.ts +1 -0
  130. package/src/providers/linear/models/issue/linearOperationHandler.ts +30 -0
  131. package/src/providers/linear/models/team/fetchLinearWorkspace.ts +30 -0
  132. package/src/providers/linear/requestLinear.ts +51 -0
  133. package/src/providers/muse/museProvider.ts +17 -0
  134. package/src/providers/notion/notionOperationHandler.ts +32 -0
  135. package/src/providers/notion/notionProvider.ts +22 -0
  136. package/src/providers/openai/openaiProvider.ts +16 -0
  137. package/src/providers/oracle/oracleProvider.ts +10 -0
  138. package/src/providers/railway/railwayProvider.ts +9 -0
  139. package/src/providers/render/renderProvider.ts +9 -0
  140. package/src/providers/slack/auth/fetchSlackIdentity.ts +10 -0
  141. package/src/providers/slack/events/normalizeSlackEvent.ts +64 -0
  142. package/src/providers/slack/events/slackAccountIdOf.ts +1 -0
  143. package/src/providers/slack/events/slackEventEnvelope.ts +4 -0
  144. package/src/providers/slack/events/slackEventEnvelopeSchema.ts +16 -0
  145. package/src/providers/slack/events/slackTeamPrefix.ts +1 -0
  146. package/src/providers/slack/events/slackTokensRevokedSchema.ts +13 -0
  147. package/src/providers/slack/events/slackUserOfAccountId.ts +2 -0
  148. package/src/providers/slack/events/verifySlackSignature.ts +17 -0
  149. package/src/providers/slack/fetchAllSlackPages.ts +12 -0
  150. package/src/providers/slack/models/channel/listSlackChannels.ts +26 -0
  151. package/src/providers/slack/models/channel/slackOperationHandler.ts +30 -0
  152. package/src/providers/slack/requestSlack.ts +22 -0
  153. package/src/providers/slack/slackPagination.ts +12 -0
  154. package/src/providers/slack/slackProvider.ts +47 -0
  155. package/src/providers/slack/slackProviderError.ts +12 -0
  156. package/src/providers/teams/teamsOperationHandler.ts +24 -0
  157. package/src/providers/teams/teamsProvider.ts +17 -0
  158. package/src/refreshProviderCredential.ts +172 -0
  159. package/src/renewalRequest.ts +1 -0
  160. package/src/resourceExternalIdSchema.ts +4 -0
  161. package/src/resourceExternalIdSchemas.ts +18 -0
  162. package/src/resourceMetadataSchema.ts +4 -0
  163. package/src/resourceMetadataSchemas.ts +9 -0
  164. package/src/subscriptionAccountId.ts +12 -0
  165. package/src/utils/capacityWindowSchema.ts +7 -0
  166. package/src/utils/headerNumber.ts +6 -0
  167. package/src/utils/jwtClaims.ts +14 -0
  168. package/src/utils/matchesHmacSha256.ts +11 -0
  169. package/src/utils/objectSchema.ts +3 -0
  170. package/src/utils/pagination/applyCaps.ts +18 -0
  171. package/src/utils/pagination/byCursorKeys.ts +7 -0
  172. package/src/utils/pagination/byCursorOptions.ts +7 -0
  173. package/src/utils/pagination/byPageKeys.ts +7 -0
  174. package/src/utils/pagination/byPageOptions.ts +8 -0
  175. package/src/utils/pagination/collectPages.ts +27 -0
  176. package/src/utils/pagination/compactRequest.ts +4 -0
  177. package/src/utils/pagination/fetchAllByCursor.ts +6 -0
  178. package/src/utils/pagination/fetchAllByPage.ts +6 -0
  179. package/src/utils/pagination/fetchAllRequestPages.ts +16 -0
  180. package/src/utils/pagination/incompletePageWalkError.ts +8 -0
  181. package/src/utils/pagination/isAnotherPage.ts +20 -0
  182. package/src/utils/pagination/iterateByCursor.ts +49 -0
  183. package/src/utils/pagination/iterateByPage.ts +59 -0
  184. package/src/utils/pagination/iterateProviderPages.ts +27 -0
  185. package/src/utils/pagination/iterateRequestPages.ts +18 -0
  186. package/src/utils/pagination/pageWalkError.ts +6 -0
  187. package/src/utils/pagination/paginationOptions.ts +9 -0
  188. package/src/utils/pagination/providerPagesOptions.ts +8 -0
  189. package/src/utils/pagination/providerPagination.ts +6 -0
  190. package/src/utils/pagination/readPage.ts +29 -0
  191. package/src/utils/pagination/readPath.ts +12 -0
  192. package/src/utils/pagination/repeatedCursorError.ts +10 -0
  193. package/src/utils/providerClient.ts +3 -0
  194. package/src/utils/providerCooldown.ts +23 -0
  195. package/src/utils/providerCooldownState.ts +4 -0
  196. package/src/utils/providerError.ts +10 -0
  197. package/src/utils/providerReading.ts +4 -0
  198. package/src/utils/providerReadingSchema.ts +8 -0
  199. package/src/utils/providerRequest.ts +22 -0
  200. package/src/utils/providerRequestInput.ts +7 -0
  201. package/src/utils/providerResponseLimit.ts +1 -0
  202. package/src/utils/providerSend.ts +1 -0
  203. package/src/utils/readProviderJson.ts +38 -0
  204. package/src/utils/readProviderLimits.ts +66 -0
  205. package/src/utils/readRateLimit.ts +29 -0
  206. package/src/utils/requestProviderJson.ts +13 -0
  207. package/src/utils/responseBudget.ts +1 -0
  208. package/src/utils/select.ts +6 -0
  209. package/src/utils/sendProviderRequest.ts +33 -0
  210. package/src/validateCredentialSecret.ts +18 -0
@@ -0,0 +1,26 @@
1
+ import { z } from 'zod';
2
+ import type { ProviderClient } from '../../../../utils/providerClient';
3
+ import { fetchAllSlackPages } from '../../fetchAllSlackPages';
4
+
5
+ const channelsSchema = z.array(z.object({ id: z.string().min(1), name: z.string().min(1) }));
6
+
7
+ export const listSlackChannels = async (client: ProviderClient) => {
8
+ let truncated = false;
9
+ const channels = channelsSchema.parse(
10
+ await fetchAllSlackPages(
11
+ client,
12
+ {
13
+ path: 'users.conversations',
14
+ query: { types: 'public_channel,private_channel', exclude_archived: 'true' },
15
+ },
16
+ {
17
+ keys: { data: 'channels' },
18
+ maxPages: 20,
19
+ onCapped: () => {
20
+ truncated = true;
21
+ },
22
+ },
23
+ ),
24
+ );
25
+ return { channels, truncated };
26
+ };
@@ -0,0 +1,30 @@
1
+ import { z } from 'zod';
2
+ import type { OperationHandler } from '../../../../operationHandler';
3
+ import { objectSchema } from '../../../../utils/objectSchema';
4
+ import { select } from '../../../../utils/select';
5
+ import { slackProviderError } from '../../slackProviderError';
6
+
7
+ export const slackOperationHandler: OperationHandler = {
8
+ request: ({ context, externalId, limit }) => {
9
+ const url = new URL(
10
+ `https://slack.com/api/${context.operation === 'messages.read' ? 'conversations.history' : 'conversations.info'}`,
11
+ );
12
+ url.searchParams.set('channel', externalId);
13
+ if (context.operation === 'messages.read')
14
+ url.searchParams.set('limit', String(Math.min(limit, 15)));
15
+ return { url };
16
+ },
17
+ parse: (body, context) => {
18
+ const data = objectSchema.parse(body);
19
+ if (data.ok !== true) throw slackProviderError(data.error);
20
+ return context.operation === 'conversations.read'
21
+ ? select(data.channel, ['id', 'name', 'is_private', 'num_members', 'topic', 'purpose'])
22
+ : {
23
+ messages: z
24
+ .array(z.unknown())
25
+ .parse(data.messages)
26
+ .map((item) => select(item, ['ts', 'text', 'user', 'type'])),
27
+ hasMore: data.has_more === true,
28
+ };
29
+ },
30
+ };
@@ -0,0 +1,22 @@
1
+ import { z } from 'zod';
2
+ import type { ProviderClient } from '../../utils/providerClient';
3
+ import { providerRequest } from '../../utils/providerRequest';
4
+ import type { ProviderRequestInput } from '../../utils/providerRequestInput';
5
+ import { requestProviderJson } from '../../utils/requestProviderJson';
6
+ import { slackProviderError } from './slackProviderError';
7
+
8
+ const slackResultSchema = z.looseObject({ ok: z.boolean(), error: z.string().optional() });
9
+
10
+ export const requestSlack = async (
11
+ { token, send = fetch }: ProviderClient,
12
+ input: ProviderRequestInput,
13
+ ) => {
14
+ const headers = new Headers(input.headers);
15
+ headers.set('Authorization', `Bearer ${token}`);
16
+ headers.set('Accept', 'application/json');
17
+ const body = slackResultSchema.parse(
18
+ await requestProviderJson(send, providerRequest('https://slack.com/api/', input, headers)),
19
+ );
20
+ if (!body.ok) throw slackProviderError(body.error);
21
+ return body;
22
+ };
@@ -0,0 +1,12 @@
1
+ import type { ProviderPagination } from '../../utils/pagination/providerPagination';
2
+
3
+ export const slackPagination = {
4
+ strategy: 'cursor',
5
+ keys: {
6
+ cursor: 'cursor',
7
+ pageSize: 'limit',
8
+ data: '',
9
+ nextCursor: 'response_metadata.next_cursor',
10
+ },
11
+ pageSize: 200,
12
+ } satisfies ProviderPagination;
@@ -0,0 +1,47 @@
1
+ import { accountResourceKind } from '@inixiative/signet/contracts';
2
+ import type { ProviderDefinition } from '../../contracts';
3
+ import { declaredOperations } from '../../declaredOperations';
4
+
5
+ const slackChannelEvents = {
6
+ 'events.message.channels': 'Receive messages posted in this public channel',
7
+ 'events.app_mention': 'Receive mentions of the connected Slack app in this channel',
8
+ } as const;
9
+
10
+ const slackAccountEvents = {
11
+ 'events.message.im': 'Receive the direct messages of this Slack account',
12
+ } as const;
13
+
14
+ export const slackProvider: ProviderDefinition = {
15
+ key: 'slack',
16
+ name: 'Slack',
17
+ documentationUrl: 'https://docs.slack.dev/reference/methods/conversations.history/',
18
+ authMethods: ['bearer', 'oauth2'],
19
+ operations: [
20
+ {
21
+ key: 'conversations.read',
22
+ name: 'Read channel details',
23
+ resourceKind: 'channel',
24
+ requiredScopes: ['channels:read or groups:read'],
25
+ },
26
+ {
27
+ key: 'messages.read',
28
+ name: 'Read channel messages',
29
+ resourceKind: 'channel',
30
+ requiredScopes: ['channels:history or groups:history'],
31
+ },
32
+ ...declaredOperations(
33
+ slackChannelEvents,
34
+ 'channel',
35
+ ['channels:history'],
36
+ ['events.message.channels'],
37
+ ),
38
+ ...declaredOperations(
39
+ slackChannelEvents,
40
+ 'channel',
41
+ ['app_mentions:read'],
42
+ ['events.app_mention'],
43
+ ),
44
+ ...declaredOperations(slackAccountEvents, accountResourceKind, ['im:history']),
45
+ ],
46
+ syncedResourceKinds: ['channel'],
47
+ };
@@ -0,0 +1,12 @@
1
+ import { ProviderError } from '../../utils/providerError';
2
+
3
+ const authenticationErrors = ['invalid_auth', 'token_expired', 'token_revoked', 'not_authed'];
4
+
5
+ export const slackProviderError = (error: unknown) =>
6
+ new ProviderError(
7
+ authenticationErrors.includes(String(error))
8
+ ? 'provider_authentication_expired'
9
+ : error === 'ratelimited'
10
+ ? 'provider_rate_limited'
11
+ : 'provider_access_denied',
12
+ );
@@ -0,0 +1,24 @@
1
+ import { z } from 'zod';
2
+ import type { OperationHandler } from '../../operationHandler';
3
+ import { objectSchema } from '../../utils/objectSchema';
4
+ import { select } from '../../utils/select';
5
+
6
+ export const teamsOperationHandler: OperationHandler = {
7
+ request: ({ metadata, id, limit }) => {
8
+ const url = new URL(
9
+ `https://graph.microsoft.com/v1.0/teams/${'teamId' in metadata ? metadata.teamId : ''}/channels/${id}/messages`,
10
+ );
11
+ url.searchParams.set('$top', String(limit));
12
+ return { url };
13
+ },
14
+ parse: (body) => {
15
+ const data = objectSchema.parse(body);
16
+ return {
17
+ messages: z
18
+ .array(z.unknown())
19
+ .parse(data.value)
20
+ .map((item) => select(item, ['id', 'subject', 'body', 'createdDateTime'])),
21
+ hasMore: typeof data['@odata.nextLink'] === 'string',
22
+ };
23
+ },
24
+ };
@@ -0,0 +1,17 @@
1
+ import type { ProviderDefinition } from '../../contracts';
2
+
3
+ export const teamsProvider: ProviderDefinition = {
4
+ key: 'teams',
5
+ name: 'Microsoft Teams',
6
+ documentationUrl:
7
+ 'https://learn.microsoft.com/en-us/graph/api/channel-list-messages?view=graph-rest-1.0',
8
+ authMethods: ['bearer', 'oauth2'],
9
+ operations: [
10
+ {
11
+ key: 'messages.read',
12
+ name: 'Read channel messages',
13
+ resourceKind: 'channel',
14
+ requiredScopes: ['ChannelMessage.Read.All or ChannelMessage.Read.Group'],
15
+ },
16
+ ],
17
+ };
@@ -0,0 +1,172 @@
1
+ import { Buffer } from 'node:buffer';
2
+ import { z } from 'zod';
3
+ import { providers } from './catalog';
4
+ import { CODEX_TOKEN_URL } from './codexTokenUrl';
5
+ import { type CredentialSecret, credentialSecretSchema, type OAuthClient } from './contracts';
6
+ import type { CredentialClient } from './credentialClient';
7
+ import { fetchRenewalResponse } from './fetchRenewalResponse';
8
+ import { mintProviderCredential } from './mintProviderCredential';
9
+ import type { RenewalRequest } from './renewalRequest';
10
+ import { jwtClaims } from './utils/jwtClaims';
11
+ import { ProviderError } from './utils/providerError';
12
+
13
+ const secondsUntilJwtExpiry = (token: string) => {
14
+ const exp = z.number().int().positive().safeParse(jwtClaims(token)?.exp);
15
+ if (!exp.success) throw new ProviderError('renewal_outcome_unknown', 409);
16
+ return z
17
+ .number()
18
+ .int()
19
+ .positive()
20
+ .max(31536000)
21
+ .parse(exp.data - Math.floor(Date.now() / 1000));
22
+ };
23
+
24
+ const refreshRequest = (
25
+ provider: string,
26
+ secret: CredentialSecret,
27
+ client?: OAuthClient,
28
+ ): RenewalRequest => {
29
+ if (!secret.oauth) throw new ProviderError('renewal_unsupported', 409);
30
+ const { refreshToken, tenantId } = secret.oauth;
31
+ const clientId = client?.clientId ?? secret.oauth.clientId;
32
+ const clientSecret = client?.clientSecret ?? secret.oauth.clientSecret;
33
+ const publicClient = provider === 'codex';
34
+ if (!clientId || (!clientSecret && !publicClient))
35
+ throw new ProviderError('renewal_unsupported', 409);
36
+ const familyOAuth = providers.find((definition) => definition.key === provider)?.oauth;
37
+ const fields = {
38
+ grant_type: 'refresh_token',
39
+ refresh_token: refreshToken,
40
+ client_id: clientId,
41
+ client_secret: clientSecret ?? '',
42
+ };
43
+ const headers = new Headers({
44
+ Accept: 'application/json',
45
+ 'Content-Type': 'application/x-www-form-urlencoded',
46
+ });
47
+ switch (provider) {
48
+ case 'slack':
49
+ return {
50
+ url: 'https://slack.com/api/oauth.v2.access',
51
+ headers,
52
+ body: new URLSearchParams(fields).toString(),
53
+ };
54
+ case 'githubUser':
55
+ return {
56
+ url: z
57
+ .url()
58
+ .parse(providers.find((definition) => definition.key === 'github')?.oauth?.tokenUrl),
59
+ headers,
60
+ body: new URLSearchParams(fields).toString(),
61
+ };
62
+ case 'linear':
63
+ return {
64
+ url: 'https://api.linear.app/oauth/token',
65
+ headers,
66
+ body: new URLSearchParams(fields).toString(),
67
+ };
68
+ case 'google':
69
+ return {
70
+ url: z.url().parse(familyOAuth?.tokenUrl),
71
+ headers,
72
+ body: new URLSearchParams(fields).toString(),
73
+ };
74
+ case 'teams':
75
+ return {
76
+ url: `https://login.microsoftonline.com/${z.uuid().parse(tenantId)}/oauth2/v2.0/token`,
77
+ headers,
78
+ body: new URLSearchParams(fields).toString(),
79
+ };
80
+ case 'jira':
81
+ case 'confluence':
82
+ headers.set('Content-Type', 'application/json');
83
+ return {
84
+ url: 'https://auth.atlassian.com/oauth/token',
85
+ headers,
86
+ body: JSON.stringify(fields),
87
+ };
88
+ case 'notion':
89
+ headers.set('Content-Type', 'application/json');
90
+ headers.set('Notion-Version', '2026-03-11');
91
+ headers.set(
92
+ 'Authorization',
93
+ `Basic ${Buffer.from(`${clientId}:${clientSecret}`).toString('base64')}`,
94
+ );
95
+ return {
96
+ url: 'https://api.notion.com/v1/oauth/token',
97
+ headers,
98
+ body: JSON.stringify({ grant_type: 'refresh_token', refresh_token: refreshToken }),
99
+ };
100
+ case 'codex':
101
+ headers.set('Content-Type', 'application/json');
102
+ return {
103
+ url: CODEX_TOKEN_URL,
104
+ headers,
105
+ body: JSON.stringify({
106
+ client_id: clientId,
107
+ grant_type: 'refresh_token',
108
+ refresh_token: refreshToken,
109
+ scope: 'openid profile email',
110
+ }),
111
+ };
112
+ default:
113
+ throw new ProviderError('renewal_unsupported', 409);
114
+ }
115
+ };
116
+
117
+ const refreshedSecret = (
118
+ provider: string,
119
+ secret: CredentialSecret,
120
+ data: Record<string, unknown>,
121
+ ) => {
122
+ if (data.error || (provider === 'slack' && data.ok !== true))
123
+ throw new ProviderError(
124
+ data.error === 'ratelimited' ? 'renewal_temporarily_unavailable' : 'renewal_rejected',
125
+ data.error === 'ratelimited' ? 503 : 409,
126
+ );
127
+ const refreshToken = secret.oauth?.refreshToken;
128
+ const refreshed = credentialSecretSchema.safeParse({
129
+ token: data.access_token,
130
+ oauth: {
131
+ ...secret.oauth,
132
+ refreshToken: data.refresh_token ?? refreshToken,
133
+ ...(typeof data.id_token === 'string' ? { idToken: data.id_token } : {}),
134
+ },
135
+ });
136
+ if (!refreshed.success) throw new ProviderError('renewal_outcome_unknown', 409);
137
+ if (
138
+ ['slack', 'linear', 'jira', 'confluence', 'notion', 'codex', 'githubUser'].includes(provider) &&
139
+ !data.refresh_token
140
+ )
141
+ throw new ProviderError('renewal_outcome_unknown', 409);
142
+ const expiresIn =
143
+ provider === 'notion' && data.expires_in === undefined
144
+ ? null
145
+ : provider === 'codex' && data.expires_in === undefined
146
+ ? secondsUntilJwtExpiry(refreshed.data.token)
147
+ : z.number().int().positive().max(31536000).safeParse(data.expires_in).data;
148
+ if (expiresIn === undefined) throw new ProviderError('renewal_outcome_unknown', 409);
149
+ return { secret: refreshed.data, expiresIn };
150
+ };
151
+
152
+ export const refreshProviderCredential = async (
153
+ client: CredentialClient,
154
+ { provider, secret: value }: { provider: string; secret: unknown },
155
+ ) => {
156
+ const secret = credentialSecretSchema.parse(value);
157
+ if (secret.clientCredentials)
158
+ return await mintProviderCredential(client, {
159
+ provider,
160
+ clientCredentials: secret.clientCredentials,
161
+ });
162
+ const data = await fetchRenewalResponse(
163
+ client.send ?? fetch,
164
+ refreshRequest(provider, secret, client.app),
165
+ );
166
+ try {
167
+ return refreshedSecret(provider, secret, data);
168
+ } catch (error) {
169
+ if (error instanceof ProviderError) throw error;
170
+ throw new ProviderError('renewal_outcome_unknown', 409);
171
+ }
172
+ };
@@ -0,0 +1 @@
1
+ export type RenewalRequest = { url: string; headers: Headers; body: string };
@@ -0,0 +1,4 @@
1
+ import type { Provider } from './contracts';
2
+ import { resourceExternalIdSchemas } from './resourceExternalIdSchemas';
3
+
4
+ export const resourceExternalIdSchema = (key: Provider) => resourceExternalIdSchemas[key];
@@ -0,0 +1,18 @@
1
+ import { threadIdSchema } from '@inixiative/signet/contracts';
2
+ import { z } from 'zod';
3
+ import { perProvider } from './perProvider';
4
+ import { githubRepositoryIdSchema } from './providers/github/models/repository/githubRepositoryIdSchema';
5
+
6
+ export const resourceExternalIdSchemas = perProvider(
7
+ z
8
+ .string()
9
+ .min(1)
10
+ .max(250)
11
+ .regex(/^[a-zA-Z0-9_:@.-]+$/)
12
+ .refine((id) => id !== '.' && id !== '..'),
13
+ {
14
+ githubOrganization: githubRepositoryIdSchema,
15
+ githubUser: githubRepositoryIdSchema,
16
+ foundry: threadIdSchema,
17
+ },
18
+ );
@@ -0,0 +1,4 @@
1
+ import type { Provider } from './contracts';
2
+ import { resourceMetadataSchemas } from './resourceMetadataSchemas';
3
+
4
+ export const resourceMetadataSchema = (key: Provider) => resourceMetadataSchemas[key];
@@ -0,0 +1,9 @@
1
+ import { z } from 'zod';
2
+ import { perProvider } from './perProvider';
3
+ import { githubRepositoryMetadataSchema } from './providers/github/models/repository/githubRepositoryMetadataSchema';
4
+
5
+ export const resourceMetadataSchemas = perProvider(z.strictObject({}), {
6
+ teams: z.strictObject({ teamId: z.uuid() }),
7
+ githubOrganization: githubRepositoryMetadataSchema,
8
+ githubUser: githubRepositoryMetadataSchema,
9
+ });
@@ -0,0 +1,12 @@
1
+ import type { SubscriptionRuntime } from './contracts';
2
+ import { jwtClaims } from './utils/jwtClaims';
3
+
4
+ export const subscriptionAccountId = (runtime: SubscriptionRuntime, accessToken: string) => {
5
+ if (runtime !== 'codex') return null;
6
+ const auth = jwtClaims(accessToken)?.['https://api.openai.com/auth'];
7
+ const accountId =
8
+ auth && typeof auth === 'object' && !Array.isArray(auth)
9
+ ? (auth as Record<string, unknown>).chatgpt_account_id
10
+ : undefined;
11
+ return typeof accountId === 'string' ? accountId : null;
12
+ };
@@ -0,0 +1,7 @@
1
+ import { z } from 'zod';
2
+
3
+ export const capacityWindowSchema = z.strictObject({
4
+ id: z.string().min(1).max(60),
5
+ usedPercent: z.number().min(0).max(100).nullable(),
6
+ resetsAt: z.number().int().nullable(),
7
+ });
@@ -0,0 +1,6 @@
1
+ // why: Number('') and Number(null) are both 0, so an absent header has to fail before it is parsed.
2
+ export const headerNumber = (value: string | null): number | null => {
3
+ if (value === null || value.trim() === '') return null;
4
+ const parsed = Number(value);
5
+ return Number.isFinite(parsed) ? parsed : null;
6
+ };
@@ -0,0 +1,14 @@
1
+ import { Buffer } from 'node:buffer';
2
+
3
+ export const jwtClaims = (token: string): Record<string, unknown> | null => {
4
+ const payload = token.split('.')[1];
5
+ if (!payload) return null;
6
+ try {
7
+ const parsed: unknown = JSON.parse(Buffer.from(payload, 'base64url').toString('utf8'));
8
+ return parsed && typeof parsed === 'object' && !Array.isArray(parsed)
9
+ ? (parsed as Record<string, unknown>)
10
+ : null;
11
+ } catch {
12
+ return null;
13
+ }
14
+ };
@@ -0,0 +1,11 @@
1
+ import { createHmac, timingSafeEqual } from 'node:crypto';
2
+
3
+ export const matchesHmacSha256 = (
4
+ message: Uint8Array | string,
5
+ hexSignature: string | null | undefined,
6
+ secret: string,
7
+ ) => {
8
+ if (!secret || !hexSignature || !/^[a-f0-9]{64}$/.test(hexSignature)) return false;
9
+ const expected = createHmac('sha256', secret).update(message).digest();
10
+ return timingSafeEqual(Buffer.from(hexSignature, 'hex'), expected);
11
+ };
@@ -0,0 +1,3 @@
1
+ import { z } from 'zod';
2
+
3
+ export const objectSchema = z.record(z.string(), z.unknown());
@@ -0,0 +1,18 @@
1
+ import type { PaginationOptions } from './paginationOptions';
2
+
3
+ const defaultMaxPages = 1000;
4
+
5
+ export const applyCaps = (
6
+ options: Pick<PaginationOptions<never>, 'maxPages' | 'maxRows' | 'onCapped'>,
7
+ progress: { pages: number; rows: number },
8
+ ): boolean => {
9
+ if (progress.rows >= (options.maxRows ?? Number.POSITIVE_INFINITY)) {
10
+ options.onCapped?.({ reason: 'maxRows', returned: progress.rows });
11
+ return true;
12
+ }
13
+ if (progress.pages >= (options.maxPages ?? defaultMaxPages)) {
14
+ options.onCapped?.({ reason: 'maxPages', returned: progress.rows });
15
+ return true;
16
+ }
17
+ return false;
18
+ };
@@ -0,0 +1,7 @@
1
+ export type ByCursorKeys = {
2
+ cursor: string;
3
+ pageSize: string;
4
+ data: string;
5
+ nextCursor: string;
6
+ hasMore?: string;
7
+ };
@@ -0,0 +1,7 @@
1
+ import type { ByCursorKeys } from './byCursorKeys';
2
+ import type { PaginationOptions } from './paginationOptions';
3
+
4
+ export type ByCursorOptions<R> = PaginationOptions<R> & {
5
+ keys: ByCursorKeys;
6
+ startCursor?: string | null;
7
+ };
@@ -0,0 +1,7 @@
1
+ export type ByPageKeys = {
2
+ page: string;
3
+ pageSize: string;
4
+ data: string;
5
+ total?: string;
6
+ totalPages?: string;
7
+ };
@@ -0,0 +1,8 @@
1
+ import type { ByPageKeys } from './byPageKeys';
2
+ import type { PaginationOptions } from './paginationOptions';
3
+
4
+ export type ByPageOptions<R, T> = PaginationOptions<R> & {
5
+ keys: ByPageKeys;
6
+ hasMore?: (response: R, items: T[], page: number) => boolean;
7
+ itemKey?: (item: T) => string;
8
+ };
@@ -0,0 +1,27 @@
1
+ import type { PaginationOptions } from './paginationOptions';
2
+
3
+ export const collectPages = async <
4
+ T,
5
+ O extends Pick<PaginationOptions<never>, 'maxRows' | 'onCapped'>,
6
+ >(
7
+ iterate: (options: O) => AsyncIterable<{ items: T[] }>,
8
+ options: O,
9
+ ): Promise<T[]> => {
10
+ let capReason: 'maxPages' | 'maxRows' | undefined;
11
+ const items: T[] = [];
12
+ const pages = iterate({
13
+ ...options,
14
+ onCapped: ({ reason }: { reason: 'maxPages' | 'maxRows' }) => {
15
+ capReason = reason;
16
+ },
17
+ });
18
+ for await (const walked of pages) items.push(...walked.items);
19
+
20
+ const maxRows = options.maxRows ?? Number.POSITIVE_INFINITY;
21
+ if (items.length > maxRows) {
22
+ items.length = maxRows;
23
+ capReason = 'maxRows';
24
+ }
25
+ if (capReason) options.onCapped?.({ reason: capReason, returned: items.length });
26
+ return items;
27
+ };
@@ -0,0 +1,4 @@
1
+ export const compactRequest = (entries: Record<string, string | number | null | undefined>) =>
2
+ Object.fromEntries(
3
+ Object.entries(entries).filter(([, value]) => value !== null && value !== undefined),
4
+ ) as Record<string, string | number>;
@@ -0,0 +1,6 @@
1
+ import type { ByCursorOptions } from './byCursorOptions';
2
+ import { collectPages } from './collectPages';
3
+ import { iterateByCursor } from './iterateByCursor';
4
+
5
+ export const fetchAllByCursor = <R, T = unknown>(options: ByCursorOptions<R>): Promise<T[]> =>
6
+ collectPages<T, ByCursorOptions<R>>(iterateByCursor<R, T>, options);
@@ -0,0 +1,6 @@
1
+ import type { ByPageOptions } from './byPageOptions';
2
+ import { collectPages } from './collectPages';
3
+ import { iterateByPage } from './iterateByPage';
4
+
5
+ export const fetchAllByPage = <R, T = unknown>(options: ByPageOptions<R, T>): Promise<T[]> =>
6
+ collectPages<T, ByPageOptions<R, T>>(iterateByPage<R, T>, options);
@@ -0,0 +1,16 @@
1
+ import type { ProviderRequestInput } from '../providerRequestInput';
2
+ import { collectPages } from './collectPages';
3
+ import { iterateRequestPages } from './iterateRequestPages';
4
+ import type { ProviderPagesOptions } from './providerPagesOptions';
5
+ import type { ProviderPagination } from './providerPagination';
6
+
7
+ export const fetchAllRequestPages = (
8
+ pagination: ProviderPagination,
9
+ request: (input: ProviderRequestInput) => Promise<unknown>,
10
+ input: ProviderRequestInput,
11
+ options: ProviderPagesOptions = {},
12
+ ) =>
13
+ collectPages(
14
+ (walk: ProviderPagesOptions) => iterateRequestPages(pagination, request, input, walk),
15
+ options,
16
+ );
@@ -0,0 +1,8 @@
1
+ import { PageWalkError } from './pageWalkError';
2
+
3
+ export class IncompletePageWalkError extends PageWalkError {
4
+ constructor(label: string, detail: string) {
5
+ super(`${label}: ${detail}`);
6
+ this.name = 'IncompletePageWalkError';
7
+ }
8
+ }
@@ -0,0 +1,20 @@
1
+ import type { ByPageKeys } from './byPageKeys';
2
+ import { readPath } from './readPath';
3
+
4
+ export const isAnotherPage = (
5
+ response: unknown,
6
+ itemCount: number,
7
+ {
8
+ keys,
9
+ pageSize,
10
+ progress,
11
+ }: { keys: ByPageKeys; pageSize?: number; progress: { pages: number; rows: number } },
12
+ ): boolean => {
13
+ if (itemCount === 0) return false;
14
+ const totalPages =
15
+ keys.totalPages === undefined ? undefined : readPath(response, keys.totalPages);
16
+ if (typeof totalPages === 'number') return progress.pages < totalPages;
17
+ const total = keys.total === undefined ? undefined : readPath(response, keys.total);
18
+ if (typeof total === 'number') return progress.rows < total;
19
+ return pageSize !== undefined && itemCount >= pageSize;
20
+ };