- Αρχική σελίδα προγραμματιστών
- Δείγματα δημιουργίας διακριτικών
Δείγματα δημιουργίας διακριτικών
Δημιουργήστε διακριτικά συνεδρίας ενσωμάτωσης MR Office σε Node, Python, Express, FastAPI ή με μία κλήση API και επαληθεύστε τα υπογεγραμμένα callback αποθήκευσης.
Δημιουργία διακριτικού συνεδρίας
Ένα διακριτικό συνεδρίας είναι ένα JWT υπογεγραμμένο με HS256 με το μυστικό κλειδί της εφαρμογής σας, για ένα άτομο και ένα αρχείο. Δημιουργήστε το μόνο στον διακομιστή σας, ένα ανά άτομο ανά φόρτωση σελίδας.
// server.js — δημιουργήστε ένα διακριτικό συνεδρίας για ένα άτομο και ένα αρχείο (Node 18+).
import { createHmac, randomUUID } from "node:crypto";
const APP_ID = process.env.MROFFICE_APP_ID; // από την κονσόλα προγραμματιστή (mroffice.ai/developers/console)
const SECRET = process.env.MROFFICE_SECRET_KEY; // mro_sk_… (μόνο διακομιστής)
const b64url = (value) => Buffer.from(JSON.stringify(value)).toString("base64url");
export function mintSessionToken({ fileKey, fileName, fileUrl, version, userId, userName, mode = "edit" }) {
const now = Math.floor(Date.now() / 1000);
const header = { alg: "HS256", typ: "JWT" };
const claims = {
iss: APP_ID,
aud: "mroffice-embed",
iat: now,
exp: now + 600, // το πολύ 3600
jti: randomUUID(), // μία χρήση
file: { key: fileKey, name: fileName, url: fileUrl, version },
mode, // "edit" ή "view"
user: { id: userId, name: userName },
};
const body = `${b64url(header)}.${b64url(claims)}`;
const signature = createHmac("sha256", SECRET).update(body).digest("base64url");
return `${body}.${signature}`;
}
// π.χ. με Express:
// app.get("/api/contracts/:id/editor-token", requireLogin, (req, res) => {
// const contract = await contracts.get(req.params.id, req.user);
// res.json({ token: mintSessionToken({
// fileKey: `contract-${contract.id}`, fileName: contract.fileName,
// fileUrl: contract.signedDownloadUrl(), version: contract.etag,
// userId: req.user.id, userName: req.user.name,
// mode: contract.canEdit(req.user) ? "edit" : "view" }) });
// });# server.py — το ίδιο διακριτικό με PyJWT (pip install pyjwt)
import os, time, uuid
import jwt
APP_ID = os.environ["MROFFICE_APP_ID"]
SECRET = os.environ["MROFFICE_SECRET_KEY"] # mro_sk_… (μόνο διακομιστής)
def mint_session_token(file_key, file_name, file_url, user_id, user_name, mode="edit", version=None):
now = int(time.time())
claims = {
"iss": APP_ID,
"aud": "mroffice-embed",
"iat": now,
"exp": now + 600,
"jti": str(uuid.uuid4()),
"file": {"key": file_key, "name": file_name, "url": file_url, "version": version},
"mode": mode,
"user": {"id": user_id, "name": user_name},
}
return jwt.encode(claims, SECRET, algorithm="HS256")curl -X POST https://mroffice.ai/api/v1/embed/sessions \
-H "Authorization: Bearer $MROFFICE_SECRET_KEY" \
-H "Content-Type: application/json" \
-d '{
"file": { "key": "contract-42", "name": "contract.docx", "url": "https://files.example.com/contract.docx?sig=…" },
"mode": "edit",
"user": { "id": "user-7", "name": "Alex" },
"ttl_seconds": 600
}'Μια διαδρομή διακριτικού στην εφαρμογή σας
Η σελίδα σας ζητά ένα διακριτικό από τον διακομιστή σας· ο διακομιστής σας ελέγχει ποιος είναι συνδεδεμένος και τι επιτρέπεται να κάνει με το αρχείο και έπειτα το υπογράφει.
// server.js — μια διαδρομή Express που καλεί η σελίδα σας για διακριτικό
import express from "express";
import { mintSessionToken } from "./mroffice-token.js"; // η συνάρτηση παραπάνω
const app = express();
app.use(express.json());
app.post("/api/contracts/:id/editor-token", requireSignedIn, async (req, res) => {
const contract = await db.contracts.find(req.params.id, { for: req.user });
if (!contract) return res.sendStatus(404);
res.json({
token: mintSessionToken({
fileKey: `contract-${contract.id}`,
fileName: contract.fileName, // contract.docx
fileUrl: await storage.signedUrl(contract.path, { expiresIn: 300 }),
version: contract.etag,
userId: req.user.id,
userName: req.user.name,
mode: contract.canEdit(req.user) ? "edit" : "view",
}),
});
});# app.py — η ίδια διαδρομή σε FastAPI (pip install fastapi pyjwt)
import os, time, uuid
import jwt
from fastapi import Depends, FastAPI, HTTPException
app = FastAPI()
@app.post("/api/contracts/{contract_id}/editor-token")
def editor_token(contract_id: str, user=Depends(current_user)):
contract = contracts.find(contract_id, for_user=user)
if contract is None:
raise HTTPException(404)
now = int(time.time())
token = jwt.encode({
"iss": os.environ["MROFFICE_APP_ID"], "aud": "mroffice-embed",
"iat": now, "exp": now + 600, "jti": str(uuid.uuid4()),
"file": {"key": f"contract-{contract.id}", "name": contract.file_name,
"url": storage.signed_url(contract.path, expires_in=300)},
"mode": "edit" if contract.can_edit(user) else "view",
"user": {"id": str(user.id), "name": user.name},
}, os.environ["MROFFICE_SECRET_KEY"], algorithm="HS256")
return {"token": token}Επαλήθευση callback αποθήκευσης
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"
}import { createHmac, timingSafeEqual } from "node:crypto";
// Χρησιμοποιήστε τα ακατέργαστα byte του σώματος, ακριβώς όπως ελήφθησαν (όχι εκ νέου σειριοποιημένο 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)