askrobots / dbbasic-object-server
Public
Runs live, versioned Python application objects on one VM, with a suite of apps: projects, notes, tasks, files and more.
document.py · 13.6 KB · 344 lines
| 1 | """site_document -- the link a document was delivered as. GET /d/{token}. |
| 2 | |
| 3 | THE RULE THIS PAGE EXISTS TO ENFORCE: |
| 4 | |
| 5 | A document that was SENT is evidence of what was sent. |
| 6 | |
| 7 | This page renders the SNAPSHOT stored on the sent_documents row, not the live |
| 8 | record. Email a quote at 4,000, change the price to 4,500, and the customer's |
| 9 | link must not silently show 4,500 -- they may be holding a printout of the |
| 10 | first one. Silently restating a document somebody was sent is the same class of |
| 11 | error as restating an approved rate or a rolled-up invoice total |
| 12 | (docs/logic-decisions.md #1 and #8), and it is worse here than in the ledger, |
| 13 | because the counterparty has a copy and we do not know it. |
| 14 | |
| 15 | A changed source is not hidden either -- hiding it would be the other half of |
| 16 | the same lie. When the live record no longer matches the fingerprint taken at |
| 17 | send time, the page keeps serving the snapshot and adds a banner naming BOTH |
| 18 | dates (sent on X; changed on Y) with a link to the current version at |
| 19 | /d/{token}?v=current. The reader chooses which one they are looking at, and the |
| 20 | page always says which one it is showing. |
| 21 | |
| 22 | Change detection compares object_records.client_record_rev of the live record |
| 23 | against the source_rev stamped when the document was sent (a row sent before |
| 24 | 0.1.3 holds compute_record_rev instead, which is still accepted). A content |
| 25 | fingerprint rather than a timestamp: a record edited in the same second it was |
| 26 | sent would slip past a timestamp comparison, and that is exactly the case where |
| 27 | the two documents differ. When the source cannot be read at all (the row was |
| 28 | deleted, the package removed), the answer is "cannot tell" and NO banner is |
| 29 | shown -- inventing "it changed" would be as wrong as inventing "it did not". |
| 30 | |
| 31 | ACCESS, in the posture site_invoice_portal established and this reuses |
| 32 | verbatim: the token is the whole credential, looked up BY TOKEN ONLY and never |
| 33 | by id, matched with hmac.compare_digest (a plain `==` on attacker-controlled |
| 34 | input leaks how many leading characters matched, via how long it took -- the |
| 35 | exact side channel a bearer token exists to close). A blank token matches |
| 36 | nothing, so a row whose token was never minted is not an accidental open door. |
| 37 | An unknown token gets the SAME "not found" page, at 404, as a document that |
| 38 | never existed -- never 403, because a 403 confirms the token namespace is worth |
| 39 | attacking, while "not found" makes a guess and a typo indistinguishable. |
| 40 | |
| 41 | No nav, no global search, no chrome beyond the shared stylesheet: somebody |
| 42 | following an emailed link must never be one click from another customer's |
| 43 | paperwork or from a sign-in wall for a system they have no account on. |
| 44 | |
| 45 | opened_at is stamped on first view and never restamped -- "did they read it?" |
| 46 | is the first thing anybody asks after sending a quote, and it comes free with a |
| 47 | tokened link. Idempotent by construction (written only when the field is |
| 48 | empty), and best-effort: no read receipt is worth breaking the page somebody is |
| 49 | actively trying to read. |
| 50 | |
| 51 | **The stamp is a POST the rendered page sends, never a side effect of the |
| 52 | GET** (bug-reports/2026-11-28-06-14-54). A GET is supposed to be safe, and in |
| 53 | an inbox it is not even a person: mail security scanners and link |
| 54 | prefetchers GET every link in a message on delivery, so a GET-side stamp |
| 55 | answered "did they read it?" with "yes" for a quote nobody had looked at -- |
| 56 | and wrote to the record, bumping its rev, for anybody holding the link. The |
| 57 | page now carries one line of script that POSTs back to its own URL |
| 58 | (navigator.sendBeacon) once it is open in a browser; POST /d/{token} does the |
| 59 | stamp and nothing else. A reader with scripts off goes unrecorded, which is |
| 60 | the honest failure for a read receipt: "not seen" rather than "seen" by a bot. |
| 61 | |
| 62 | The PDF button is drawn only when a PDF engine is actually configured |
| 63 | (object_documents.pdf_engine_status), which today is never. Print -> Save as |
| 64 | PDF already works and the page says so instead. |
| 65 | """ |
| 66 | |
| 67 | import hmac |
| 68 | import html |
| 69 | import os |
| 70 | from datetime import datetime, timezone |
| 71 | |
| 72 | import object_documents |
| 73 | import object_money |
| 74 | import object_record_changes |
| 75 | import object_records |
| 76 | |
| 77 | ACTOR = "site_document" |
| 78 | COLLECTION = "sent_documents" |
| 79 | |
| 80 | |
| 81 | def _base_dir(): |
| 82 | return os.environ.get("DBBASIC_DATA_DIR", "data") |
| 83 | |
| 84 | |
| 85 | def _text(value): |
| 86 | return str(value if value is not None else "").strip() |
| 87 | |
| 88 | |
| 89 | def _settings(base): |
| 90 | values = {} |
| 91 | try: |
| 92 | # access: box configuration |
| 93 | for row in object_records.read_collection_records("app_settings", |
| 94 | base_dir=base): |
| 95 | key, value = _text(row.get("key")), _text(row.get("value")) |
| 96 | if key and value: |
| 97 | values[key] = value |
| 98 | except Exception: |
| 99 | pass |
| 100 | return values |
| 101 | |
| 102 | |
| 103 | def _find_by_token(base, token): |
| 104 | """The only lookup this page performs: a full scan matched in constant |
| 105 | time, never a keyed lookup by id. A blank token matches nothing.""" |
| 106 | token = _text(token) |
| 107 | if not token: |
| 108 | return None |
| 109 | try: |
| 110 | # access: capability link: reached only through the sent document's secret token |
| 111 | rows = object_records.read_collection_records(COLLECTION, base_dir=base) |
| 112 | except Exception: |
| 113 | return None |
| 114 | for row in rows: |
| 115 | candidate = _text(row.get("token")) |
| 116 | if not candidate: |
| 117 | continue |
| 118 | if hmac.compare_digest(candidate, token): |
| 119 | return row |
| 120 | return None |
| 121 | |
| 122 | |
| 123 | def _stamp_opened(base, row): |
| 124 | """Once, ever. Written only when opened_at is empty, so a reader who |
| 125 | refreshes twenty times still opened it once -- and every failure is |
| 126 | swallowed, because a read receipt is not worth a broken page.""" |
| 127 | if _text(row.get("opened_at")): |
| 128 | return |
| 129 | try: |
| 130 | now = datetime.now(timezone.utc).isoformat().replace("+00:00", "Z") |
| 131 | # access: capability link: reached only through the sent document's secret token |
| 132 | object_records.update_collection_record( |
| 133 | COLLECTION, row["id"], {"opened_at": now}, |
| 134 | base_dir=base, actor=ACTOR) |
| 135 | except Exception: |
| 136 | pass |
| 137 | |
| 138 | |
| 139 | def _source_record(base, source): |
| 140 | """The live record behind a sent document, or None when it cannot be |
| 141 | read at all -- which is 'cannot tell', not 'unchanged'.""" |
| 142 | source = _text(source) |
| 143 | if source.count("/") != 1: |
| 144 | return None |
| 145 | collection, _, record_id = source.partition("/") |
| 146 | if not _text(collection) or not _text(record_id): |
| 147 | return None |
| 148 | try: |
| 149 | # access: capability link: reached only through the sent document's secret token |
| 150 | record = object_records.get_collection_record(_text(collection), |
| 151 | _text(record_id), |
| 152 | base_dir=base) |
| 153 | except Exception: |
| 154 | return None |
| 155 | return record or None |
| 156 | |
| 157 | |
| 158 | def _changed_on(base, source): |
| 159 | """The day the source last changed, from the record change log. Best |
| 160 | effort: the banner is better with a date and still true without one.""" |
| 161 | source = _text(source) |
| 162 | if source.count("/") != 1: |
| 163 | return "" |
| 164 | collection, _, record_id = source.partition("/") |
| 165 | try: |
| 166 | page = object_record_changes.list_record_changes( |
| 167 | _text(collection), record_id=_text(record_id), base_dir=base, |
| 168 | limit=1, tail_only=True) |
| 169 | except Exception: |
| 170 | return "" |
| 171 | changes = page.get("changes") or [] |
| 172 | if not changes: |
| 173 | return "" |
| 174 | return _text(changes[0].get("timestamp"))[:10] |
| 175 | |
| 176 | |
| 177 | def _live_model(base, row, settings): |
| 178 | """Re-render the CURRENT version of the document from the live record. |
| 179 | |
| 180 | Only reached from ?v=current -- an explicit request for the other thing. |
| 181 | Uses the same pure fold the snapshot was built with, so "current" and |
| 182 | "sent" cannot be two renderers that drift. |
| 183 | """ |
| 184 | kind = _text(row.get("kind")) |
| 185 | try: |
| 186 | spec = object_documents.source_spec(kind) |
| 187 | except object_documents.UnknownKindError: |
| 188 | return None |
| 189 | if spec is None: |
| 190 | return None |
| 191 | record = _source_record(base, row.get("source")) |
| 192 | if record is None: |
| 193 | return None |
| 194 | |
| 195 | record_id = _text(row.get("source")).partition("/")[2] |
| 196 | lines = [] |
| 197 | if spec.get("lines_collection"): |
| 198 | try: |
| 199 | # access: capability link: reached only through the sent document's secret token |
| 200 | rows = object_records.read_collection_records( |
| 201 | spec["lines_collection"], base_dir=base) |
| 202 | lines = [line for line in rows |
| 203 | if _text(line.get(spec["lines_fk"])) == record_id] |
| 204 | lines.sort(key=lambda line: _text(line.get("description"))) |
| 205 | except Exception: |
| 206 | lines = [] |
| 207 | |
| 208 | currency = _text(record.get("currency")) or "USD" |
| 209 | |
| 210 | def money(cents): |
| 211 | try: |
| 212 | return object_money.format_amount(cents or 0, currency, base_dir=base) |
| 213 | except Exception: |
| 214 | return f"{cents or 0} (minor units)" |
| 215 | |
| 216 | facts = object_documents.facts_from_records(kind, record, lines, money=money) |
| 217 | try: |
| 218 | return object_documents.build_model(kind, facts, settings, |
| 219 | require_business=False) |
| 220 | except object_documents.DocumentError: |
| 221 | return None |
| 222 | |
| 223 | |
| 224 | def _esc(value): |
| 225 | return html.escape(_text(value)) |
| 226 | |
| 227 | |
| 228 | def _not_found(): |
| 229 | return { |
| 230 | "status": 404, |
| 231 | "content_type": "text/html; charset=utf-8", |
| 232 | "body": """<!doctype html> |
| 233 | <html lang="en"> |
| 234 | <head> |
| 235 | <meta charset="utf-8"> |
| 236 | <meta name="viewport" content="width=device-width, initial-scale=1"> |
| 237 | <meta name="referrer" content="no-referrer"> |
| 238 | <title>Not found</title> |
| 239 | <link rel="stylesheet" href="/style"> |
| 240 | </head> |
| 241 | <body> |
| 242 | <div style="max-width:34rem;margin:0 auto;padding:3rem 1.25rem;text-align:center"> |
| 243 | <h1>Not found</h1> |
| 244 | <p>This document link is not valid. It may have been mistyped, or the business |
| 245 | that sent it may have issued a newer one. Contact them for a fresh link.</p> |
| 246 | </div> |
| 247 | </body> |
| 248 | </html>""", |
| 249 | } |
| 250 | |
| 251 | |
| 252 | def _changed_banner(token, sent_on, changed_on): |
| 253 | """Both dates, named, with the way to the other version. |
| 254 | |
| 255 | Not a warning colour and not an apology: documents change, and the only |
| 256 | unacceptable outcome is a reader who cannot tell which one they have. |
| 257 | """ |
| 258 | when = (f" on {_esc(changed_on)}" if changed_on else " since") |
| 259 | return ( |
| 260 | '<div class="doc-banner"><strong>You are reading the version that was ' |
| 261 | f'sent to you on {_esc(sent_on)}.</strong>' |
| 262 | f'This document was changed{when}. ' |
| 263 | f'<a href="/d/{_esc(token)}?v=current">See the current version</a>.' |
| 264 | "</div>") |
| 265 | |
| 266 | |
| 267 | def _current_banner(token, sent_on, changed_on): |
| 268 | when = (f" on {_esc(changed_on)}" if changed_on else "") |
| 269 | return ( |
| 270 | '<div class="doc-banner"><strong>This is the CURRENT version of this ' |
| 271 | f'document, changed{when}.</strong>' |
| 272 | f'The version sent to you on {_esc(sent_on)} is ' |
| 273 | f'<a href="/d/{_esc(token)}">still here</a>, unchanged.' |
| 274 | "</div>") |
| 275 | |
| 276 | |
| 277 | def GET(request): |
| 278 | base = _base_dir() |
| 279 | row = _find_by_token(base, request.get("token")) |
| 280 | if row is None: |
| 281 | return _not_found() |
| 282 | |
| 283 | settings = _settings(base) |
| 284 | |
| 285 | try: |
| 286 | snapshot = object_documents.model_from_snapshot(row.get("snapshot")) |
| 287 | except object_documents.DocumentError: |
| 288 | # The snapshot is the document. A half-parsed one is not evidence of |
| 289 | # anything, and rendering something else under this link is exactly |
| 290 | # what this page exists to prevent. |
| 291 | return _not_found() |
| 292 | |
| 293 | token = _text(row.get("token")) |
| 294 | sent_on = _text(row.get("sent_at"))[:10] |
| 295 | |
| 296 | # Has the source moved since we froze it? An exact question, asked of the |
| 297 | # platform's own record fingerprint. Blank on either side means "cannot |
| 298 | # tell", which shows no banner rather than a false one. |
| 299 | stored_rev = _text(row.get("source_rev")) |
| 300 | live = _source_record(base, row.get("source")) if stored_rev else None |
| 301 | changed = False |
| 302 | if live is not None: |
| 303 | try: |
| 304 | collection = _text(row.get("source")).partition("/")[0] |
| 305 | # Rows sent before 0.1.3 hold the unkeyed fingerprint; either |
| 306 | # matching means the source is as it was sent. |
| 307 | changed = (object_records.client_record_rev(collection, live, base_dir=base) != stored_rev |
| 308 | and object_records.compute_record_rev(live) != stored_rev) |
| 309 | except Exception: |
| 310 | changed = False |
| 311 | changed_on = _changed_on(base, row.get("source")) if changed else "" |
| 312 | |
| 313 | pdf = object_documents.pdf_engine_status( |
| 314 | settings.get(object_documents.PDF_ENGINE_SETTING)) |
| 315 | size = settings.get(object_documents.PAGE_SIZE_SETTING) |
| 316 | |
| 317 | want_current = _text(request.get("v")).lower() == "current" |
| 318 | if want_current and changed: |
| 319 | model = _live_model(base, row, settings) |
| 320 | if model is not None: |
| 321 | return object_documents.render_page( |
| 322 | model, banner=_current_banner(token, sent_on, changed_on), |
| 323 | chrome=False, pdf=pdf["available"], size=size, beacon=True) |
| 324 | # Could not re-render the live record -- fall through to the snapshot |
| 325 | # rather than showing an error page to somebody who asked a reasonable |
| 326 | # question. The banner below still says the document changed. |
| 327 | |
| 328 | banner = _changed_banner(token, sent_on, changed_on) if changed else "" |
| 329 | return object_documents.render_page( |
| 330 | snapshot, banner=banner, chrome=False, pdf=pdf["available"], size=size, |
| 331 | beacon=True) |
| 332 | |
| 333 | |
| 334 | def POST(request): |
| 335 | """The page's own view beacon: stamp opened_at (once) and nothing else. |
| 336 | Same token lookup and same 404 as the GET, so it answers no question |
| 337 | about which tokens exist that the GET does not already answer.""" |
| 338 | base = _base_dir() |
| 339 | row = _find_by_token(base, request.get("token")) |
| 340 | if row is None: |
| 341 | return _not_found() |
| 342 | _stamp_opened(base, row) |
| 343 | return {"status": 200, "content_type": "application/json", |
| 344 | "body": '{"ok": true}'} |