# Save callback

Source: https://mroffice.ai/en/developers/embed/callbacks

When a save writes a new version, MR Office POSTs to your callback URL. A save that fails sends document.save_failed with the error.

```http
POST https://your-app.example/mroffice/callback
Content-Type: application/json
MRO-Signature: t=1795100212,v1=5f1c…e9a2
MRO-Event-Id: 6f0a1c1e-…
Idempotency-Key: 6f0a1c1e-…

{
  "id": "6f0a1c1e-…",
  "type": "document.saved",
  "created": "2026-11-19T15:03:11+00:00",
  "app_id": "7f1d2c3b-…",
  "document": {
    "id": "…", "key": "contract-42", "name": "contract.docx",
    "version": 3, "previous_version": 2, "partner_version": "etag-17",
    "sha256": "…", "size": 48211,
    "content_type": "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
    "source": "url"
  },
  "save": { "id": "…", "reason": "manual", "editors": ["user-7", "user-9"], "saved_at": "…" },
  "download_url": "https://mroffice.ai/api/v1/embed/download/…?expires=…&signature=…",
  "download_expires_at": "2026-11-19T16:03:11+00:00"
}
```

- Verify MRO-Signature before anything else: t is a Unix timestamp, each v1 is HMAC-SHA256(webhook key, "<t>.<raw body>") in hex (two v1 values while a rotated key is still accepted). Refuse timestamps older than five minutes.
- Answer any 2xx within 20 seconds. Optionally answer { "version": "<your new version>" }: the next tokens' file.version is compared with it.
- Anything else is retried after 10 s, 30 s, 2 min, 10 min, 30 min, 1 h, 3 h and 6 h (410 Gone stops). The id and Idempotency-Key are the same on every retry: store each event once.
- download_url works for an hour (each retry of a callback carries a fresh one). While a version is kept you can fetch it with your key: GET /api/v1/embed/documents/{key}/content?version=N; a deleted one answers 410 embed_version_purged.

With the package's server helper:

```js
// The callback, with the package's server helper (any Web Crypto runtime).
import { verifyCallback } from "mroffice-embed/server";

app.post("/mroffice/callback", express.raw({ type: "application/json" }), async (req, res) => {
  let event;
  try {
    event = await verifyCallback(req.body, req.get("MRO-Signature"), process.env.MROFFICE_WEBHOOK_SECRET);
  } catch {
    return res.status(401).end();                       // not signed with your webhook key
  }
  if (await seen(event.id)) return res.json({ ok: true });   // a callback may come twice
  // … store event.download_url's file, as below
  res.json({ ok: true });
});
```

Verify in Node:

```js
import { createHmac, timingSafeEqual } from "node:crypto";

// Use the raw body bytes, exactly as received (not re-serialised JSON).
export function verifyMROfficeSignature(rawBody, header, webhookSecret, toleranceSeconds = 300) {
  const parts = Object.groupBy(header.split(","), (item) => item.split("=")[0].trim());
  const t = Number(parts.t?.[0]?.split("=")[1]);
  if (!Number.isFinite(t) || Math.abs(Date.now() / 1000 - t) > toleranceSeconds) return false;
  const expected = createHmac("sha256", webhookSecret).update(`${t}.`).update(rawBody).digest();
  return (parts.v1 ?? []).some((item) => {
    const given = Buffer.from(item.split("=")[1] ?? "", "hex");
    return given.length === expected.length && timingSafeEqual(given, expected);
  });
}

// app.post("/mroffice/callback", express.raw({ type: "application/json" }), async (req, res) => {
//   if (!verifyMROfficeSignature(req.body, req.get("MRO-Signature"), process.env.MROFFICE_WEBHOOK_SECRET))
//     return res.status(401).end();
//   const event = JSON.parse(req.body);
//   if (await seen(event.id)) return res.json({ ok: true });          // idempotent
//   if (event.type === "document.saved") {
//     const file = await fetch(event.download_url).then((r) => r.arrayBuffer());
//     const etag = await contracts.storeVersion(event.document.key, file, event.document.version);
//     return res.json({ version: etag });   // your new version: compared with the next token's file.version
//   }
//   res.json({ ok: true });
// });
```

Verify in Python:

```python
import hashlib, hmac, time

def verify_mroffice_signature(raw_body: bytes, header: str, webhook_secret: str, tolerance: int = 300) -> bool:
    pairs = [item.split("=", 1) for item in header.split(",") if "=" in item]
    timestamps = [value for key, value in pairs if key.strip() == "t"]
    signatures = [value for key, value in pairs if key.strip() == "v1"]
    if not timestamps or not timestamps[0].isdigit() or abs(time.time() - int(timestamps[0])) > tolerance:
        return False
    expected = hmac.new(webhook_secret.encode(), f"{timestamps[0]}.".encode() + raw_body, hashlib.sha256).hexdigest()
    return any(hmac.compare_digest(expected, candidate.strip()) for candidate in signatures)
```
