@inixiative/integrations 0.0.0-stage → 0.2.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 (214) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +50 -2
  3. package/package.json +56 -4
  4. package/src/catalog/declaredOperations.ts +9 -0
  5. package/src/catalog/eventLeaves.ts +5 -0
  6. package/src/catalog/familyProducts.ts +5 -0
  7. package/src/catalog/findProvider.ts +5 -0
  8. package/src/catalog/integrationEventResource.ts +20 -0
  9. package/src/catalog/integrationKeyedKinds.ts +4 -0
  10. package/src/catalog/isAccountSuppliedByHost.ts +6 -0
  11. package/src/catalog/isEventLeaf.ts +1 -0
  12. package/src/catalog/isFamilyManaged.ts +7 -0
  13. package/src/catalog/isUncalledLeaf.ts +6 -0
  14. package/src/catalog/operationLeaves.ts +6 -0
  15. package/src/catalog/providerEvent.ts +3 -0
  16. package/src/catalog/providerEventSchema.ts +3 -0
  17. package/src/catalog/providerFamily.ts +4 -0
  18. package/src/catalog/providerHasEvents.ts +8 -0
  19. package/src/catalog/providerModel.ts +12 -0
  20. package/src/catalog/providers.ts +54 -0
  21. package/src/contracts.ts +107 -0
  22. package/src/credentials/codexClientId.ts +2 -0
  23. package/src/credentials/codexTokenUrl.ts +1 -0
  24. package/src/credentials/consentReason.ts +4 -0
  25. package/src/credentials/consentReasonSchema.ts +21 -0
  26. package/src/credentials/credentialClient.ts +4 -0
  27. package/src/credentials/exchangeOauthCode.ts +61 -0
  28. package/src/credentials/fetchRenewalResponse.ts +41 -0
  29. package/src/credentials/mintProviderCredential.ts +68 -0
  30. package/src/credentials/providerExchangeTimeoutMs.ts +1 -0
  31. package/src/credentials/refreshProviderCredential.ts +172 -0
  32. package/src/credentials/renewalRequest.ts +1 -0
  33. package/src/credentials/subscriptionAccountId.ts +12 -0
  34. package/src/credentials/validateCredentialSecret.ts +18 -0
  35. package/src/index.ts +3 -0
  36. package/src/operations/buildProviderRequest.ts +54 -0
  37. package/src/operations/executeProvider.ts +26 -0
  38. package/src/operations/findOperationHandler.ts +6 -0
  39. package/src/operations/operationHandler.ts +8 -0
  40. package/src/operations/operationHandlers.ts +41 -0
  41. package/src/operations/operationRequestInput.ts +12 -0
  42. package/src/operations/providerRequestSpec.ts +1 -0
  43. package/src/providers/anthropic/anthropicProvider.ts +16 -0
  44. package/src/providers/archive/archiveCandidate.ts +1 -0
  45. package/src/providers/archive/archiveConfigurationSchema.ts +3 -0
  46. package/src/providers/archive/archiveProvider.ts +21 -0
  47. package/src/providers/archive/isLocalArchive.ts +5 -0
  48. package/src/providers/archive/localArchiveConfigurationSchema.ts +5 -0
  49. package/src/providers/archive/localArchiveSourceId.ts +8 -0
  50. package/src/providers/chorus/chorusProvider.ts +22 -0
  51. package/src/providers/claude/claudeProvider.ts +17 -0
  52. package/src/providers/codex/codexProvider.ts +17 -0
  53. package/src/providers/confluence/confluenceOperationHandler.ts +14 -0
  54. package/src/providers/confluence/confluenceProvider.ts +16 -0
  55. package/src/providers/discord/discordOperationHandler.ts +30 -0
  56. package/src/providers/discord/discordProvider.ts +22 -0
  57. package/src/providers/drive/driveOperationHandler.ts +21 -0
  58. package/src/providers/drive/driveProvider.ts +18 -0
  59. package/src/providers/foundry/foundryProvider.ts +33 -0
  60. package/src/providers/geminiApi/geminiApiProvider.ts +16 -0
  61. package/src/providers/github/auth/fetchGithubAppInstallation.ts +21 -0
  62. package/src/providers/github/auth/fetchGithubOrganizationRole.ts +27 -0
  63. package/src/providers/github/auth/fetchGithubUser.ts +11 -0
  64. package/src/providers/github/auth/fetchGithubUserInstallation.ts +21 -0
  65. package/src/providers/github/auth/githubAppClient.ts +4 -0
  66. package/src/providers/github/auth/githubAppInstallUrl.ts +20 -0
  67. package/src/providers/github/auth/githubAppJwt.ts +16 -0
  68. package/src/providers/github/auth/githubClientForApp.ts +11 -0
  69. package/src/providers/github/auth/githubInstallation.ts +4 -0
  70. package/src/providers/github/auth/githubInstallationAccountId.ts +4 -0
  71. package/src/providers/github/auth/githubInstallationFromAccountId.ts +4 -0
  72. package/src/providers/github/auth/githubInstallationSchema.ts +12 -0
  73. package/src/providers/github/auth/githubPermissionCovers.ts +14 -0
  74. package/src/providers/github/auth/githubPermissionScopes.ts +4 -0
  75. package/src/providers/github/auth/githubProviderForOwner.ts +6 -0
  76. package/src/providers/github/auth/githubUserAuthorizeUrl.ts +10 -0
  77. package/src/providers/github/events/githubEventRepositoryId.ts +10 -0
  78. package/src/providers/github/events/githubNotification.ts +4 -0
  79. package/src/providers/github/events/githubNotificationSchema.ts +9 -0
  80. package/src/providers/github/events/listGithubNotifications.ts +27 -0
  81. package/src/providers/github/events/normalizeGithubEvent.ts +200 -0
  82. package/src/providers/github/events/normalizeGithubNotification.ts +56 -0
  83. package/src/providers/github/events/verifyGithubSignature.ts +7 -0
  84. package/src/providers/github/fetchAllGithubPages.ts +12 -0
  85. package/src/providers/github/githubApiVersion.ts +1 -0
  86. package/src/providers/github/githubOrganizationProvider.ts +13 -0
  87. package/src/providers/github/githubPagination.ts +7 -0
  88. package/src/providers/github/githubProvider.ts +13 -0
  89. package/src/providers/github/githubRequestHeaders.ts +9 -0
  90. package/src/providers/github/githubUserProvider.ts +13 -0
  91. package/src/providers/github/iterateGithubPages.ts +12 -0
  92. package/src/providers/github/models/account/githubAccount.ts +17 -0
  93. package/src/providers/github/models/repository/githubOperationHandler.ts +36 -0
  94. package/src/providers/github/models/repository/githubRepository.ts +40 -0
  95. package/src/providers/github/models/repository/githubRepositoryIdSchema.ts +3 -0
  96. package/src/providers/github/models/repository/githubRepositoryMetadataSchema.ts +6 -0
  97. package/src/providers/github/models/repository/githubRepositoryName.ts +4 -0
  98. package/src/providers/github/models/repository/githubRepositoryNameSchema.ts +9 -0
  99. package/src/providers/github/models/repository/githubTreeEntryModeSchema.ts +3 -0
  100. package/src/providers/github/models/repository/githubTreeEntryTypeForMode.ts +14 -0
  101. package/src/providers/github/models/repository/githubTreeEntryTypeSchema.ts +3 -0
  102. package/src/providers/github/models/repository/listInstallationRepositories.ts +31 -0
  103. package/src/providers/github/models/repository/listUserRepositories.ts +36 -0
  104. package/src/providers/github/models/repository/readGithubObject.ts +85 -0
  105. package/src/providers/github/models/repository/readGithubRepositoryName.ts +4 -0
  106. package/src/providers/github/requestGithub.ts +18 -0
  107. package/src/providers/gmail/buildGmailMessageRequest.ts +22 -0
  108. package/src/providers/gmail/fetchGmailMessages.ts +81 -0
  109. package/src/providers/gmail/gmailOperationHandler.ts +12 -0
  110. package/src/providers/gmail/gmailProvider.ts +19 -0
  111. package/src/providers/google/auth/buildGoogleAuthorizationUrl.ts +33 -0
  112. package/src/providers/google/auth/verifyGoogleIdToken.ts +22 -0
  113. package/src/providers/google/googleProvider.ts +13 -0
  114. package/src/providers/jira/jiraOperationHandler.ts +14 -0
  115. package/src/providers/jira/jiraProvider.ts +16 -0
  116. package/src/providers/linear/auth/linearIntegrationSecret.ts +6 -0
  117. package/src/providers/linear/events/createLinearWebhook.ts +30 -0
  118. package/src/providers/linear/events/deleteLinearWebhook.ts +13 -0
  119. package/src/providers/linear/events/linearUserSchema.ts +3 -0
  120. package/src/providers/linear/events/linearWebhook.ts +3 -0
  121. package/src/providers/linear/events/linearWebhookPayload.ts +4 -0
  122. package/src/providers/linear/events/linearWebhookPayloadSchema.ts +13 -0
  123. package/src/providers/linear/events/listLinearWebhooks.ts +44 -0
  124. package/src/providers/linear/events/normalizeLinearEvent.ts +127 -0
  125. package/src/providers/linear/events/repairLinearWebhook.ts +17 -0
  126. package/src/providers/linear/events/verifyLinearSignature.ts +25 -0
  127. package/src/providers/linear/fetchAllLinearPages.ts +40 -0
  128. package/src/providers/linear/linearClient.ts +5 -0
  129. package/src/providers/linear/linearPagination.ts +13 -0
  130. package/src/providers/linear/linearProvider.ts +12 -0
  131. package/src/providers/linear/linearRequestInput.ts +1 -0
  132. package/src/providers/linear/models/issue/linearIssue.ts +11 -0
  133. package/src/providers/linear/models/issue/linearOperationHandler.ts +30 -0
  134. package/src/providers/linear/models/team/fetchLinearWorkspace.ts +30 -0
  135. package/src/providers/linear/models/team/linearTeam.ts +18 -0
  136. package/src/providers/linear/requestLinear.ts +51 -0
  137. package/src/providers/muse/museProvider.ts +17 -0
  138. package/src/providers/notion/notionOperationHandler.ts +32 -0
  139. package/src/providers/notion/notionProvider.ts +22 -0
  140. package/src/providers/openai/openaiProvider.ts +16 -0
  141. package/src/providers/oracle/oracleProvider.ts +10 -0
  142. package/src/providers/railway/railwayProvider.ts +9 -0
  143. package/src/providers/render/renderProvider.ts +9 -0
  144. package/src/providers/slack/auth/fetchSlackIdentity.ts +10 -0
  145. package/src/providers/slack/events/normalizeSlackEvent.ts +64 -0
  146. package/src/providers/slack/events/slackAccountIdOf.ts +1 -0
  147. package/src/providers/slack/events/slackEventEnvelope.ts +4 -0
  148. package/src/providers/slack/events/slackEventEnvelopeSchema.ts +16 -0
  149. package/src/providers/slack/events/slackTeamPrefix.ts +1 -0
  150. package/src/providers/slack/events/slackTokensRevokedSchema.ts +13 -0
  151. package/src/providers/slack/events/slackUserOfAccountId.ts +2 -0
  152. package/src/providers/slack/events/verifySlackSignature.ts +17 -0
  153. package/src/providers/slack/fetchAllSlackPages.ts +12 -0
  154. package/src/providers/slack/models/account/slackAccount.ts +13 -0
  155. package/src/providers/slack/models/channel/listSlackChannels.ts +26 -0
  156. package/src/providers/slack/models/channel/slackChannel.ts +31 -0
  157. package/src/providers/slack/models/channel/slackOperationHandler.ts +30 -0
  158. package/src/providers/slack/requestSlack.ts +22 -0
  159. package/src/providers/slack/slackPagination.ts +12 -0
  160. package/src/providers/slack/slackProvider.ts +12 -0
  161. package/src/providers/slack/slackProviderError.ts +12 -0
  162. package/src/providers/teams/teamsOperationHandler.ts +24 -0
  163. package/src/providers/teams/teamsProvider.ts +17 -0
  164. package/src/resources/integrationConfigurationSchemas.ts +11 -0
  165. package/src/resources/perProvider.ts +20 -0
  166. package/src/resources/resourceExternalIdSchema.ts +4 -0
  167. package/src/resources/resourceExternalIdSchemas.ts +18 -0
  168. package/src/resources/resourceMetadataSchema.ts +4 -0
  169. package/src/resources/resourceMetadataSchemas.ts +9 -0
  170. package/src/utils/capacityWindowSchema.ts +7 -0
  171. package/src/utils/headerNumber.ts +6 -0
  172. package/src/utils/jwtClaims.ts +14 -0
  173. package/src/utils/matchesHmacSha256.ts +11 -0
  174. package/src/utils/objectSchema.ts +3 -0
  175. package/src/utils/pagination/applyCaps.ts +18 -0
  176. package/src/utils/pagination/byCursorKeys.ts +7 -0
  177. package/src/utils/pagination/byCursorOptions.ts +7 -0
  178. package/src/utils/pagination/byPageKeys.ts +7 -0
  179. package/src/utils/pagination/byPageOptions.ts +8 -0
  180. package/src/utils/pagination/collectPages.ts +27 -0
  181. package/src/utils/pagination/compactRequest.ts +4 -0
  182. package/src/utils/pagination/fetchAllByCursor.ts +6 -0
  183. package/src/utils/pagination/fetchAllByPage.ts +6 -0
  184. package/src/utils/pagination/fetchAllRequestPages.ts +16 -0
  185. package/src/utils/pagination/incompletePageWalkError.ts +8 -0
  186. package/src/utils/pagination/isAnotherPage.ts +20 -0
  187. package/src/utils/pagination/iterateByCursor.ts +49 -0
  188. package/src/utils/pagination/iterateByPage.ts +59 -0
  189. package/src/utils/pagination/iterateProviderPages.ts +27 -0
  190. package/src/utils/pagination/iterateRequestPages.ts +18 -0
  191. package/src/utils/pagination/pageWalkError.ts +6 -0
  192. package/src/utils/pagination/paginationOptions.ts +9 -0
  193. package/src/utils/pagination/providerPagesOptions.ts +8 -0
  194. package/src/utils/pagination/providerPagination.ts +6 -0
  195. package/src/utils/pagination/readPage.ts +29 -0
  196. package/src/utils/pagination/readPath.ts +12 -0
  197. package/src/utils/pagination/repeatedCursorError.ts +10 -0
  198. package/src/utils/providerClient.ts +3 -0
  199. package/src/utils/providerCooldown.ts +23 -0
  200. package/src/utils/providerCooldownState.ts +4 -0
  201. package/src/utils/providerError.ts +10 -0
  202. package/src/utils/providerReading.ts +4 -0
  203. package/src/utils/providerReadingSchema.ts +8 -0
  204. package/src/utils/providerRequest.ts +22 -0
  205. package/src/utils/providerRequestInput.ts +7 -0
  206. package/src/utils/providerResponseLimit.ts +1 -0
  207. package/src/utils/providerSend.ts +1 -0
  208. package/src/utils/readProviderJson.ts +38 -0
  209. package/src/utils/readProviderLimits.ts +66 -0
  210. package/src/utils/readRateLimit.ts +29 -0
  211. package/src/utils/requestProviderJson.ts +13 -0
  212. package/src/utils/responseBudget.ts +1 -0
  213. package/src/utils/select.ts +6 -0
  214. package/src/utils/sendProviderRequest.ts +33 -0
