The API prepares the post. Only I publish it.
I write my blog posts in HackMD. When a note in my blog folder is ready, I click Publish there.
My blog API hears about it through a webhook. It fetches the note, saves it as a draft and emails me. I read the draft on my blog, fix what needs fixing and publish it myself.
This post walks through how that works, what it refuses to do, and what is still missing.
The flow, step by step
- I click Publish on a note in my blog folder.
- HackMD sends a signed
note.publishedevent to my API. - The API checks the delivery, records it, and answers right away.
- After answering, it fetches the note through the HackMD API.
- It checks the note’s owner, folder and publish state.
- It converts the markdown and saves the post as a draft in Postgres.
- It emails me a link to the draft.
- I review the draft and publish it from my blog editor.
The API never does step 8. Only I do.
| Part | Job |
|---|---|
| HackMD | Where I write, and where the webhook comes from |
| Webhook endpoint | Checks each delivery and records it |
| Inbox table | Remembers every event id, so nothing runs twice |
| HackMD API | Gives the API the actual note content |
| Postgres | Holds the draft |
| Tells me a draft is waiting |
One event starts it
HackMD sends many webhook events. There are events for notes being created, updated, deleted, moved, published and unpublished. There are folder events and a test ping too.[1]
My API imports on exactly one of them.
| Event | What my API does |
|---|---|
ping (the test button) |
Answers “pong” and skips the database |
note.published |
Records it, answers 202, imports after the response |
| Any other event | Records it as ignored, answers 200, calls nothing |
| An event id it has seen | Answers 200 “duplicate” and stops |
Why so strict? Because I edit notes all day. If every save made a draft, my blog editor would fill with junk. Publish is the one click that means “I think this is ready.”
My webhook is scoped to my blog folder, so HackMD only sends events for notes in it. The API double-checks the folder and owner anyway.[2]
A HackMD webhook carries no note content. The docs call it “a signal, not a copy of the note.”[2:1] So the API fetches the note itself.
Check the signature on raw bytes
The endpoint is public. Anyone can send it a POST, so the signature check comes first.
HackMD signs each delivery with a secret that only HackMD and my server know. The X-HackMD-Signature header holds sha256= and an HMAC-SHA256 of the raw request body.[2:2]
The key words are “raw body.” If NestJS parses the JSON first, the bytes can change. Then the HMAC never matches. So the app keeps the original bytes:
const app = await NestFactory.create<NestExpressApplication>(AppModule, { rawBody: true });
JSON parsing still works as before. The exact bytes also wait on req.rawBody. Then the check is short. This is simplified from my API, with the same logic:
import { createHmac, timingSafeEqual } from 'node:crypto';
const SIGNATURE = /^sha256=([0-9a-f]{64})$/;
export function verifySignature(rawBody: Buffer, header: string | undefined, secret: string): boolean {
const match = typeof header === 'string' ? SIGNATURE.exec(header) : null;
if (!match?.[1] || !secret) return false;
const expected = createHmac('sha256', secret).update(rawBody).digest();
const received = Buffer.from(match[1], 'hex');
return received.length === expected.length && timingSafeEqual(received, expected);
}
Three details are worth copying:
- The header must match a strict pattern. Anything else fails.
- An empty secret fails. A missing config should never mean “accept everything.”
timingSafeEqualcompares in constant time. A plain===can leak how many characters matched.[3]
The signature is one check of several. Each failure gets its own answer:
| Check | If it fails |
|---|---|
| The body is under a size cap | 413 |
| The body is not empty | 400 |
| The signature matches | 401 |
The X-HackMD-Hook-Id header matches my webhook (checked after the signature, optional) |
403 |
| The body has the expected shape | 400 |
| The event is fresh | 401 |
The size cap lives on the body parser itself, like app.useBodyParser('json', { limit: '...' }). NestJS reads the whole body before any handler runs, so a check in the handler comes too late.[4]
Old deliveries don’t count
A valid signature proves HackMD sent the message. It does not prove HackMD sent it just now. Someone could capture a real delivery and replay it later.
So the API checks the event’s age, using the createdAt inside the signed body. HackMD sends it as an ISO date string, so the API parses it first.[2:3] Again simplified:
export function isFresh(createdAt: string, now: number, maxAgeMs: number, maxSkewMs: number): boolean {
const createdAtMs = Date.parse(createdAt);
if (Number.isNaN(createdAtMs)) return false;
return createdAtMs >= now - maxAgeMs && createdAtMs <= now + maxSkewMs;
}
Every value here is in milliseconds. A date that doesn’t parse is rejected.
An event may be a few minutes old. It may also be slightly in the future, for clock drift. Anything else is rejected.
The window alone doesn’t stop a replay inside it. The event-id inbox does that. Inside the window, the event-id primary key rejects a replayed copy. So I keep inbox rows at least as long as the freshness window.
HackMD’s guide suggests checking the X-HackMD-Timestamp header.[2:4] The signature covers only the body, not that header, so I read the time from the signed body instead.
Read the time from the signed body. A header outside the signature is a value an attacker controls.
Answer first, work later
Fetching a note and writing to Postgres takes time. HackMD does not need to wait for that. So the endpoint records the event, answers, and imports afterwards:
this.runner.schedule(envelope.eventId);
return { httpStatus: HttpStatus.ACCEPTED, body: { status: 'accepted' } };
The event goes into a small inbox table first, keyed by HackMD’s event id. Webhook deliveries can arrive more than once, so the id is the primary key. A second copy changes nothing.
This order has a cost. HackMD hears “accepted” before the import runs. If the import fails, HackMD never knows. The inbox row is how my API remembers to try again.
Four gates before any write
After fetching the note, the API checks four things. Simplified again:
function gate(note: NoteSummary, config: ImportConfig): SkipReason | null {
const ownerAllowed = note.teamPath
? config.allowedTeamPaths.includes(note.teamPath)
: note.userPath !== null && config.allowedUserPaths.includes(note.userPath);
if (!ownerAllowed) return 'ignored_owner';
if (!config.blogFolderId || !note.folderPaths.some((f) => f.id === config.blogFolderId)) return 'ignored_folder';
if (note.publishType === 'slide' || note.publishType === 'book') return 'ignored_publish_type';
if (note.publishedAt === null) return 'ignored_not_published';
return null;
}
In plain words:
- The note must belong to me or my team workspace.
- It must sit in my blog folder. If no blog folder is set, nothing gets in. A missing config never means “accept everything.”
- Slides and books are skipped.
- The note must be published right now.
Each gate returns a named reason, so the logs say why a note was skipped. “ignored_folder” is much easier to debug than “nothing happened.”
Drafts only, always
Every new import is saved with status draft and no publish date. Two more rules protect my work.
- Published posts are frozen. Once I publish a post on the blog, HackMD can never change it.
- My edits win. If I edit the draft in my blog editor, later imports leave it alone.
if (existing.status !== 'draft') return { ...base, outcome: 'skipped_published', postId: existing.postId };
if (existing.postUpdatedAt.getTime() > existing.linkUpdatedAt.getTime() + LOCAL_EDIT_TOLERANCE_MS) {
return { ...base, outcome: 'skipped_local_edits', postId: existing.postId };
}
So publishing again in HackMD refreshes a draft only while it is untouched. If the content did not change, a hash check skips the write.
The import can create and refresh drafts. It can never publish, unpublish or overwrite a published post.
The markdown also gets a cleanup pass before it is saved:
| HackMD writes | The blog gets |
|---|---|
| Front matter | Removed; title, description and tags are read from it |
[TOC] |
Removed; the post page builds its own contents list |
:::success, :::danger |
Mapped to the blog’s tip and warning blocks |
| YouTube, Vimeo and gist embeds | A plain link |
| Image size suffixes | Removed |
| Raw HTML | Escaped, never run |
A Postgres advisory lock allows one import per note at a time. A slug clash gets a few retries with a new slug.
The review email
When a new draft lands, the API emails me. The first line reads: “A new draft was imported from HackMD. Nothing has been published.”
The email links to the draft in my editor and back to the HackMD note. It also lists what to check by hand, like an image still hosted on HackMD.
Updates to an existing draft send no email. Only new drafts do.
The email goes out at most once. Before sending, the API claims the event row in the database. A duplicate delivery or a retry finds the claim and stops. The cost: if the server crashes between the claim and the send, I get no email. I picked “maybe zero” over “maybe two.”
The email logs keep only the post id and the provider’s error name. No addresses, no titles, no note content.
When a delivery goes missing
Webhooks get lost. HackMD’s docs add a sharper case. Every real delivery counts toward the workspace API quota. When the quota runs out, deliveries are skipped and never sent later.[2:5]
So a reconcile job runs every few hours. It does three things:
- Retries events that got stuck or failed, up to a few attempts.
- Once a day, lists my recent notes. Published blog-folder notes that never got imported are imported now.
- Deletes inbox rows older than the freshness window.
The catch-up builds each event id from a hash. So if I delete a draft on purpose, the catch-up does not bring it back.
I also get an alert email for a failed import, an empty quota, or a run of bad signatures. Alerts are rate-capped, so a bad night sends one email, not fifty.
What I’d take from this
- Treat a webhook as a doorbell. It tells you something happened, then you fetch the facts. This holds when the payload has no content. It costs one API call per event.
- Verify the bytes you received. Turn on raw body handling before you write the HMAC check. It costs one option at startup.[4:1]
- Let a person hold the Publish button. Automation can prepare a post. Publishing stays a click. The cost is one extra step each time, and I am happy to pay it.
- Build the safety net for boring failures. Lost deliveries and quiet months break more pipelines than attackers do. The catch-up cost me a job, a table and two near misses.
Want to see where HackMD and I started? I used its API as a free database in my zero-cost personal dashboard.
My writing desk is now a folder in HackMD. My blog is still the place where I decide.
Sources
- HackMD, Webhooks guide (folder scope, signature, quota): https://hackmd.io/@docs/webhooks-guide
- HackMD, Webhook events: https://hackmd.io/@docs/webhooks-events
- HackMD blog, webhooks announcement (Sep 28, 2026): https://hackmd.io/blog/2026/09/28/hackmd-webhooks-2026
- Node.js crypto,
timingSafeEqual: https://nodejs.org/api/crypto.html#cryptotimingsafeequala-b - NestJS, raw body: https://docs.nestjs.com/faq/raw-body
- markdown-it options (
html): https://github.com/markdown-it/markdown-it#init-with-presets-and-options
ALI GAMAL · Tech Lead · Front-End Architecture · Angular
Written by Ali Gamal. More at alidevhub.com and blog.alidevhub.com.
GitHub @Arigatouz · X @AliDevEgy · LinkedIn alidevegy · Bluesky @arigatouz.bsky.social · dev.to arigatouz
HackMD lists all event types on its webhook events page: https://hackmd.io/@docs/webhooks-events ↩︎
HackMD Webhooks guide: https://hackmd.io/@docs/webhooks-guide ↩︎ ↩︎ ↩︎ ↩︎ ↩︎ ↩︎
Node.js docs for
crypto.timingSafeEqual: https://nodejs.org/api/crypto.html#cryptotimingsafeequala-b ↩︎NestJS docs on raw body support: https://docs.nestjs.com/faq/raw-body ↩︎ ↩︎