@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,31 @@
1
+ import { z } from 'zod';
2
+ import { providerResourceLimit } from '../../../../contracts';
3
+ import type { ProviderClient } from '../../../../utils/providerClient';
4
+ import { ProviderError } from '../../../../utils/providerError';
5
+ import { fetchAllGithubPages } from '../../fetchAllGithubPages';
6
+ import { githubRepositoryName } from './githubRepositoryName';
7
+
8
+ const totalSchema = z.object({ total_count: z.number().int().min(0) });
9
+ const repositoriesSchema = z.array(
10
+ z.object({ id: z.number().int().positive(), full_name: z.string() }),
11
+ );
12
+
13
+ export const listInstallationRepositories = async (client: ProviderClient) => {
14
+ const repositories = repositoriesSchema.parse(
15
+ await fetchAllGithubPages(
16
+ client,
17
+ { path: '/installation/repositories' },
18
+ {
19
+ keys: { data: 'repositories' },
20
+ onResponse: (response) => {
21
+ if (totalSchema.parse(response).total_count > providerResourceLimit)
22
+ throw new ProviderError('too_many_repositories', 409);
23
+ },
24
+ },
25
+ ),
26
+ );
27
+ const listed = new Map(
28
+ repositories.map(({ id, full_name }) => [String(id), githubRepositoryName(full_name)]),
29
+ );
30
+ return [...listed].map(([id, fullName]) => ({ id, fullName }));
31
+ };
@@ -0,0 +1,36 @@
1
+ import { z } from 'zod';
2
+ import { providerResourceLimit } from '../../../../contracts';
3
+ import type { ProviderClient } from '../../../../utils/providerClient';
4
+ import { ProviderError } from '../../../../utils/providerError';
5
+ import { fetchAllGithubPages } from '../../fetchAllGithubPages';
6
+ import { githubRepositoryName } from './githubRepositoryName';
7
+
8
+ const installationsSchema = z.array(z.object({ id: z.number().int().positive() }));
9
+ const repositoriesSchema = z.array(
10
+ z.object({ id: z.number().int().positive(), full_name: z.string() }),
11
+ );
12
+
13
+ // why: a GitHub App user token reaches only repositories in the App's installations the user sees.
14
+ export const listUserRepositories = async (client: ProviderClient) => {
15
+ const installations = installationsSchema.parse(
16
+ await fetchAllGithubPages(
17
+ client,
18
+ { path: '/user/installations' },
19
+ { keys: { data: 'installations' } },
20
+ ),
21
+ );
22
+ const listed = new Map<string, string>();
23
+ for (const installation of installations) {
24
+ const repositories = repositoriesSchema.parse(
25
+ await fetchAllGithubPages(
26
+ client,
27
+ { path: `/user/installations/${installation.id}/repositories` },
28
+ { keys: { data: 'repositories' } },
29
+ ),
30
+ );
31
+ for (const repository of repositories)
32
+ listed.set(String(repository.id), githubRepositoryName(repository.full_name));
33
+ if (listed.size > providerResourceLimit) throw new ProviderError('too_many_repositories', 409);
34
+ }
35
+ return [...listed].map(([id, fullName]) => ({ id, fullName }));
36
+ };
@@ -0,0 +1,85 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { gitObjectIdSchema } from '@inixiative/signet/contracts';
3
+ import { z } from 'zod';
4
+ import type { ProviderContext } from '../../../../contracts';
5
+ import { ProviderError } from '../../../../utils/providerError';
6
+ import { githubTreeEntryModeSchema } from './githubTreeEntryModeSchema';
7
+ import { githubTreeEntryTypeForMode } from './githubTreeEntryTypeForMode';
8
+ import { githubTreeEntryTypeSchema } from './githubTreeEntryTypeSchema';
9
+
10
+ export const readGithubObject = (data: unknown, context: ProviderContext, objectId: string) => {
11
+ const identity = z.object({ sha: gitObjectIdSchema }).parse(data);
12
+ if (identity.sha !== objectId) throw new ProviderError('provider_invalid_response');
13
+ if (context.operation === 'commits.read')
14
+ return z
15
+ .object({ sha: gitObjectIdSchema, tree: z.object({ sha: gitObjectIdSchema }) })
16
+ .parse(data);
17
+ if (context.operation === 'trees.read') {
18
+ const tree = z
19
+ .object({
20
+ sha: gitObjectIdSchema,
21
+ truncated: z.literal(false),
22
+ tree: z
23
+ .array(
24
+ z
25
+ .object({
26
+ path: z
27
+ .string()
28
+ .min(1)
29
+ .max(255)
30
+ .refine(
31
+ (path) =>
32
+ path !== '.' &&
33
+ path !== '..' &&
34
+ [...path].every(
35
+ (character) =>
36
+ character.charCodeAt(0) >= 32 &&
37
+ character.charCodeAt(0) !== 127 &&
38
+ character !== '/' &&
39
+ character !== String.fromCharCode(92),
40
+ ),
41
+ ),
42
+ mode: githubTreeEntryModeSchema,
43
+ type: githubTreeEntryTypeSchema,
44
+ sha: gitObjectIdSchema,
45
+ size: z
46
+ .number()
47
+ .int()
48
+ .min(0)
49
+ .max(512 * 1024)
50
+ .optional(),
51
+ })
52
+ .refine((entry) => githubTreeEntryTypeForMode[entry.mode] === entry.type),
53
+ )
54
+ .max(context.limit),
55
+ })
56
+ .parse(data);
57
+ if (new Set(tree.tree.map((entry) => entry.path)).size !== tree.tree.length)
58
+ throw new ProviderError('provider_invalid_response');
59
+ return tree;
60
+ }
61
+ const blob = z
62
+ .object({
63
+ sha: gitObjectIdSchema,
64
+ encoding: z.literal('base64'),
65
+ size: z
66
+ .number()
67
+ .int()
68
+ .min(0)
69
+ .max(512 * 1024),
70
+ content: z
71
+ .string()
72
+ .max(750000)
73
+ .regex(/^[A-Za-z0-9+/=\r\n]*$/),
74
+ })
75
+ .parse(data);
76
+ const encoded = blob.content.replace(/[\r\n]/g, '');
77
+ const bytes = Buffer.from(encoded, 'base64');
78
+ if (
79
+ bytes.toString('base64') !== encoded ||
80
+ bytes.length !== blob.size ||
81
+ createHash('sha1').update(`blob ${bytes.length}\0`).update(bytes).digest('hex') !== blob.sha
82
+ )
83
+ throw new ProviderError('provider_invalid_response');
84
+ return { sha: blob.sha, encoding: blob.encoding, size: blob.size, content: encoded };
85
+ };
@@ -0,0 +1,4 @@
1
+ import { githubRepositoryNameSchema } from './githubRepositoryNameSchema';
2
+
3
+ export const readGithubRepositoryName = (fullName: string) =>
4
+ githubRepositoryNameSchema.safeParse(fullName.toLowerCase()).data ?? null;
@@ -0,0 +1,18 @@
1
+ import type { ProviderClient } from '../../utils/providerClient';
2
+ import { providerRequest } from '../../utils/providerRequest';
3
+ import type { ProviderRequestInput } from '../../utils/providerRequestInput';
4
+ import { requestProviderJson } from '../../utils/requestProviderJson';
5
+ import { githubRequestHeaders } from './githubRequestHeaders';
6
+
7
+ export const requestGithub = async (
8
+ { token, send = fetch }: ProviderClient,
9
+ input: ProviderRequestInput,
10
+ ) =>
11
+ await requestProviderJson(
12
+ send,
13
+ providerRequest(
14
+ 'https://api.github.com',
15
+ input,
16
+ githubRequestHeaders(new Headers(input.headers), token),
17
+ ),
18
+ );
@@ -0,0 +1,22 @@
1
+ import { ProviderError } from '../../utils/providerError';
2
+
3
+ const gmailMessageIdPattern = /^[A-Za-z0-9_-]{1,64}$/;
4
+
5
+ export const buildGmailMessageRequest = (
6
+ listRequest: Request,
7
+ messageId: unknown,
8
+ signal: AbortSignal = listRequest.signal,
9
+ ) => {
10
+ if (typeof messageId !== 'string' || !gmailMessageIdPattern.test(messageId))
11
+ throw new ProviderError('provider_invalid_response');
12
+ const url = new URL(`https://gmail.googleapis.com/gmail/v1/users/me/messages/${messageId}`);
13
+ url.searchParams.set('format', 'metadata');
14
+ for (const header of ['From', 'To', 'Subject', 'Date'])
15
+ url.searchParams.append('metadataHeaders', header);
16
+ return new Request(url.toString(), {
17
+ method: 'GET',
18
+ headers: listRequest.headers,
19
+ redirect: 'error',
20
+ signal,
21
+ });
22
+ };
@@ -0,0 +1,81 @@
1
+ import { z } from 'zod';
2
+ import type { ProviderContext } from '../../contracts';
3
+ import { providerResponseLimit } from '../../utils/providerResponseLimit';
4
+ import type { ProviderSend } from '../../utils/providerSend';
5
+ import { readProviderJson } from '../../utils/readProviderJson';
6
+ import { sendProviderRequest } from '../../utils/sendProviderRequest';
7
+ import { buildGmailMessageRequest } from './buildGmailMessageRequest';
8
+
9
+ const gmailConcurrency = 10;
10
+ const listSchema = z.object({
11
+ messages: z.array(z.object({ id: z.string() })).default([]),
12
+ nextPageToken: z.string().optional(),
13
+ });
14
+ const messageSchema = z.object({
15
+ id: z.string(),
16
+ threadId: z.string(),
17
+ snippet: z.string().default(''),
18
+ payload: z
19
+ .object({ headers: z.array(z.object({ name: z.string(), value: z.string() })).default([]) })
20
+ .default({ headers: [] }),
21
+ });
22
+
23
+ const projectMessage = (value: unknown) => {
24
+ const message = messageSchema.parse(value);
25
+ const header = (name: string) =>
26
+ message.payload.headers.find((item) => item.name.toLowerCase() === name.toLowerCase())?.value ??
27
+ null;
28
+ return {
29
+ id: message.id,
30
+ threadId: message.threadId,
31
+ from: header('From'),
32
+ to: header('To'),
33
+ subject: header('Subject'),
34
+ date: header('Date'),
35
+ snippet: message.snippet,
36
+ };
37
+ };
38
+
39
+ export const fetchGmailMessages = async (
40
+ { send }: { send: ProviderSend },
41
+ { listRequest, context }: { listRequest: Request; context: ProviderContext },
42
+ ) => {
43
+ const budget = { remainingBytes: providerResponseLimit };
44
+ const list = listSchema.parse(
45
+ await readProviderJson(await sendProviderRequest(send, listRequest), budget),
46
+ );
47
+ const ids = list.messages.slice(0, context.limit).map((item) => item.id);
48
+ const batch = new AbortController();
49
+ const signal = AbortSignal.any([listRequest.signal, batch.signal]);
50
+ const fetchGmailMessage = async (id: string) => {
51
+ let deleted = false;
52
+ const response = await sendProviderRequest(
53
+ async (request) => {
54
+ const result = await send(request);
55
+ if (result.status !== 404) return result;
56
+ deleted = true;
57
+ await result.body?.cancel();
58
+ return Response.json(null);
59
+ },
60
+ buildGmailMessageRequest(listRequest, id, signal),
61
+ );
62
+ if (deleted) {
63
+ await response.body?.cancel();
64
+ return [];
65
+ }
66
+ return [projectMessage(await readProviderJson(response, budget))];
67
+ };
68
+ const messages: ReturnType<typeof projectMessage>[] = [];
69
+ for (let start = 0; start < ids.length; start += gmailConcurrency)
70
+ messages.push(
71
+ ...(
72
+ await Promise.all(ids.slice(start, start + gmailConcurrency).map(fetchGmailMessage)).catch(
73
+ (error: unknown) => {
74
+ batch.abort();
75
+ throw error;
76
+ },
77
+ )
78
+ ).flat(),
79
+ );
80
+ return { messages, hasMore: Boolean(list.nextPageToken) || list.messages.length > ids.length };
81
+ };
@@ -0,0 +1,12 @@
1
+ import type { OperationHandler } from '../../operationHandler';
2
+
3
+ // why: Gmail reads its own response (a label listing, then a fetch per message), so parse passes it through.
4
+ export const gmailOperationHandler: OperationHandler = {
5
+ request: ({ externalId, limit }) => {
6
+ const url = new URL('https://gmail.googleapis.com/gmail/v1/users/me/messages');
7
+ url.searchParams.set('labelIds', externalId);
8
+ url.searchParams.set('maxResults', String(limit));
9
+ return { url };
10
+ },
11
+ parse: (body) => body,
12
+ };
@@ -0,0 +1,19 @@
1
+ import type { ProviderDefinition } from '../../contracts';
2
+
3
+ export const gmailProvider: ProviderDefinition = {
4
+ key: 'gmail',
5
+ name: 'Gmail',
6
+ documentationUrl:
7
+ 'https://developers.google.com/workspace/gmail/api/reference/rest/v1/users.messages/list',
8
+ authMethods: ['oauth2'],
9
+ family: 'google',
10
+ oauthScopes: ['https://www.googleapis.com/auth/gmail.readonly'],
11
+ operations: [
12
+ {
13
+ key: 'messages.read',
14
+ name: 'Read the newest messages in a label',
15
+ resourceKind: 'label',
16
+ requiredScopes: ['https://www.googleapis.com/auth/gmail.readonly'],
17
+ },
18
+ ],
19
+ };
@@ -0,0 +1,33 @@
1
+ import { z } from 'zod';
2
+ import type { Provider } from '../../../contracts';
3
+ import { findProvider } from '../../../findProvider';
4
+
5
+ export const buildGoogleAuthorizationUrl = (input: {
6
+ clientId: string;
7
+ redirectUri: string;
8
+ products: Provider[];
9
+ state: string;
10
+ codeChallenge: string;
11
+ loginHint?: string;
12
+ }) => {
13
+ const url = new URL(z.url().parse(findProvider('google')?.oauth?.authorizeUrl));
14
+ const scopes = [
15
+ ...new Set([
16
+ ...input.products.flatMap((product) => findProvider(product)?.oauthScopes ?? []),
17
+ 'openid',
18
+ 'email',
19
+ ]),
20
+ ];
21
+ url.searchParams.set('client_id', input.clientId);
22
+ url.searchParams.set('redirect_uri', input.redirectUri);
23
+ url.searchParams.set('response_type', 'code');
24
+ url.searchParams.set('scope', scopes.join(' '));
25
+ url.searchParams.set('state', input.state);
26
+ url.searchParams.set('code_challenge', input.codeChallenge);
27
+ url.searchParams.set('code_challenge_method', 'S256');
28
+ url.searchParams.set('access_type', 'offline');
29
+ url.searchParams.set('include_granted_scopes', 'true');
30
+ url.searchParams.set('prompt', 'consent');
31
+ if (input.loginHint) url.searchParams.set('login_hint', input.loginHint);
32
+ return url.toString();
33
+ };
@@ -0,0 +1,22 @@
1
+ import { decodeJwt } from 'jose';
2
+ import { z } from 'zod';
3
+ import { ProviderError } from '../../../utils/providerError';
4
+
5
+ const claimsSchema = z.object({
6
+ iss: z.enum(['accounts.google.com', 'https://accounts.google.com']),
7
+ aud: z.string(),
8
+ sub: z.string().min(1).max(255),
9
+ email: z.string().min(1).max(320),
10
+ email_verified: z.literal(true),
11
+ });
12
+
13
+ export const verifyGoogleIdToken = (idToken: string, clientId: string) => {
14
+ let claims: z.infer<typeof claimsSchema>;
15
+ try {
16
+ claims = claimsSchema.parse(decodeJwt(idToken));
17
+ } catch {
18
+ throw new ProviderError('id_token_invalid', 502);
19
+ }
20
+ if (claims.aud !== clientId) throw new ProviderError('id_token_invalid', 502);
21
+ return { sub: claims.sub, email: claims.email };
22
+ };
@@ -0,0 +1,13 @@
1
+ import type { ProviderDefinition } from '../../contracts';
2
+
3
+ export const googleProvider: ProviderDefinition = {
4
+ key: 'google',
5
+ name: 'Google',
6
+ documentationUrl: 'https://developers.google.com/identity/protocols/oauth2/web-server',
7
+ authMethods: ['oauth2'],
8
+ operations: [],
9
+ oauth: {
10
+ authorizeUrl: 'https://accounts.google.com/o/oauth2/v2/auth',
11
+ tokenUrl: 'https://oauth2.googleapis.com/token',
12
+ },
13
+ };
@@ -0,0 +1,14 @@
1
+ import type { OperationHandler } from '../../operationHandler';
2
+ import { objectSchema } from '../../utils/objectSchema';
3
+ import { select } from '../../utils/select';
4
+
5
+ export const jiraOperationHandler: OperationHandler = {
6
+ request: ({ configuration, id }) => {
7
+ const url = new URL(
8
+ `https://api.atlassian.com/ex/jira/${'cloudId' in configuration ? configuration.cloudId : ''}/rest/api/3/issue/${id}`,
9
+ );
10
+ url.searchParams.set('fields', 'summary,description,status');
11
+ return { url };
12
+ },
13
+ parse: (body) => select(objectSchema.parse(body), ['id', 'key', 'fields']),
14
+ };
@@ -0,0 +1,16 @@
1
+ import type { ProviderDefinition } from '../../contracts';
2
+
3
+ export const jiraProvider: ProviderDefinition = {
4
+ key: 'jira',
5
+ name: 'Jira',
6
+ documentationUrl: 'https://developer.atlassian.com/cloud/jira/platform/rest/v3/api-group-issues/',
7
+ authMethods: ['bearer', 'oauth2'],
8
+ operations: [
9
+ {
10
+ key: 'issues.read',
11
+ name: 'Read an issue',
12
+ resourceKind: 'issue',
13
+ requiredScopes: ['read:jira-work'],
14
+ },
15
+ ],
16
+ };
@@ -0,0 +1,6 @@
1
+ import { createHmac } from 'node:crypto';
2
+
3
+ export const linearIntegrationSecret = (signingSecret: string, integrationId: string) =>
4
+ createHmac('sha256', signingSecret)
5
+ .update(`linear-webhook:integration:${integrationId}`)
6
+ .digest('hex');
@@ -0,0 +1,30 @@
1
+ import { z } from 'zod';
2
+ import type { LinearClient } from '../linearClient';
3
+ import { requestLinear } from '../requestLinear';
4
+
5
+ const createdSchema = z.object({
6
+ webhookCreate: z.object({
7
+ success: z.boolean(),
8
+ webhook: z.object({ id: z.string() }).nullish(),
9
+ }),
10
+ });
11
+
12
+ export const createLinearWebhook = async (
13
+ client: LinearClient,
14
+ { url, secret, label, teamId }: { url: string; secret: string; label: string; teamId?: string },
15
+ ) =>
16
+ createdSchema.parse(
17
+ await requestLinear(client, {
18
+ query:
19
+ 'mutation WebhookCreate($input: WebhookCreateInput!) { webhookCreate(input: $input) { success webhook { id } } }',
20
+ variables: {
21
+ input: {
22
+ url,
23
+ secret,
24
+ label,
25
+ resourceTypes: ['Issue', 'Comment'],
26
+ ...(teamId ? { teamId } : { allPublicTeams: true }),
27
+ },
28
+ },
29
+ }),
30
+ ).webhookCreate.success;
@@ -0,0 +1,13 @@
1
+ import { z } from 'zod';
2
+ import type { LinearClient } from '../linearClient';
3
+ import { requestLinear } from '../requestLinear';
4
+
5
+ const deletedSchema = z.object({ webhookDelete: z.object({ success: z.boolean() }) });
6
+
7
+ export const deleteLinearWebhook = async (client: LinearClient, { id }: { id: string }) =>
8
+ deletedSchema.parse(
9
+ await requestLinear(client, {
10
+ query: 'mutation WebhookDelete($id: String!) { webhookDelete(id: $id) { success } }',
11
+ variables: { id },
12
+ }),
13
+ ).webhookDelete.success;
@@ -0,0 +1,3 @@
1
+ import { z } from 'zod';
2
+
3
+ export const linearUserSchema = z.object({ id: z.string().min(1), url: z.string().optional() });
@@ -0,0 +1,3 @@
1
+ import type { listLinearWebhooks } from './listLinearWebhooks';
2
+
3
+ export type LinearWebhook = Awaited<ReturnType<typeof listLinearWebhooks>>[number];
@@ -0,0 +1,4 @@
1
+ import type { z } from 'zod';
2
+ import type { linearWebhookPayloadSchema } from './linearWebhookPayloadSchema';
3
+
4
+ export type LinearWebhookPayload = z.infer<typeof linearWebhookPayloadSchema>;
@@ -0,0 +1,13 @@
1
+ import { z } from 'zod';
2
+ import { linearUserSchema } from './linearUserSchema';
3
+
4
+ export const linearWebhookPayloadSchema = z.object({
5
+ action: z.string().min(1),
6
+ type: z.string().min(1),
7
+ organizationId: z.string().min(1),
8
+ createdAt: z.string().min(1),
9
+ url: z.string().nullish(),
10
+ actor: linearUserSchema.nullish(),
11
+ updatedFrom: z.record(z.string(), z.unknown()).nullish(),
12
+ data: z.looseObject({}),
13
+ });
@@ -0,0 +1,44 @@
1
+ import { z } from 'zod';
2
+ import { ProviderError } from '../../../utils/providerError';
3
+ import { fetchAllLinearPages } from '../fetchAllLinearPages';
4
+ import type { LinearClient } from '../linearClient';
5
+
6
+ const webhooksSchema = z.array(
7
+ z.object({
8
+ id: z.string(),
9
+ url: z.string().nullish(),
10
+ allPublicTeams: z.boolean(),
11
+ enabled: z.boolean(),
12
+ secret: z.string().nullish(),
13
+ resourceTypes: z.array(z.string()),
14
+ team: z.object({ id: z.string() }).nullish(),
15
+ }),
16
+ );
17
+
18
+ const webhooksQuery =
19
+ 'query Webhooks($first: Int, $after: String) { webhooks(first: $first, after: $after) { pageInfo { hasNextPage endCursor } nodes { id url allPublicTeams enabled secret resourceTypes team { id } } } }';
20
+
21
+ export const listLinearWebhooks = async (client: LinearClient) => {
22
+ const webhooks = webhooksSchema.parse(
23
+ await fetchAllLinearPages(
24
+ client,
25
+ { query: webhooksQuery },
26
+ {
27
+ connection: 'webhooks',
28
+ maxPages: 40,
29
+ onCapped: () => {
30
+ throw new ProviderError('provider_invalid_response');
31
+ },
32
+ },
33
+ ),
34
+ );
35
+ return webhooks.map((webhook) => ({
36
+ id: webhook.id,
37
+ url: webhook.url ?? null,
38
+ allPublicTeams: webhook.allPublicTeams,
39
+ enabled: webhook.enabled,
40
+ secret: webhook.secret ?? null,
41
+ resourceTypes: webhook.resourceTypes,
42
+ teamId: webhook.team?.id ?? null,
43
+ }));
44
+ };