- الصفحة الرئيسية للمطورين
- تضمين المحررات
- رد اتصال الحفظ
رد اتصال الحفظ
رد اتصال الحفظ
عندما يكتب الحفظ إصدارًا جديدًا، يرسل MR Office طلب POST إلى عنوان URL لرد الاتصال. أما الحفظ الذي يفشل فيرسل document.save_failed مع الخطأ.
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"
}- تحقق من MRO-Signature قبل أي شيء آخر: t طابع زمني Unix، وكل v1 هو HMAC-SHA256(مفتاح خطاف الويب، "<t>.<raw body>") بالنظام السداسي عشري (قيمتا v1 أثناء قبول مفتاح مُدوَّر لا يزال). ارفض الطوابع الزمنية الأقدم من خمس دقائق.
- أجب بأي 2xx خلال 20 ثانية. واختياريًا أجب بـ { "version": "<your new version>" }: تُقارَن به قيمة file.version في الرموز المميزة التالية.
- يُعاد أي شيء آخر بعد 10 ث و30 ث و2 د و10 د و30 د و1 س و3 س و6 س (410 Gone يوقف). يبقى id وIdempotency-Key نفسيهما في كل إعادة محاولة: خزّن كل حدث مرة واحدة.
- يعمل download_url لمدة ساعة (كل إعادة محاولة لرد اتصال تحمل واحدًا جديدًا). ما دام الإصدار محفوظًا يمكنك جلبه بمفتاحك: GET /api/v1/embed/documents/{key}/content?version=N؛ أما المحذوف فيجيب بـ 410 embed_version_purged.
// رد الاتصال، مع مساعد الخادم الخاص بالحزمة (أي بيئة تشغيل 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(); // غير موقّع بمفتاح خطاف الويب الخاص بك
}
if (await seen(event.id)) return res.json({ ok: true }); // قد يصل رد الاتصال مرتين
// … خزّن ملف event.download_url، كما هو موضح أدناه
res.json({ ok: true });
});import { createHmac, timingSafeEqual } from "node:crypto";
// استخدم بايتات النص الأساسي الخام كما وردت تمامًا (وليس 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 });
// });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)