Linje

Implementation guide

Receive email and attachments as webhooks in Node.js

Turn incoming email into a verified, durably stored application event. Run the example locally, then connect a real inbox.

Start with an email, finish with a committed event.

Your application needs a delivery note from a customer. They send an email with a file attached. Your backend needs the message and the file, even if it was temporarily unavailable when the email arrived.

This guide builds a Node.js webhook receiver for that boundary. Linje receives and parses the email; the receiver verifies the webhook, saves the event in SQLite, and acknowledges it after the write commits. A companion guide adds replies against a specific order.

  1. Email and attachment
  2. Linje inbox
  3. Signed HTTP POST
  4. SQLite commit

The example uses Node.js 24.x with its built-in HTTP, crypto, and SQLite modules. There are no npm dependencies. Some Node 24 releases print an experimental warning for node:sqlite. You can run the local exercise without an account; real email delivery requires a Linje project token and a public HTTPS endpoint.

Run the failure-and-retry exercise locally.

Download the complete example, or use the commands below. Work in a private directory, separate from your public website files.

curl -fsS https://linje.systems/examples/inbound-replies.zip -o inbound-replies.zip
unzip inbound-replies.zip
cd inbound-replies
node setup.mjs
DEMO_FAIL_FIRST=1 node --env-file=.env server.mjs

setup.mjs creates a private .env with a random inbox secret and LINJE_INBOX_ID=demo-inbox. It refuses to overwrite an existing file. The receiver listens on 127.0.0.1:3000. In a second terminal, in the same directory:

node --env-file=.env simulate.mjs
node inspect.mjs

The simulator sends the same synthetic event three times, with a fresh signature timestamp on each attempt. The receiver deliberately fails once before committing:

Attempt 1: 503 demo: fail before commit; retry this event
Attempt 2: 200 stored
Attempt 3: 200 duplicate

Inspection shows one event and one pending reply against the demonstration order order_82921. Restarting the server preserves that row and its deduplication key. Running the simulator again creates a new event, so it adds a row. Its attachment is metadata only; there are no real downloadable bytes until you receive a real email.

Run the included checks with node --test example.test.mjs. They exercise the actual HTTP receiver, signature failures, duplicate deliveries, transaction rollback, and attachment downloads.

Verify the original bytes before parsing JSON.

Linje signs timestamp + "." + raw_body with HMAC-SHA256 using the inbox secret. The x-linje-timestamp header is Unix time in milliseconds. The signature header is hex, normally prefixed with sha256=.

export function verifySignature(secret, timestamp, signature, body, now = Date.now()) {
  if (typeof timestamp !== "string" || !/^\d{13}$/.test(timestamp)) return false;
  if (Math.abs(now - Number(timestamp)) > 5 * 60 * 1000) return false;
  if (typeof signature !== "string") return false;
  const hex = signature.replace(/^sha256=/, "");
  if (!/^[a-fA-F0-9]{64}$/.test(hex)) return false;
  const expected = createHmac("sha256", secret).update(`${timestamp}.`).update(body).digest();
  return timingSafeEqual(expected, Buffer.from(hex, "hex"));
}

The server collects raw request bytes and runs this function before JSON.parse(). Reformatting JSON changes the bytes and invalidates the signature. If you use Express instead, capture the raw body on this route before a JSON middleware transforms it.

The five-minute window rejects old requests and timestamps too far in the future. Keep the receiver's clock synchronized. A valid signature establishes that the webhook came through Linje; email content still requires your application's normal validation.

Acknowledge after durable storage, deduplicate by inbound ID.

A network timeout can occur after your application commits but before Linje receives the HTTP 200. The next attempt must return success without creating another comment or starting the same job again.

The example makes inbound-id the primary key in inbound_events. One SQLite transaction stores the event and any pending order reply. An existing inbound ID returns 200 duplicate. A storage error rolls the transaction back and returns 503.

BEGIN IMMEDIATE;
-- Insert inbound_events using inbound_id as the primary key.
-- If it already exists: commit and return 200 duplicate.
-- Otherwise: insert a pending reply if the order exists.
COMMIT;
-- Only now return 200 stored.

See server.mjs for the complete transaction. The payload also has a stable event-id. The per-attempt x-linje-delivery-id header is useful for logs, but changes between attempts and therefore cannot deduplicate the email.

This example stores to one local database on a durable disk. A multi-instance application needs shared durable storage and a uniqueness constraint scoped to its project or tenant model. If processing starts work in another system, use a transactional outbox rather than making that remote call between the database write and acknowledgement.

