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.
danq9
signup: the person chooses the password and name on the confirm page
83c7aa6
2 weeks, 5 days ago
History
document.py · 11.6 KB · 310 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.compute_record_rev of the live record |
| 23 | against the source_rev stamped when the document was sent. A content |
| 24 | fingerprint rather than a timestamp: a record edited in the same second it was |
| 25 | sent would slip past a timestamp comparison, and that is exactly the case where |
| 26 | the two documents differ. When the source cannot be read at all (the row was |
| 27 | deleted, the package removed), the answer is "cannot tell" and NO banner is |
| 28 | shown -- inventing "it changed" would be as wrong as inventing "it did not". |
| 29 | |
| 30 | ACCESS, in the posture site_invoice_portal established and this reuses |
| 31 | verbatim: the token is the whole credential, looked up BY TOKEN ONLY and never |
| 32 | by id, matched with hmac.compare_digest (a plain `==` on attacker-controlled |
| 33 | input leaks how many leading characters matched, via how long it took -- the |
| 34 | exact side channel a bearer token exists to close). A blank token matches |
| 35 | nothing, so a row whose token was never minted is not an accidental open door. |
| 36 | An unknown token gets the SAME "not found" page, at 404, as a document that |
| 37 | never existed -- never 403, because a 403 confirms the token namespace is worth |
| 38 | attacking, while "not found" makes a guess and a typo indistinguishable. |
| 39 | |
| 40 | No nav, no global search, no chrome beyond the shared stylesheet: somebody |
| 41 | following an emailed link must never be one click from another customer's |
| 42 | paperwork or from a sign-in wall for a system they have no account on. |
| 43 | |
| 44 | opened_at is stamped on first view and never restamped -- "did they read it?" |
| 45 | is the first thing anybody asks after sending a quote, and it comes free with a |
| 46 | tokened link. Idempotent by construction (written only when the field is |
| 47 | empty), and best-effort: no read receipt is worth breaking the page somebody is |
| 48 | actively trying to read. |
| 49 | |
| 50 | The PDF button is drawn only when a PDF engine is actually configured |
| 51 | (object_documents.pdf_engine_status), which today is never. Print -> Save as |
| 52 | PDF already works and the page says so instead. |
| 53 | """ |
| 54 | |
| 55 | import hmac |
| 56 | import html |
| 57 | import os |
| 58 | from datetime import datetime, timezone |
| 59 | |
| 60 | import object_documents |
| 61 | import object_money |
| 62 | import object_record_changes |
| 63 | import object_records |
| 64 | |
| 65 | ACTOR = "site_document" |
| 66 | COLLECTION = "sent_documents" |
| 67 | |
| 68 | |
| 69 | def _base_dir(): |
| 70 | return os.environ.get("DBBASIC_DATA_DIR", "data") |
| 71 | |
| 72 | |
| 73 | def _text(value): |
| 74 | return str(value if value is not None else "").strip() |
| 75 | |
| 76 | |
| 77 | def _settings(base): |
| 78 | values = {} |
| 79 | try: |
| 80 | for row in object_records.read_collection_records("app_settings", |
| 81 | base_dir=base): |
| 82 | key, value = _text(row.get("key")), _text(row.get("value")) |
| 83 | if key and value: |
| 84 | values[key] = value |
| 85 | except Exception: |
| 86 | pass |
| 87 | return values |
| 88 | |
| 89 | |
| 90 | def _find_by_token(base, token): |
| 91 | """The only lookup this page performs: a full scan matched in constant |
| 92 | time, never a keyed lookup by id. A blank token matches nothing.""" |
| 93 | token = _text(token) |
| 94 | if not token: |
| 95 | return None |
| 96 | try: |
| 97 | rows = object_records.read_collection_records(COLLECTION, base_dir=base) |
| 98 | except Exception: |
| 99 | return None |
| 100 | for row in rows: |
| 101 | candidate = _text(row.get("token")) |
| 102 | if not candidate: |
| 103 | continue |
| 104 | if hmac.compare_digest(candidate, token): |
| 105 | return row |
| 106 | return None |
| 107 | |
| 108 | |
| 109 | def _stamp_opened(base, row): |
| 110 | """Once, ever. Written only when opened_at is empty, so a reader who |
| 111 | refreshes twenty times still opened it once -- and every failure is |
| 112 | swallowed, because a read receipt is not worth a broken page.""" |
| 113 | if _text(row.get("opened_at")): |
| 114 | return |
| 115 | try: |
| 116 | now = datetime.now(timezone.utc).isoformat().replace("+00:00", "Z") |
| 117 | object_records.update_collection_record( |
| 118 | COLLECTION, row["id"], {"opened_at": now}, |
| 119 | base_dir=base, actor=ACTOR) |
| 120 | except Exception: |
| 121 | pass |
| 122 | |
| 123 | |
| 124 | def _source_record(base, source): |
| 125 | """The live record behind a sent document, or None when it cannot be |
| 126 | read at all -- which is 'cannot tell', not 'unchanged'.""" |
| 127 | source = _text(source) |
| 128 | if source.count("/") != 1: |
| 129 | return None |
| 130 | collection, _, record_id = source.partition("/") |
| 131 | if not _text(collection) or not _text(record_id): |
| 132 | return None |
| 133 | try: |
| 134 | record = object_records.get_collection_record(_text(collection), |
| 135 | _text(record_id), |
| 136 | base_dir=base) |
| 137 | except Exception: |
| 138 | return None |
| 139 | return record or None |
| 140 | |
| 141 | |
| 142 | def _changed_on(base, source): |
| 143 | """The day the source last changed, from the record change log. Best |
| 144 | effort: the banner is better with a date and still true without one.""" |
| 145 | source = _text(source) |
| 146 | if source.count("/") != 1: |
| 147 | return "" |
| 148 | collection, _, record_id = source.partition("/") |
| 149 | try: |
| 150 | page = object_record_changes.list_record_changes( |
| 151 | _text(collection), record_id=_text(record_id), base_dir=base, |
| 152 | limit=1, tail_only=True) |
| 153 | except Exception: |
| 154 | return "" |
| 155 | changes = page.get("changes") or [] |
| 156 | if not changes: |
| 157 | return "" |
| 158 | return _text(changes[0].get("timestamp"))[:10] |
| 159 | |
| 160 | |
| 161 | def _live_model(base, row, settings): |
| 162 | """Re-render the CURRENT version of the document from the live record. |
| 163 | |
| 164 | Only reached from ?v=current -- an explicit request for the other thing. |
| 165 | Uses the same pure fold the snapshot was built with, so "current" and |
| 166 | "sent" cannot be two renderers that drift. |
| 167 | """ |
| 168 | kind = _text(row.get("kind")) |
| 169 | try: |
| 170 | spec = object_documents.source_spec(kind) |
| 171 | except object_documents.UnknownKindError: |
| 172 | return None |
| 173 | if spec is None: |
| 174 | return None |
| 175 | record = _source_record(base, row.get("source")) |
| 176 | if record is None: |
| 177 | return None |
| 178 | |
| 179 | record_id = _text(row.get("source")).partition("/")[2] |
| 180 | lines = [] |
| 181 | if spec.get("lines_collection"): |
| 182 | try: |
| 183 | rows = object_records.read_collection_records( |
| 184 | spec["lines_collection"], base_dir=base) |
| 185 | lines = [line for line in rows |
| 186 | if _text(line.get(spec["lines_fk"])) == record_id] |
| 187 | lines.sort(key=lambda line: _text(line.get("description"))) |
| 188 | except Exception: |
| 189 | lines = [] |
| 190 | |
| 191 | currency = _text(record.get("currency")) or "USD" |
| 192 | |
| 193 | def money(cents): |
| 194 | try: |
| 195 | return object_money.format_amount(cents or 0, currency, base_dir=base) |
| 196 | except Exception: |
| 197 | return f"{cents or 0} (minor units)" |
| 198 | |
| 199 | facts = object_documents.facts_from_records(kind, record, lines, money=money) |
| 200 | try: |
| 201 | return object_documents.build_model(kind, facts, settings, |
| 202 | require_business=False) |
| 203 | except object_documents.DocumentError: |
| 204 | return None |
| 205 | |
| 206 | |
| 207 | def _esc(value): |
| 208 | return html.escape(_text(value)) |
| 209 | |
| 210 | |
| 211 | def _not_found(): |
| 212 | return { |
| 213 | "status": 404, |
| 214 | "content_type": "text/html; charset=utf-8", |
| 215 | "body": """<!doctype html> |
| 216 | <html lang="en"> |
| 217 | <head> |
| 218 | <meta charset="utf-8"> |
| 219 | <meta name="viewport" content="width=device-width, initial-scale=1"> |
| 220 | <meta name="referrer" content="no-referrer"> |
| 221 | <title>Not found</title> |
| 222 | <link rel="stylesheet" href="/style"> |
| 223 | </head> |
| 224 | <body> |
| 225 | <div style="max-width:34rem;margin:0 auto;padding:3rem 1.25rem;text-align:center"> |
| 226 | <h1>Not found</h1> |
| 227 | <p>This document link is not valid. It may have been mistyped, or the business |
| 228 | that sent it may have issued a newer one. Contact them for a fresh link.</p> |
| 229 | </div> |
| 230 | </body> |
| 231 | </html>""", |
| 232 | } |
| 233 | |
| 234 | |
| 235 | def _changed_banner(token, sent_on, changed_on): |
| 236 | """Both dates, named, with the way to the other version. |
| 237 | |
| 238 | Not a warning colour and not an apology: documents change, and the only |
| 239 | unacceptable outcome is a reader who cannot tell which one they have. |
| 240 | """ |
| 241 | when = (f" on {_esc(changed_on)}" if changed_on else " since") |
| 242 | return ( |
| 243 | '<div class="doc-banner"><strong>You are reading the version that was ' |
| 244 | f'sent to you on {_esc(sent_on)}.</strong>' |
| 245 | f'This document was changed{when}. ' |
| 246 | f'<a href="/d/{_esc(token)}?v=current">See the current version</a>.' |
| 247 | "</div>") |
| 248 | |
| 249 | |
| 250 | def _current_banner(token, sent_on, changed_on): |
| 251 | when = (f" on {_esc(changed_on)}" if changed_on else "") |
| 252 | return ( |
| 253 | '<div class="doc-banner"><strong>This is the CURRENT version of this ' |
| 254 | f'document, changed{when}.</strong>' |
| 255 | f'The version sent to you on {_esc(sent_on)} is ' |
| 256 | f'<a href="/d/{_esc(token)}">still here</a>, unchanged.' |
| 257 | "</div>") |
| 258 | |
| 259 | |
| 260 | def GET(request): |
| 261 | base = _base_dir() |
| 262 | row = _find_by_token(base, request.get("token")) |
| 263 | if row is None: |
| 264 | return _not_found() |
| 265 | |
| 266 | settings = _settings(base) |
| 267 | _stamp_opened(base, row) |
| 268 | |
| 269 | try: |
| 270 | snapshot = object_documents.model_from_snapshot(row.get("snapshot")) |
| 271 | except object_documents.DocumentError: |
| 272 | # The snapshot is the document. A half-parsed one is not evidence of |
| 273 | # anything, and rendering something else under this link is exactly |
| 274 | # what this page exists to prevent. |
| 275 | return _not_found() |
| 276 | |
| 277 | token = _text(row.get("token")) |
| 278 | sent_on = _text(row.get("sent_at"))[:10] |
| 279 | |
| 280 | # Has the source moved since we froze it? An exact question, asked of the |
| 281 | # platform's own record fingerprint. Blank on either side means "cannot |
| 282 | # tell", which shows no banner rather than a false one. |
| 283 | stored_rev = _text(row.get("source_rev")) |
| 284 | live = _source_record(base, row.get("source")) if stored_rev else None |
| 285 | changed = False |
| 286 | if live is not None: |
| 287 | try: |
| 288 | changed = object_records.compute_record_rev(live) != stored_rev |
| 289 | except Exception: |
| 290 | changed = False |
| 291 | changed_on = _changed_on(base, row.get("source")) if changed else "" |
| 292 | |
| 293 | pdf = object_documents.pdf_engine_status( |
| 294 | settings.get(object_documents.PDF_ENGINE_SETTING)) |
| 295 | size = settings.get(object_documents.PAGE_SIZE_SETTING) |
| 296 | |
| 297 | want_current = _text(request.get("v")).lower() == "current" |
| 298 | if want_current and changed: |
| 299 | model = _live_model(base, row, settings) |
| 300 | if model is not None: |
| 301 | return object_documents.render_page( |
| 302 | model, banner=_current_banner(token, sent_on, changed_on), |
| 303 | chrome=False, pdf=pdf["available"], size=size) |
| 304 | # Could not re-render the live record -- fall through to the snapshot |
| 305 | # rather than showing an error page to somebody who asked a reasonable |
| 306 | # question. The banner below still says the document changed. |
| 307 | |
| 308 | banner = _changed_banner(token, sent_on, changed_on) if changed else "" |
| 309 | return object_documents.render_page( |
| 310 | snapshot, banner=banner, chrome=False, pdf=pdf["available"], size=size) |