Runs live, versioned Python application objects on one VM, with a suite of apps: projects, notes, tasks, files and more.
Box-to-box exchange of business documents
Status: phase 0 is built, and phase 1's fixes for what the two-company simulation found (packages app-exchange and app-bills, root modules object_exchange and object_exchange_box). Two companies' boxes can become trading partners and send each other signed purchase orders, order confirmations, invoices, credit notes, remittances and goods receipts; each document is verified, stored verbatim, answered with a signed receipt and turned into the right local record. Since phase 1 a remittance can pay part of a bill or several bills, credit notes reduce both sides' balances, every line carries its unit, confirmations are compared and resolved line by line, disconnecting and refusing are signed notices the other side records, and one check says what a box needs to trade. What is built, how to use it and where it differs from the proposal come first; the proposal follows, unchanged except where it now says what was decided. Email fallback, the Peppol bridge, statements, despatch advice, three-way match and a directory are not built (see "What is left").
What is built (phase 0, as phase 1 left it)
| Piece | Where | What it does |
|---|---|---|
| Profile | GET /.well-known/dbbasic (core route) → site_exchange_profile | Domain, company name, exchange endpoint, Ed25519 public keys (active and retired, with key ids and rotation vouches), accepted document types, DRON document version, profile version; signed by the active key. 404 until the box is named, 409 naming the fix if the private key is missing. |
| Identity and keys | exchange_identity, exchange_keys; private keys in <data dir>/exchange/private/ | Domain and name set once (op=setup); the domain is then frozen. Private keys are 0600 files in a 0700 directory, outside every directory a runtime backup copies, never served or logged. Rotation (op=rotate_key) lists the old key as retired, deletes its private half, and has the old key sign (vouch for) the new one. |
| Trading partners | trading_partners, action_exchange_admin | connect fetches the partner's profile from its own domain, pins its keys and sends a signed request; the partner's owner sees it as pending (attention) and accepts, which checks the request was signed with the key the requester's domain publishes, pins its keys and answers. disconnect refuses everything from that partner from the next request on. set_types says which document types may cross in each direction. Admins and the owner role only. |
| Inbound | POST /webhooks/exchange (core raw-body route) → webhook_exchange | Checks in order (below), stores the raw body verbatim in exchange_inbox (frozen, unique on sender + document id), answers with a signed receipt. A resend stores nothing and returns the first receipt; the same id on a different document is refused. |
| Mapping | object_exchange_box._map_*, as the exchange_partner principal | See the table below. A document that cannot be mapped stays in the inbox, needs_attention, with the reason (attention), and op=remap retries it once a package is installed. |
| Outbound | action_exchange_send → exchange_outbox | Makes the signed envelope from a business record (one per record and type) and queues it. |
| Delivery | system_exchange_deliver, scheduled every three minutes | Posts each due document with a freshly signed delivery stamp, verifies the partner's receipt against its pinned keys and keeps it; a refusal stops the row (dead, attention, op=requeue); no answer backs off from 1 minute doubling to 6 hours, 12 attempts. |
| Supplier bills | app-bills: supplier_bills, supplier_bill_lines | The payable side. Received → approved → paid, by people only. An exchanged bill is the supplier's document and is frozen from creation. |
What each document becomes:
| Type | Sent from | At the receiver |
|---|---|---|
purchase_order | an orders row with doc_type: purchase (name the partner) | a draft sale order and its lines, owned by whoever accepted the partner; totals stamped by the mapper; lines that do not add up to the stated total are flagged |
order_confirmation | the sale order made from that purchase order (response derived from its lines; rejected answers every line rejected) | compared with our purchase order line by line; differences are attention until a person accepts (our order changed to match, recorded) or rejects them (action_exchange_resolve) |
invoice | an invoices row whose source order came from the partner's purchase order (or name the partner) | a supplier bill in received, linked to our purchase order; never paid automatically |
credit_note | an invoices row with doc_type: credit_note (credits_invoice_id names the invoice it credits); sending applies it there (invoice_credits) | a supplier bill of type credit note, applied to the bill it credits (supplier_bill_credits), or on account |
remittance | a supplier_payments row (app-bills): one transfer, its lines saying how much went to each bill | awaiting_confirmation: a claim, not money, marked as a part payment when it is one. A person who sees it in the bank confirms it (action_exchange_confirm_remittance), which records exactly those amounts under the payments collection's own rules, and refuses an amount above what the invoice owes after payments and credits |
receipt | an app-receiving receipt that is received | recorded against the sale order it answers |
The inbound checks, in order: body size (512 KiB) and shape; the sender is a connected partner (one answer for unknown and disconnected); the document's signature and the delivery stamp's signature are by keys pinned for that partner (a new key is pinned only when a pinned key vouched for it); both verify; the stamp names this envelope (by SHA-256) and is within the clock window (DBBASIC_EXCHANGE_CLOCK_WINDOW_SECONDS, default 300); the recipient is this box; the document is well formed; its type is one this partner may send and this box accepts; and (sender, document id) is new.
What phase 1 added (found by the two-company simulation)
Each row is a gap the BeanCo / Brewly simulation found on phase 0, and each is proven end to end on both boxes in tests/test_exchange_phase1.py.
| Gap | What is built |
|---|---|
| A 60% payment could not be said | Supplier payments (app-bills): supplier_payments is one transfer (date, reference, currency) spread over bills by supplier_payment_lines, each any amount. A bill's paid_cents, credited_cents and outstanding_cents are derived from those rows. Sending a payment (collection: supplier_payments) makes a remittance whose settles[] says exactly what was paid on each bill, possibly several bills of one supplier; then the payment is frozen (remitted). The seller records exactly those amounts once a person confirms them against the bank, and refuses an amount above what the invoice still owes after payments and credits. |
| A credit note reduced nobody's balance; the seller showed it as due | Credits that net. At the buyer a received credit note is applied in the same act that records it (supplier_bill_credits): to the bill it credits, or on account. At the seller, sending a credit note applies it as it says (invoice_credits, app-invoices). invoices.balance_due_cents is now total less paid less credits applied to it less what of the credit note itself was applied, so a credited invoice owes less and an applied credit note owes nothing. Invoice 374.00, 60% paid, 18.50 credited: both boxes say 131.10. Payment-driven invoice status is unchanged (a credit is not a payment). |
| 10 kg and 10 bags arrived alike | Units. order_lines, invoice_lines and supplier_bill_lines carry unit_code (UN/ECE Rec 20). A sent line uses the line's code, else its product's free-text unit coded (kg → KGM, bags → XBG), else C62; a unit nobody can code is refused. Quantities are decimal strings. |
| A confirmation was compared on its total; nothing resolved a difference | Line-level confirmations. The seller's confirmation answers each of the buyer's lines (ref_line_id, line_status accepted/changed/rejected/added; rejected lines are sent with quantity 0) and its response is derived from the lines. The buyer compares quantity, unit and price line by line and lists every difference as attention. action_exchange_resolve accepts (the purchase order is changed to match, each write in the change log under that person's name, totals restamped) or rejects. |
| Disconnecting or refusing told the other side nothing | Notices. Disconnecting sends a signed connection_end; the other box records the partner disconnected by them, with the reason, and stops sending. A document refused after the sender is proven (a type not taken, malformed, an id reused) is answered with a signed refusal receipt; a person can refuse any received document later (action_exchange_resolve decision refuse), which sends a signed document_refusal. Either way the sender keeps the signed refusal on its outbox row (refused, attention "Documents a partner refused") and the record it was made from says "Refused by <partner>: <reason>" (exchange_status). |
| Setup needed someone who knew the internals | The readiness check (action_exchange_admin op=check): trading name, signing key and where its backup is (op=record_key_backup), daemon and scheduler, totals reactions, who holds owner and manager, partners waiting, packages missing; each with its fix in plain words. Totals on send: a record never totalled is totalled the way the totals reactions would before it is sent; a stored total that disagrees with its lines is refused naming both. |
What is signed, added in phase 1:
- A refusal receipt is a receipt with
"status": "refused"and two more
keys, code (the refusal's stable code) and reason, signed by the refusing box; it comes back in the refusal's answer as refusal. Only a box that has verified the sender signs one; a stranger still gets the same unsigned not_a_partner as before.
connection_endanddocument_refusalare control envelopes, signed and
delivered like any document and never stored in the inbox. document_refusal's body is {document_id, envelope_sha256, code, reason} and names the refused document by its id and the hash of its envelope.
- A confirmation line may carry
ref_line_id(the buyer's line it answers)
and line_status; any line may carry unit_code. Unknown keys inside a line are still allowed, so a phase 0 box reads a phase 1 document.
The envelope
{
"dron_document": "0.1",
"id": "doc-6f1c...",
"type": "invoice",
"sender": "supplier.example",
"recipient": "shop.example",
"created_at": "2026-12-03T09:30:00Z",
"refs": [{"id": "doc-91ab...", "type": "purchase_order"}],
"body": {
"number": "INV-77", "issue_date": "2026-12-03", "due_date": "2027-01-02",
"currency": "EUR",
"lines": [{"line_id": "1", "description": "Widget", "quantity": "12",
"unit_code": "C62", "unit_price_minor": 1850,
"line_extension_minor": 22200, "tax_rate_bps": 0}],
"totals": {"line_extension_minor": 22200, "tax_minor": 0,
"payable_minor": 22200}
}
}
Field meanings, with their UBL 2.1 / EN 16931 equivalents (the Peppol bridge is a mapping of these names, not a redesign):
| Field | Meaning | UBL / EN 16931 |
|---|---|---|
id | the sender's unique id for this document; delivery is idempotent on (sender, id) | cbc:UUID |
type | purchase_order, order_confirmation, invoice, credit_note, remittance, receipt | Order, OrderResponse, Invoice, CreditNote, RemittanceAdvice, ReceiptAdvice |
refs[] | earlier documents this one answers, by id and type | cac:OrderReference, cac:BillingReference (BT-13, BT-25) |
body.number | the sender's own document number | cbc:ID (BT-1) |
body.issue_date, body.due_date | dates, YYYY-MM-DD | cbc:IssueDate (BT-2), cbc:DueDate (BT-9) |
body.currency | ISO 4217 code | cbc:DocumentCurrencyCode (BT-5) |
lines[].quantity | decimal string | cbc:InvoicedQuantity / cbc:Quantity (BT-129) |
lines[].unit_code | UN/ECE Recommendation 20 code (C62 one, H87 piece) | @unitCode (BT-130) |
lines[].unit_price_minor | net unit price, integer minor units | cac:Price/cbc:PriceAmount (BT-146) |
lines[].line_extension_minor | line net amount, integer minor units | cbc:LineExtensionAmount (BT-131) |
lines[].tax_rate_bps | tax rate in basis points (2000 = 20%) | cbc:Percent (BT-152) |
totals.line_extension_minor | sum of line net amounts | cbc:LineExtensionAmount (BT-106) |
totals.charge_minor | document-level charges (carriage) | cbc:ChargeTotalAmount (BT-108) |
totals.tax_minor | tax total | cac:TaxTotal/cbc:TaxAmount (BT-110) |
totals.payable_minor | amount due | cbc:PayableAmount (BT-115) |
body.response (confirmation) | accepted, rejected, amended | cbc:OrderResponseCode |
lines[].ref_line_id, lines[].line_status (confirmation) | the buyer's line this answers; accepted, changed, rejected, added | cac:OrderLineReference/cbc:LineID, cbc:LineStatusCode |
body.paid_minor, paid_on, payment_reference, settles[] (remittance) | amount paid, date, structured reference (ISO 11649 RF...), and the invoices settled with their amounts | cbc:PaidAmount, cbc:PaidDate, cbc:PaymentID, cac:InvoiceDocumentReference |
body.received_on, lines[].quantity_received, quantity_rejected (receipt) | goods received | cbc:ReceivedQuantity, cbc:RejectedQuantity |
Money is always an integer in minor units with an ISO 4217 code; a float anywhere in a document is refused.
What is signed, exactly
The canonical serialisation of a JSON value is json.dumps(value, sort_keys=True, separators=(",", ":"), ensure_ascii=False, allow_nan=False) encoded as UTF-8: keys sorted, no whitespace, strings as UTF-8. Floats are refused (they are where JSON libraries disagree), and object keys must be ASCII (where code-point and UTF-16 key order would differ), which makes the form byte-for-byte RFC 8785 (JCS) for every valid document; another engine can use a JCS library.
What goes on the wire is:
{"dron_delivery": "0.1",
"envelope": {...},
"signature": {"alg": "ed25519", "key_id": "ed25519:690b13c16d90c9cc", "value": "<base64url>"},
"delivery": {"sender": "...", "recipient": "...", "envelope_sha256": "<hex>",
"sent_at": "2026-12-03T09:30:05Z"},
"delivery_signature": {"alg": "ed25519", "key_id": "...", "value": "..."},
"key_vouches": [...]}
signatureis a detached Ed25519 signature over the canonical bytes of
envelope. It is made once and kept forever by both sides.
delivery_signatureis over the canonical bytes of
{"dron_delivery": "0.1", ...delivery}, signed afresh on every attempt. The clock window applies to it, so a captured request cannot be replayed later while a retried document can be days old.
- The receipt is `{"dron_receipt": "0.1", document_id, document_type, sender,
recipient, envelope_sha256, received_at, "status": "stored"}`, signed by the receiver over its canonical bytes.
- A vouch is the old key's signature over
{"dron_key_vouch": "0.1", key_id, public_key} of the new key.
- A key id is
ed25519:plus the first 16 hex characters of the SHA-256 of
the raw 32-byte public key; public keys and signatures are base64url without padding. Each signed object carries its own marker key, so a signature over one can never be presented as another.
How to use it
- Install the extra on each box:
pip install 'dbbasic-object-server[exchange]'
(it adds cryptography). Without it every exchange call answers 409 and says to install it; nothing else on the box changes.
- Install the packages:
app-exchange, plusapp-orders(purchase orders
and sale orders), app-invoices and app-payments (to invoice and be paid), app-bills (to receive invoices), app-receiving (goods receipts). A document whose target package is missing waits in the inbox and can be remapped later.
- Name the box, as an admin or a user with the
ownerrole:
POST /objects/action_exchange_admin {"op": "setup", "domain": "shop.example", "company_name": "Shop Ltd"}. The domain must be the one the box is served on over HTTPS; it cannot be changed later. Check GET /.well-known/dbbasic.
- Back up the private key yourself. It is
<data dir>/exchange/private/<hex>.key, and no runtime backup includes it. Keep it with your other deployment secrets. A box restored without it refuses to sign until it is put back or the key is rotated (and partners then reconnect).
- Connect:
{"op": "connect", "domain": "supplier.example"}. The supplier's
owner sees "Partners asking to connect" on the home page, finds the row in trading_partners and sends {"op": "accept", "partner_id": "..."}. Narrow what crosses with {"op": "set_types", "partner_id": "...", "receive_types": ["order_confirmation", "invoice", "credit_note"]}.
- Check the box:
{"op": "check"}answers ready or not, with one finding
and one fix per thing (key backup, daemon, totals reactions, roles, partners, packages). After backing up the key, say where: {"op": "record_key_backup", "where": "1Password, vault Ops"}.
- Send a record: `POST /objects/action_exchange_send {"collection": "orders",
"record_id": "...", "partner": "supplier.example"}. The caller must be staff (an admin, the owner role or role:manager; a plain registered user is a customer) and allowed to update the record. Give the people who run the books role:manager: invoice money, payments and order status are theirs. The daemon delivers within three minutes (the daemon needs the scheduler extra for its cron schedules); see the result in exchange_outbox or on /exchange. A line's unit is its unit_code, or its product's unit` coded; a record never totalled is totalled on send, and one whose total disagrees with its lines is refused with both numbers.
- Look at what arrived on
/exchange. Supplier invoices are on/bills,
waiting to be approved. To pay, record a supplier_payments row (date, reference, currency, supplier) and one supplier_payment_lines row per bill with the amount paid on it (any amount; several bills at once), then send the payment (collection: supplier_payments). A bill's outstanding_cents is what is left after payments and credits. At the supplier, a remittance waits under "Remittances to confirm against the bank" until somebody confirms it: POST /objects/action_exchange_confirm_remittance {"inbox_id": "..."} (staff who may record a payment: role:manager or an admin).
- A credit note: an
invoicesrow withdoc_type: credit_noteand
credits_invoice_id; sending it applies it to that invoice on both boxes. There is one credit-note model. A credit note issued at the counter (action_counter_correct, settle credit_note: it cites the order line, carries a reason code and an approval, and never credits more than was sold) is the same kind of row, already applied by its own invoice_credits row (source counter), and is sent the same way. A credit-note line that names the credited invoice's line (invoice_lines.credits_line_id, stamped by the counter, settable by staff) is sent with ref_line_id naming it. A line of an invoice that was sent is not voided at the counter: it is credited.
- A confirmation that differs from your order is attention, listing each
line. Decide: POST /objects/action_exchange_resolve {"inbox_id": "...", "decision": "accept"} (or "reject"). To refuse any received document: {"decision": "refuse", "note": "why"}; the sender is told.
- Rotate the key when needed:
{"op": "rotate_key"}. Partners pin the new
key from the vouch carried on your next delivery; what the old key signed still verifies. Record the new key's backup again.
- End a relationship: `{"op": "disconnect", "partner_id": "...", "reason":
"..."}`; the partner's box is told and shows you disconnected.
How phase 0 differs from the proposal below
- Document type names follow the business words people use
(purchase_order, order_confirmation, receipt) rather than order/order_response/despatch_advice; credit_note and remittance moved into phase 0, despatch_advice and statement did not.
- JSON envelope, not UBL XML (open decision 1): field meanings are named
after UBL / EN 16931 above.
- Request signatures are a signed delivery stamp inside the JSON body,
not RFC 9421 HTTP Message Signatures: the stamp is checked with the same code as the document, and it survives proxies that rewrite headers.
- Profile carries domain, company name, endpoint, keys, types and
versions; no separate box id, country or tax ids yet. It is signed by its active key, but trust comes only from the keys pinned when partners connected.
- Key rotation keeps every retired public key listed and has the old key
vouch for the new one; a key nobody pinned vouched for is refused, and the partner must reconnect. Key storage (open decision 2): a 0600 file under the data directory, excluded from runtime backups; who may rotate: admins and the owner role.
- The inbox is
exchange_inbox(frozen bylocked_whenfrom creation;
unique on sender + id), and the outbox exchange_outbox.
- Mapping is code in
object_exchange_box, one function per type; what
it may write is declared, as permission rules granting the exchange_partner role create on exactly orders, order_lines, supplier_bills and supplier_bill_lines. Moving "which type becomes which record" into package manifests is left for phase 1.
- What is automatic (open decision 3): received purchase orders become
draft orders; invoices become bills waiting for approval and are never paid; remittances record nothing until a person confirms them.
Proven: two companies traded (2026-11-30)
Phase 0 was run as a two-company simulation the day it was built: an AI agent played the owners of BeanCo Roasters (supplier) and Brewly (café, buyer), each on its own box with its own data, keys and users, plus an attacker on a third box that was never connected. Everything went through each box's HTTP API; nothing was retyped between the companies.
- Brewly asked to connect, BeanCo accepted; both sides showed connected.
- Brewly's purchase order (3 lines, 411.00) became a draft sale order at
BeanCo with the same lines and total.
- BeanCo shipped 8 of 10 kg and confirmed 374.00 as "amended"; Brewly's side
flagged the difference as attention and left its own order alone.
- BeanCo's invoice became a supplier bill at Brewly in
received, paid by
nothing but a person.
- Brewly's remittance waited at BeanCo as awaiting confirmation; a clerk
could not confirm it, a manager could, and only then was the payment recorded and BeanCo's invoice settled.
- BeanCo's credit note for a damaged kilogram arrived linked to the bill it
credits.
- Two failed deliveries were retried with backoff and arrived once; a
resend and a byte-for-byte replay were recognised and stored nothing new; BeanCo rotated its key mid-way and kept trading.
- Refused: an invoice "from BeanCo" signed with the attacker's key
(key_not_pinned), the attacker's own unconnected domain (not_a_partner), BeanCo's real invoice with the amount edited (bad_signature), a remittance replayed after the clock window (stale_delivery), and an invoice sent after Brewly disconnected BeanCo.
- Document ids matched on both sides throughout.
Limits of that proof: both boxes ran in one process with an in-process transport (sockets blocked), so real HTTPS, DNS and two machines are not yet exercised; the delivery pass was ticked by hand instead of by the daemon; the bank match was a person's confirmation.
What is left
- From the simulation, still open:
- settled (the owner's decision of 2026-11-30): an issued invoice's
total never changes and its status follows the money
(`object_corrections.money_status`): fully credited reads `credited`,
credited and paid back reads `refunded`, a credit on a paid bill reads
`credit_owed`, and a refund with no credit note reopens the invoice.
The payments hook's overpayment ceiling now subtracts the credit notes
applied to the invoice, so a payment typed by hand meets the same
balance the exchange's confirm checks;
- a credit note made by hand and never sent has no
invoice_creditsrow
and still reads its total as a balance due until someone applies it (the
formula language cannot branch on `doc_type`, so the application row is
what zeroes it). One issued at the counter (app-counter's
`action_counter_correct`) is applied in the act that issues it (source
`counter`), so it nets at once; sending it later applies nothing twice;
- rejecting an amended confirmation is recorded here and not sent to the
seller; a counter-offer is a new purchase order;
- with the totals reactions off a seller who edits lines must restamp the
total before sending (the send refuses and says so); the check
recommends turning change dispatch on;
- the readiness check is an action that answers JSON; a page for it is
not built.
- Email fallback (phase 3): not built. A partner without a box gets
nothing from the exchange.
- Phase 1, rest: despatch advice; three-way match of a bill against the
purchase order and goods receipt before approval (locked_checks); posting supplier bills and payments to the books; mapping declared in package manifests rather than code; linking a partner to a local contact or organization; the order totals and other reactions running through the change dispatcher instead of the mapper stamping them; per-partner rate limits; a disconnect notice is sent once, so a partner that was down at that moment is not told later (it is refused all the same).
- Phase 2 and 3:
statement, the Peppol bridge, an opt-in directory,
the change log's hash chain that would make document hashes there tamper-evident.
- Large documents by reference (pull) and multi-recipient delivery.
The rest of this page is the proposal as agreed, kept for its reasoning.
Why
A simulation of two companies, a shop buying from a supplier, each on its own box, closed the whole purchase cycle with both books agreeing. But every step that crossed from one company to the other was retyped by hand: the supplier keyed in the shop's order, the shop keyed in the supplier's invoice, each side keyed in the payment. The two boxes shared no identifiers, so nothing could say that the shop's purchase order 1042 and the supplier's sales order SO-77 were the same order. Agreement at the end was reached by people, not by the boxes.
The goal is that one company's box can send a business document to another company's box, the receiving box can check who sent it and that it was not altered, and the document becomes the right local record with both sides holding the same identifiers and the same evidence.
Options considered
None of these is rejected outright; each is not enough on its own.
- Email only. Everyone has it and the outbox already sends it. But a PDF in
an inbox is for a human to read and retype; there is no identity beyond a forgeable From line, no receipt, no idempotency, no structure. It stays as the fallback (phase 3), not the base.
- Each box calls the other's record API with keys. Works for two boxes you
run both of. It makes every company hand out write credentials into its own books, tied to its own schema, and the other side must know your collection names. A partner should be able to deliver a document, not edit records.
- A central hub. One place that routes and stores everyone's documents is
simple to reason about and is exactly the dependency, cost and single point of failure a self-hosted box exists to avoid.
- EDI (X12 or EDIFACT over AS2). The established answer, with signed
documents and signed receipts (MDNs). We borrow the ideas (signed receipt, store-and-forward, document types in a fixed order). We do not adopt the formats or the toolchain: they are expensive to implement and unfriendly to small companies.
- Peppol (UBL, EN 16931, through access points). The right interoperability
target for invoices across companies on other software and for public-sector buyers. It needs a registered access point and network membership, so it is a later bridge. Field meanings in our envelope follow UBL and EN 16931 so the bridge is a mapping, not a redesign.
- ActivityPub-style federation. We borrow the shape: an actor with an
inbox, delivery by signed HTTP POST, and the actor's key published at a known URL. We do not borrow social semantics or open-world delivery; trading partners here are an explicit, mutual allow list.
- Blockchain. Not needed. What it would give this case is authorship, tamper
evidence and a shared record, and signed documents plus a hash-chained change log (see "Proof and reconciliation") provide them between two parties without a ledger nobody asked to run.
The design
1. Identity: the domain is the company
A box is identified by the domain it is served from. It publishes a signed profile at /.well-known/dbbasic:
- box id (stable, so a domain change does not orphan history)
- legal name, country, tax ids
- inbox URL
- Ed25519 public key, plus the previous public key for rotation
- accepted document types
- the DRON document version it speaks (see dron.md)
The profile is signed by the key it carries, so a copy fetched later can be checked against the pinned fingerprint (below). Trust comes from the partner relationship, not from the profile alone.
2. Trading partners: explicit, mutual, revocable
Documents are accepted only from a partner. A relationship is made by:
- one owner sends a connection request naming their box;
- the other box's owner accepts it;
- each side pins the other's key fingerprint at that moment;
- each side records, per direction, which document types are allowed;
- each side links the partner to a local contact or entity record, so a
received order lands under a known customer.
Either side can revoke at any time; once revoked, every later document is refused. A key change by a partner is accepted only through the rotation fields in the profile (new key vouched for by the pinned one); otherwise the partner is suspended until an owner re-confirms.
3. The document envelope
Every document is one DRON document: JSON, versioned, signed. A short and illustrative example, as proposed (the built envelope is described under "The envelope" at the top of this page):
{
"dron_document": "0.1",
"id": "doc_01J9ZK3Q7V8M2N4P5R6S",
"type": "order",
"issued_at": "2026-12-01T09:30:00Z",
"from": "shop.example",
"to": "supplier.example",
"refs": {"buyer_number": "PO-1042", "in_reply_to": null},
"body": {
"currency": "EUR",
"lines": [
{"seller_sku": "WID-10", "buyer_sku": "A-553", "gtin": "04012345678901",
"quantity": 12, "unit": "H87", "unit_price": 1850}
]
},
"sha256": "<hash of the canonical body>",
"signature": "<Ed25519 signature over the canonical document>"
}
Rules:
idis globally unique and is what makes delivery idempotent.refscarriesin_reply_to(the id of the document this answers) and each
side's own number (buyer_number, seller_number), so both sides can find the record on their own side.
- Money is an integer in minor units with an ISO 4217 currency code
(1850 is 18.50 EUR). Quantities use UN/ECE unit codes (H87 is "piece"). Lines can carry the seller's SKU, the buyer's SKU and a GTIN.
- Field meanings follow UBL and EN 16931 wherever an equivalent exists.
sha256andsignatureare over a canonical serialisation of the document.
Document types, in the order they would be built: order, order_response, despatch_advice, invoice, credit_note, remittance, statement.
4. Transport
- Push over HTTPS, signed with HTTP Message Signatures (RFC 9421), to the
partner's inbox URL.
- A signed receipt returns from the receiving box once the document is
stored (in the spirit of an AS2 MDN). The sender records it against the document. A receipt means "stored and passed the checks", not "accepted by the business".
- Store-and-forward. Sending is a record in an outgoing collection, drained
by the daemon with retries and backoff, the way the existing email outbox is (see write-pipeline.md and the email_outbox collection in app-packages.md). A partner that is down for a day costs a delay, not a lost order.
- Idempotency. The receiver's inbox declares the document
idunique
(validation-and-logic.md), so a retry of something already stored is recognised and answered with the same receipt.
- Pull for large documents. The envelope carries a URL and hash; the
receiver fetches the body.
- Email fallback: a human-readable PDF with the signed JSON attached
(the hybrid idea of Factur-X), for partners with no reachable box.
5. Inbound handling
A received document passes checks first, in order: the sender is an active partner, the signature verifies against the pinned key, the type is allowed in that direction, and size and rate limits hold. Only then is it written, verbatim, to an inbox_documents collection that is append-only and frozen with locked_when (validation-and-logic.md), so what arrived cannot be edited afterwards by anyone.
Turning the document into local records is declared by packages, not coded per partner. For example, app-orders would declare that it receives order and creates a sales order, and a future supplier-bills package would declare that it receives invoice and creates a bill. The mapping runs as a narrow partner principal under the normal permission engine (permissions-model.md), which can create the mapped records and nothing else. Relations the mapping writes carry requires like any other writer's (permissions-model.md).
Two firm rules:
- Invoices are never paid automatically. A received invoice becomes a bill
waiting for a person.
- Three-way match. A bill is checked against the purchase order and the
receipt (or despatch advice) before it can be approved; a mismatch is shown, not corrected silently. A decision across collections like this is the job of locked_checks (validation-and-logic.md).
6. Proof and reconciliation
Both sides keep the signed original and every receipt. Each document's hash is also recorded in the change log; the log becomes tamper-evident once it is hash-chained, which does not exist yet and is a dependency of that claim, not something this proposal provides. Periodically a statement document lists a side's open items by document id, so the other side compares ids rather than re-reading PDFs; differences are listed, not auto-fixed.
7. Payments
Money never moves between boxes. A remittance document tells the payee that a payment was made: amount, currency, the invoice ids it settles and a structured reference (an ISO 11649 RF creditor reference) that the payee's bank import can match to the invoice. The bank statement stays the proof of payment.
Security summary
- Authenticity: Ed25519 signatures on documents and on HTTP requests; keys
pinned per partner; rotation only through the pinned key.
- Authorisation: explicit mutual partner list, per-direction document types,
revocable at any time; a partner principal that can only create mapped records.
- Integrity: sha256 and signature; inbox rows frozen by
locked_when; hashes in
the change log.
- Replay and duplication: globally unique
idenforced byunique. - Abuse: size and rate limits before storage; unknown senders refused before
any parsing beyond the headers.
- Money: no automatic payment, ever; three-way match before a bill is approved.
- Secrets: the private signing key is the most sensitive item on the box; how
it is held is an open decision below.
Why it fits dbbasic
Most of it is declarations over mechanisms that exist: the outbox and daemon for delivery, unique for idempotency, locked_when for an immutable inbox, locked_checks for cross-record decisions, relations with requires and the permission engine for what a partner may touch, the change log for evidence. Exchange itself would be declared in packages (which document type creates which record), in the style of dron.md, rather than written as per-partner code. And it is peer to peer: no hub, no shared database, each company keeps its own box.
Phased plan
- Phase 0 (built). Identity profile, trading partners, inbox, signed
order and invoice. Measured by rerunning the two-company simulation with zero retyped steps across the boundary: tests/test_exchange_documents.py does this between two boxes, and as built phase 0 also carries the order confirmation, remittance, credit note and goods receipt, and the supplier bills package (see "What is built" at the top).
- Phase 1.
order_response,despatch_advice,remittance; a supplier
bills package; sales order to invoice and purchase order to bill linking.
- Phase 2.
statement,credit_note. - Phase 3. Email fallback, Peppol bridge, an opt-in directory.
Open decisions for the owner
- JSON envelope or UBL XML from day one. JSON is far simpler to build and
test now; UBL XML removes a later mapping for the Peppol bridge. Phase 0 built JSON, with UBL / EN 16931 meanings named per field.
- Key storage and protection. Where the Ed25519 private key lives
(see secrets-and-credentials.md), who can rotate it, and what happens if it leaks. Phase 0: a 0600 file under the data directory, outside runtime backups; admins and the owner role rotate. If it leaks: rotate (the old key vouches for the new one, so partners follow), and since the leaked key can vouch too, have each partner disconnect and reconnect, which re-pins from the profile. Revoking a leaked key without reconnecting is not built.
- What is automatic per partner. Proposed default: orders opt-in per
partner, invoices never automatic. Phase 0: a purchase order becomes a draft (nothing is committed until a person confirms the order); invoices are never paid; set_types switches a type off per partner and direction. A per-partner opt-in for orders is not built.
- An opt-in directory so companies can find each other's boxes, versus
exchanging profiles by hand.
- When to build the Peppol bridge, given it needs an access point and
membership.