- Home per sviluppatori
- Incorporare gli editor
- Callback di salvataggio
Callback di salvataggio
Callback di salvataggio
Quando un salvataggio scrive una nuova versione, MR Office invia una richiesta POST al tuo URL di callback. Un salvataggio non riuscito invia document.save_failed con l'errore.
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"
}- Verifica MRO-Signature prima di ogni altra cosa: t è un timestamp Unix, ogni v1 è HMAC-SHA256(chiave del webhook, "<t>.<raw body>") in esadecimale (due valori v1 finché una chiave ruotata è ancora accettata). Rifiuta i timestamp più vecchi di cinque minuti.
- Rispondi con un qualsiasi 2xx entro 20 secondi. Facoltativamente rispondi { "version": "<your new version>" }: il file.version dei token successivi viene confrontato con esso.
- Qualsiasi altra risposta viene ritentata dopo 10 s, 30 s, 2 min, 10 min, 30 min, 1 h, 3 h e 6 h (410 Gone interrompe i tentativi). L'id e l'Idempotency-Key sono gli stessi a ogni tentativo: memorizza ogni evento una sola volta.
- download_url funziona per un'ora (ogni nuovo tentativo di un callback ne porta uno nuovo). Finché una versione è conservata puoi recuperarla con la tua chiave: GET /api/v1/embed/documents/{key}/content?version=N; una versione eliminata risponde 410 embed_version_purged.
// Il callback, con l'helper server del pacchetto (qualsiasi runtime con Web Crypto).
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(); // non firmato con la tua chiave del webhook
}
if (await seen(event.id)) return res.json({ ok: true }); // un callback può arrivare due volte
// … memorizza il file di event.download_url, come sotto
res.json({ ok: true });
});import { createHmac, timingSafeEqual } from "node:crypto";
// Usa i byte grezzi del body, esattamente come ricevuti (non JSON riserializzato).
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 });
// });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)