Skip to content

feat(backend): add webhook delivery system for card view events#187

Closed
Dipti45sktech wants to merge 3 commits into
Dev-Card:mainfrom
Dipti45sktech:Feat
Closed

feat(backend): add webhook delivery system for card view events#187
Dipti45sktech wants to merge 3 commits into
Dev-Card:mainfrom
Dipti45sktech:Feat

Conversation

@Dipti45sktech

@Dipti45sktech Dipti45sktech commented May 19, 2026

Copy link
Copy Markdown
Contributor

Summary

Implements the webhook delivery system described in issue #40. Users can register external URLs to receive signed POST requests whenever their card or profile is viewed. The system handles payload signing with HMAC-SHA256, retries failed deliveries with exponential backoff, and logs every attempt for observability.

The contact.saved event is wired into the schema and validation but isn't dispatched yet since the contact-save feature doesn't exist in the codebase - left a TODO for when that gets built.

Closes #40


What Changed

  • prisma/schema.prisma - Added WebhookEndpoint and WebhookDelivery models with a relation back to User. Endpoints store an encrypted secret and a list of subscribed event types. Deliveries track status, response codes, attempt counts, and retry scheduling.
  • src/utils/webhookDispatch.ts (new) - Core dispatch logic. dispatchWebhook() finds matching endpoints for a user+event, creates delivery records, then fires off async HTTP POSTs. Each request is signed with X-DevCard-Signature: sha256=<hex> using HMAC-SHA256. Failed deliveries retry up to 3 times at 30s, 5min, and 30min intervals.
  • src/routes/webhooks.ts (new) - CRUD routes for managing webhook endpoints: register (max 5 per user), list, delete, view delivery logs (paginated), and rotate secret. Secrets are auto-generated, encrypted at rest, and only shown in plaintext once at creation/rotation.
  • src/app.ts - Registered the new webhook routes at /api/webhooks.
  • src/routes/public.ts - Hooked dispatchWebhook() into the two card/profile view handlers so card.viewed events fire after view tracking.
  • src/__tests__/webhooks.test.ts (new) - 17 tests covering endpoint registration, max limit enforcement, validation, listing, deletion, delivery logs pagination, secret rotation, HMAC signature correctness, and delivery success/failure/timeout scenarios.

How to Test

  1. Run pnpm install from the repo root
  2. Run pnpm test from apps/backend - all 25 tests should pass (17 new + 8 existing)
  3. To verify the schema, run npx prisma migrate dev from apps/backend (requires a running Postgres instance)
  4. To test manually, start the dev server and:
    • POST /api/webhooks with { "url": "https://your-endpoint.com", "events": ["card.viewed"] } (needs auth token)
    • Visit a public profile at GET /api/u/:username - your endpoint should receive a signed POST

Additional Context

  • The tsc build has errors but they're all pre-existing across the codebase (e.g. app.authenticate type augmentation missing from every route file, implicit any params in cards.ts, follow.ts, etc.). My new files only carry the same authenticate pattern - webhookDispatch.ts compiles clean.
  • Retries are handled with in-process setTimeout for now. For production at scale, this should probably move to a proper job queue (e.g. BullMQ backed by the existing Redis instance), but that felt out of scope for this PR.
  • The contact.saved event type is accepted in endpoint registration and validation, but nothing dispatches it yet since there's no contact-save feature. Added a TODO comment in public.ts so it's easy to wire up later.
  • Secrets are encrypted using the existing AES-256-GCM utility in encryption.ts - no new crypto dependencies.

@Dipti45sktech

Copy link
Copy Markdown
Contributor Author

Hi @ShantKhatri, could you please review my PR?

@Harxhit Harxhit added gssoc:approved Required label for every approved PR. Gives the base +50 points and enables contribution tracking. critical Includes schema, architecture, or other critical core functionality changes. labels May 19, 2026
@Harxhit

Harxhit commented May 19, 2026

Copy link
Copy Markdown
Collaborator

Hi @ShantKhatri, could you please review my PR?

Could you please add the test proofs in the PR description as well? Since this PR involves schema changes, I have marked it as critical, so the review may take some additional time.

