Runs live, versioned Python application objects on one VM, with a suite of apps: projects, notes, tasks, files and more.

9 downloads

Install on DigitalOcean Download zip
Clone
Clone with git
git clone https://gitstable.com/git/askrobots/dbbasic-object-server.git
HTTPS
https://gitstable.com/git/askrobots/dbbasic-object-server.git
SSH
ssh://git@gitstable.com:2222/askrobots/dbbasic-object-server.git

Cloning needs no sign-in. Pushing over HTTPS asks for your username and an access token. SSH needs your key under SSH keys.

Daniel Quellhorst Changelog for this batch. 65ef78d 3 hours, 49 minutes ago History
privacy.py · 36.7 KB · 898 lines
1"""site_privacy -- a privacy policy that is a FOLD over this server's
2configuration, not a template somebody filled in once.
3
4GET /privacy the policy
5GET /cookies the cookie table on its own
6GET /privacy.json the same fold, machine-readable, for anyone who wants
7 to diff it between deploys
8
9Almost every privacy policy on the web is a lie of omission, and not
10because anyone set out to lie: the policy is written once, by a template,
11and the software changes weekly. Nothing connects the two, so nothing
12notices when they part company. This one is generated from the live
13settings, so it cannot claim a 30-day retention while the box keeps 180,
14cannot mention a payment processor that is not configured, and cannot
15stay silent about a cookie the server sets.
16
17The load-bearing property is that it is a fold, in the same family as the
18nav registry (`action_nav_entries`) and the attention counts: install the
19shop and the policy grows a payments paragraph with nobody remembering to
20write one; switch analytics off and the traffic section disappears
21entirely. A policy that CAN drift from the software is the normal case;
22one that cannot is worth having.
23
24## What this object refuses to do, and why it is a refusal rather than a gap
25
26**It does not write legal text.** No lawful bases, no legitimate-interest
27balancing, no Standard Contractual Clauses, no adequacy decisions, no
28transfer mechanisms, no retention justifications, no claims about which
29regimes apply to the operator's business. It states FACTS about this
30system -- what is stored, where, for how long, which third parties are
31configured, what a cookie does -- and stops.
32
33That boundary is the same one this system holds everywhere else. A
34generated paragraph asserting "we rely on legitimate interests under
35Article 6(1)(f)" would be a confident sentence about somebody else's legal
36position, produced by a program that cannot know their business, their
37customers or their regulator, and pasted into a document a regulator
38reads. Wrong legal text is worse than no legal text, because it is
39evidence of a claim the operator never made and cannot support.
40
41`privacy.extra_markdown` is where the operator's own reviewed wording
42goes. It is rendered verbatim, under its own heading, so a reader can see
43which half of the page is machine-generated fact and which half is a
44human's legal statement. (`app_settings` caps a value at 500 characters,
45so long text belongs in a document this links to rather than inline.)
46
47**It refuses to render at all until it is signed.** A policy with no named
48controller and no contact address is not a policy; it is a page shaped
49like one, and it is worse than nothing because it looks like compliance
50while giving a reader nobody to write to. Absent
51`privacy.controller_name`, `privacy.contact_email` or
52`privacy.jurisdiction`, this page says exactly which settings are missing
53and renders no claims whatsoever about the system. The cookie table is
54still served at /cookies, because the browser-facing facts are true
55regardless of who signed them.
56
57## The settings it folds
58
59 privacy.controller_name who is responsible for the data (required)
60 privacy.contact_email where a subject writes (required)
61 privacy.jurisdiction where the controller is established (required)
62 privacy.extra_markdown the operator's own reviewed legal text
63
64Everything else is read from the running configuration: the analytics
65env, the cookie switches, which packages are installed, and which third
66parties actually have credentials.
67"""
68
69import html
70import json
71import os
72from pathlib import Path
73
74import object_ai
75import object_analytics
76import object_email
77import object_identity
78import object_package_baselines
79import object_packages
80import object_records
81import object_service_keys
82import object_stripe
83
84DATA_DIR_ENV = "DBBASIC_DATA_DIR"
85SETTINGS_COLLECTION = "app_settings"
86
87CONTROLLER_NAME_KEY = "privacy.controller_name"
88CONTACT_EMAIL_KEY = "privacy.contact_email"
89JURISDICTION_KEY = "privacy.jurisdiction"
90EXTRA_MARKDOWN_KEY = "privacy.extra_markdown"
91CARRIER_PROVIDER_KEY = "carrier.provider"
92
93REQUIRED_SETTINGS = (
94 (CONTROLLER_NAME_KEY, "the name of the person or company responsible for this data"),
95 (CONTACT_EMAIL_KEY, "an address a visitor can actually write to"),
96 (JURISDICTION_KEY, "where that controller is established, e.g. 'England and Wales'"),
97)
98
99# The shop's basket cookie lives in app-shop (objects/site/shop.py, COOKIE)
100# and its lifetime is a literal in the header that object builds. Restated
101# here because a package may not import another package's objects -- and
102# pinned by tests/test_privacy.py, which reads the literal back out of
103# app-shop's source and fails if the two ever disagree. A disclosure that
104# can drift from the cookie it describes is the drift this whole page
105# exists to prevent.
106CART_COOKIE_NAME = "cart"
107CART_COOKIE_MAX_AGE = 1209600 # 14 days
108CART_COOKIE_PACKAGE = "app-shop"
109
110# The apps whose presence changes what this policy says, and the
111# collection each one owns. Nothing else is folded, and nothing else is
112# reported: /privacy is public, and the full inventory of what an
113# operator installed is not a visitor's business.
114FOLDED_PACKAGES = {
115 "app-shop": ("carts",),
116 "app-orders": ("orders",),
117 "app-invoices": ("invoices",),
118 "app-payments": ("payments",),
119 "app-shipping": ("shipments",),
120}
121
122
123# === the registry of cookies this server can set ============================
124#
125# THE list. tests/test_privacy.py sweeps every source file on the box for
126# anything that sets a cookie and fails unless each name it finds appears
127# here, naming the undisclosed cookie in the failure message. A cookie
128# added anywhere in this repo therefore breaks the build until somebody
129# writes down what it is for and whether it is strictly necessary.
130#
131# `strictly_necessary` is the ePrivacy question and it is the only one on
132# this page with a consent consequence: a cookie needed for a service the
133# user actively asked for (the session they signed in to, the basket they
134# filled) needs no consent; anything else does. Two of three here are
135# necessary, which is why this server's default posture needs no banner.
136COOKIE_DISCLOSURES = (
137 {
138 "name": "dbbasic_session",
139 "purpose": "Keeps you signed in after you enter your password.",
140 "strictly_necessary": True,
141 "necessary_because": "you asked to sign in, and there is no way to stay "
142 "signed in without it",
143 "set_when": "You sign in.",
144 "requires": "",
145 },
146 {
147 "name": CART_COOKIE_NAME,
148 "purpose": "Remembers which basket is yours, so what you put in it is "
149 "still there on the next page. It holds an opaque token, "
150 "not the contents.",
151 "strictly_necessary": True,
152 "necessary_because": "you asked for a basket; a shop cannot keep one "
153 "without a way to recognise it",
154 "set_when": "You put something in the basket.",
155 "requires": "package:" + CART_COOKIE_PACKAGE,
156 },
157 {
158 "name": object_analytics.VISITOR_COOKIE_NAME,
159 "purpose": "An opaque random token used to tell a returning visit from "
160 "a new one in this site's own traffic figures. It carries no "
161 "name, no email and no account, and it is never joined to a "
162 "signed-in identity.",
163 "strictly_necessary": False,
164 "necessary_because": "",
165 "set_when": "You open a page — unless your browser sends Do Not Track "
166 "or Global Privacy Control, in which case it is never set.",
167 "requires": "setting:visitor_cookie",
168 },
169)
170
171# What a page_views row actually holds. Named field by field rather than
172# summarised, because "usage data" is the phrasing that lets a policy mean
173# anything.
174PAGE_VIEW_FIELDS = (
175 ("IP address", "the address the request came from"),
176 ("Host", "which of this server's sites was asked"),
177 ("Path and method", "the URL requested and how"),
178 ("Status", "what the server answered"),
179 ("User agent", "the browser or client string your software sent"),
180 ("Referrer", "the page that linked you here, if your browser sent one"),
181 ("Visitor token", "the dbbasic_visitor cookie value, when that cookie is on"),
182 ("Timestamp", "when"),
183)
184
185_STYLE = """
186.pp { max-width: 46rem; }
187.pp h2 { font-size: 1.05rem; margin: 1.8rem 0 .4rem; }
188.pp h3 { font-size: .95rem; margin: 1.2rem 0 .3rem; }
189.pp p, .pp li { line-height: 1.55; }
190.pp table { width: 100%; border-collapse: collapse; margin: .6rem 0 1.2rem; }
191.pp th, .pp td { text-align: left; padding: .35rem .5rem; vertical-align: top;
192 border-bottom: 1px solid var(--line, #38384a); font-size: .9rem; }
193.pp .yes { color: var(--accent, #b5713a); font-weight: 600; }
194.pp .note { border-left: 3px solid var(--line, #55556a); padding: .1rem 0 .1rem .7rem;
195 margin: .6rem 0 1.2rem; font-size: .88rem; opacity: .85; }
196.pp .refusal { border: 1px solid var(--accent, #b5713a); border-radius: 8px;
197 padding: .8rem 1rem; margin: 1rem 0; }
198.pp code { font-size: .85em; }
199"""
200
201
202def _esc(value):
203 return html.escape(str(value if value is not None else ""), quote=True)
204
205
206def _data_dir():
207 return os.environ.get(DATA_DIR_ENV, object_records.DEFAULT_DATA_DIR)
208
209
210# --- reading the box ---------------------------------------------------------
211
212def _settings(base):
213 """Every privacy.* setting as a plain dict, missing collection and all.
214
215 Duplicated rather than shared, like every other package that reads
216 app_settings -- see docs/logic-decisions.md #4."""
217 values = {}
218 try:
219 # access: box configuration
220 rows = object_records.read_collection_records(
221 SETTINGS_COLLECTION, base_dir=base)
222 except Exception:
223 return values
224 for row in rows:
225 key = str(row.get("key") or "").strip()
226 value = str(row.get("value") or "").strip()
227 if key and value:
228 values[key] = value
229 return values
230
231
232def _schema_present(base, collection):
233 """Whether this box knows a collection at all.
234
235 Cheaper and more honest than reading it: the question is "does this
236 server store shipments", not "has it stored one yet". An empty
237 shipments collection is still a server that ships things.
238 """
239 return (Path(base) / "schemas" / f"{collection}.json").is_file()
240
241
242def installed_packages(base, *, root=None):
243 """Which of the apps this policy folds over are installed on this box.
244
245 Only those apps, deliberately. The full inventory of what an operator
246 has installed is not a visitor's business and /privacy is public; what
247 a visitor is owed is the apps that touch their data, which is exactly
248 the list below.
249
250 Two signals, either sufficient, because either one alone is wrong
251 somewhere real:
252
253 * an install baseline (object_package_baselines) -- the crisp record
254 that `install_package` ran here. Absent on a box whose packages
255 predate baselines, which would drop a payments section from a
256 server that plainly takes payments.
257 * the package's own collection present in the data directory -- the
258 schema exists, so this server stores that kind of record whether or
259 not anybody stamped a baseline. Emptiness proves nothing either
260 way: a shipments collection with no rows is still a server that
261 ships things.
262
263 The manifest merely being present under packages/ is NOT sufficient.
264 This repo ships every app it has, and a policy that grew a fulfilment
265 section on a box that never installed the shop would be inventing
266 processing rather than reporting it. `list_packages` is still what
267 decides the candidate set, so an app removed from the box drops out
268 of the policy with it.
269 """
270 installed = set()
271 try:
272 summaries = (object_packages.list_packages(root=root) if root
273 else object_packages.list_packages())
274 except Exception:
275 return installed
276 shipped = {summary.get("id") or "" for summary in summaries}
277
278 for package_id, collections in FOLDED_PACKAGES.items():
279 if package_id not in shipped:
280 continue
281 try:
282 baseline = object_package_baselines.load_baseline(
283 package_id, base_dir=base)
284 except Exception:
285 baseline = None
286 if baseline is not None or any(_schema_present(base, name)
287 for name in collections):
288 installed.add(package_id)
289 return installed
290
291
292def _ai_services(base):
293 """AI providers this box has a key for, by name.
294
295 Read from the stored-service-key metadata, never the keys themselves.
296 Restricted to the services object_ai can actually call, so a key
297 somebody stored for something else is not reported as an AI
298 sub-processor.
299 """
300 services = set()
301 try:
302 path = object_service_keys.service_keys_path(base)
303 except Exception:
304 return []
305 try:
306 import csv
307 with open(path, newline="") as handle:
308 for row in csv.DictReader(handle, delimiter="\t"):
309 service = (row.get("service") or "").strip()
310 if service in object_ai.SUPPORTED_SERVICES:
311 services.add(service)
312 except (OSError, ValueError):
313 return []
314 return sorted(services)
315
316
317# === the fold ================================================================
318
319def policy(*, base=None, env=None, packages_root=None):
320 """Everything the page and the JSON are rendered from. One fold, three
321 surfaces -- /privacy, /cookies and /privacy.json cannot disagree
322 because there is nothing for them to disagree about.
323
324 No timestamps in here, deliberately: /privacy.json is meant to be
325 diffed between deploys, and a generated-at stamp would make every
326 fetch differ from the last one and hide the changes that matter.
327 """
328 base = _data_dir() if base is None else base
329 env = os.environ if env is None else env
330 settings = _settings(base)
331 installed = installed_packages(base, root=packages_root)
332
333 missing = [key for key, _why in REQUIRED_SETTINGS if not settings.get(key)]
334 controller = {
335 "name": settings.get(CONTROLLER_NAME_KEY, ""),
336 "contact_email": settings.get(CONTACT_EMAIL_KEY, ""),
337 "jurisdiction": settings.get(JURISDICTION_KEY, ""),
338 "missing_settings": missing,
339 "signed": not missing,
340 }
341
342 analytics_on = object_analytics.analytics_enabled(env)
343 cookie_on = object_analytics.visitor_cookie_enabled(env)
344 analytics = {
345 "enabled": analytics_on,
346 "visitor_cookie": cookie_on,
347 "visitor_cookie_days": object_analytics.visitor_days(env) if cookie_on else 0,
348 "retention_days": object_analytics.retention_days(env) if analytics_on else 0,
349 "max_rows": object_analytics.max_rows(env) if analytics_on else 0,
350 "fields": [{"field": name, "meaning": meaning}
351 for name, meaning in PAGE_VIEW_FIELDS
352 if analytics_on and (cookie_on or name != "Visitor token")],
353 "respects_dnt": True,
354 }
355
356 return {
357 "controller": controller,
358 "analytics": analytics,
359 "cookies": cookie_table(base=base, env=env, installed=installed),
360 "processing": _processing(base, env, installed),
361 "subprocessors": subprocessors(base=base, env=env, installed=installed),
362 "rights": _rights(controller, analytics),
363 "extra_markdown": settings.get(EXTRA_MARKDOWN_KEY, ""),
364 "installed_packages": sorted(installed),
365 }
366
367
368def disclosed_cookie_names():
369 """Every cookie name this server is disclosed as being able to set.
370
371 The set the codebase sweep in tests/test_privacy.py checks itself
372 against. Deliberately NOT filtered by configuration: the sweep is
373 asking "is this cookie written down anywhere", and a box with no shop
374 installed must still fail if somebody adds an undisclosed cookie to
375 the shop.
376 """
377 return {entry["name"] for entry in COOKIE_DISCLOSURES}
378
379
380def cookie_max_age_seconds(name, *, env=None):
381 """The real Max-Age this server puts on one cookie, in seconds.
382
383 Read from the same places the cookie itself is built from, so the
384 published number cannot be a number somebody typed.
385 """
386 env = os.environ if env is None else env
387 if name == object_analytics.VISITOR_COOKIE_NAME:
388 return object_analytics.visitor_days(env) * 86400
389 if name == CART_COOKIE_NAME:
390 return CART_COOKIE_MAX_AGE
391 if name == "dbbasic_session":
392 return object_identity.DEFAULT_SESSION_TTL_SECONDS
393 return 0
394
395
396def cookie_table(*, base=None, env=None, installed=None):
397 """The cookies THIS server, as configured, can put in a browser.
398
399 Filtered by configuration rather than listing the catalogue: telling a
400 visitor about a basket cookie on a box with no shop is noise, and
401 listing an analytics cookie that is switched off would be the page
402 lying in the direction that flatters nobody.
403 """
404 base = _data_dir() if base is None else base
405 env = os.environ if env is None else env
406 if installed is None:
407 installed = installed_packages(base)
408
409 rows = []
410 for entry in COOKIE_DISCLOSURES:
411 requires = entry["requires"]
412 if requires.startswith("package:"):
413 if requires.split(":", 1)[1] not in installed:
414 continue
415 elif requires == "setting:visitor_cookie":
416 if not (object_analytics.visitor_cookie_enabled(env)
417 and object_analytics.analytics_enabled(env)):
418 continue
419 seconds = cookie_max_age_seconds(entry["name"], env=env)
420 rows.append({
421 "name": entry["name"],
422 "purpose": entry["purpose"],
423 "strictly_necessary": entry["strictly_necessary"],
424 "necessary_because": entry["necessary_because"],
425 "set_when": entry["set_when"],
426 "max_age_seconds": seconds,
427 "max_age_days": round(seconds / 86400, 2) if seconds else 0,
428 "first_party": True,
429 "http_only": True,
430 "same_site": "Lax",
431 })
432 return rows
433
434
435def _processing(base, env, installed):
436 """The sections that exist only because the thing they describe does.
437
438 Each entry is a fact about a collection this box actually has, so a
439 server that does not sell anything has no payments paragraph to be
440 wrong about.
441 """
442 sections = []
443
444 if object_analytics.analytics_enabled(env):
445 sections.append({
446 "id": "traffic",
447 "title": "Traffic to this site",
448 "why": "To see how many people visit, which pages they read, and "
449 "to spot attacks and broken links.",
450 "kept": f"{object_analytics.retention_days(env)} days",
451 "shared_with": [],
452 })
453 else:
454 sections.append({
455 "id": "traffic",
456 "title": "Traffic to this site",
457 "why": "Not collected. This server keeps no record of visits: no "
458 "page log, no visitor counter, no third-party analytics "
459 "script of any kind.",
460 "kept": "nothing is stored",
461 "shared_with": [],
462 })
463
464 if "app-orders" in installed or "app-invoices" in installed:
465 sections.append({
466 "id": "orders",
467 "title": "Orders and invoices",
468 "why": "To take, fulfil and account for what you bought. These are "
469 "business records.",
470 "kept": "for as long as the law requires business records to be "
471 "kept, which is longer than you might expect",
472 "shared_with": [],
473 })
474
475 if "app-payments" in installed:
476 stripe_configured = object_stripe.stripe_config_from_env(env).configured
477 sections.append({
478 "id": "payments",
479 "title": "Payments",
480 "why": "To take payment and to reconcile it against your invoice.",
481 "kept": "with the invoice it pays",
482 "shared_with": (["Stripe"] if stripe_configured else []),
483 "note": ("Card details are entered on Stripe's own pages and never "
484 "reach this server; what it stores is the amount, the "
485 "date and Stripe's reference."
486 if stripe_configured else
487 "No payment provider is configured on this server; "
488 "payments are recorded by hand."),
489 })
490
491 if "app-shipping" in installed:
492 carrier = _settings(base).get(CARRIER_PROVIDER_KEY, "").strip().lower()
493 integrated = carrier not in ("", "none", "manual")
494 sections.append({
495 "id": "fulfilment",
496 "title": "Delivery",
497 "why": "To get the parcel to the address you gave.",
498 "kept": "with the order it belongs to",
499 "shared_with": ([carrier] if integrated else []),
500 "note": ("Your delivery address and name are sent to this carrier "
501 "so a label can be produced."
502 if integrated else
503 "No carrier account is connected to this server, so no "
504 "address is sent to one from here."),
505 })
506
507 smtp = object_email.smtp_config_from_env(env)
508 if smtp.mode != "disabled":
509 sections.append({
510 "id": "email",
511 "title": "Email we send you",
512 "why": "Order confirmations, invoices and replies to things you "
513 "asked about.",
514 "kept": "with the record that caused it",
515 "shared_with": ([smtp.host] if smtp.mode == "live" and smtp.host
516 else []),
517 "note": ("Outgoing mail is handed to this mail server for "
518 "delivery." if smtp.mode == "live" and smtp.host else
519 "Mail is written to a local log on this server rather "
520 "than sent."),
521 })
522
523 ai_services = _ai_services(base)
524 if ai_services:
525 sections.append({
526 "id": "ai",
527 "title": "AI features",
528 "why": "Text you type into an AI feature on this server is sent to "
529 "the provider below to answer it.",
530 "kept": "the request is not stored by this server beyond its usage "
531 "record (which service, how many tokens, when)",
532 "shared_with": list(ai_services),
533 "note": "AI features are only reachable by a signed-in operator of "
534 "this server, not by visitors.",
535 })
536
537 return sections
538
539
540def subprocessors(*, base=None, env=None, installed=None):
541 """Third parties that actually have credentials on this box.
542
543 Derived, so it is a list nobody has to remember to update: a key
544 removed from the environment removes the row, and a provider nobody
545 configured never appears. It is a list of who this server CAN send
546 data to, which is the question a reader is asking.
547 """
548 base = _data_dir() if base is None else base
549 env = os.environ if env is None else env
550 if installed is None:
551 installed = installed_packages(base)
552
553 rows = []
554 if "app-payments" in installed and object_stripe.stripe_config_from_env(env).configured:
555 rows.append({
556 "name": "Stripe",
557 "role": "Payment processing",
558 "data": "your name, email address, and the amount and reference of "
559 "the payment",
560 "because": "DBBASIC_STRIPE_SECRET_KEY and "
561 "DBBASIC_STRIPE_WEBHOOK_SECRET are configured",
562 })
563
564 carrier = _settings(base).get(CARRIER_PROVIDER_KEY, "").strip().lower()
565 if "app-shipping" in installed and carrier not in ("", "none", "manual"):
566 rows.append({
567 "name": carrier,
568 "role": "Delivery",
569 "data": "the delivery name and address on your order",
570 "because": f"app_settings {CARRIER_PROVIDER_KEY} is set to "
571 f"{carrier!r}",
572 })
573
574 smtp = object_email.smtp_config_from_env(env)
575 if smtp.mode == "live" and smtp.host:
576 rows.append({
577 "name": smtp.host,
578 "role": "Email delivery",
579 "data": "your email address and the contents of mail sent to you",
580 "because": "DBBASIC_SMTP_MODE is live and DBBASIC_SMTP_HOST is set",
581 })
582
583 for service in _ai_services(base):
584 rows.append({
585 "name": service,
586 "role": "AI features",
587 "data": "the text an operator of this server types into an AI "
588 "feature, and whatever server records that feature reads "
589 "to answer it",
590 "because": f"an API key for {service} is stored on this server",
591 })
592
593 return rows
594
595
596def _rights(controller, analytics):
597 """What a subject can actually be given here, stated as capability
598 rather than as law. `export` is real -- action_export_subject_data
599 folds every collection keyed to an email. Erasure is deliberately
600 absent rather than promised: see that object's docstring."""
601 return {
602 "contact_email": controller["contact_email"],
603 "export": "Ask, and everything this server holds against your email "
604 "address can be exported and sent to you.",
605 "correction": "Ask, and a wrong name, address or email will be "
606 "corrected.",
607 "erasure": "Ask. Orders, invoices and payments are business records "
608 "with a statutory retention period and usually cannot be "
609 "deleted; contact details that are not part of such a "
610 "record can be.",
611 "traffic": ("Traffic records are keyed to an address and a token with "
612 "no link to a person, so they cannot be searched for you "
613 "in either direction; they age out on the retention above."
614 if analytics["enabled"] else
615 "No traffic records exist, so there are none to ask about."),
616 }
617
618
619# === rendering ===============================================================
620
621def _markdown_ish(text):
622 """Paragraphs and line breaks, escaped. Deliberately not a Markdown
623 engine: this is an operator's legal text and the failure mode of a
624 half-implemented renderer is a mangled legal sentence."""
625 paragraphs = [block.strip() for block in str(text or "").split("\n\n")
626 if block.strip()]
627 return "".join(f"<p>{_esc(block).replace(chr(10), '<br>')}</p>"
628 for block in paragraphs)
629
630
631def _days(value):
632 """14, not 14.0. A lifetime rendered with a spurious decimal reads as
633 a computed estimate rather than the exact number of seconds this
634 server writes."""
635 return int(value) if float(value) == int(value) else value
636
637
638def _cookie_row_html(row):
639 necessary = ('<span class="yes">Yes</span>' if row["strictly_necessary"]
640 else "No")
641 because = (f'<br><span class="muted">{_esc(row["necessary_because"])}</span>'
642 if row["necessary_because"] else "")
643 return (f'<tr><td><code>{_esc(row["name"])}</code></td>'
644 f'<td>{_esc(row["purpose"])}'
645 f'<br><span class="muted">{_esc(row["set_when"])}</span></td>'
646 f'<td>{_days(row["max_age_days"])} days'
647 f'<br><span class="muted">Max-Age={row["max_age_seconds"]}</span>'
648 f'</td>'
649 f'<td>{necessary}{because}</td></tr>')
650
651
652def _cookie_table_html(rows):
653 if not rows:
654 return ('<p>This server sets <strong>no cookies at all</strong> in the '
655 'configuration it is running.</p>')
656 body = "".join(_cookie_row_html(row) for row in rows)
657 return f"""
658<table>
659<thead><tr><th>Cookie</th><th>What it is for</th><th>How long</th>
660<th>Strictly necessary?</th></tr></thead>
661<tbody>{body}</tbody></table>
662<p class="note">Every cookie above is <strong>first-party</strong> (set by
663this server, sent only back to it), <strong>HttpOnly</strong> (no script on
664the page can read it) and <strong>SameSite=Lax</strong>. None of them is an
665advertising or cross-site identifier, and there is no third-party script on
666any page of this site to set one.</p>
667"""
668
669
670def _analytics_html(analytics):
671 if not analytics["enabled"]:
672 return """
673<h2>What is recorded about your visit</h2>
674<p><strong>Nothing.</strong> This server keeps no log of page views: no
675record of which pages were read, no visitor counter, and no third-party
676analytics script. Requests may appear briefly in ordinary web-server
677operational logs, which is not something this application stores or
678reads.</p>
679"""
680 fields = "".join(
681 f"<tr><td>{_esc(row['field'])}</td><td>{_esc(row['meaning'])}</td></tr>"
682 for row in analytics["fields"])
683 cookie_line = (
684 f"A <code>{_esc(object_analytics.VISITOR_COOKIE_NAME)}</code> cookie is "
685 f"set so a returning visit can be told from a new one; it is described "
686 f"in the table below."
687 if analytics["visitor_cookie"] else
688 "<strong>No cookie is involved.</strong> Visits are counted by network "
689 "address, which means a returning visitor is indistinguishable from a "
690 "new one — that is the trade this server makes rather than storing an "
691 "identifier on your device.")
692 return f"""
693<h2>What is recorded about your visit</h2>
694<p>Every request this server answers appends one row to its own log, on its
695own disk. No third party is involved and no script is served to your browser
696to do it. {cookie_line}</p>
697<table>
698<thead><tr><th>Field</th><th>What it is</th></tr></thead>
699<tbody>{fields}</tbody></table>
700<p>Those rows are kept for <strong>{analytics["retention_days"]} days</strong>
701and then deleted, and the log is additionally capped at
702{analytics["max_rows"]:,} rows so the oldest are dropped if it fills sooner.
703Both figures are read from this server's own configuration by the page you
704are reading, so they are the numbers actually in force.</p>
705<p class="note"><strong>Do Not Track and Global Privacy Control are
706honoured.</strong> If your browser sends either signal, no cookie is set for
707you at all. You are still counted by address, because asking not to be
708remembered is not the same as asking not to be counted.</p>
709"""
710
711
712def _processing_html(sections):
713 parts = []
714 for section in sections:
715 shared = section.get("shared_with") or []
716 shared_line = (
717 f"<p>Shared with: {_esc(', '.join(shared))}.</p>" if shared else "")
718 note = (f"<p>{_esc(section['note'])}</p>" if section.get("note") else "")
719 parts.append(
720 f"<h3>{_esc(section['title'])}</h3>"
721 f"<p>{_esc(section['why'])}</p>{note}{shared_line}"
722 f"<p class=\"muted\">Kept: {_esc(section['kept'])}.</p>")
723 return "".join(parts)
724
725
726def _subprocessors_html(rows):
727 if not rows:
728 return ("<p>None. No third party is configured on this server, so "
729 "nothing you give it is sent anywhere else.</p>")
730 body = "".join(
731 f"<tr><td>{_esc(row['name'])}</td><td>{_esc(row['role'])}</td>"
732 f"<td>{_esc(row['data'])}</td></tr>" for row in rows)
733 return f"""
734<table>
735<thead><tr><th>Who</th><th>What for</th><th>What they receive</th></tr></thead>
736<tbody>{body}</tbody></table>
737<p class="note">This list is generated from the credentials actually
738configured on this server, not maintained by hand. A provider that is not
739set up cannot appear on it, and one that is set up cannot be left off.</p>
740"""
741
742
743def _unsigned_html(fold):
744 """The refusal. It names the missing settings and states no policy.
745
746 Rendering a policy body under a heading with nobody's name on it would
747 be the worst of both: a reader would take it for a commitment and have
748 no one to hold to it.
749 """
750 missing = set(fold["controller"]["missing_settings"])
751 rows = "".join(
752 f"<tr><td><code>{_esc(key)}</code></td><td>{_esc(why)}</td>"
753 f"<td>{'<strong>missing</strong>' if key in missing else 'set'}</td></tr>"
754 for key, why in REQUIRED_SETTINGS)
755 return f"""
756<div class="breadcrumb"><a href="/">Home</a> / Privacy</div>
757<h1>No privacy policy has been published for this server</h1>
758<div class="refusal">
759<p>This page generates a privacy policy from the server's own
760configuration, and it will not publish one that nobody has signed. A policy
761with no named controller and no address to write to looks like compliance
762while giving a reader nobody to contact, which is worse than saying
763nothing.</p>
764<p>The operator of this server needs to set the following in
765<code>app_settings</code>:</p>
766<table>
767<thead><tr><th>Setting</th><th>What it is</th><th></th></tr></thead>
768<tbody>{rows}</tbody></table>
769<p>Optionally also <code>{_esc(EXTRA_MARKDOWN_KEY)}</code>, for reviewed
770legal wording of your own. This page never writes legal text itself — it
771states facts about the software and stops.</p>
772</div>
773<p>The cookie facts are true regardless of who signed them, so they are
774published anyway: <a href="/cookies">what this server stores in your
775browser</a>.</p>
776"""
777
778
779def _policy_html(fold):
780 controller = fold["controller"]
781 extra = fold["extra_markdown"]
782 extra_html = (f"<h2>Additional terms from {_esc(controller['name'])}</h2>"
783 f"{_markdown_ish(extra)}"
784 f"<p class=\"note\">The section above is the operator's own "
785 f"text. Everything else on this page is generated from this "
786 f"server's configuration.</p>") if extra else ""
787 rights = fold["rights"]
788 return f"""
789<div class="breadcrumb"><a href="/">Home</a> / Privacy</div>
790<h1>Privacy</h1>
791<p class="note">This page is <strong>generated from this server's live
792configuration</strong> every time it is loaded — the retention periods, the
793cookie lifetimes and the list of third parties below are read from the
794settings actually in force, not from a template. It describes what the
795software does. It contains no legal interpretation, because the software
796is not in a position to offer any.</p>
797
798<h2>Who is responsible</h2>
799<p><strong>{_esc(controller['name'])}</strong>, established in
800{_esc(controller['jurisdiction'])}, is responsible for the information
801described here. Write to
802<a href="mailto:{_esc(controller['contact_email'])}">
803{_esc(controller['contact_email'])}</a> about anything on this page.</p>
804
805{_analytics_html(fold["analytics"])}
806
807<h2>Cookies</h2>
808{_cookie_table_html(fold["cookies"])}
809
810<h2>What else this server holds, and why</h2>
811{_processing_html(fold["processing"])}
812
813<h2>Who else receives it</h2>
814{_subprocessors_html(fold["subprocessors"])}
815
816<h2>What you can ask for</h2>
817<ul>
818<li><strong>A copy of your data.</strong> {_esc(rights['export'])}</li>
819<li><strong>A correction.</strong> {_esc(rights['correction'])}</li>
820<li><strong>Deletion.</strong> {_esc(rights['erasure'])}</li>
821</ul>
822<p>{_esc(rights['traffic'])}</p>
823<p>Write to <a href="mailto:{_esc(controller['contact_email'])}">
824{_esc(controller['contact_email'])}</a>.</p>
825
826{extra_html}
827
828<p class="note">A machine-readable version of everything above is at
829<a href="/privacy.json">/privacy.json</a>, and the cookie table on its own is
830at <a href="/cookies">/cookies</a>. They are the same fold over the same
831settings, so they cannot disagree with this page.</p>
832"""
833
834
835def _cookies_page_html(fold):
836 return f"""
837<div class="breadcrumb"><a href="/">Home</a> / <a href="/privacy">Privacy</a>
838 / Cookies</div>
839<h1>Cookies</h1>
840<p>Everything this server can store in your browser, with the lifetime it
841actually sets. Read from the running configuration, so it is the current
842list rather than a list somebody maintained.</p>
843{_cookie_table_html(fold["cookies"])}
844<p><a href="/privacy">The full privacy page</a> &middot;
845<a href="/privacy.json">machine-readable</a></p>
846"""
847
848
849def _page(title, body):
850 return {
851 "status": 200,
852 "content_type": "text/html; charset=utf-8",
853 "body": f"""<!doctype html>
854<html lang="en">
855<head>
856<meta charset="utf-8">
857<meta name="viewport" content="width=device-width, initial-scale=1">
858<title>{_esc(title)}</title>
859<link rel="stylesheet" href="/style">
860<style>{_STYLE}</style>
861</head>
862<body>
863<div class="wrap pp">
864<header class="app"><h1><a href="/">DBBASIC</a></h1></header>
865{body}
866</div>
867<script src="/nav"></script>
868</body>
869</html>""",
870 }
871
872
873def GET(request):
874 path = str((request or {}).get("_path") or "/privacy").strip().lower()
875 fold = policy()
876
877 if path.endswith(".json"):
878 # The JSON surface is served whether or not the policy is signed:
879 # an unsigned fold is still an honest answer, and it says so in
880 # `controller.signed` and `controller.missing_settings` rather
881 # than by 404ing and leaving a monitor guessing.
882 return {
883 "status": 200,
884 "content_type": "application/json; charset=utf-8",
885 "body": json.dumps(fold, indent=2, sort_keys=True),
886 }
887
888 if path.rstrip("/").endswith("/cookies"):
889 return _page("Cookies", _cookies_page_html(fold))
890
891 if not fold["controller"]["signed"]:
892 return _page("Privacy", _unsigned_html(fold))
893 return _page("Privacy", _policy_html(fold))
894
895
896def POST(request):
897 # Reading a policy is a read either way.
898 return GET(request)