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
notary.py · 13.4 KB · 353 lines
1"""site_notary -- the public face of the notary.
2
3 GET /notary what it is, and a box to check a digest
4 GET /notary/{digest} was this recorded here, and when
5 GET /notary/{digest}.json the same answer, machine-readable
6
7## Why the check is public
8
9An attestation that only its submitter can look up is not an attestation,
10it is a favour. The entire value of lodging a digest with an independent
11party is that a third person -- a customer, an auditor, a court, the other
12side of an argument -- can verify it without needing an account here, a
13relationship with the operator, or anybody's permission. So this page
14answers anybody, and it answers the same way every time.
15
16That is also why the answer for an unknown digest is a plain "not
17recorded here" rather than a 404: a checker asking about a digest they
18were given deserves a sentence explaining that absence proves nothing,
19not a browser error page they will read as a fault.
20
21## The file is hashed in the browser and never uploaded
22
23The page carries a drop box that computes a sha256 with SubtleCrypto,
24locally, and fills the digest in. Nothing is sent. This is the one feature
25here that is not strictly necessary, and it earns its place by making the
26central claim visible rather than merely stated: a visitor can watch their
27own file produce a digest without a request leaving the machine, and then
28decide for themselves whether notarizing something confidential is safe.
29A page that only ASSERTS "we never see your content" is asking to be
30believed; one that demonstrates it is not.
31
32## What it will not say
33
34Every answer renders object_notary.attestation() -- what the record
35proves, what it does not, and what it rests on -- immediately beside the
36result rather than in a footnote. The failure mode of a notary is not
37technical. It is a reader taking "notarized" to mean verified, owned or
38approved, and then relying on it. The wording lives in object_notary so
39this page, the JSON and the submission receipt cannot drift into three
40different strengths of the same promise.
41"""
42
43import html
44import json
45import os
46
47import object_notary
48import object_records
49
50COLLECTION = "notarizations"
51SETTINGS_COLLECTION = "app_settings"
52PUBLIC_SUBMISSION_KEY = "notary.public_submission"
53
54_STYLE = """
55.nt { max-width: 46rem; }
56.nt h2 { font-size: 1.05rem; margin: 1.8rem 0 .4rem; }
57.nt p, .nt li { line-height: 1.55; }
58.nt .digest { font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
59 font-size: .82rem; word-break: break-all; }
60.nt .card { border: 1px solid var(--line, #38384a); border-radius: 8px;
61 padding: .9rem 1.1rem; margin: 1rem 0; }
62.nt .hit { border-color: var(--accent, #b5713a); }
63.nt .when { font-size: 1.35rem; font-weight: 600; margin: .3rem 0 .1rem; }
64.nt .note { border-left: 3px solid var(--line, #55556a); padding: .1rem 0 .1rem .7rem;
65 margin: .6rem 0 1.2rem; font-size: .88rem; opacity: .85; }
66.nt .cols { display: grid; gap: 1rem; grid-template-columns: 1fr 1fr; }
67@media (max-width: 40rem) { .nt .cols { grid-template-columns: 1fr; } }
68.nt .cols h3 { font-size: .9rem; margin: 0 0 .4rem; text-transform: uppercase;
69 letter-spacing: .04em; opacity: .75; }
70.nt .cols ul { margin: 0; padding-left: 1.1rem; font-size: .9rem; }
71.nt input[type=text] { width: 100%; font-family: ui-monospace, monospace;
72 font-size: .85rem; padding: .5rem .6rem; box-sizing: border-box; }
73.nt .drop { border: 1px dashed var(--line, #55556a); border-radius: 8px;
74 padding: 1.1rem; text-align: center; font-size: .9rem; margin: .6rem 0; }
75.nt .drop.over { border-color: var(--accent, #b5713a); }
76"""
77
78
79def _esc(value):
80 return html.escape(str(value if value is not None else ""), quote=True)
81
82
83def _base_dir():
84 return os.environ.get("DBBASIC_DATA_DIR", "data")
85
86
87def _rows(base):
88 try:
89 # access: open by design: the lookup answers only for a digest the caller supplies (the site_notary grant reason)
90 return object_records.read_collection_records(COLLECTION, base_dir=base)
91 except Exception:
92 return []
93
94
95def _public_submission_allowed(base):
96 try:
97 # access: box configuration
98 rows = object_records.read_collection_records(
99 SETTINGS_COLLECTION, base_dir=base)
100 except Exception:
101 return False
102 for row in rows:
103 if str(row.get("key") or "").strip() == PUBLIC_SUBMISSION_KEY:
104 return str(row.get("value") or "").strip().lower() in {
105 "1", "true", "yes", "on"}
106 return False
107
108
109def lookup(digest, *, base=None, algorithm=None):
110 """The answer, as a plain dict. One fold, three surfaces.
111
112 Tries every supported algorithm when none is named, because a checker
113 handed a bare hex string knows what it is only by its length -- and
114 refusing to look because they did not say sha512 would be pedantry
115 standing between somebody and the fact they came for.
116 """
117 base = _base_dir() if base is None else base
118 rows = _rows(base)
119 candidates = ([algorithm] if algorithm
120 else sorted(object_notary.ALGORITHMS))
121 for name in candidates:
122 normalized = object_notary.normalize_digest(digest, name)
123 if not normalized:
124 continue
125 found = object_notary.first_seen(normalized, rows, name)
126 if found is not None:
127 return object_notary.receipt(found)
128 return object_notary.receipt(None, found=False)
129
130
131# --- rendering ---------------------------------------------------------------
132
133def _attestation_html(attestation):
134 proves = "".join(f"<li>{_esc(line)}</li>"
135 for line in attestation.get("proves") or [])
136 denies = "".join(f"<li>{_esc(line)}</li>"
137 for line in attestation.get("does_not_prove") or [])
138 rests = "".join(f"<p class=\"note\">{_esc(line)}</p>"
139 for line in attestation.get("rests_on") or [])
140 proves_block = (f"<div><h3>What this proves</h3><ul>{proves}</ul></div>"
141 if proves else "")
142 return f"""
143<div class="cols">
144{proves_block}
145<div><h3>What it does not prove</h3><ul>{denies}</ul></div>
146</div>
147{rests}
148"""
149
150
151def _result_html(digest, answer):
152 shown = _esc(object_notary.normalize_digest(digest, "sha512")
153 or object_notary.normalize_digest(digest, "sha256")
154 or digest)
155 if not answer["found"]:
156 return f"""
157<div class="breadcrumb"><a href="/">Home</a> / <a href="/notary">Notary</a>
158 / Check</div>
159<h1>Not recorded here</h1>
160<p class="digest">{shown}</p>
161<div class="card">
162<p>This server has <strong>no record of that digest</strong>.</p>
163<p>That is not evidence of anything. A digest is absent because nobody
164lodged it here — which may mean it was lodged with a different notary,
165lodged under a different algorithm, or never lodged at all. Absence from
166this log proves nothing about the data, its age or its author.</p>
167</div>
168<p><a href="/notary">Check another, or lodge one</a></p>
169"""
170
171 return f"""
172<div class="breadcrumb"><a href="/">Home</a> / <a href="/notary">Notary</a>
173 / Check</div>
174<h1>Recorded</h1>
175<p class="digest">{_esc(answer['digest'])}</p>
176<div class="card hit">
177<p class="muted">First recorded by this server at</p>
178<p class="when"><time datetime="{_esc(answer['first_seen_at'])}">
179{_esc(answer['first_seen_at'])}</time></p>
180<p class="muted">{_esc(answer['first_seen_at'])} UTC &mdash; the canonical
181value, shown because an attestation is evidence and evidence should not
182change shape with who is reading it. The line above is the same instant in
183your own timezone.</p>
184<p class="muted">{_esc(answer['algorithm'])}{
185 ' &middot; ' + _esc(answer['label']) if answer.get('label') else ''}</p>
186</div>
187{_attestation_html(answer['attestation'])}
188<p><a href="/notary/{_esc(answer['digest'])}.json">This answer as JSON</a>
189 &middot; <a href="/notary">check another</a></p>
190"""
191
192
193def _index_html(base, count):
194 open_submission = _public_submission_allowed(base)
195 submit_line = (
196 "<p>Anyone may lodge a digest with this server.</p>"
197 if open_submission else
198 "<p>Lodging a digest here requires an account or a service key. "
199 "Checking one does not, and never will.</p>")
200 return f"""
201<div class="breadcrumb"><a href="/">Home</a> / Notary</div>
202<h1>Notary</h1>
203<p>This server keeps an <strong>append-only list of digests and the moment
204each was first seen</strong>. Lodge one now, and at any point in the future
205anybody can confirm that the data it was computed from already existed by
206then.</p>
207<p class="note">It holds <strong>{count:,}</strong> digest{
208 '' if count == 1 else 's'} and <strong>no content whatsoever</strong>.
209There is no field for a file, no code path that would accept one, and
210nothing here worth stealing. That is the design, not a stage it will grow
211out of.</p>
212
213<h2>Check a digest</h2>
214<form id="check" onsubmit="return goCheck(event)">
215<p><input type="text" id="digest" name="digest" autocomplete="off"
216 spellcheck="false" placeholder="paste a sha256 or sha512 hex digest"></p>
217<p><button type="submit">Check</button></p>
218</form>
219
220<div class="drop" id="drop">
221<strong>Or drop a file here</strong> to hash it.<br>
222<span class="muted">It is hashed by your browser and never uploaded — no
223request leaves this machine, and this server never learns anything about
224it.</span>
225<div><input type="file" id="file"></div>
226</div>
227
228<h2>Lodging one</h2>
229{submit_line}
230<pre><code>POST /objects/action_notarize
231{{"digest": "&lt;hex&gt;", "algorithm": "sha256", "label": "optional note"}}</code></pre>
232<p>Submitting the same digest twice returns the <strong>original</strong>
233record and its original time. A later submission cannot make something
234earlier, so nothing here can walk a timestamp forward.</p>
235
236<h2>What this is for</h2>
237<ul>
238<li>Anchoring the head of a ledger somewhere its own server cannot reach,
239so rewriting history means also rewriting a record held elsewhere.</li>
240<li>A contract, a photograph before an insurance claim, source code at a
241release, experimental data before it is analysed.</li>
242<li>Anywhere somebody may later need to say <em>this existed then, and here
243is an independent party that saw it</em>.</li>
244</ul>
245
246{_attestation_html(object_notary.attestation())}
247
248<script>
249function goCheck(event) {{
250 event.preventDefault();
251 var value = document.getElementById('digest').value.trim();
252 if (value) location.href = '/notary/' + encodeURIComponent(value);
253 return false;
254}}
255(function () {{
256 var drop = document.getElementById('drop');
257 var input = document.getElementById('file');
258 var box = document.getElementById('digest');
259 if (!drop || !window.crypto || !window.crypto.subtle) {{
260 if (drop) drop.innerHTML = '<span class="muted">Your browser cannot ' +
261 'hash files locally here (it needs a secure context), so paste a ' +
262 'digest above instead. Nothing is uploaded either way.</span>';
263 return;
264 }}
265 function hash(file) {{
266 if (!file) return;
267 drop.classList.remove('over');
268 var reader = new FileReader();
269 reader.onload = function () {{
270 crypto.subtle.digest('SHA-256', reader.result).then(function (buf) {{
271 var hex = Array.prototype.map.call(new Uint8Array(buf), function (b) {{
272 return ('00' + b.toString(16)).slice(-2);
273 }}).join('');
274 box.value = hex;
275 box.focus();
276 }});
277 }};
278 reader.readAsArrayBuffer(file);
279 }}
280 input.addEventListener('change', function () {{ hash(input.files[0]); }});
281 ['dragenter', 'dragover'].forEach(function (name) {{
282 drop.addEventListener(name, function (e) {{
283 e.preventDefault(); drop.classList.add('over');
284 }});
285 }});
286 drop.addEventListener('dragleave', function () {{
287 drop.classList.remove('over');
288 }});
289 drop.addEventListener('drop', function (e) {{
290 e.preventDefault();
291 hash(e.dataTransfer.files && e.dataTransfer.files[0]);
292 }});
293}})();
294</script>
295"""
296
297
298def _page(title, body):
299 return {
300 "status": 200,
301 "content_type": "text/html; charset=utf-8",
302 "body": f"""<!doctype html>
303<html lang="en">
304<head>
305<meta charset="utf-8">
306<meta name="viewport" content="width=device-width, initial-scale=1">
307<title>{_esc(title)}</title>
308<link rel="stylesheet" href="/style">
309<style>{_STYLE}</style>
310</head>
311<body>
312<div class="wrap nt">
313<header class="app"><h1><a href="/">DBBASIC</a></h1></header>
314{body}
315</div>
316<script src="/nav"></script>
317</body>
318</html>""",
319 }
320
321
322def GET(request):
323 request = request or {}
324 base = _base_dir()
325 digest = str(request.get("digest") or "").strip()
326
327 wants_json = digest.lower().endswith(".json")
328 if wants_json:
329 digest = digest[:-len(".json")]
330
331 if not digest:
332 return _page("Notary", _index_html(base, len(_rows(base))))
333
334 answer = lookup(digest, base=base)
335 if wants_json:
336 # 200 either way, including for a digest that is not here. "Not
337 # recorded" is a complete and correct answer to the question asked,
338 # and a monitor that has to distinguish a 404-meaning-absent from a
339 # 404-meaning-broken will eventually get it wrong.
340 return {
341 "status": 200,
342 "content_type": "application/json; charset=utf-8",
343 "body": json.dumps(answer, indent=2, sort_keys=True),
344 }
345 return _page("Notary", _result_html(digest, answer))
346
347
348def POST(request):
349 # Checking a digest is a read however it is spelled. Lodging one is
350 # action_notarize, deliberately a different object: a page that both
351 # answered questions and wrote rows would be one refactor away from
352 # recording a digest somebody only meant to look up.
353 return GET(request)