Comment thread apps/backend/prisma/schema.prisma
Comment thread apps/backend/prisma/schema.prisma
Comment thread apps/backend/prisma/schema.prisma
Comment thread apps/backend/prisma/schema.prisma
Comment thread apps/backend/prisma/schema.prisma
Comment thread apps/backend/prisma/schema.prisma
Comment thread apps/backend/src/routes/webhooks.ts Outdated
Comment thread apps/backend/src/routes/webhooks.ts Outdated
Comment thread apps/backend/src/routes/webhooks.ts
Comment thread apps/backend/src/routes/webhooks.ts Outdated
Comment thread apps/backend/src/routes/webhooks.ts Outdated
Comment thread apps/backend/src/routes/webhooks.ts
@Harxhit

Harxhit commented May 19, 2026

Copy link
Copy Markdown
Collaborator

Error handling around the business logic can be improved here.

@Dipti45sktech

Copy link
Copy Markdown
Contributor Author

Hi @ShantKhatri , I've corrected all the issues mentioned by @Harxhit . I'm also adding the test proofs here for review.
Kindly look into it..
image

@Dipti45sktech Dipti45sktech requested a review from Harxhit May 22, 2026 19:17
- Add updatedAt, errorMessage, deliveredAt fields to WebhookDelivery
- Add indexes on endpointId and status+nextRetryAt for query performance
- Add Fastify request schema to POST and GET webhook routes
- Wrap count check and create in  to prevent race conditions
- Add limit to GET /api/webhooks findMany query
- Fix  mock in webhook tests
- All 25 tests passing
@ShantKhatri

Copy link
Copy Markdown
Contributor

Hi @ShantKhatri , I've corrected all the issues mentioned by @Harxhit . I'm also adding the test proofs here for review. Kindly look into it.. image

CC: @Harxhit

@Harxhit

Harxhit commented May 28, 2026

Copy link
Copy Markdown
Collaborator

@Dipti45sktech Please fix merge conflicts and please add tests results for apps/backend/src/tests/webhooks.test.ts this file.

@Dipti45sktech

Copy link
Copy Markdown
Contributor Author

@Dipti45sktech Please fix merge conflicts and please add tests results for apps/backend/src/tests/webhooks.test.ts this file.

Sure sorry for the wait I had my exams going , I will fix the merge conflicts and add test cases asap

@github-actions

github-actions Bot commented Jun 2, 2026

Copy link
Copy Markdown

CI Results — ❌ Some checks failed

🖥️ Backend (❌ failure)

Check Status
Lint ❌ failure
Test ❌ failure
Typecheck ❌ failure

📱 Mobile (⏭️ skipped)

Check Status
Lint ⚪ unknown
Test ⚪ unknown

🌐 Web (⏭️ skipped)

Check Status
Check ⚪ unknown
Build ⚪ unknown

🕐 Last updated: Tue, 02 Jun 2026 19:54:49 GMT

Resolve conflicts in schema.prisma, app.ts, and public.ts:
- Keep both webhook and team relations on User
- Restore EventAttendee relations (were wrongly folded into WebhookDelivery)
- Add missing WebhookEndpoint model referenced by webhook routes/dispatch
- Relocate card.viewed webhook dispatch into publicService after main's refactor
- Combine team + webhook route registrations and imports
@Dipti45sktech

Copy link
Copy Markdown
Contributor Author

@Dipti45sktech Please fix merge conflicts and please add tests results for apps/backend/src/tests/webhooks.test.ts this file.

Greetings @Harxhit I have fixed the merge conflicts could you please have a review again .

@Harxhit

Harxhit commented Jun 3, 2026

Copy link
Copy Markdown
Collaborator

@Dipti45sktech Please fix merge conflicts and please add tests results for apps/backend/src/tests/webhooks.test.ts this file.

Sure sorry for the wait I had my exams going , I will fix the merge conflicts and add test cases asap

I have given you inline suggestions please make changes.

@Dipti45sktech

Copy link
Copy Markdown
Contributor Author

Hi @Harxhit I'm closing this PR due to failing test issues. I'll be opening a new PR for this.. Thank you.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

critical Includes schema, architecture, or other critical core functionality changes. gssoc:approved Required label for every approved PR. Gives the base +50 points and enables contribution tracking.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

backend: implement webhook delivery system for card view and contact-save events

3 participants