diff --git a/packages/corsair/core/constants.ts b/packages/corsair/core/constants.ts index 93ce1126d..00da1cdcd 100644 --- a/packages/corsair/core/constants.ts +++ b/packages/corsair/core/constants.ts @@ -18,7 +18,6 @@ export const BaseProviders = [ 'abyssale', 'accrediblecertificates', 'activecampaign', - 'anchorbrowser', 'activetrail', 'addresszen', 'aeroleads', @@ -40,14 +39,15 @@ export const BaseProviders = [ 'ambientweather', 'amcards', 'amplitude', + 'anchorbrowser', 'anthropicadministrator', 'apaleo', 'api2pdf', 'apibible', - 'apipie', 'apify', 'apilabz', 'apininjas', + 'apipie', 'apisports', 'asana', 'asindataapi', @@ -92,8 +92,8 @@ export const BaseProviders = [ 'facebook', 'figma', 'firecrawl', - 'formbricks', 'fireflies', + 'formbricks', 'gemini', 'github', 'gitlab', @@ -123,6 +123,7 @@ export const BaseProviders = [ 'linear', 'linkedin', 'loyverse', + 'mailcheck', 'mailchimp', 'mailtrap', 'monday', @@ -185,7 +186,6 @@ export const ProviderDisplayNames = { abyssale: 'Abyssale', accrediblecertificates: 'Accredible Certificates', activecampaign: 'ActiveCampaign', - anchorbrowser: 'Anchor Browser', activetrail: 'Active Trail', addresszen: 'Addresszen', aeroleads: 'Aeroleads', @@ -207,14 +207,15 @@ export const ProviderDisplayNames = { ambientweather: 'Ambient Weather', amcards: 'AMcards', amplitude: 'Amplitude', + anchorbrowser: 'Anchor Browser', anthropicadministrator: 'Anthropic Administrator', apaleo: 'Apaleo', api2pdf: 'API2PDF', apibible: 'API.Bible', - apipie: 'APIpie AI', apify: 'Apify', apilabz: 'API Labz', apininjas: 'API Ninjas', + apipie: 'APIpie AI', apisports: 'API-Sports', asana: 'Asana', asindataapi: 'ASIN Data API', @@ -259,8 +260,8 @@ export const ProviderDisplayNames = { facebook: 'Facebook', figma: 'Figma', firecrawl: 'Firecrawl', - formbricks: 'Formbricks', fireflies: 'Fireflies', + formbricks: 'Formbricks', gemini: 'Gemini', github: 'GitHub', gitlab: 'GitLab', @@ -290,6 +291,7 @@ export const ProviderDisplayNames = { linear: 'Linear', linkedin: 'LinkedIn', loyverse: 'Loyverse', + mailcheck: 'Mailcheck', mailchimp: 'Mailchimp', mailtrap: 'Mailtrap', monday: 'Monday', @@ -359,7 +361,6 @@ export type AllProviders = | 'abyssale' | 'accrediblecertificates' | 'activecampaign' - | 'anchorbrowser' | 'activetrail' | 'addresszen' | 'aeroleads' @@ -381,14 +382,15 @@ export type AllProviders = | 'ambientweather' | 'amcards' | 'amplitude' + | 'anchorbrowser' | 'anthropicadministrator' | 'apaleo' | 'api2pdf' | 'apibible' - | 'apipie' | 'apify' | 'apilabz' | 'apininjas' + | 'apipie' | 'apisports' | 'asana' | 'asindataapi' @@ -433,8 +435,8 @@ export type AllProviders = | 'facebook' | 'figma' | 'firecrawl' - | 'formbricks' | 'fireflies' + | 'formbricks' | 'gemini' | 'github' | 'gitlab' @@ -464,6 +466,7 @@ export type AllProviders = | 'linear' | 'linkedin' | 'loyverse' + | 'mailcheck' | 'mailchimp' | 'mailtrap' | 'monday' diff --git a/packages/mailcheck/client.ts b/packages/mailcheck/client.ts new file mode 100644 index 000000000..bfb975ee2 --- /dev/null +++ b/packages/mailcheck/client.ts @@ -0,0 +1,61 @@ +import type { ApiRequestOptions } from 'corsair/http'; +import type { OpenAPIConfig } from 'corsair/http'; +import { request } from 'corsair/http'; + +export class MailcheckAPIError extends Error { + constructor( + message: string, + public readonly code?: string, + ) { + super(message); + this.name = 'MailcheckAPIError'; + } +} + +// TODO: Update with your API base URL +const MAILCHECK_API_BASE = 'https://api.mailcheck.ing/v1'; + +export async function makeMailcheckRequest( + endpoint: string, + apiKey: string, + options: { + method?: 'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH'; + body?: Record; + query?: Record; + } = {}, +): Promise { + const { method = 'GET', body, query } = options; + + const config: OpenAPIConfig = { + BASE: MAILCHECK_API_BASE, + VERSION: '1.0.0', + WITH_CREDENTIALS: false, + CREDENTIALS: 'omit', + TOKEN: apiKey, + HEADERS: { + 'Content-Type': 'application/json', + + 'Authorization': apiKey, + }, + }; + + const requestOptions: ApiRequestOptions = { + method, + url: endpoint, + body: + method === 'POST' || method === 'PUT' || method === 'PATCH' + ? body + : undefined, + mediaType: 'application/json; charset=utf-8', + query: method === 'GET' ? query : undefined, + }; + + try { + return await request(config, requestOptions); + } catch (error) { + if (error instanceof Error) { + throw new MailcheckAPIError(error.message); + } + throw new MailcheckAPIError('Unknown error'); + } +} diff --git a/packages/mailcheck/endpoints/index.ts b/packages/mailcheck/endpoints/index.ts new file mode 100644 index 000000000..fb2886db9 --- /dev/null +++ b/packages/mailcheck/endpoints/index.ts @@ -0,0 +1,9 @@ +import { verifyEmail } from './verify-email'; +import { validateDomain } from './validate-domain'; + +export const Mailcheck = { + verifyEmail, + validateDomain, +}; + +export * from './types'; \ No newline at end of file diff --git a/packages/mailcheck/endpoints/types.ts b/packages/mailcheck/endpoints/types.ts new file mode 100644 index 000000000..030c56910 --- /dev/null +++ b/packages/mailcheck/endpoints/types.ts @@ -0,0 +1,43 @@ +import { z } from 'zod'; + +const VerifyEmailInputSchema = z.object({ + email: z.string(), + verify: z.boolean().optional(), + check_breach: z.boolean().optional(), +}); +export type VerifyEmailInput = z.infer; + +const VerifyEmailResponseSchema = z.object({ + email: z.string(), +}).passthrough(); +export type VerifyEmailResponse = z.infer; + +const ValidateDomainInputSchema = z.object({ + domain: z.string(), +}); +export type ValidateDomainInput = z.infer; + +const ValidateDomainResponseSchema = z.object({ + domain: z.string(), +}).passthrough(); +export type ValidateDomainResponse = z.infer; + +export type MailcheckEndpointInputs = { + verifyEmail: VerifyEmailInput; + validateDomain: ValidateDomainInput; +}; + +export type MailcheckEndpointOutputs = { + verifyEmail: VerifyEmailResponse; + validateDomain: ValidateDomainResponse; +}; + +export const MailcheckEndpointInputSchemas = { + verifyEmail: VerifyEmailInputSchema, + validateDomain: ValidateDomainInputSchema, +} as const; + +export const MailcheckEndpointOutputSchemas = { + verifyEmail: VerifyEmailResponseSchema, + validateDomain: ValidateDomainResponseSchema, +} as const; \ No newline at end of file diff --git a/packages/mailcheck/endpoints/validate-domain.ts b/packages/mailcheck/endpoints/validate-domain.ts new file mode 100644 index 000000000..632a8b613 --- /dev/null +++ b/packages/mailcheck/endpoints/validate-domain.ts @@ -0,0 +1,15 @@ +import { logEventFromContext } from 'corsair/core'; +import type { MailcheckEndpoints } from '..'; +import type { MailcheckEndpointOutputs } from './types'; +import { makeMailcheckRequest } from '../client'; + +export const validateDomain: MailcheckEndpoints['validateDomain'] = async (ctx, input) => { + const response = await makeMailcheckRequest( + `domain/${input.domain}`, + ctx.key, + { method: 'GET' }, + ); + + await logEventFromContext(ctx, 'mailcheck.validate_domain', { ...input }, 'completed'); + return response; +}; diff --git a/packages/mailcheck/endpoints/verify-email.ts b/packages/mailcheck/endpoints/verify-email.ts new file mode 100644 index 000000000..878d6847f --- /dev/null +++ b/packages/mailcheck/endpoints/verify-email.ts @@ -0,0 +1,22 @@ +import { logEventFromContext } from 'corsair/core'; +import type { MailcheckEndpoints } from '..'; +import type { MailcheckEndpointOutputs } from './types'; +import { makeMailcheckRequest } from '../client'; + +export const verifyEmail: MailcheckEndpoints['verifyEmail'] = async (ctx, input) => { + const response = await makeMailcheckRequest( + 'verify', + ctx.key, + { + method: 'POST', + body: { + email: input.email, + verify: input.verify ?? true, + check_breach: input.check_breach ?? false, + }, + }, + ); + + await logEventFromContext(ctx, 'mailcheck.verify_email', { ...input }, 'completed'); + return response; +}; \ No newline at end of file diff --git a/packages/mailcheck/error-handlers.ts b/packages/mailcheck/error-handlers.ts new file mode 100644 index 000000000..c2af29acd --- /dev/null +++ b/packages/mailcheck/error-handlers.ts @@ -0,0 +1,31 @@ +import { ApiError } from 'corsair/http'; +import type { CorsairErrorHandler } from 'corsair/core'; + +export const errorHandlers = { + RATE_LIMIT_ERROR: { + match: (error: Error) => { + if (error instanceof ApiError && error.status === 429) return true; + const msg = error.message.toLowerCase(); + return msg.includes('rate_limited') || msg.includes('429'); + }, + handler: async (error: Error) => { + let retryAfterMs: number | undefined; + if (error instanceof ApiError && error.retryAfter !== undefined) { + retryAfterMs = error.retryAfter; + } + return { maxRetries: 5, headersRetryAfterMs: retryAfterMs }; + }, + }, + AUTH_ERROR: { + match: (error: Error) => { + if (error instanceof ApiError && error.status === 401) return true; + const msg = error.message.toLowerCase(); + return msg.includes('unauthorized') || msg.includes('invalid_auth'); + }, + handler: async () => ({ maxRetries: 0 }), + }, + DEFAULT: { + match: () => true, + handler: async () => ({ maxRetries: 0 }), + }, +} satisfies CorsairErrorHandler; diff --git a/packages/mailcheck/index.ts b/packages/mailcheck/index.ts new file mode 100644 index 000000000..63781c7c8 --- /dev/null +++ b/packages/mailcheck/index.ts @@ -0,0 +1,215 @@ +import type { + BindEndpoints, + BindWebhooks, + CorsairEndpoint, + CorsairErrorHandler, + CorsairPlugin, + CorsairPluginContext, + CorsairWebhook, + KeyBuilderContext, + PickAuth, + PluginAuthConfig, + PluginPermissionsConfig, + RequiredPluginEndpointMeta, + RequiredPluginEndpointSchemas, + RequiredPluginWebhookSchemas, +} from 'corsair/core'; +import type { AuthTypes } from 'corsair/core'; +import type { MailcheckEndpointInputs, MailcheckEndpointOutputs } from './endpoints/types'; +import { MailcheckEndpointInputSchemas, MailcheckEndpointOutputSchemas } from './endpoints/types'; +import type { + MailcheckWebhookOutputs, + ExampleEvent, +} from './webhooks/types'; +import { ExampleEventSchema } from './webhooks/types'; +import { Mailcheck } from './endpoints'; +import { MailcheckSchema } from './schema'; +import { ExampleWebhooks } from './webhooks'; +import { errorHandlers } from './error-handlers'; +import { matchMailcheckTenantWebhook } from './webhooks/tenant-matcher'; +import { resolveMailcheckOAuthWebhookTenantLink } from './webhooks/oauth-tenant-link'; + +export type MailcheckPluginOptions = { + authType?: PickAuth<'api_key' | 'oauth_2'>; + key?: string; + webhookSecret?: string; + hooks?: InternalMailcheckPlugin['hooks']; + webhookHooks?: InternalMailcheckPlugin['webhookHooks']; + errorHandlers?: CorsairErrorHandler; + permissions?: PluginPermissionsConfig; +}; + +export type MailcheckContext = CorsairPluginContext + typeof MailcheckSchema, + MailcheckPluginOptions +>; + +export type MailcheckKeyBuilderContext = KeyBuilderContext; + +export type MailcheckBoundEndpoints = BindEndpoints; + +type MailcheckEndpoint + K extends keyof MailcheckEndpointOutputs, +> = CorsairEndpoint + MailcheckContext, + MailcheckEndpointInputs[K], + MailcheckEndpointOutputs[K] +>; + +export type MailcheckEndpoints = { + verifyEmail: MailcheckEndpoint<'verifyEmail'>; + validateDomain: MailcheckEndpoint<'validateDomain'>; +}; + +type MailcheckWebhook + K extends keyof MailcheckWebhookOutputs, + TEvent, +> = CorsairWebhook; + +export type MailcheckWebhooks = { + example: MailcheckWebhook<'example', ExampleEvent>; +}; + +export type MailcheckBoundWebhooks = BindWebhooks; + +const mailcheckEndpointsNested = { + email: { + verify: Mailcheck.verifyEmail, + }, + domain: { + validate: Mailcheck.validateDomain, + }, +} as const; + +const mailcheckWebhooksNested = { + example: { + example: ExampleWebhooks.example, + }, +} as const; + +export const mailcheckEndpointSchemas = { + 'email.verify': { + input: MailcheckEndpointInputSchemas.verifyEmail, + output: MailcheckEndpointOutputSchemas.verifyEmail, + }, + 'domain.validate': { + input: MailcheckEndpointInputSchemas.validateDomain, + output: MailcheckEndpointOutputSchemas.validateDomain, + }, +} as const satisfies RequiredPluginEndpointSchemas; + +const mailcheckWebhookSchemas = { + 'example.example': { + description: 'An example webhook event', + payload: ExampleEventSchema, + response: ExampleEventSchema, + }, +} as const satisfies RequiredPluginWebhookSchemas; + +const defaultAuthType: AuthTypes = 'api_key' as const; + +const mailcheckEndpointMeta = { + 'email.verify': { + riskLevel: 'read', + description: 'Verify an email address for syntax, MX, SMTP validity, and optional breach check', + }, + 'domain.validate': { + riskLevel: 'read', + description: 'Validate a domain for disposability, MX records, domain age, and spam indicators', + }, +} as const satisfies RequiredPluginEndpointMeta; + +export const mailcheckAuthConfig = { + api_key: { + account: ['tenant_external_id'] as const, + }, + oauth_2: { + account: ['tenant_external_id'] as const, + }, +} as const satisfies PluginAuthConfig; + +export type BaseMailcheckPlugin = CorsairPlugin + 'mailcheck', + typeof MailcheckSchema, + typeof mailcheckEndpointsNested, + typeof mailcheckWebhooksNested, + T, + typeof defaultAuthType +>; + +export type InternalMailcheckPlugin = BaseMailcheckPlugin; + +export type ExternalMailcheckPlugin = + BaseMailcheckPlugin; + +export function mailcheck( + incomingOptions: MailcheckPluginOptions & T = {} as MailcheckPluginOptions & T, +): ExternalMailcheckPlugin { + const options = { + ...incomingOptions, + authType: incomingOptions.authType ?? defaultAuthType, + }; + return { + id: 'mailcheck', + authConfig: mailcheckAuthConfig, + schema: MailcheckSchema, + options: options, + hooks: options.hooks, + webhookHooks: options.webhookHooks, + endpoints: mailcheckEndpointsNested, + webhooks: mailcheckWebhooksNested, + endpointMeta: mailcheckEndpointMeta, + endpointSchemas: mailcheckEndpointSchemas, + webhookSchemas: mailcheckWebhookSchemas, + pluginWebhookMatcher: (request) => { + const headers = request.headers; + return 'x-mailcheck-signature' in headers; + }, + pluginTenantWebhookMatcher: matchMailcheckTenantWebhook, + oauthWebhookTenantLinkResolver: resolveMailcheckOAuthWebhookTenantLink, + errorHandlers: { + ...errorHandlers, + ...options.errorHandlers, + }, + keyBuilder: async (ctx: MailcheckKeyBuilderContext, source) => { + if (source === 'webhook' && options.webhookSecret) { + return options.webhookSecret; + } + + if (source === 'webhook') { + const res = await ctx.keys.get_webhook_signature(); + return res ?? ''; + } + + if (source === 'endpoint' && options.key) { + return options.key; + } + + if (source === 'endpoint' && ctx.authType === 'api_key') { + const res = await ctx.keys.get_api_key(); + return res ?? ''; + } + + if (source === 'endpoint' && ctx.authType === 'oauth_2') { + const res = await ctx.keys.get_access_token(); + return res ?? ''; + } + + return ''; + }, + } satisfies InternalMailcheckPlugin; +} + +export type { + ExampleEvent, + MailcheckWebhookOutputs, +} from './webhooks/types'; + +export type { + MailcheckEndpointInputs, + MailcheckEndpointOutputs, + VerifyEmailInput, + VerifyEmailResponse, + ValidateDomainInput, + ValidateDomainResponse, +} from './endpoints/types'; \ No newline at end of file diff --git a/packages/mailcheck/jest.config.cjs b/packages/mailcheck/jest.config.cjs new file mode 100644 index 000000000..8c6218f64 --- /dev/null +++ b/packages/mailcheck/jest.config.cjs @@ -0,0 +1,55 @@ +module.exports = { + preset: 'ts-jest', + testEnvironment: 'node', + roots: [''], + testMatch: [ + '**/*.test.ts', + '**/tests/**/*.test.ts', + '**/plugins/**/*.test.ts', + '**/setup/**/*.test.ts', + ], + collectCoverageFrom: [ + '**/*.ts', + '!**/*.d.ts', + '!**/node_modules/**', + '!**/dist/**', + '!jest.config.ts', + '!tests/**', + ], + moduleFileExtensions: ['ts', 'tsx', 'js', 'jsx', 'json'], + transform: { + '^.+\\.yaml$': '/../corsair/jest-yaml-transform.cjs', + '^.+\\.ts$': [ + 'ts-jest', + { + useESM: true, + tsconfig: { + esModuleInterop: true, + allowSyntheticDefaultImports: true, + verbatimModuleSyntax: false, + module: 'ESNext', + moduleResolution: 'Bundler', + }, + }, + ], + '.*\\.js$': [ + 'ts-jest', + { + useESM: true, + tsconfig: { + esModuleInterop: true, + allowSyntheticDefaultImports: true, + }, + }, + ], + }, + moduleNameMapper: { + '^corsair/core$': '/../corsair/core.ts', + '^corsair/http$': '/../corsair/http.ts', + '^(\\.\\.?/.*)\\.js$': '$1', + }, + transformIgnorePatterns: ['node_modules/(?!.*uuid.*)'], + extensionsToTreatAsEsm: ['.ts'], + testTimeout: 30000, + verbose: true, +}; diff --git a/packages/mailcheck/package.json b/packages/mailcheck/package.json new file mode 100644 index 000000000..73b78fe40 --- /dev/null +++ b/packages/mailcheck/package.json @@ -0,0 +1,44 @@ +{ + "name": "@corsair-dev/mailcheck", + "version": "0.1.0", + "description": "Mailcheck plugin for Corsair", + "type": "module", + "main": "./dist/index.js", + "module": "./dist/index.js", + "types": "./dist/index.d.ts", + "exports": { + ".": { + "dev-source": "./index.ts", + "types": "./dist/index.d.ts", + "default": "./dist/index.js" + } + }, + "scripts": { + "build": "rm -rf dist && tsc --build --force && tsup", + "typecheck": "tsc --noEmit", + "test": "jest" + }, + "peerDependencies": { + "corsair": ">=0.1.0", + "zod": "^4.1.13" + }, + "devDependencies": { + "@types/jest": "^29.5.14", + "corsair": "workspace:*", + "jest": "^29.7.0", + "ts-jest": "^29.4.9", + "tsup": "^8.0.1", + "typescript": "catalog:", + "zod": "^4.1.13" + }, + "keywords": [ + "corsair", + "mailcheck", + "plugin" + ], + "author": "", + "license": "Apache-2.0", + "files": [ + "dist" + ] +} diff --git a/packages/mailcheck/schema.test.ts b/packages/mailcheck/schema.test.ts new file mode 100644 index 000000000..9746eb599 --- /dev/null +++ b/packages/mailcheck/schema.test.ts @@ -0,0 +1,20 @@ +import { MailcheckSchema } from './schema'; + +describe('Mailcheck schema', () => { + it('declares a semver version', () => { + expect(MailcheckSchema.version).toBeDefined(); + expect(MailcheckSchema.version).toMatch(/^\d+\.\d+\.\d+$/); + }); + + it('declares an entities map', () => { + expect(typeof MailcheckSchema.entities).toBe('object'); + expect(MailcheckSchema.entities).not.toBeNull(); + expect(Array.isArray(Object.keys(MailcheckSchema.entities))).toBe(true); + for (const entity of Object.values(MailcheckSchema.entities)) { + expect(entity).toBeDefined(); + } + }); +}); + +// Per .github/PLUGIN_PR_RULES.md (R2), every implemented endpoint +// needs a corresponding test. diff --git a/packages/mailcheck/schema/database.ts b/packages/mailcheck/schema/database.ts new file mode 100644 index 000000000..5e39e231c --- /dev/null +++ b/packages/mailcheck/schema/database.ts @@ -0,0 +1,9 @@ +import { z } from 'zod'; + +// TODO: Define your database entities here +// export const MailcheckExample = z.object({ +// id: z.string(), +// name: z.string(), +// created_at: z.coerce.date().nullable().optional(), +// }); +// export type MailcheckExample = z.infer; diff --git a/packages/mailcheck/schema/index.ts b/packages/mailcheck/schema/index.ts new file mode 100644 index 000000000..07b3c343c --- /dev/null +++ b/packages/mailcheck/schema/index.ts @@ -0,0 +1,4 @@ +export const MailcheckSchema = { + version: '1.0.0', + entities: {}, +} as const; diff --git a/packages/mailcheck/tsconfig.json b/packages/mailcheck/tsconfig.json new file mode 100644 index 000000000..92fa48e0b --- /dev/null +++ b/packages/mailcheck/tsconfig.json @@ -0,0 +1,30 @@ +{ + "extends": "../../tsconfig.base.json", + "compilerOptions": { + "lib": [ + "esnext" + ], + "types": [ + "node", + "jest" + ], + "module": "ESNext", + "moduleResolution": "Bundler", + "outDir": "./dist", + "rootDir": "./", + "composite": true, + "incremental": true, + "emitDeclarationOnly": true, + "declaration": true, + "declarationMap": true, + "skipLibCheck": true + }, + "include": [ + "./**/*" + ], + "exclude": [ + "dist", + "node_modules" + ], + "references": [] +} diff --git a/packages/mailcheck/tsup.config.ts b/packages/mailcheck/tsup.config.ts new file mode 100644 index 000000000..3ec221e23 --- /dev/null +++ b/packages/mailcheck/tsup.config.ts @@ -0,0 +1,15 @@ +import { defineConfig } from 'tsup'; + +export default defineConfig({ + clean: false, + dts: false, + format: ['esm'], + target: 'esnext', + platform: 'node', + bundle: true, + splitting: true, + minify: true, + outDir: 'dist', + external: ['corsair', 'zod'], + entry: ['index.ts'], +}); diff --git a/packages/mailcheck/webhooks/example.ts b/packages/mailcheck/webhooks/example.ts new file mode 100644 index 000000000..ecd4bc853 --- /dev/null +++ b/packages/mailcheck/webhooks/example.ts @@ -0,0 +1,27 @@ +import { logEventFromContext } from 'corsair/core'; +import type { MailcheckWebhooks } from '..'; +import { createMailcheckMatch, verifyMailcheckWebhookSignature } from './types'; + +export const example: MailcheckWebhooks['example'] = { + match: createMailcheckMatch('example'), + + handler: async (ctx, request) => { + const verification = verifyMailcheckWebhookSignature(request, ctx.key); + if (!verification.valid) { + return { + success: false, + statusCode: 401, + error: verification.error || 'Signature verification failed', + }; + } + + const event = request.payload; + if (event.type !== 'example') { + return { success: true, data: undefined }; + } + + await logEventFromContext(ctx, 'mailcheck.webhook.example', { ...event }, 'completed'); + + return { success: true, data: event }; + }, +}; diff --git a/packages/mailcheck/webhooks/index.ts b/packages/mailcheck/webhooks/index.ts new file mode 100644 index 000000000..c04b25e53 --- /dev/null +++ b/packages/mailcheck/webhooks/index.ts @@ -0,0 +1,9 @@ +import { example } from './example'; + +export const ExampleWebhooks = { + example: example, +}; + +export * from './types'; +export * from './tenant-matcher'; +export * from './oauth-tenant-link'; diff --git a/packages/mailcheck/webhooks/oauth-tenant-link.ts b/packages/mailcheck/webhooks/oauth-tenant-link.ts new file mode 100644 index 000000000..561e1e2e7 --- /dev/null +++ b/packages/mailcheck/webhooks/oauth-tenant-link.ts @@ -0,0 +1,31 @@ +import type { TokenResponse, WebhookTenantMatch } from 'corsair/core'; +import { asRecord, toExternalId } from 'corsair/core'; + +// TODO: Rename linkType 'tenant_external_id' to match pluginTenantWebhookMatcher. +// Called after OAuth to store the routing id on corsair_accounts.config. +export async function resolveMailcheckOAuthWebhookTenantLink( + tokens: TokenResponse, +): Promise { + // TODO: Read from token response when the provider includes a stable id. + // const externalId = toExternalId(asRecord(tokens.team)?.id); + const externalId = toExternalId(tokens.tenant_external_id); + if (externalId) { + return { linkType: 'tenant_external_id', externalId }; + } + + const accessToken = tokens.access_token; + if (!accessToken) return null; + + // TODO: Fetch from provider API when the token response omits the id. + // const response = await fetch('https://api.example.com/me', { + // headers: { Authorization: `Bearer ${accessToken}` }, + // }); + // if (!response.ok) return null; + // const payload = (await response.json()) as { id?: string }; + // const fetchedId = toExternalId(payload.id); + // return fetchedId + // ? { linkType: 'tenant_external_id', externalId: fetchedId } + // : null; + + return null; +} diff --git a/packages/mailcheck/webhooks/tenant-matcher.ts b/packages/mailcheck/webhooks/tenant-matcher.ts new file mode 100644 index 000000000..efbed42a8 --- /dev/null +++ b/packages/mailcheck/webhooks/tenant-matcher.ts @@ -0,0 +1,25 @@ +import type { RawWebhookRequest, WebhookTenantMatch } from 'corsair/core'; +import { asRecord, firstString, readBodyRecord } from 'corsair/core'; + +// TODO: Rename linkType 'tenant_external_id' to match the provider field +// (e.g. team_id, installation_id, organization_id). Must match authConfig.account +// and oauthWebhookTenantLinkResolver. +// Return null for URL verification / handshake payloads that have no tenant id. +export function matchMailcheckTenantWebhook( + request: RawWebhookRequest, +): WebhookTenantMatch | null { + const body = readBodyRecord(request); + if (!body) return null; + + // TODO: Extract the stable external id from the webhook payload. + // Example: + // const externalId = firstString([body.tenant_external_id, asRecord(body.data)?.id]); + const externalId = firstString([ + body.tenant_external_id, + asRecord(body.data)?.tenant_external_id, + ]); + + if (!externalId) return null; + + return { linkType: 'tenant_external_id', externalId }; +} diff --git a/packages/mailcheck/webhooks/types.ts b/packages/mailcheck/webhooks/types.ts new file mode 100644 index 000000000..cf05a828a --- /dev/null +++ b/packages/mailcheck/webhooks/types.ts @@ -0,0 +1,58 @@ +import type { CorsairWebhookMatcher, RawWebhookRequest, WebhookRequest } from 'corsair/core'; +import { z } from 'zod'; + +export const MailcheckWebhookPayloadSchema = z.object({ + type: z.string(), + created_at: z.string(), + data: z.record(z.string(), z.unknown()), +}); + +export type MailcheckWebhookPayload = z.infer< + typeof MailcheckWebhookPayloadSchema +>; + +export const ExampleEventSchema = MailcheckWebhookPayloadSchema.extend({ + type: z.literal('example'), + data: z + .object({ + id: z.string(), + }) + .loose(), +}); + +export type ExampleEvent = z.infer; + +export type MailcheckWebhookOutputs = { + example: ExampleEvent; +}; + +function parseBody(body: unknown): Record | null { + if (typeof body === 'string') { + try { + const parsed = JSON.parse(body); + return parsed !== null && typeof parsed === 'object' && !Array.isArray(parsed) + ? (parsed as Record) + : null; + } catch { + return null; + } + } + return body !== null && typeof body === 'object' && !Array.isArray(body) + ? (body as Record) + : null; +} + +export function createMailcheckMatch(eventType: string): CorsairWebhookMatcher { + return (request: RawWebhookRequest) => { + const parsedBody = parseBody(request.body); + return parsedBody !== null && parsedBody.type === eventType; + }; +} + +export function verifyMailcheckWebhookSignature( + request: WebhookRequest, + secret: string, +): { valid: boolean; error?: string } { + // TODO: Implement webhook signature verification + return { valid: true }; +}