-
-
Notifications
You must be signed in to change notification settings - Fork 37
feat(dymo): Add Dymo fraud detection plugin for subscription validation #117
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
Samuel-Fikre
wants to merge
5
commits into
getpaykit:main
Choose a base branch
from
Samuel-Fikre:feat/dymo-plugin
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from 4 commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
e01e8dd
feat(paykit): add onBeforeSubscribe hook to plugin interface
Samuel-Fikre 51d287c
feat(paykit): add timeout and error handling to plugin hooks
Samuel-Fikre 5304dfb
feat(dymo): implement fraud detection plugin with parallel validation
Samuel-Fikre 10becc8
test(dymo): add unit tests for fraud blocking
Samuel-Fikre 6353910
refactor(dymo): convert to factory function, add runtime validation, …
Samuel-Fikre File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,31 @@ | ||
| { | ||
| "name": "@paykitjs/dymo", | ||
| "version": "0.0.1", | ||
| "description": "Dymo AI fraud protection for PayKit", | ||
| "files": [ | ||
| "dist" | ||
| ], | ||
| "type": "module", | ||
| "exports": { | ||
| ".": { | ||
| "types": "./dist/index.d.ts", | ||
| "import": "./dist/index.js" | ||
| } | ||
| }, | ||
| "scripts": { | ||
| "build": "tsdown", | ||
| "typecheck": "tsc --noEmit", | ||
| "test": "vitest" | ||
| }, | ||
| "dependencies": { | ||
| "zod": "^3.25.76" | ||
| }, | ||
| "devDependencies": { | ||
| "paykitjs": "workspace:*", | ||
| "tsdown": "^0.21.1", | ||
| "vitest": "^4.0.18" | ||
| }, | ||
| "peerDependencies": { | ||
| "paykitjs": "workspace:*" | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,206 @@ | ||
| import type { BeforeSubscribeHookCtx } from "paykitjs"; | ||
| import { beforeEach, describe, expect, it, vi } from "vitest"; | ||
|
|
||
| import { DymoPlugin } from "../plugin"; | ||
|
|
||
| function createMockHookContext( | ||
| overrides: Partial<BeforeSubscribeHookCtx> = {}, | ||
| ): BeforeSubscribeHookCtx { | ||
| return { | ||
| customerId: "customer_123", | ||
| customerEmail: "test@example.com", | ||
| plan: { | ||
| id: "pro-plan", | ||
| name: "Pro Plan", | ||
| priceAmount: 2900, | ||
| priceInterval: "month", | ||
| trialDays: null, | ||
| group: "default", | ||
| hash: "abc123", | ||
| isDefault: false, | ||
| includes: [], | ||
| }, | ||
| ip: "192.168.1.1", | ||
| ...overrides, | ||
| }; | ||
| } | ||
|
|
||
| describe("DymoPlugin", () => { | ||
| beforeEach(() => { | ||
| vi.clearAllMocks(); | ||
| }); | ||
|
|
||
| it("should allow subscription when email and IP are valid", async () => { | ||
| const plugin = new DymoPlugin({ | ||
| apiKey: "test-key", | ||
| resilience: { enabled: false }, | ||
| }); | ||
|
|
||
| const mockClient = { | ||
| isValidEmail: vi.fn().mockResolvedValue({ | ||
| allow: true, | ||
| reasons: [], | ||
| }), | ||
| isValidIP: vi.fn().mockResolvedValue({ | ||
| allow: true, | ||
| reasons: [], | ||
| }), | ||
| }; | ||
|
|
||
| plugin["client"] = mockClient; | ||
|
|
||
| const ctx = createMockHookContext(); | ||
|
|
||
| await expect(plugin.onBeforeSubscribe(ctx)).resolves.not.toThrow(); | ||
| expect(mockClient.isValidEmail).toHaveBeenCalledWith("test@example.com"); | ||
| expect(mockClient.isValidIP).toHaveBeenCalledWith("192.168.1.1"); | ||
| }); | ||
|
|
||
| it("should block subscription when email is fraudulent", async () => { | ||
| const plugin = new DymoPlugin({ | ||
| apiKey: "test-key", | ||
| resilience: { enabled: false }, | ||
| }); | ||
|
|
||
| const mockClient = { | ||
| isValidEmail: vi.fn().mockResolvedValue({ | ||
| allow: false, | ||
| reasons: ["FRAUD", "DISPOSABLE"], | ||
| }), | ||
| isValidIP: vi.fn().mockResolvedValue({ | ||
| allow: true, | ||
| reasons: [], | ||
| }), | ||
| }; | ||
|
|
||
| plugin["client"] = mockClient; | ||
|
|
||
| const ctx = createMockHookContext(); | ||
|
|
||
| await expect(plugin.onBeforeSubscribe(ctx)).rejects.toThrow( | ||
| "Fraud detection blocked subscription for test@example.com: FRAUD, DISPOSABLE", | ||
| ); | ||
| }); | ||
|
|
||
| it("should block subscription when IP is fraudulent", async () => { | ||
| const plugin = new DymoPlugin({ | ||
| apiKey: "test-key", | ||
| resilience: { enabled: false }, | ||
| }); | ||
|
|
||
| const mockClient = { | ||
| isValidEmail: vi.fn().mockResolvedValue({ | ||
| allow: true, | ||
| reasons: [], | ||
| }), | ||
| isValidIP: vi.fn().mockResolvedValue({ | ||
| allow: false, | ||
| reasons: ["VPN", "TOR_NETWORK"], | ||
| }), | ||
| }; | ||
|
|
||
| plugin["client"] = mockClient; | ||
|
|
||
| const ctx = createMockHookContext(); | ||
|
|
||
| await expect(plugin.onBeforeSubscribe(ctx)).rejects.toThrow( | ||
| "Fraud detection blocked subscription for test@example.com: VPN, TOR_NETWORK", | ||
| ); | ||
| }); | ||
|
|
||
| it("should skip email check when customerEmail is undefined", async () => { | ||
| const plugin = new DymoPlugin({ | ||
| apiKey: "test-key", | ||
| resilience: { enabled: false }, | ||
| }); | ||
|
|
||
| const mockClient = { | ||
| isValidEmail: vi.fn(), | ||
| isValidIP: vi.fn().mockResolvedValue({ | ||
| allow: true, | ||
| reasons: [], | ||
| }), | ||
| }; | ||
|
|
||
| plugin["client"] = mockClient; | ||
|
|
||
| const ctx = createMockHookContext({ customerEmail: undefined }); | ||
|
|
||
| await expect(plugin.onBeforeSubscribe(ctx)).resolves.not.toThrow(); | ||
| expect(mockClient.isValidEmail).not.toHaveBeenCalled(); | ||
| expect(mockClient.isValidIP).toHaveBeenCalledWith("192.168.1.1"); | ||
| }); | ||
|
|
||
| it("should skip IP check when ip is undefined", async () => { | ||
| const plugin = new DymoPlugin({ | ||
| apiKey: "test-key", | ||
| resilience: { enabled: false }, | ||
| }); | ||
|
|
||
| const mockClient = { | ||
| isValidEmail: vi.fn().mockResolvedValue({ | ||
| allow: true, | ||
| reasons: [], | ||
| }), | ||
| isValidIP: vi.fn(), | ||
| }; | ||
|
|
||
| plugin["client"] = mockClient; | ||
|
|
||
| const ctx = createMockHookContext({ ip: undefined }); | ||
|
|
||
| await expect(plugin.onBeforeSubscribe(ctx)).resolves.not.toThrow(); | ||
| expect(mockClient.isValidEmail).toHaveBeenCalledWith("test@example.com"); | ||
| expect(mockClient.isValidIP).not.toHaveBeenCalled(); | ||
| }); | ||
|
|
||
| it("should allow subscription when resilience is enabled and API fails", async () => { | ||
| const plugin = new DymoPlugin({ | ||
| apiKey: "test-key", | ||
| resilience: { enabled: true }, | ||
| }); | ||
|
|
||
| const mockClient = { | ||
| isValidEmail: vi.fn().mockRejectedValue(new Error("API error")), | ||
| isValidIP: vi.fn().mockRejectedValue(new Error("API error")), | ||
| }; | ||
|
|
||
| plugin["client"] = mockClient; | ||
|
|
||
| const consoleWarnSpy = vi.spyOn(console, "warn").mockImplementation(() => {}); | ||
|
|
||
| const ctx = createMockHookContext(); | ||
|
|
||
| await expect(plugin.onBeforeSubscribe(ctx)).resolves.not.toThrow(); | ||
| expect(consoleWarnSpy).toHaveBeenCalledWith("[PayKit-Dymo] Resilience active: Skipping check."); | ||
|
|
||
| consoleWarnSpy.mockRestore(); | ||
| }); | ||
|
|
||
| it("should throw when resilience is disabled and API fails", async () => { | ||
| const plugin = new DymoPlugin({ | ||
| apiKey: "test-key", | ||
| resilience: { enabled: false }, | ||
| }); | ||
|
|
||
| const mockClient = { | ||
| isValidEmail: vi.fn().mockRejectedValue(new Error("API error")), | ||
| isValidIP: vi.fn().mockResolvedValue({ | ||
| allow: true, | ||
| reasons: [], | ||
| }), | ||
| }; | ||
|
|
||
| plugin["client"] = mockClient; | ||
|
|
||
| const ctx = createMockHookContext(); | ||
|
|
||
| await expect(plugin.onBeforeSubscribe(ctx)).rejects.toThrow("Fraud check service unavailable."); | ||
| }); | ||
|
|
||
| it("should validate config with Zod on initialization", () => { | ||
| expect(() => { | ||
| new DymoPlugin({ apiKey: "", resilience: { enabled: true } }); | ||
| }).toThrow("Dymo API Key is required"); | ||
| }); | ||
| }); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,53 @@ | ||
| import { type DymoConfig } from "./schema"; | ||
|
|
||
| export interface DymoResponse { | ||
| allow: boolean; | ||
| reasons: string[]; | ||
| email?: string; | ||
| ip?: string; | ||
| } | ||
|
|
||
| export const createDymoClient = (config: DymoConfig) => { | ||
| const baseUrl = "https://api.dymo.ai/v1"; | ||
|
|
||
| /** | ||
| * Private request handler | ||
| */ | ||
| const request = async ( | ||
| endpoint: string, | ||
| data: Record<string, unknown>, | ||
| ): Promise<DymoResponse> => { | ||
| const controller = new AbortController(); | ||
|
|
||
| const timeoutId = setTimeout(() => controller.abort(), 5000); | ||
|
|
||
| try { | ||
| const response = await fetch(`${baseUrl}${endpoint}`, { | ||
| method: "POST", | ||
| headers: { | ||
| Authorization: `Bearer ${config.apiKey}`, | ||
| "Content-Type": "application/json", | ||
| }, | ||
| body: JSON.stringify({ | ||
| ...data, | ||
| // Pass the user's custom deny rules directly to the API | ||
| rules: config.rules, | ||
| }), | ||
| signal: controller.signal, | ||
| }); | ||
|
|
||
| if (!response.ok) { | ||
| throw new Error(`Dymo API Error: ${response.status} ${response.statusText}`); | ||
| } | ||
|
|
||
| return (await response.json()) as DymoResponse; | ||
| } finally { | ||
| clearTimeout(timeoutId); | ||
| } | ||
| }; | ||
|
|
||
| return { | ||
| isValidEmail: (email: string) => request("/validate/email", { email }), | ||
| isValidIP: (ip: string) => request("/validate/ip", { ip }), | ||
| }; | ||
| }; | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,3 @@ | ||
| export { DymoPlugin } from "./plugin"; | ||
| export type { DymoConfig } from "./schema"; | ||
| export type { DymoResponse } from "./client"; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,49 @@ | ||
| import type { PayKitPlugin, BeforeSubscribeHookCtx } from "paykitjs"; | ||
|
|
||
| import { createDymoClient, type DymoResponse } from "./client"; | ||
| import { dymoConfigSchema, type DymoConfig } from "./schema"; | ||
|
|
||
| export class DymoPlugin implements PayKitPlugin { | ||
| id = "paykit-dymo-fraud"; | ||
| private client; | ||
| private config; | ||
|
|
||
| constructor(options: DymoConfig) { | ||
| this.config = dymoConfigSchema.parse(options); | ||
| this.client = createDymoClient(this.config); | ||
| } | ||
|
|
||
| async onBeforeSubscribe(ctx: BeforeSubscribeHookCtx) { | ||
| try { | ||
| // DATA FETCH: No more DB calls here! Core provides it. | ||
| const { customerEmail, ip } = ctx; | ||
|
|
||
| const [emailResult, ipResult] = await Promise.all([ | ||
| customerEmail | ||
| ? this.client.isValidEmail(customerEmail) | ||
| : Promise.resolve<DymoResponse>({ allow: true, reasons: [] }), | ||
| ip | ||
| ? this.client.isValidIP(ip) | ||
| : Promise.resolve<DymoResponse>({ allow: true, reasons: [] }), | ||
| ]); | ||
|
|
||
| if (!emailResult.allow || !ipResult.allow) { | ||
| const reasons = [...(emailResult.reasons || []), ...(ipResult.reasons || [])]; | ||
| throw new Error( | ||
| `Fraud detection blocked subscription for ${customerEmail || "unknown"}: ${reasons.join(", ")}`, | ||
| ); | ||
| } | ||
| } catch (error: unknown) { | ||
| if (error instanceof Error && error.message.includes("Fraud detection")) { | ||
| throw error; | ||
| } | ||
|
|
||
| if (this.config.resilience.enabled) { | ||
| console.warn("[PayKit-Dymo] Resilience active: Skipping check."); | ||
| return; | ||
| } | ||
|
|
||
| throw new Error("Fraud check service unavailable.", { cause: error }); | ||
| } | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,35 @@ | ||
| import * as z from "zod"; | ||
|
|
||
| export const dymoConfigSchema = z.object({ | ||
| apiKey: z.string().min(1, "Dymo API Key is required"), | ||
|
|
||
| /** | ||
| * Rules for blocking transactions. | ||
| */ | ||
| rules: z | ||
| .object({ | ||
| email: z | ||
| .object({ | ||
| deny: z.array(z.string()).default(["FRAUD", "INVALID", "NO_MX_RECORDS"]), | ||
| }) | ||
| .optional(), | ||
| ip: z | ||
| .object({ | ||
| deny: z.array(z.string()).default(["FRAUD", "VPN", "TOR_NETWORK"]), | ||
| }) | ||
| .optional(), | ||
| }) | ||
| .optional(), | ||
|
|
||
| /** | ||
| * Resilience configuration (Fail-Open logic). | ||
| * If true, errors calling the Dymo API won't block the subscription. | ||
| */ | ||
| resilience: z | ||
| .object({ | ||
| enabled: z.boolean().default(true), | ||
| }) | ||
| .default({ enabled: true }), | ||
| }); | ||
|
|
||
| export type DymoConfig = z.infer<typeof dymoConfigSchema>; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,7 @@ | ||
| { | ||
| "extends": "../../tsconfig.base.json", | ||
| "compilerOptions": { | ||
| "rootDir": "src" | ||
| }, | ||
| "include": ["src"] | ||
| } |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.