@@ -0,0 +1,64 @@
1
+ import type { IntegrationEvent } from '@inixiative/signet/contracts';
2
+ import { z } from 'zod';
3
+ import type { ProviderEvent } from '../../../catalog/providerEvent';
4
+ import { providerEventSchema } from '../../../catalog/providerEventSchema';
5
+ import type { SlackEventEnvelope } from './slackEventEnvelope';
6
+
7
+ const excerptLength = 500;
8
+
9
+ const postedSubtypes = ['thread_broadcast', 'file_share'];
10
+
11
+ const messageSchema = z.object({
12
+ type: z.enum(['message', 'app_mention']),
13
+ subtype: z.string().optional(),
14
+ channel: z.string().min(1),
15
+ channel_type: z.string().optional(),
16
+ user: z.string().min(1),
17
+ text: z.string().default(''),
18
+ ts: z.string().min(1),
19
+ thread_ts: z.string().optional(),
20
+ });
21
+ type SlackMessage = z.infer<typeof messageSchema>;
22
+
23
+ const mentionPattern = /<@([UW][A-Z0-9]+)(?:\|[^>]*)?>/g;
24
+
25
+ const slackMentions = (text: string) => [
26
+ ...new Set([...text.matchAll(mentionPattern)].map((match) => match[1]!)),
27
+ ];
28
+
29
+ const typeOf = (message: SlackMessage) => {
30
+ if (message.type === 'app_mention') return 'app_mention';
31
+ if (message.channel_type === 'im') return 'message.im';
32
+ if (message.channel_type === 'channel') return 'message.channels';
33
+ return null;
34
+ };
35
+
36
+ export const normalizeSlackEvent = (input: {
37
+ integrationId: string;
38
+ provider: string;
39
+ envelope: SlackEventEnvelope;
40
+ body: unknown;
41
+ }): ProviderEvent | null => {
42
+ const parsed = messageSchema.safeParse(input.envelope.event);
43
+ if (!parsed.success) return null;
44
+ const message = parsed.data;
45
+ if (message.subtype && !postedSubtypes.includes(message.subtype)) return null;
46
+ const type = typeOf(message);
47
+ if (!type) return null;
48
+ const event = providerEventSchema.safeParse({
49
+ eventId: input.envelope.event_id,
50
+ integrationId: input.integrationId,
51
+ provider: input.provider,
52
+ type,
53
+ at: new Date(input.envelope.event_time * 1000).toISOString(),
54
+ actor: { login: message.user, id: message.user },
55
+ scope: message.channel,
56
+ mentions: slackMentions(message.text),
57
+ assignees: [],
58
+ requestedReviewers: [],
59
+ subject: {},
60
+ ...(message.text ? { excerpt: message.text.slice(0, excerptLength) } : {}),
61
+ payload: input.body,
62
+ });
63
+ return event.success ? event.data : null;
64
+ };
@@ -0,0 +1 @@
1
+ export const slackAccountIdOf = (teamId: string, userId: string) => `${teamId}:${userId}`;
@@ -0,0 +1,4 @@
1
+ import type { z } from 'zod';
2
+ import type { slackEventEnvelopeSchema } from './slackEventEnvelopeSchema';
3
+
4
+ export type SlackEventEnvelope = z.infer<typeof slackEventEnvelopeSchema>;
@@ -0,0 +1,16 @@
1
+ import { z } from 'zod';
2
+
3
+ const slackAuthorizationSchema = z.object({
4
+ team_id: z.string().nullish(),
5
+ user_id: z.string().nullish(),
6
+ is_bot: z.boolean().optional(),
7
+ });
8
+
9
+ export const slackEventEnvelopeSchema = z.object({
10
+ type: z.literal('event_callback'),
11
+ team_id: z.string().min(1),
12
+ event_id: z.string().min(1),
13
+ event_time: z.number().int(),
14
+ authorizations: z.array(slackAuthorizationSchema).default([]),
15
+ event: z.looseObject({ type: z.string().min(1) }),
16
+ });
@@ -0,0 +1 @@
1
+ export const slackTeamPrefix = (teamId: string) => `${teamId}:`;
@@ -0,0 +1,13 @@
1
+ import { z } from 'zod';
2
+
3
+ export const slackTokensRevokedSchema = z.object({
4
+ type: z.literal('event_callback'),
5
+ team_id: z.string().min(1),
6
+ event: z.object({
7
+ type: z.literal('tokens_revoked'),
8
+ tokens: z.object({
9
+ oauth: z.array(z.string()).default([]),
10
+ bot: z.array(z.string()).default([]),
11
+ }),
12
+ }),
13
+ });
@@ -0,0 +1,2 @@
1
+ export const slackUserOfAccountId = (externalAccountId: string | null) =>
2
+ externalAccountId?.split(':')[1] ?? null;
@@ -0,0 +1,17 @@
1
+ import { matchesHmacSha256 } from '../../../utils/matchesHmacSha256';
2
+
3
+ const replayWindowSeconds = 5 * 60;
4
+
5
+ export const verifySlackSignature = (
6
+ rawBody: Uint8Array,
7
+ headers: Headers,
8
+ secret: string,
9
+ now = Date.now(),
10
+ ) => {
11
+ const timestamp = headers.get('x-slack-request-timestamp') ?? '';
12
+ if (!/^\d{1,12}$/.test(timestamp)) return false;
13
+ if (Math.abs(now / 1000 - Number(timestamp)) > replayWindowSeconds) return false;
14
+ const signature = /^v0=([a-f0-9]{64})$/.exec(headers.get('x-slack-signature') ?? '')?.[1];
15
+ const basestring = Buffer.concat([Buffer.from(`v0:${timestamp}:`), rawBody]);
16
+ return matchesHmacSha256(basestring, signature, secret);
17
+ };
@@ -0,0 +1,12 @@
1
+ import { fetchAllRequestPages } from '../../utils/pagination/fetchAllRequestPages';
2
+ import type { ProviderPagesOptions } from '../../utils/pagination/providerPagesOptions';
3
+ import type { ProviderClient } from '../../utils/providerClient';
4
+ import type { ProviderRequestInput } from '../../utils/providerRequestInput';
5
+ import { requestSlack } from './requestSlack';
6
+ import { slackPagination } from './slackPagination';
7
+
8
+ export const fetchAllSlackPages = (
9
+ client: ProviderClient,
10
+ input: ProviderRequestInput,
11
+ options?: ProviderPagesOptions,
12
+ ) => fetchAllRequestPages(slackPagination, (page) => requestSlack(client, page), input, options);
@@ -0,0 +1,13 @@
1
+ import { accountResourceKind } from '@inixiative/signet/contracts';
2
+ import { declaredOperations } from '../../../../catalog/declaredOperations';
3
+ import type { ProviderModel } from '../../../../catalog/providerModel';
4
+
5
+ export const slackAccount = {
6
+ kind: accountResourceKind,
7
+ operations: [],
8
+ events: declaredOperations(
9
+ { 'events.message.im': 'Receive the direct messages of this Slack account' },
10
+ accountResourceKind,
11
+ ['im:history'],
12
+ ),
13
+ } satisfies ProviderModel;
@@ -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,31 @@
1
+ import { declaredOperations } from '../../../../catalog/declaredOperations';
2
+ import type { ProviderModel } from '../../../../catalog/providerModel';
3
+
4
+ const kind = 'channel';
5
+
6
+ const events = {
7
+ 'events.message.channels': 'Receive messages posted in this public channel',
8
+ 'events.app_mention': 'Receive mentions of the connected Slack app in this channel',
9
+ } as const;
10
+
11
+ export const slackChannel = {
12
+ kind,
13
+ operations: [
14
+ {
15
+ key: 'conversations.read',
16
+ name: 'Read channel details',
17
+ resourceKind: kind,
18
+ requiredScopes: ['channels:read or groups:read'],
19
+ },
20
+ {
21
+ key: 'messages.read',
22
+ name: 'Read channel messages',
23
+ resourceKind: kind,
24
+ requiredScopes: ['channels:history or groups:history'],
25
+ },
26
+ ],
27
+ events: [
28
+ ...declaredOperations(events, kind, ['channels:history'], ['events.message.channels']),
29
+ ...declaredOperations(events, kind, ['app_mentions:read'], ['events.app_mention']),
30
+ ],
31
+ } satisfies ProviderModel;
@@ -0,0 +1,30 @@
1
+ import { z } from 'zod';
2
+ import type { OperationHandler } from '../../../../operations/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,12 @@
1
+ import type { ProviderDefinition } from '../../contracts';
2
+ import { slackAccount } from './models/account/slackAccount';
3
+ import { slackChannel } from './models/channel/slackChannel';
4
+
5
+ export const slackProvider: ProviderDefinition = {
6
+ key: 'slack',
7
+ name: 'Slack',
8
+ documentationUrl: 'https://docs.slack.dev/reference/methods/conversations.history/',
9
+ authMethods: ['bearer', 'oauth2'],
10
+ operations: [...slackChannel.operations, ...slackChannel.events, ...slackAccount.events],
11
+ syncedResourceKinds: [slackChannel.kind],
12
+ };
@@ -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 '../../operations/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,11 @@
1
+ import { z } from 'zod';
2
+ import { archiveConfigurationSchema } from '../providers/archive/archiveConfigurationSchema';
3
+ import { perProvider } from './perProvider';
4
+
5
+ const atlassianConfigurationSchema = z.strictObject({ cloudId: z.uuid() });
6
+
7
+ export const integrationConfigurationSchemas = perProvider(z.strictObject({}), {
8
+ jira: atlassianConfigurationSchema,
9
+ confluence: atlassianConfigurationSchema,
10
+ archive: archiveConfigurationSchema,
11
+ });
@@ -0,0 +1,20 @@
1
+ import type { z } from 'zod';
2
+ import { type Provider, providerSchema } from '../contracts';
3
+
4
+ type PerProvider<TFallback, TOverrides> = {
5
+ [P in Provider]: P extends keyof TOverrides ? TOverrides[P] : TFallback;
6
+ };
7
+
8
+ export const perProvider = <
9
+ TFallback extends z.ZodType,
10
+ TOverrides extends Partial<Record<Provider, z.ZodType>>,
11
+ >(
12
+ fallback: TFallback,
13
+ overrides: TOverrides,
14
+ ): PerProvider<TFallback, TOverrides> =>
15
+ Object.fromEntries(
16
+ providerSchema.options.map((provider) => [
17
+ provider,
18
+ overrides[provider as keyof TOverrides] ?? fallback,
19
+ ]),
20
+ ) as PerProvider<TFallback, TOverrides>;
@@ -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 { githubRepositoryIdSchema } from '../providers/github/models/repository/githubRepositoryIdSchema';
4
+ import { perProvider } from './perProvider';
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 { githubRepositoryMetadataSchema } from '../providers/github/models/repository/githubRepositoryMetadataSchema';
3
+ import { perProvider } from './perProvider';
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,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
+ };