Connect a real Linje inbox.

Create a project in the Linje portal and copy its project token. Stop the demo server in the first terminal before changing the inbox configuration. Run the API commands below in the second terminal, where you ran the simulator. Provision an inactive inbox first, using the same secret already in .env:

umask 077
export LINJE_PROJECT_TOKEN='your-project-token'
node --env-file=.env --input-type=module -e '
  console.log(JSON.stringify({
    active: false,
    secret: process.env.LINJE_INBOX_SECRET
  }));
' | curl -fsS https://api.linje.systems/v1/inboxes/provision \
  -H "Authorization: Bearer $LINJE_PROJECT_TOKEN" \
  -H 'Content-Type: application/json' \
  --data-binary @- > inbox.json

node -e '
  const { inbox } = JSON.parse(require("node:fs").readFileSync("inbox.json"));
  console.log("Inbox ID:", inbox.id);
  console.log("Email address:", inbox.address);
'

Replace demo-inbox in .env with the returned inbox ID. Keep the secret unchanged. The saved API response may contain credentials; keep it private. In the first terminal, start the receiver again without the failure flag and leave it running:

node --env-file=.env server.mjs

Expose this loopback service through an HTTPS reverse proxy or a development tunnel. Use a publicly resolvable address; Linje's webhook validation rejects private network destinations. Back in the second terminal, activate the inbox with that endpoint, using the returned inbox ID. The project token exported during provisioning is still needed in this terminal:

export LINJE_INBOX_ID='the-returned-inbox-id'
curl -fsS -X PATCH \
  "https://api.linje.systems/v1/inboxes/$LINJE_INBOX_ID" \
  -H "Authorization: Bearer $LINJE_PROJECT_TOKEN" \
  -H 'Content-Type: application/json' \
  --data-binary '{
    "active": true,
    "webhook-url": "https://your-public-host.example/linje/inbound"
  }'

Send a plain email with a small attachment to the address returned during provisioning. Run node inspect.mjs again. The real inbound ID and attachment ID should now be present. A message sent directly to the inbox has no order route, so inspection labels it unmatched; it is still stored.

Download attachments outside the webhook request.

The verified envelope includes an attachments array with file metadata and download.url references. Signed download links expire. Keeping a URL in your database does not keep its authorization valid indefinitely.

The companion downloader uses the project's authenticated attachment endpoint instead. Copy the two IDs from inspect.mjs and choose your own destination filename:

export LINJE_PROJECT_TOKEN='your-project-token'
node download.mjs INBOUND_ID ATTACHMENT_ID ./delivery-note.bin

The script checks that the attachment belongs to an event this receiver verified and stored, constructs the API URL on api.linje.systems, and streams the response to a new private file. It never forwards the token to a URL from email content and never uses the sender's filename as a path. It refuses redirects, existing output files, and downloads above 10 MiB.

The receiver caps HTTP bodies at 4 MiB. Inline attachment data can increase payload size; align this limit with your actual Linje payloads. Downloading in a separate worker keeps slow file transfers out of the webhook acknowledgement. Apply your own scanning and access policy before opening files or showing them to users.

Recover delivery without creating a second email.

Linje stores inbound email before attempting its webhook. Transient callback failures are retried. If the email was accepted while your endpoint was broken, inspect its attempts and requeue the stored event after fixing the handler:

export INBOUND_ID='the-real-inbound-id'
curl -fsS \
  "https://api.linje.systems/v1/inbound/messages/$INBOUND_ID/attempts" \
  -H "Authorization: Bearer $LINJE_PROJECT_TOKEN"

curl -fsS -X POST \
  "https://api.linje.systems/v1/inbound/messages/$INBOUND_ID/replay" \
  -H "Authorization: Bearer $LINJE_PROJECT_TOKEN"

Replay requeues webhook delivery; it does not send another email. When the delivery worker calls your endpoint, an already committed inbound ID returns duplicate. A 401, 400, or 413 requires fixing the secret, envelope handling, clock, or body limit; replay alone cannot fix it.

The local 503 exercise demonstrates the same application-side boundary, without sending any live email. For a real delivery test, keep DEMO_FAIL_FIRST unset.

Attach the next reply to its original object.

A verified message now survives a temporary outage. The next step is preserving the context of the email that prompted it.

Build the reply workflow

Reference: inbound webhooks · email to webhook · public OpenAPI contract · Node.js SQLite API.