#!/usr/bin/env python3
"""Keep a knowledge base fresh with the Ujeebu Crawl API: the webhook receiver (Flask).
When a crawl job ends, Ujeebu sends one signed POST to /hooks/crawl. This receiver checks the
signature, answers at once, then downloads the job's archive, checks its checksum and compares
each page's sha256 with the previous run, so only new and changed pages are processed again.
pip install flask requests
UJEEBU_API_KEY=your-key python3 receiver.py
"""
import hashlib
import hmac
import io
import json
import os
import tarfile
import threading
import time
import requests
from flask import Flask, abort, request
API_KEY = os.environ.get("UJEEBU_API_KEY", "YOUR_API_KEY") # webhooks are signed with your API key
HASHES_FILE = "page-hashes.json" # url -> sha256 of the content last processed
MAX_AGE = 300 # refuse a call signed more than 5 minutes ago
app = Flask(__name__)
seen_ids = set() # X-Ujeebu-Webhook-Id of the calls already accepted
lock = threading.Lock() # one refresh at a time
def signature_ok(raw_body, timestamp, signature):
"""HMAC-SHA256 of "<timestamp>.<raw body>" keyed with your API key, compared in constant time."""
if not timestamp.isdigit() or abs(time.time() - int(timestamp)) > MAX_AGE:
return False
digest = hmac.new(API_KEY.encode(), timestamp.encode() + b"." + raw_body, hashlib.sha256).hexdigest()
return hmac.compare_digest("sha256=" + digest, signature)
def download_archive(archive):
"""The job's tar.gz archive as {file name: bytes}, once its sha256 matches."""
raw = requests.get(archive["url"], timeout=300).content
if hashlib.sha256(raw).hexdigest() != archive["checksum_sha256"]:
raise ValueError("archive checksum mismatch")
with tarfile.open(fileobj=io.BytesIO(raw), mode="r:gz") as tar:
return {m.name: tar.extractfile(m).read() for m in tar.getmembers() if m.isfile()}
def reprocess(url, markdown):
"""Your pipeline: chunk, embed and upsert this page (see the previous tutorial)."""
print(f" process {url} ({len(markdown)} chars)")
def remove(url):
"""Your pipeline: delete this page's chunks from the knowledge base."""
print(f" remove {url}")
def refresh(event):
files = download_archive(event["archive"])
manifest = json.loads(files["manifest.json"])
with lock:
hashes = {}
if os.path.exists(HASHES_FILE):
with open(HASHES_FILE) as f:
hashes = json.load(f)
changed = unchanged = removed = 0
for page in manifest["pages"]:
url = page["url"]
if page["state"] == "done":
if hashes.get(url) == page["sha256"]:
unchanged += 1
continue
reprocess(url, files[page["file"]].decode("utf-8"))
hashes[url] = page["sha256"]
changed += 1
elif page.get("error_class") == "not_found" and url in hashes:
remove(url) # the page is gone (404 or 410)
del hashes[url]
removed += 1
with open(HASHES_FILE, "w") as f:
json.dump(hashes, f, indent=1)
print(f"{event['job_id']}: {changed} new or changed, {unchanged} unchanged, "
f"{removed} removed ({event['credits_used']} credits)")
@app.post("/hooks/crawl")
def crawl_webhook():
raw = request.get_data() # the raw bytes: the signature covers them exactly
if not signature_ok(raw, request.headers.get("X-Ujeebu-Timestamp", ""),
request.headers.get("X-Ujeebu-Signature", "")):
abort(401)
webhook_id = request.headers.get("X-Ujeebu-Webhook-Id", "")
if webhook_id in seen_ids:
return "", 200 # a retry of a call already accepted
seen_ids.add(webhook_id)
event = json.loads(raw)
if event["event"] != "crawl.job.completed": # crawl.job.failed or crawl.job.cancelled
print(f"{event['job_id']}: {event['event']} ({event['stop_reason']}), nothing to refresh")
return "", 200
threading.Thread(target=refresh, args=(event,), daemon=True).start()
return "", 202 # answer at once; the refresh runs in the background
if __name__ == "__main__":
app.run(host="0.0.0.0", port=int(os.environ.get("PORT", 8000)))
#!/usr/bin/env node
/**
* Keep a knowledge base fresh with the Ujeebu Crawl API: the webhook receiver (Express).
*
* When a crawl job ends, Ujeebu sends one signed POST to /hooks/crawl. This receiver checks the
* signature, answers at once, then downloads the job's archive, checks its checksum and compares
* each page's sha256 with the previous run, so only new and changed pages are processed again.
*
* npm install express
* UJEEBU_API_KEY=your-key node receiver.js (Node.js 18 or later)
*/
const crypto = require('crypto');
const fs = require('fs');
const zlib = require('zlib');
const express = require('express');
const API_KEY = process.env.UJEEBU_API_KEY || 'YOUR_API_KEY'; // webhooks are signed with your API key
const HASHES_FILE = 'page-hashes.json'; // url -> sha256 of the content last processed
const MAX_AGE = 300; // refuse a call signed more than 5 minutes ago
const seenIds = new Set(); // X-Ujeebu-Webhook-Id of the calls already accepted
let queue = Promise.resolve(); // one refresh at a time
/** HMAC-SHA256 of "<timestamp>.<raw body>" keyed with your API key, compared in constant time. */
function signatureOk(rawBody, timestamp, signature) {
if (!/^\d+$/.test(timestamp) || Math.abs(Date.now() / 1000 - Number(timestamp)) > MAX_AGE) return false;
const digest = crypto.createHmac('sha256', API_KEY).update(`${timestamp}.`).update(rawBody).digest('hex');
const expected = Buffer.from(`sha256=${digest}`);
const given = Buffer.from(signature);
return given.length === expected.length && crypto.timingSafeEqual(given, expected);
}
/** The files of a tar archive as {name: Buffer} (the archive's names are short, plain ustar). */
function untar(tar) {
const files = {};
const field = (header, start, end) => header.toString('utf8', start, end).replace(/\0[\s\S]*$/, '').trim();
for (let offset = 0; offset + 512 <= tar.length;) {
const header = tar.subarray(offset, offset + 512);
const name = field(header, 0, 100);
if (!name) break; // the empty blocks that end the archive
const size = parseInt(field(header, 124, 136), 8) || 0;
const type = header[156];
if (type === 48 || type === 0) files[name] = tar.subarray(offset + 512, offset + 512 + size); // '0' or NUL: a file
offset += 512 + Math.ceil(size / 512) * 512;
}
return files;
}
/** The job's tar.gz archive as {file name: Buffer}, once its sha256 matches. */
async function downloadArchive(archive) {
const response = await fetch(archive.url);
if (!response.ok) throw new Error(`archive download: ${response.status}`);
const raw = Buffer.from(await response.arrayBuffer());
if (crypto.createHash('sha256').update(raw).digest('hex') !== archive.checksum_sha256) {
throw new Error('archive checksum mismatch');
}
return untar(zlib.gunzipSync(raw));
}
/** Your pipeline: chunk, embed and upsert this page (see the previous tutorial). */
function reprocess(url, markdown) {
console.log(` process ${url} (${markdown.length} chars)`);
}
/** Your pipeline: delete this page's chunks from the knowledge base. */
function remove(url) {
console.log(` remove ${url}`);
}
async function refresh(event) {
const files = await downloadArchive(event.archive);
const manifest = JSON.parse(files['manifest.json'].toString('utf8'));
const hashes = fs.existsSync(HASHES_FILE) ? JSON.parse(fs.readFileSync(HASHES_FILE, 'utf8')) : {};
let changed = 0;
let unchanged = 0;
let removed = 0;
for (const page of manifest.pages) {
if (page.state === 'done') {
if (hashes[page.url] === page.sha256) {
unchanged += 1;
continue;
}
reprocess(page.url, files[page.file].toString('utf8'));
hashes[page.url] = page.sha256;
changed += 1;
} else if (page.error_class === 'not_found' && page.url in hashes) {
remove(page.url); // the page is gone (404 or 410)
delete hashes[page.url];
removed += 1;
}
}
fs.writeFileSync(HASHES_FILE, JSON.stringify(hashes, null, 1));
console.log(`${event.job_id}: ${changed} new or changed, ${unchanged} unchanged, ` +
`${removed} removed (${event.credits_used} credits)`);
}
const app = express();
app.post('/hooks/crawl', express.raw({ type: '*/*', limit: '1mb' }), (req, res) => {
const raw = Buffer.isBuffer(req.body) ? req.body : Buffer.alloc(0); // the signature covers these exact bytes
if (!signatureOk(raw, req.get('X-Ujeebu-Timestamp') || '', req.get('X-Ujeebu-Signature') || '')) {
return res.sendStatus(401);
}
const webhookId = req.get('X-Ujeebu-Webhook-Id') || '';
if (seenIds.has(webhookId)) return res.sendStatus(200); // a retry of a call already accepted
seenIds.add(webhookId);
const event = JSON.parse(raw.toString('utf8'));
if (event.event !== 'crawl.job.completed') { // crawl.job.failed or crawl.job.cancelled
console.log(`${event.job_id}: ${event.event} (${event.stop_reason}), nothing to refresh`);
return res.sendStatus(200);
}
queue = queue.then(() => refresh(event)).catch((err) => console.error(`${event.job_id}: ${err.message}`));
return res.sendStatus(202); // answer at once; the refresh runs in the background
});
app.listen(process.env.PORT || 8000, () => console.log('Listening for crawl webhooks on /hooks/crawl'));