@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,33 @@
1
+ import {
2
+ conversationPermissionNames,
3
+ conversationPermissionSchema,
4
+ conversationResourceKind,
5
+ threadOperationNames,
6
+ threadOperationSchema,
7
+ } from '@inixiative/signet/contracts';
8
+ import { declaredOperations } from '../../catalog/declaredOperations';
9
+ import type { ProviderDefinition } from '../../contracts';
10
+
11
+ export const foundryProvider: ProviderDefinition = {
12
+ key: 'foundry',
13
+ name: 'Foundry',
14
+ documentationUrl: 'https://github.com/inixiative/foundry',
15
+ authMethods: [],
16
+ inbound: true,
17
+ delivery: 'installationSocket',
18
+ holderHandleKinds: [conversationResourceKind],
19
+ operations: [
20
+ ...declaredOperations(
21
+ threadOperationNames,
22
+ conversationResourceKind,
23
+ [],
24
+ threadOperationSchema.options,
25
+ ),
26
+ ...declaredOperations(
27
+ conversationPermissionNames,
28
+ conversationResourceKind,
29
+ [],
30
+ conversationPermissionSchema.options,
31
+ ),
32
+ ],
33
+ };
@@ -0,0 +1,16 @@
1
+ import type { ProviderDefinition } from '../../contracts';
2
+
3
+ export const geminiApiProvider: ProviderDefinition = {
4
+ key: 'geminiApi',
5
+ name: 'Gemini API',
6
+ documentationUrl: 'https://ai.google.dev/api/generate-content',
7
+ authMethods: ['apiKey'],
8
+ operations: [
9
+ {
10
+ key: 'inference.create',
11
+ name: 'Run inference',
12
+ resourceKind: 'model',
13
+ requiredScopes: ['inference'],
14
+ },
15
+ ],
16
+ };
@@ -0,0 +1,21 @@
1
+ import { ProviderError } from '../../../utils/providerError';
2
+ import { requestGithub } from '../requestGithub';
3
+ import type { GithubAppClient } from './githubAppClient';
4
+ import { githubClientForApp } from './githubClientForApp';
5
+ import { githubInstallationSchema } from './githubInstallationSchema';
6
+
7
+ export const fetchGithubAppInstallation = async (
8
+ appClient: GithubAppClient,
9
+ { installationId }: { installationId: string },
10
+ ) => {
11
+ try {
12
+ return githubInstallationSchema.parse(
13
+ await requestGithub(await githubClientForApp(appClient), {
14
+ path: `/app/installations/${encodeURIComponent(installationId)}`,
15
+ }),
16
+ );
17
+ } catch (error) {
18
+ if (error instanceof ProviderError && error.code === 'provider_not_found') return null;
19
+ throw error;
20
+ }
21
+ };
@@ -0,0 +1,27 @@
1
+ import { z } from 'zod';
2
+ import type { ProviderClient } from '../../../utils/providerClient';
3
+ import { ProviderError } from '../../../utils/providerError';
4
+ import { requestGithub } from '../requestGithub';
5
+
6
+ const membershipSchema = z.object({ state: z.string(), role: z.string() });
7
+
8
+ export const fetchGithubOrganizationRole = async (
9
+ client: ProviderClient,
10
+ { organizationLogin }: { organizationLogin: string },
11
+ ) => {
12
+ try {
13
+ const membership = membershipSchema.parse(
14
+ await requestGithub(client, {
15
+ path: `/user/memberships/orgs/${encodeURIComponent(organizationLogin)}`,
16
+ }),
17
+ );
18
+ return membership.state === 'active' ? membership.role : null;
19
+ } catch (error) {
20
+ if (
21
+ error instanceof ProviderError &&
22
+ ['provider_not_found', 'provider_access_denied'].includes(error.code)
23
+ )
24
+ return null;
25
+ throw error;
26
+ }
27
+ };
@@ -0,0 +1,11 @@
1
+ import { z } from 'zod';
2
+ import type { ProviderClient } from '../../../utils/providerClient';
3
+ import { requestGithub } from '../requestGithub';
4
+
5
+ const githubUserSchema = z.object({
6
+ id: z.number().int().positive(),
7
+ login: z.string().min(1).max(39),
8
+ });
9
+
10
+ export const fetchGithubUser = async (client: ProviderClient) =>
11
+ githubUserSchema.parse(await requestGithub(client, { path: '/user' }));
@@ -0,0 +1,21 @@
1
+ import type { ProviderClient } from '../../../utils/providerClient';
2
+ import { iterateGithubPages } from '../iterateGithubPages';
3
+ import { githubInstallationSchema } from './githubInstallationSchema';
4
+
5
+ export const fetchGithubUserInstallation = async (
6
+ client: ProviderClient,
7
+ { installationId }: { installationId: string },
8
+ ) => {
9
+ const pages = iterateGithubPages(
10
+ client,
11
+ { path: '/user/installations' },
12
+ { keys: { data: 'installations' }, maxPages: 10 },
13
+ );
14
+ for await (const { items } of pages)
15
+ for (const candidate of items) {
16
+ const installation = githubInstallationSchema.safeParse(candidate);
17
+ if (installation.success && String(installation.data.id) === installationId)
18
+ return installation.data;
19
+ }
20
+ return null;
21
+ };
@@ -0,0 +1,4 @@
1
+ import type { SigningClient } from '../../../contracts';
2
+ import type { ProviderSend } from '../../../utils/providerSend';
3
+
4
+ export type GithubAppClient = { app: SigningClient; send?: ProviderSend };
@@ -0,0 +1,20 @@
1
+ import { z } from 'zod';
2
+ import { requestGithub } from '../requestGithub';
3
+ import type { GithubAppClient } from './githubAppClient';
4
+ import { githubClientForApp } from './githubClientForApp';
5
+
6
+ const githubAppSchema = z.object({
7
+ html_url: z.url({ protocol: /^https$/, hostname: /^github\.com$/ }),
8
+ });
9
+
10
+ export const githubAppInstallUrl = async (
11
+ appClient: GithubAppClient,
12
+ { state }: { state: string },
13
+ ) => {
14
+ const { html_url } = githubAppSchema.parse(
15
+ await requestGithub(await githubClientForApp(appClient), { path: '/app' }),
16
+ );
17
+ const url = new URL(`${html_url.replace(/\/+$/, '')}/installations/new`);
18
+ url.searchParams.set('state', state);
19
+ return url.toString();
20
+ };
@@ -0,0 +1,16 @@
1
+ import { createPrivateKey } from 'node:crypto';
2
+ import { SignJWT } from 'jose';
3
+ import type { SigningClient } from '../../../contracts';
4
+
5
+ export const githubAppJwt = async (
6
+ app: Pick<SigningClient, 'appId' | 'privateKey'>,
7
+ now = new Date(),
8
+ ) => {
9
+ const issuedAt = Math.floor(now.getTime() / 1000) - 60;
10
+ return await new SignJWT({})
11
+ .setProtectedHeader({ alg: 'RS256', typ: 'JWT' })
12
+ .setIssuer(app.appId)
13
+ .setIssuedAt(issuedAt)
14
+ .setExpirationTime(issuedAt + 540)
15
+ .sign(createPrivateKey(app.privateKey.replace(/\\n/g, '\n')));
16
+ };
@@ -0,0 +1,11 @@
1
+ import type { ProviderClient } from '../../../utils/providerClient';
2
+ import type { GithubAppClient } from './githubAppClient';
3
+ import { githubAppJwt } from './githubAppJwt';
4
+
5
+ export const githubClientForApp = async ({
6
+ app,
7
+ send,
8
+ }: GithubAppClient): Promise<ProviderClient> => ({
9
+ token: await githubAppJwt(app),
10
+ send,
11
+ });
@@ -0,0 +1,4 @@
1
+ import type { z } from 'zod';
2
+ import type { githubInstallationSchema } from './githubInstallationSchema';
3
+
4
+ export type GithubInstallation = z.infer<typeof githubInstallationSchema>;
@@ -0,0 +1,4 @@
1
+ export const githubInstallationAccountId = (installation: {
2
+ id: number;
3
+ account: { id: number };
4
+ }) => `${installation.id}:${installation.account.id}`;
@@ -0,0 +1,4 @@
1
+ export const githubInstallationFromAccountId = (externalAccountId: string | null) => {
2
+ const [id, accountId] = (externalAccountId ?? '').split(':').map(Number);
3
+ return id && accountId ? { id, account: { id: accountId } } : null;
4
+ };
@@ -0,0 +1,12 @@
1
+ import { z } from 'zod';
2
+
3
+ export const githubInstallationSchema = z.object({
4
+ id: z.number().int().positive(),
5
+ app_id: z.number().int().positive(),
6
+ account: z.object({
7
+ id: z.number().int().positive(),
8
+ login: z.string().min(1).max(39),
9
+ type: z.string(),
10
+ }),
11
+ suspended_at: z.string().nullable().default(null),
12
+ });
@@ -0,0 +1,14 @@
1
+ const levelRanks: Record<string, number> = { read: 1, write: 2, admin: 3 };
2
+
3
+ const parsePermission = (scope: string) => {
4
+ const [permission, level] = scope.split(':');
5
+ const rank = level === undefined ? undefined : levelRanks[level];
6
+ return rank === undefined ? null : { permission, rank };
7
+ };
8
+
9
+ export const githubPermissionCovers = (granted: string, required: string) => {
10
+ const held = parsePermission(granted);
11
+ const needed = parsePermission(required);
12
+ if (!held || !needed) return granted === required;
13
+ return held.permission === needed.permission && held.rank >= needed.rank;
14
+ };
@@ -0,0 +1,4 @@
1
+ export const githubPermissionScopes = (permissions: Record<string, string>) =>
2
+ Object.entries(permissions)
3
+ .map(([permission, level]) => `${permission}:${level}`)
4
+ .sort();
@@ -0,0 +1,6 @@
1
+ import type { OwnerRef } from '@inixiative/signet/contracts';
2
+
3
+ export const githubProviderForOwner = (
4
+ ownerModel: OwnerRef['ownerModel'],
5
+ ): 'githubOrganization' | 'githubUser' =>
6
+ ownerModel === 'Organization' || ownerModel === 'Space' ? 'githubOrganization' : 'githubUser';
@@ -0,0 +1,10 @@
1
+ import { z } from 'zod';
2
+ import { findProvider } from '../../../catalog/findProvider';
3
+ import type { OAuthClient } from '../../../contracts';
4
+
5
+ export const githubUserAuthorizeUrl = (app: Pick<OAuthClient, 'clientId'>, state: string) => {
6
+ const url = new URL(z.url().parse(findProvider('github')?.oauth?.authorizeUrl));
7
+ url.searchParams.set('client_id', app.clientId);
8
+ url.searchParams.set('state', state);
9
+ return url.toString();
10
+ };
@@ -0,0 +1,10 @@
1
+ import type { IntegrationEvent } from '@inixiative/signet/contracts';
2
+ import { z } from 'zod';
3
+ import { githubRepositoryIdSchema } from '../models/repository/githubRepositoryIdSchema';
4
+
5
+ const repositoryIdSchema = z.object({ repository: z.object({ id: z.number().int() }) });
6
+
7
+ export const githubEventRepositoryId = (event: Pick<IntegrationEvent, 'payload'>) => {
8
+ const id = repositoryIdSchema.safeParse(event.payload).data?.repository.id;
9
+ return id === undefined ? null : (githubRepositoryIdSchema.safeParse(String(id)).data ?? null);
10
+ };
@@ -0,0 +1,4 @@
1
+ import type { z } from 'zod';
2
+ import type { githubNotificationSchema } from './githubNotificationSchema';
3
+
4
+ export type GithubNotification = z.infer<typeof githubNotificationSchema>;
@@ -0,0 +1,9 @@
1
+ import { z } from 'zod';
2
+
3
+ export const githubNotificationSchema = z.looseObject({
4
+ id: z.string().min(1),
5
+ reason: z.string(),
6
+ updated_at: z.string(),
7
+ subject: z.object({ title: z.string(), url: z.url().nullable(), type: z.string() }),
8
+ repository: z.object({ id: z.number().int(), full_name: z.string() }),
9
+ });
@@ -0,0 +1,27 @@
1
+ import { z } from 'zod';
2
+ import type { ProviderClient } from '../../../utils/providerClient';
3
+ import { fetchAllGithubPages } from '../fetchAllGithubPages';
4
+ import { githubNotificationSchema } from './githubNotificationSchema';
5
+
6
+ export const listGithubNotifications = async (
7
+ client: ProviderClient,
8
+ { since }: { since: Date },
9
+ ) => {
10
+ let truncated = false;
11
+ const notifications = z.array(githubNotificationSchema).parse(
12
+ await fetchAllGithubPages(
13
+ client,
14
+ {
15
+ path: '/notifications',
16
+ query: { all: 'true', participating: 'true', since: since.toISOString(), per_page: 50 },
17
+ },
18
+ {
19
+ maxPages: 10,
20
+ onCapped: () => {
21
+ truncated = true;
22
+ },
23
+ },
24
+ ),
25
+ );
26
+ return { notifications, truncated };
27
+ };
@@ -0,0 +1,200 @@
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 { readGithubRepositoryName } from '../models/repository/readGithubRepositoryName';
6
+
7
+ const excerptLength = 500;
8
+
9
+ const userSchema = z.object({ login: z.string().min(1), id: z.number().int() });
10
+ const loginsSchema = z.array(z.object({ login: z.string().min(1) })).default([]);
11
+ const textSchema = z.string().nullish();
12
+
13
+ const repositorySchema = z.object({ id: z.number().int(), full_name: z.string() });
14
+
15
+ const threadSchema = z.object({
16
+ id: z.number().int(),
17
+ number: z.number().int(),
18
+ title: z.string(),
19
+ html_url: z.url(),
20
+ body: textSchema,
21
+ updated_at: z.string(),
22
+ assignees: loginsSchema,
23
+ });
24
+
25
+ const pullRequestSchema = threadSchema.extend({ requested_reviewers: loginsSchema });
26
+
27
+ const commentSchema = z.object({
28
+ id: z.number().int(),
29
+ body: textSchema,
30
+ html_url: z.url(),
31
+ created_at: z.string(),
32
+ });
33
+
34
+ const base = { repository: repositorySchema, sender: userSchema.nullish() };
35
+
36
+ const payloadSchemas = {
37
+ 'issue_comment.created': z.object({ ...base, issue: threadSchema, comment: commentSchema }),
38
+ 'issues.opened': z.object({ ...base, issue: threadSchema }),
39
+ 'issues.assigned': z.object({ ...base, issue: threadSchema, assignee: userSchema }),
40
+ 'pull_request.opened': z.object({ ...base, pull_request: pullRequestSchema }),
41
+ 'pull_request.closed': z.object({ ...base, pull_request: pullRequestSchema }),
42
+ 'pull_request.review_requested': z.object({
43
+ ...base,
44
+ pull_request: pullRequestSchema,
45
+ requested_reviewer: userSchema,
46
+ }),
47
+ 'pull_request.assigned': z.object({
48
+ ...base,
49
+ pull_request: pullRequestSchema,
50
+ assignee: userSchema,
51
+ }),
52
+ 'pull_request_review.submitted': z.object({
53
+ ...base,
54
+ pull_request: pullRequestSchema,
55
+ review: commentSchema.omit({ created_at: true }).extend({
56
+ submitted_at: z.string(),
57
+ state: z.string(),
58
+ }),
59
+ }),
60
+ 'pull_request_review_comment.created': z.object({
61
+ ...base,
62
+ pull_request: pullRequestSchema,
63
+ comment: commentSchema,
64
+ }),
65
+ } as const;
66
+
67
+ type GithubEventType = keyof typeof payloadSchemas;
68
+
69
+ const isGithubEventType = (type: string): type is GithubEventType =>
70
+ Object.hasOwn(payloadSchemas, type);
71
+
72
+ const mentionPattern = /(?<![\w`/@.-])@([a-z0-9](?:[a-z0-9]|-(?=[a-z0-9])){0,38})(?![\w/-])/gi;
73
+
74
+ const login = (value: string) => value.toLowerCase();
75
+
76
+ const githubMentions = (text: string | null | undefined) => [
77
+ ...new Set([...(text ?? '').matchAll(mentionPattern)].map((match) => login(match[1]!))),
78
+ ];
79
+
80
+ const logins = (users: { login: string }[]) => [...new Set(users.map((user) => login(user.login)))];
81
+
82
+ const isoAt = (value: string) => new Date(value).toISOString();
83
+
84
+ type Parsed<T extends GithubEventType> = z.infer<(typeof payloadSchemas)[T]>;
85
+
86
+ type Fields = Pick<
87
+ IntegrationEvent,
88
+ 'mentions' | 'assignees' | 'requestedReviewers' | 'subject' | 'excerpt' | 'at'
89
+ >;
90
+
91
+ const thread = (item: z.infer<typeof threadSchema>) => ({
92
+ title: item.title,
93
+ url: item.html_url,
94
+ number: item.number,
95
+ });
96
+
97
+ const excerpt = (text: string | null | undefined) =>
98
+ text ? { excerpt: text.slice(0, excerptLength) } : {};
99
+
100
+ const none = { mentions: [], assignees: [], requestedReviewers: [] };
101
+
102
+ const fieldsOf: { [T in GithubEventType]: (payload: Parsed<T>) => Fields } = {
103
+ 'issue_comment.created': ({ issue, comment }) => ({
104
+ ...none,
105
+ mentions: githubMentions(comment.body),
106
+ subject: { ...thread(issue), url: comment.html_url },
107
+ ...excerpt(comment.body),
108
+ at: isoAt(comment.created_at),
109
+ }),
110
+ 'issues.opened': ({ issue }) => ({
111
+ ...none,
112
+ mentions: githubMentions(issue.body),
113
+ assignees: logins(issue.assignees),
114
+ subject: thread(issue),
115
+ ...excerpt(issue.body),
116
+ at: isoAt(issue.updated_at),
117
+ }),
118
+ 'issues.assigned': ({ issue, assignee }) => ({
119
+ ...none,
120
+ assignees: logins([assignee]),
121
+ subject: thread(issue),
122
+ at: isoAt(issue.updated_at),
123
+ }),
124
+ 'pull_request.opened': ({ pull_request }) => ({
125
+ mentions: githubMentions(pull_request.body),
126
+ assignees: logins(pull_request.assignees),
127
+ requestedReviewers: logins(pull_request.requested_reviewers),
128
+ subject: thread(pull_request),
129
+ ...excerpt(pull_request.body),
130
+ at: isoAt(pull_request.updated_at),
131
+ }),
132
+ 'pull_request.closed': ({ pull_request }) => ({
133
+ ...none,
134
+ subject: thread(pull_request),
135
+ at: isoAt(pull_request.updated_at),
136
+ }),
137
+ 'pull_request.review_requested': ({ pull_request, requested_reviewer }) => ({
138
+ ...none,
139
+ requestedReviewers: logins([requested_reviewer]),
140
+ subject: thread(pull_request),
141
+ at: isoAt(pull_request.updated_at),
142
+ }),
143
+ 'pull_request.assigned': ({ pull_request, assignee }) => ({
144
+ ...none,
145
+ assignees: logins([assignee]),
146
+ subject: thread(pull_request),
147
+ at: isoAt(pull_request.updated_at),
148
+ }),
149
+ 'pull_request_review.submitted': ({ pull_request, review }) => ({
150
+ ...none,
151
+ mentions: githubMentions(review.body),
152
+ subject: { ...thread(pull_request), url: review.html_url },
153
+ ...excerpt(review.body),
154
+ at: isoAt(review.submitted_at),
155
+ }),
156
+ 'pull_request_review_comment.created': ({ pull_request, comment }) => ({
157
+ ...none,
158
+ mentions: githubMentions(comment.body),
159
+ subject: { ...thread(pull_request), url: comment.html_url },
160
+ ...excerpt(comment.body),
161
+ at: isoAt(comment.created_at),
162
+ }),
163
+ };
164
+
165
+ const normalize = <T extends GithubEventType>(type: T, payload: unknown) => {
166
+ const parsed = payloadSchemas[type].safeParse(payload);
167
+ if (!parsed.success) return null;
168
+ const data = parsed.data as Parsed<T>;
169
+ const scope = readGithubRepositoryName(data.repository.full_name);
170
+ if (!scope) return null;
171
+ const fields = fieldsOf[type](data);
172
+ return {
173
+ ...fields,
174
+ actor: data.sender ? { login: login(data.sender.login), id: String(data.sender.id) } : null,
175
+ scope,
176
+ };
177
+ };
178
+
179
+ export const normalizeGithubEvent = (input: {
180
+ integrationId: string;
181
+ provider: string;
182
+ event: string;
183
+ deliveryId: string;
184
+ payload: unknown;
185
+ }): ProviderEvent | null => {
186
+ const action = z.object({ action: z.string() }).safeParse(input.payload).data?.action;
187
+ const type = action ? `${input.event}.${action}` : input.event;
188
+ if (!isGithubEventType(type)) return null;
189
+ const fields = normalize(type, input.payload);
190
+ if (!fields) return null;
191
+ const event = providerEventSchema.safeParse({
192
+ eventId: input.deliveryId,
193
+ integrationId: input.integrationId,
194
+ provider: input.provider,
195
+ type,
196
+ ...fields,
197
+ payload: input.payload,
198
+ });
199
+ return event.success ? event.data : null;
200
+ };
@@ -0,0 +1,56 @@
1
+ import type { IntegrationEvent } from '@inixiative/signet/contracts';
2
+ import type { ProviderEvent } from '../../../catalog/providerEvent';
3
+ import { providerEventSchema } from '../../../catalog/providerEventSchema';
4
+ import { readGithubRepositoryName } from '../models/repository/readGithubRepositoryName';
5
+ import type { GithubNotification } from './githubNotification';
6
+
7
+ const namedBy = {
8
+ mention: 'mentions',
9
+ review_requested: 'requestedReviewers',
10
+ assign: 'assignees',
11
+ } as const;
12
+
13
+ const isNamingReason = (reason: string): reason is keyof typeof namedBy =>
14
+ Object.hasOwn(namedBy, reason);
15
+
16
+ const apiSubjectPattern =
17
+ /^https:\/\/api\.github\.com\/repos\/([^/]+\/[^/]+)\/(issues|pulls)\/(\d+)$/;
18
+
19
+ const subjectLink = (url: string | null) => {
20
+ const match = url ? apiSubjectPattern.exec(url) : null;
21
+ if (!match) return {};
22
+ const [, repository, kind, number] = match;
23
+ return {
24
+ url: `https://github.com/${repository}/${kind === 'pulls' ? 'pull' : 'issues'}/${number}`,
25
+ number: Number(number),
26
+ };
27
+ };
28
+
29
+ export const normalizeGithubNotification = (input: {
30
+ integrationId: string;
31
+ provider: string;
32
+ login: string;
33
+ notification: GithubNotification;
34
+ }): ProviderEvent | null => {
35
+ const { notification } = input;
36
+ if (!isNamingReason(notification.reason)) return null;
37
+ const scope = readGithubRepositoryName(notification.repository.full_name);
38
+ if (!scope) return null;
39
+ const login = input.login.toLowerCase();
40
+ const event = providerEventSchema.safeParse({
41
+ eventId: `${notification.id}:${notification.updated_at}`,
42
+ integrationId: input.integrationId,
43
+ provider: input.provider,
44
+ type: `notifications.${notification.reason}`,
45
+ at: new Date(notification.updated_at).toISOString(),
46
+ actor: null,
47
+ scope,
48
+ mentions: [],
49
+ assignees: [],
50
+ requestedReviewers: [],
51
+ [namedBy[notification.reason]]: [login],
52
+ subject: { title: notification.subject.title, ...subjectLink(notification.subject.url) },
53
+ payload: notification,
54
+ });
55
+ return event.success ? event.data : null;
56
+ };
@@ -0,0 +1,7 @@
1
+ import { matchesHmacSha256 } from '../../../utils/matchesHmacSha256';
2
+
3
+ export const verifyGithubSignature = (
4
+ rawBody: Uint8Array,
5
+ signature: string | null | undefined,
6
+ secret: string,
7
+ ) => matchesHmacSha256(rawBody, /^sha256=([a-f0-9]{64})$/.exec(signature ?? '')?.[1], secret);
@@ -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 { githubPagination } from './githubPagination';
6
+ import { requestGithub } from './requestGithub';
7
+
8
+ export const fetchAllGithubPages = (
9
+ client: ProviderClient,
10
+ input: ProviderRequestInput,
11
+ options?: ProviderPagesOptions,
12
+ ) => fetchAllRequestPages(githubPagination, (page) => requestGithub(client, page), input, options);
@@ -0,0 +1 @@
1
+ export const githubApiVersion = '2026-03-10';
@@ -0,0 +1,13 @@
1
+ import type { ProviderDefinition } from '../../contracts';
2
+ import { githubRepository } from './models/repository/githubRepository';
3
+
4
+ export const githubOrganizationProvider: ProviderDefinition = {
5
+ key: 'githubOrganization',
6
+ name: 'GitHub organization',
7
+ documentationUrl:
8
+ 'https://docs.github.com/en/apps/creating-github-apps/authenticating-with-a-github-app/authenticating-as-a-github-app-installation',
9
+ authMethods: ['clientCredentials'],
10
+ family: 'github',
11
+ operations: [...githubRepository.operations, ...githubRepository.events],
12
+ eventResourceExternalId: githubRepository.externalIdOfEvent,
13
+ };
@@ -0,0 +1,7 @@
1
+ import type { ProviderPagination } from '../../utils/pagination/providerPagination';
2
+
3
+ export const githubPagination = {
4
+ strategy: 'page',
5
+ keys: { page: 'page', pageSize: 'per_page', data: '', total: 'total_count' },
6
+ pageSize: 100,
7
+ } satisfies ProviderPagination;
@@ -0,0 +1,13 @@
1
+ import type { ProviderDefinition } from '../../contracts';
2
+
3
+ export const githubProvider: ProviderDefinition = {
4
+ key: 'github',
5
+ name: 'GitHub',
6
+ documentationUrl: 'https://docs.github.com/en/apps/overview',
7
+ authMethods: ['oauth2'],
8
+ operations: [],
9
+ oauth: {
10
+ authorizeUrl: 'https://github.com/login/oauth/authorize',
11
+ tokenUrl: 'https://github.com/login/oauth/access_token',
12
+ },
13
+ };
@@ -0,0 +1,9 @@
1
+ import { githubApiVersion } from './githubApiVersion';
2
+
3
+ export const githubRequestHeaders = (headers: Headers, token?: string) => {
4
+ headers.set('Accept', 'application/vnd.github+json');
5
+ headers.set('X-GitHub-Api-Version', githubApiVersion);
6
+ headers.set('User-Agent', 'inixiative-integrations');
7
+ if (token) headers.set('Authorization', `Bearer ${token}`);
8
+ return headers;
9
+ };