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
test_local_time.py · 11.8 KB · 284 lines
| 1 | """Timestamps: stored in UTC, read in the viewer's own zone. |
| 2 | |
| 3 | Every timestamp this server STORES is UTC, which is correct and is not |
| 4 | negotiable — a stamp without a zone is a bug waiting for the clocks to |
| 5 | change. Every timestamp a person READS should be in their own zone, which |
| 6 | is a rendering question. |
| 7 | |
| 8 | The generative renderer already got this right by accident of being |
| 9 | client-side (`new Date(iso)` parses UTC, `toLocaleString` prints local). |
| 10 | Server-rendered pages did not, because a Python f-string has no idea who |
| 11 | is reading it. So the convention is one element — `<time datetime="...">` |
| 12 | — converted by the shared `/nav` script that every page already loads. |
| 13 | |
| 14 | THREE THINGS THIS FILE PINS, each of which is a decision rather than an |
| 15 | implementation detail: |
| 16 | |
| 17 | 1. The browser's zone is the DEFAULT and is NEVER TRANSMITTED. It is |
| 18 | available and deliberately used only in the browser: a timezone is a |
| 19 | real fingerprinting signal, so posting it back to store would be |
| 20 | collecting an identifying attribute nobody asked us to collect. |
| 21 | 2. A DATE is not a DATETIME. Converting a date across zones actively |
| 22 | breaks it — an invoice dated the 1st is dated the 1st in Tokyo. |
| 23 | 3. Evidence keeps its canonical UTC form on screen. A notary attestation |
| 24 | that changed shape with who was reading it would be a worse |
| 25 | attestation. |
| 26 | """ |
| 27 | |
| 28 | import pathlib |
| 29 | |
| 30 | REPO_ROOT = pathlib.Path(__file__).resolve().parents[1] |
| 31 | PACKAGES = REPO_ROOT / "packages" |
| 32 | |
| 33 | NAV = PACKAGES / "app-theme" / "objects" / "site" / "nav.py" |
| 34 | |
| 35 | |
| 36 | def nav_js(): |
| 37 | return NAV.read_text() |
| 38 | |
| 39 | |
| 40 | def time_block(): |
| 41 | """Just the local-time IIFE. The privacy claim is about THIS block -- |
| 42 | scanning the whole script would catch the unrelated logout POST and |
| 43 | turn a real assertion into a false one.""" |
| 44 | source = NAV.read_text() |
| 45 | start = source.index("// === local time") |
| 46 | return source[start:] |
| 47 | |
| 48 | |
| 49 | # --- the shared helper ---------------------------------------------------------- |
| 50 | |
| 51 | def test_the_shared_script_localises_time_elements(): |
| 52 | """One convention, applied by the script every page already loads, |
| 53 | rather than 34 pages each remembering to convert.""" |
| 54 | js = nav_js() |
| 55 | assert "window.dbbasicTime" in js |
| 56 | assert 'querySelectorAll("time[datetime]")' in js |
| 57 | assert "toLocaleString" in js |
| 58 | |
| 59 | |
| 60 | def test_the_browser_zone_is_never_sent_to_the_server(): |
| 61 | """THE privacy decision. A timezone is one of the higher-entropy bits |
| 62 | in a browser fingerprint, so reading it to format text is free and |
| 63 | posting it back to store would be collecting an identifying attribute |
| 64 | nobody asked us to collect -- which /privacy is a fold over.""" |
| 65 | js = time_block() |
| 66 | |
| 67 | # It is read only inside the reporting helper, never assembled into a |
| 68 | # request body or query string. |
| 69 | assert "resolvedOptions().timeZone" in js |
| 70 | for smell in ('body: JSON.stringify({timezone', |
| 71 | '"timezone="', "timezone=' +", 'tz=" +', |
| 72 | 'method: "PUT"', 'method: "POST"'): |
| 73 | assert smell not in js, smell |
| 74 | |
| 75 | # The only network call this block makes is a READ of the caller's |
| 76 | # own prefs. |
| 77 | prefs_calls = js.count('fetch("/prefs"') |
| 78 | assert prefs_calls == 1 |
| 79 | assert 'fetch("/prefs", {credentials: "same-origin"})' in js |
| 80 | |
| 81 | |
| 82 | def test_a_stored_preference_overrides_the_browser(): |
| 83 | """The real case the browser gets wrong: a business whose books are |
| 84 | kept in one zone regardless of where the person reading them sits.""" |
| 85 | js = nav_js() |
| 86 | assert '"display.timezone"' in js |
| 87 | assert "o.timeZone = zone" in js |
| 88 | |
| 89 | |
| 90 | def test_an_unparseable_stamp_is_left_showing_utc_rather_than_blanked(): |
| 91 | """Honest beats empty. A page that blanks a timestamp it could not |
| 92 | parse has destroyed the only information it had.""" |
| 93 | js = nav_js() |
| 94 | assert "if (!out) return;" in js |
| 95 | assert "leave UTC showing" in js |
| 96 | |
| 97 | |
| 98 | def test_a_bad_timezone_preference_cannot_blank_the_page(): |
| 99 | """A typo in a pref must degrade to the browser's zone, not throw |
| 100 | inside a render loop and leave every timestamp unconverted.""" |
| 101 | js = nav_js() |
| 102 | assert "catch (e) { return d.toLocaleString(); }" in js |
| 103 | |
| 104 | |
| 105 | def test_a_bare_stamp_with_no_zone_marker_is_treated_as_utc(): |
| 106 | """This server's own contract: it writes UTC. A stamp that reached a |
| 107 | page without a Z would otherwise be parsed as LOCAL by the browser, |
| 108 | which silently shifts every value by the reader's offset.""" |
| 109 | js = nav_js() |
| 110 | assert 'if (!/[Zz]|[+-]\\d{2}:?\\d{2}$/.test(text)) text += "Z";' in js |
| 111 | |
| 112 | |
| 113 | def test_content_rendered_after_load_is_converted_too(): |
| 114 | """The generative list, a form panel and a realtime push all arrive |
| 115 | after DOMContentLoaded. Without this a page would convert only what |
| 116 | the server sent and silently miss everything the client added.""" |
| 117 | assert "MutationObserver" in nav_js() |
| 118 | |
| 119 | |
| 120 | # --- the pages ------------------------------------------------------------------ |
| 121 | |
| 122 | def test_server_rendered_datetimes_use_the_time_element(): |
| 123 | """The sweep, pinned. A page that prints a bare ISO stamp is showing |
| 124 | UTC to somebody who does not live there.""" |
| 125 | for path, field in ( |
| 126 | (PACKAGES / "app-notary" / "objects" / "site" / "notary.py", |
| 127 | "first_seen_at"), |
| 128 | (PACKAGES / "app-integrity" / "objects" / "site" / "ledger_integrity.py", |
| 129 | "taken_at"), |
| 130 | ): |
| 131 | source = path.read_text() |
| 132 | assert f'<time datetime="{{_esc(' in source, path.name |
| 133 | assert field in source |
| 134 | |
| 135 | |
| 136 | def test_a_date_is_not_converted_because_a_date_is_not_an_instant(): |
| 137 | """An invoice dated the 1st is dated the 1st in Tokyo. Shifting a |
| 138 | date by a timezone offset turns it into the 31st for half the world, |
| 139 | which is a data corruption dressed as a courtesy.""" |
| 140 | sheet = (PACKAGES / "app-receiving" / "objects" / "site" |
| 141 | / "receiving_sheet.py").read_text() |
| 142 | assert "received_on" in sheet |
| 143 | assert "<time datetime" not in sheet |
| 144 | |
| 145 | |
| 146 | def test_the_notary_keeps_its_canonical_utc_on_screen(): |
| 147 | """An attestation is evidence, and evidence should not change shape |
| 148 | with who is reading it. Local time for the human, UTC for the record, |
| 149 | both visible.""" |
| 150 | notary = (PACKAGES / "app-notary" / "objects" / "site" / "notary.py").read_text() |
| 151 | assert "UTC" in notary |
| 152 | assert "canonical" in notary |
| 153 | assert "evidence should not" in notary |
| 154 | |
| 155 | |
| 156 | # --- the generative form: display, load AND save -------------------------------- |
| 157 | # |
| 158 | # Found by creating a note and reading its Created field: "2026-07-27 |
| 159 | # 09:39" for something made at 4:39am. The list renderer had been right |
| 160 | # all along (relDate is client-side), so an earlier claim that "the |
| 161 | # generative layer already handles this" was true of lists and false of |
| 162 | # detail and edit -- which is why it needed checking rather than asserting. |
| 163 | |
| 164 | FORM = PACKAGES / "app-theme" / "objects" / "site" / "form.py" |
| 165 | |
| 166 | |
| 167 | def test_a_read_only_datetime_is_shown_in_the_readers_zone(): |
| 168 | """It sliced the ISO string, which shows UTC digits to somebody who |
| 169 | does not live there.""" |
| 170 | js = FORM.read_text() |
| 171 | assert "window.dbbasicTime && window.dbbasicTime.format(v)" in js |
| 172 | # and degrades to the old behaviour rather than blanking |
| 173 | assert 'local || v.slice(0, 16).replace("T", " ")' in js |
| 174 | |
| 175 | |
| 176 | def test_a_datetime_input_is_fed_local_and_answers_in_utc(): |
| 177 | """THE data-corruption fix. <input type="datetime-local"> is local by |
| 178 | definition: it was being fed a UTC slice, so it displayed the wrong |
| 179 | hour AND handed that wall-clock back to be stored as UTC. Every edit |
| 180 | shifted the value by the reader's offset, compounding each round trip. |
| 181 | Nine editable datetime fields across seven collections were reachable |
| 182 | through this one control.""" |
| 183 | js = FORM.read_text() |
| 184 | assert "function utcToLocalInput" in js |
| 185 | assert "function localInputToUtc" in js |
| 186 | assert "esc(utcToLocalInput(v))" in js # load: UTC -> local |
| 187 | assert "localInputToUtc(el.value)" in js # save: local -> UTC |
| 188 | assert "d.toISOString()" in js |
| 189 | # The old raw slice must not survive on either path. |
| 190 | assert "value=\"' + esc(v.slice(0, 16))" not in js |
| 191 | |
| 192 | |
| 193 | def test_the_round_trip_is_lossless_in_principle(): |
| 194 | """utcToLocalInput and localInputToUtc are inverses: the first drops |
| 195 | the offset for the control, the second puts it back. Pinned as a |
| 196 | property because a one-way conversion is exactly how the original bug |
| 197 | happened.""" |
| 198 | js = FORM.read_text() |
| 199 | load = js.split("function utcToLocalInput")[1].split("function localInputToUtc")[0] |
| 200 | save = js.split("function localInputToUtc")[1].split("\n }")[0] |
| 201 | # Load builds a zone-less wall-clock string from local getters... |
| 202 | assert "getHours()" in load and "getMinutes()" in load |
| 203 | assert "toISOString" not in load |
| 204 | # ...and save parses that back as local and emits UTC. |
| 205 | assert "new Date(String(v))" in save |
| 206 | assert "toISOString" in save |
| 207 | |
| 208 | |
| 209 | def test_editable_datetime_fields_really_exist_so_this_matters(): |
| 210 | """Not hypothetical: these are in default forms today, reachable |
| 211 | through the one generic control.""" |
| 212 | import json as _json |
| 213 | import glob as _glob |
| 214 | found = [] |
| 215 | for path in _glob.glob(str(PACKAGES / "*" / "schemas" / "*.json")): |
| 216 | schema = _json.loads(pathlib.Path(path).read_text()) |
| 217 | in_forms = set() |
| 218 | for spec in (schema.get("forms") or {}).values(): |
| 219 | in_forms.update(spec.get("fields") or []) |
| 220 | for field in schema["fields"]: |
| 221 | if (field.get("type") in ("datetime", "timestamp") |
| 222 | and not field.get("read_only") |
| 223 | and field["name"] in in_forms): |
| 224 | found.append((schema["name"], field["name"])) |
| 225 | assert len(found) >= 5, found |
| 226 | assert ("events", "starts_at") in found |
| 227 | |
| 228 | |
| 229 | # --- the picker ----------------------------------------------------------------- |
| 230 | # |
| 231 | # display.timezone was writable over PUT /prefs/... from the moment the |
| 232 | # formatter shipped, and had nowhere a person would ever find it -- which |
| 233 | # is the same as not existing. |
| 234 | |
| 235 | APPEARANCE = PACKAGES / "app-theme" / "objects" / "site" / "appearance.py" |
| 236 | |
| 237 | |
| 238 | def test_the_timezone_pref_has_a_place_a_person_can_find_it(): |
| 239 | page = APPEARANCE.read_text() |
| 240 | assert 'id="tz"' in page |
| 241 | assert "/prefs/display.timezone" in page |
| 242 | assert 'method: "PUT"' in page |
| 243 | |
| 244 | |
| 245 | def test_the_default_option_is_the_browser_not_a_named_zone(): |
| 246 | """Blank means 'use the browser', which stays the default because it |
| 247 | is right more often and requires nobody to decide anything.""" |
| 248 | page = APPEARANCE.read_text() |
| 249 | assert '<option value="">Whatever my browser says (recommended)</option>' in page |
| 250 | |
| 251 | |
| 252 | def test_the_page_says_the_zone_is_not_transmitted(): |
| 253 | """The privacy property is only worth having if a user is told about |
| 254 | it -- an undisclosed protection is indistinguishable from none.""" |
| 255 | page = APPEARANCE.read_text() |
| 256 | assert "Nothing is sent to the server to work that out" in page |
| 257 | assert "unless you choose one below" in page |
| 258 | |
| 259 | |
| 260 | def test_the_picker_writes_the_documented_pref_contract(): |
| 261 | """PUT /prefs/{key} takes {"value": "<string>"} -- a mismatch here |
| 262 | would fail silently in the browser and look like the pref not |
| 263 | sticking.""" |
| 264 | page = APPEARANCE.read_text() |
| 265 | assert 'body: JSON.stringify({value: sel.value})' in page |
| 266 | assert 'credentials: "same-origin"' in page |
| 267 | |
| 268 | |
| 269 | def test_the_zone_list_degrades_rather_than_bundling_a_database(): |
| 270 | """Intl.supportedValuesOf where it exists, a short explicit list where |
| 271 | it does not. Shipping 400 names to render a dropdown nobody scrolls is |
| 272 | not worth the bytes, and an exotic zone can still be PUT directly.""" |
| 273 | page = APPEARANCE.read_text() |
| 274 | assert 'Intl.supportedValuesOf("timeZone")' in page |
| 275 | assert "catch (e)" in page |
| 276 | assert '"UTC"' in page |
| 277 | |
| 278 | |
| 279 | def test_the_public_invoice_portal_shows_a_customers_own_time(): |
| 280 | """The portal is public and a customer may be on another continent; |
| 281 | paid_at is a datetime, so a raw stamp put UTC on somebody's receipt.""" |
| 282 | portal = (PACKAGES / "app-invoices" / "objects" / "site" |
| 283 | / "invoice_portal.py").read_text() |
| 284 | assert '<time datetime="{_esc(paid_at)}">' in portal |