- Beranda developer
- Sematkan editor
- Callback penyimpanan
Callback penyimpanan
Callback penyimpanan
Ketika sebuah penyimpanan menulis versi baru, MR Office mengirim POST ke URL callback Anda. Penyimpanan yang gagal mengirim document.save_failed beserta galatnya.
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"
}- Verifikasi MRO-Signature sebelum apa pun: t adalah stempel waktu Unix, setiap v1 adalah HMAC-SHA256(kunci webhook, "<t>.<raw body>") dalam heksadesimal (dua nilai v1 selama kunci yang dirotasi masih diterima). Tolak stempel waktu yang lebih lama dari lima menit.
- Jawab dengan 2xx apa pun dalam 20 detik. Secara opsional jawab { "version": "<your new version>" }: file.version pada token berikutnya dibandingkan dengannya.
- Jawaban lain dicoba ulang setelah 10 dtk, 30 dtk, 2 mnt, 10 mnt, 30 mnt, 1 jam, 3 jam, dan 6 jam (410 Gone menghentikannya). id dan Idempotency-Key sama pada setiap percobaan ulang: catat setiap event satu kali.
- download_url berfungsi selama satu jam (setiap percobaan ulang callback membawa yang baru). Selama sebuah versi masih disimpan, Anda dapat mengambilnya dengan kunci Anda: GET /api/v1/embed/documents/{key}/content?version=N; versi yang sudah dihapus menjawab 410 embed_version_purged.
// Callback-nya, dengan helper server dari paketnya (runtime Web Crypto apa pun).
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(); // tidak ditandatangani dengan kunci webhook Anda
}
if (await seen(event.id)) return res.json({ ok: true }); // sebuah callback bisa datang dua kali
// … simpan file dari event.download_url, seperti di bawah
res.json({ ok: true });
});import { createHmac, timingSafeEqual } from "node:crypto";
// Gunakan byte mentah body, persis seperti yang diterima (bukan JSON yang diserialisasi ulang).
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)