egzoscore 0.2.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- egzos/__init__.py +11 -0
- egzos/_ids.py +29 -0
- egzos/_signals.py +39 -0
- egzos/_term.py +33 -0
- egzos/_types.py +1023 -0
- egzos/api/__init__.py +150 -0
- egzos/api/app.py +1574 -0
- egzos/api/blobs.py +92 -0
- egzos/api/throttle.py +190 -0
- egzos/auth.py +176 -0
- egzos/authz/__init__.py +5 -0
- egzos/authz/presence.py +778 -0
- egzos/authz/values.py +32 -0
- egzos/backends/__init__.py +8 -0
- egzos/backends/base.py +91 -0
- egzos/backends/postgres.py +490 -0
- egzos/backends/sqlite.py +524 -0
- egzos/binding.py +309 -0
- egzos/cli/__init__.py +1092 -0
- egzos/cli/__main__.py +11 -0
- egzos/confirm.py +455 -0
- egzos/container.py +222 -0
- egzos/identity.py +1104 -0
- egzos/ledger.py +167 -0
- egzos/mcp/__init__.py +3 -0
- egzos/mcp/http.py +90 -0
- egzos/mcp/server.py +287 -0
- egzos/model.py +242 -0
- egzos/py.typed +0 -0
- egzos/resolver.py +115 -0
- egzos/store/__init__.py +10 -0
- egzos/store/autotitle.py +31 -0
- egzos/store/blobs.py +120 -0
- egzos/store/find.py +120 -0
- egzos/store/items.py +233 -0
- egzos/store/nodes.py +193 -0
- egzos/store/objects.py +143 -0
- egzos/store/uploads.py +369 -0
- egzos/trust.py +675 -0
- egzos/web/__init__.py +88 -0
- egzos/web/app.py +965 -0
- egzos/web/static/htmx.LICENSE +13 -0
- egzos/web/static/htmx.min.js +1 -0
- egzos/web/static/lifeboat.css +140 -0
- egzos/web/static/lifeboat.js +12 -0
- egzos/web/strings.py +133 -0
- egzos/web/templates/_manifest_row.html +3 -0
- egzos/web/templates/_shell.html +29 -0
- egzos/web/templates/_window.html +7 -0
- egzos/web/templates/base.html +24 -0
- egzos/web/templates/error.html +10 -0
- egzos/web/templates/home.html +39 -0
- egzos/web/templates/item.html +91 -0
- egzos/web/templates/notfound.html +6 -0
- egzos/web/templates/pending.html +107 -0
- egzos/web/tokens.css +294 -0
- egzoscore-0.2.0.dist-info/METADATA +135 -0
- egzoscore-0.2.0.dist-info/RECORD +62 -0
- egzoscore-0.2.0.dist-info/WHEEL +4 -0
- egzoscore-0.2.0.dist-info/entry_points.txt +2 -0
- egzoscore-0.2.0.dist-info/licenses/LICENSE +65 -0
- egzoscore-0.2.0.dist-info/licenses/NOTICE +6 -0
egzos/cli/__main__.py
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
# Copyright 2026 Ali Sasanian
|
|
2
|
+
# SPDX-License-Identifier: LicenseRef-PolyForm-Strict-1.0.0
|
|
3
|
+
"""Allow `python -m egzos.cli` to invoke the CLI."""
|
|
4
|
+
from __future__ import annotations
|
|
5
|
+
|
|
6
|
+
import sys
|
|
7
|
+
|
|
8
|
+
from egzos.cli import main
|
|
9
|
+
|
|
10
|
+
if __name__ == "__main__":
|
|
11
|
+
sys.exit(main())
|
egzos/confirm.py
ADDED
|
@@ -0,0 +1,455 @@
|
|
|
1
|
+
# Copyright 2026 Ali Sasanian
|
|
2
|
+
# SPDX-License-Identifier: LicenseRef-PolyForm-Strict-1.0.0
|
|
3
|
+
"""
|
|
4
|
+
The confirm (identity.md §5, rest.md §4.2–§4.3): how a person says yes to something that widens who
|
|
5
|
+
can see an item, and to every human-only act.
|
|
6
|
+
|
|
7
|
+
Two legs on one route. The first leg issues a challenge bound to this request — the principal, the
|
|
8
|
+
act, its subject and destination, and the audience delta — and shows who would newly see the item.
|
|
9
|
+
The second leg presents the challenge and a proof. As one transaction the challenge is spent
|
|
10
|
+
(confirmed or refused alike, so a refusal never leaves a challenge to retry), its binding checked,
|
|
11
|
+
and the proof verified; the act lands in the same transaction. Every concluded proof is a
|
|
12
|
+
`step_up` entry, with `details.proof` and, for a refusal, `details.reason`.
|
|
13
|
+
|
|
14
|
+
Two proofs. `biometric`: a WebAuthn assertion with user verification from a credential the person
|
|
15
|
+
registered here (Face ID, Touch ID, Windows Hello), verified by the maintained `webauthn` library
|
|
16
|
+
against the stored public key. `button`: an explicit confirm, only for a person with no registered
|
|
17
|
+
credential, and only where `confirm.allow_button` is on — once a person has a credential, every
|
|
18
|
+
confirm of theirs needs it, so a stolen session cannot fall back to the button.
|
|
19
|
+
|
|
20
|
+
A credential belongs to a relying party: the browser origin it was made on (`egzos.io`, a fork's
|
|
21
|
+
UI). The door passes the request's `Origin` only when it is one of `identity.browser_origins`, so an
|
|
22
|
+
assertion made on any other origin never verifies.
|
|
23
|
+
"""
|
|
24
|
+
|
|
25
|
+
from __future__ import annotations
|
|
26
|
+
|
|
27
|
+
import base64
|
|
28
|
+
import hashlib
|
|
29
|
+
import json
|
|
30
|
+
import secrets
|
|
31
|
+
import time
|
|
32
|
+
from collections.abc import Callable
|
|
33
|
+
from datetime import UTC, datetime
|
|
34
|
+
from typing import Any
|
|
35
|
+
from urllib.parse import urlsplit
|
|
36
|
+
|
|
37
|
+
from webauthn import (
|
|
38
|
+
generate_authentication_options,
|
|
39
|
+
generate_registration_options,
|
|
40
|
+
options_to_json,
|
|
41
|
+
verify_authentication_response,
|
|
42
|
+
verify_registration_response,
|
|
43
|
+
)
|
|
44
|
+
from webauthn.helpers.structs import (
|
|
45
|
+
AuthenticatorSelectionCriteria,
|
|
46
|
+
PublicKeyCredentialDescriptor,
|
|
47
|
+
ResidentKeyRequirement,
|
|
48
|
+
UserVerificationRequirement,
|
|
49
|
+
)
|
|
50
|
+
|
|
51
|
+
from egzos._ids import ulid
|
|
52
|
+
from egzos._types import ConfirmChallenge, ConfirmCredential, ConfirmState
|
|
53
|
+
from egzos.identity import SKEW_SECONDS
|
|
54
|
+
from egzos.ledger import Ledger
|
|
55
|
+
from egzos.model import Token, now_iso
|
|
56
|
+
|
|
57
|
+
#: rest.md §4.2 item 5: a challenge lives `step_up.window_seconds`, never less than this.
|
|
58
|
+
MIN_CHALLENGE_SECONDS = 60
|
|
59
|
+
#: How long an expired challenge is kept, so a late second leg still reads `spent` or `stale`.
|
|
60
|
+
CHALLENGE_KEEP_SECONDS = 86400
|
|
61
|
+
#: rest.md §4.3: how old a sign-in may be where an act needs a fresh one.
|
|
62
|
+
FRESH_SIGN_IN_SECONDS = 300
|
|
63
|
+
PROOFS = ("biometric", "button")
|
|
64
|
+
#: rest.md §4.2 item 4's closed reasons: `terminal` for any proof from a terminal's token
|
|
65
|
+
#: (identity.md §5), and §4.3's `not_fresh` and `registered`.
|
|
66
|
+
REASONS = ("stale", "spent", "foreign", "mismatch", "assertion", "button_off", "delta_changed",
|
|
67
|
+
"terminal", "not_fresh", "registered")
|
|
68
|
+
RP_NAME = "egzos"
|
|
69
|
+
#: rest.md §4.3's closed reasons, from the confirm's own (`REASONS`): an add's, and a removal's.
|
|
70
|
+
ADD_REASONS = {"button_off": "button_refused", "assertion": "no_proof"}
|
|
71
|
+
REMOVE_REASONS = {"button_off": "button_refused", "assertion": "assertion"}
|
|
72
|
+
CREDENTIAL_NAME_MAX = 64
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def _iso(ts: float) -> str:
|
|
76
|
+
"""Fixed width, microseconds always written, so two of these compare as the times they are
|
|
77
|
+
(a1r on #289: `isoformat` drops a zero fraction, and `Z` sorts after `.`)."""
|
|
78
|
+
return datetime.fromtimestamp(ts, UTC).strftime("%Y-%m-%dT%H:%M:%S.%fZ")
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def _epoch(text: str) -> float:
|
|
82
|
+
return datetime.fromisoformat(text).timestamp()
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def _b64(raw: bytes) -> str:
|
|
86
|
+
return base64.urlsafe_b64encode(raw).rstrip(b"=").decode()
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def _unb64(text: str) -> bytes:
|
|
90
|
+
return base64.urlsafe_b64decode(text + "=" * (-len(text) % 4))
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
def rp_of(origin: str | None) -> str | None:
|
|
94
|
+
return urlsplit(origin).hostname if origin else None
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
def person_of(token: Token) -> str:
|
|
98
|
+
"""Whose credentials a confirm draws on: the interactive principal's owner — `user:<sub>` for
|
|
99
|
+
a provider sign-in, at a terminal too, the owner token's owner for the container's own."""
|
|
100
|
+
return token.owner
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
def terminal_of(token: Token) -> str | None:
|
|
104
|
+
"""The client id of the terminal `token` came through, or None (identity.md §3a). Such a
|
|
105
|
+
token concludes no confirm and is offered no assertion (identity.md §5)."""
|
|
106
|
+
return getattr(token, "terminal", None)
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
class Confirm:
|
|
110
|
+
def __init__(
|
|
111
|
+
self,
|
|
112
|
+
state: ConfirmState,
|
|
113
|
+
ledger: Ledger,
|
|
114
|
+
config: Callable[[str], Any],
|
|
115
|
+
*,
|
|
116
|
+
window_seconds: Callable[[], int],
|
|
117
|
+
clock: Callable[[], float] = time.time,
|
|
118
|
+
salt: Callable[[], str] = lambda: "",
|
|
119
|
+
):
|
|
120
|
+
self.state = state
|
|
121
|
+
self.ledger = ledger
|
|
122
|
+
self.config = config
|
|
123
|
+
self.window_seconds = window_seconds
|
|
124
|
+
self.clock = clock
|
|
125
|
+
# Per container: what a person's WebAuthn user handle is derived with.
|
|
126
|
+
self.salt = salt
|
|
127
|
+
|
|
128
|
+
# -- credentials ------------------------------------------------------------------------------
|
|
129
|
+
def credentials(self, person: str, rp_id: str | None = None) -> list[ConfirmCredential]:
|
|
130
|
+
return [
|
|
131
|
+
c for c in self.state.list_credentials(person)
|
|
132
|
+
if not c["removed"] and (rp_id is None or c["rp_id"] == rp_id)
|
|
133
|
+
]
|
|
134
|
+
|
|
135
|
+
def _request_options(self, person: str, rp_id: str | None, challenge: str) -> Any:
|
|
136
|
+
creds = self.credentials(person, rp_id) if rp_id else []
|
|
137
|
+
if not creds:
|
|
138
|
+
return None # rest.md §4.2 item 7: no credential here, so no assertion is possible
|
|
139
|
+
options = generate_authentication_options(
|
|
140
|
+
rp_id=rp_id,
|
|
141
|
+
challenge=challenge.encode(),
|
|
142
|
+
allow_credentials=[
|
|
143
|
+
PublicKeyCredentialDescriptor(id=_unb64(c["credential_id"])) for c in creds
|
|
144
|
+
],
|
|
145
|
+
user_verification=UserVerificationRequirement.REQUIRED,
|
|
146
|
+
)
|
|
147
|
+
return json.loads(options_to_json(options))
|
|
148
|
+
|
|
149
|
+
def _challenge(self, token: Token, *, act: str, subject: str, destination: str | None,
|
|
150
|
+
delta: list[str]) -> ConfirmChallenge:
|
|
151
|
+
lifetime = max(MIN_CHALLENGE_SECONDS, self.window_seconds())
|
|
152
|
+
# A day after it expired a challenge only answers `stale`; forget it (a1r on #289).
|
|
153
|
+
self.state.forget_challenges(_iso(self.clock() - CHALLENGE_KEEP_SECONDS))
|
|
154
|
+
challenge: ConfirmChallenge = {
|
|
155
|
+
"id": secrets.token_urlsafe(32),
|
|
156
|
+
"principal": token.id,
|
|
157
|
+
"act": act,
|
|
158
|
+
"subject": subject,
|
|
159
|
+
"destination": destination,
|
|
160
|
+
"delta": sorted(delta),
|
|
161
|
+
"expires_at": _iso(self.clock() + lifetime),
|
|
162
|
+
}
|
|
163
|
+
self.state.put_challenge(challenge)
|
|
164
|
+
return challenge
|
|
165
|
+
|
|
166
|
+
# -- the first leg ----------------------------------------------------------------------------
|
|
167
|
+
def issue(
|
|
168
|
+
self,
|
|
169
|
+
token: Token,
|
|
170
|
+
*,
|
|
171
|
+
act: str,
|
|
172
|
+
subject: str,
|
|
173
|
+
destination: str | None,
|
|
174
|
+
delta: list[str],
|
|
175
|
+
newly: list[str],
|
|
176
|
+
origin: str | None = None,
|
|
177
|
+
) -> dict[str, Any]:
|
|
178
|
+
"""A fresh challenge for this exact request, and the answer the first leg carries. The
|
|
179
|
+
caller appends the first leg's `context.fetch`: showing `newly` is a read. To a terminal's
|
|
180
|
+
token `webauthn` is null whatever the person has registered, and no credential is listed:
|
|
181
|
+
the act is finished in a browser (rest.md §4.2 item 7)."""
|
|
182
|
+
challenge = self._challenge(token, act=act, subject=subject, destination=destination,
|
|
183
|
+
delta=delta)
|
|
184
|
+
webauthn = None if terminal_of(token) is not None else self._request_options(
|
|
185
|
+
person_of(token), rp_of(origin), challenge["id"])
|
|
186
|
+
return {
|
|
187
|
+
"result": "confirm",
|
|
188
|
+
"newly": newly,
|
|
189
|
+
"challenge": challenge["id"],
|
|
190
|
+
"webauthn": webauthn,
|
|
191
|
+
"expires_at": challenge["expires_at"],
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
# -- the second leg ---------------------------------------------------------------------------
|
|
195
|
+
def conclude(
|
|
196
|
+
self,
|
|
197
|
+
token: Token,
|
|
198
|
+
presented: Any,
|
|
199
|
+
*,
|
|
200
|
+
act: str,
|
|
201
|
+
subject: str,
|
|
202
|
+
destination: str | None,
|
|
203
|
+
delta: list[str],
|
|
204
|
+
origin: str | None = None,
|
|
205
|
+
biometric_only: bool = False,
|
|
206
|
+
fresh_sign_in: bool = False,
|
|
207
|
+
refusal: str | None = None,
|
|
208
|
+
) -> str | None:
|
|
209
|
+
"""Spend the presented challenge and judge the proof. `None` is confirmed; otherwise the
|
|
210
|
+
reason it was refused. Either way one `step_up` is appended. Run it inside the act's own
|
|
211
|
+
transaction, so a confirmed proof and the act it confirms land together. `fresh_sign_in`:
|
|
212
|
+
the button also needs a fresh sign-in (rest.md §4.3); a biometric never does. `refusal`:
|
|
213
|
+
a reason of `REASONS` the act's own check found inside that transaction (rest.md §4.3's
|
|
214
|
+
`registered`), which refuses a proof that would otherwise confirm. A terminal's token
|
|
215
|
+
concludes refused, `terminal`, whatever it presents (identity.md §5)."""
|
|
216
|
+
if not isinstance(presented, dict) or presented.get("proof") not in PROOFS:
|
|
217
|
+
raise ValueError("confirm needs a challenge and a proof")
|
|
218
|
+
challenge_id = presented.get("challenge")
|
|
219
|
+
if not isinstance(challenge_id, str) or not challenge_id:
|
|
220
|
+
raise ValueError("confirm needs a challenge and a proof")
|
|
221
|
+
if refusal is not None and refusal not in REASONS:
|
|
222
|
+
raise ValueError(f"not a reason a confirm is refused for: {refusal!r}")
|
|
223
|
+
proof = presented["proof"]
|
|
224
|
+
reason = self._judge(token, challenge_id, presented, act=act, subject=subject,
|
|
225
|
+
destination=destination, delta=delta, origin=origin,
|
|
226
|
+
biometric_only=biometric_only, fresh_sign_in=fresh_sign_in)
|
|
227
|
+
if reason is None:
|
|
228
|
+
reason = refusal
|
|
229
|
+
details: dict[str, Any] = {"via": "confirm", "act": act, "proof": proof,
|
|
230
|
+
"outcome": "refused" if reason else "confirmed"}
|
|
231
|
+
if reason:
|
|
232
|
+
details["reason"] = reason
|
|
233
|
+
terminal = terminal_of(token)
|
|
234
|
+
if terminal is not None: # identity.md §3a, as the door's stamp would add it
|
|
235
|
+
details["terminal"] = terminal
|
|
236
|
+
self.ledger.append("step_up", actor=token.owner, principal=token.principal,
|
|
237
|
+
subject=subject, **details)
|
|
238
|
+
return reason
|
|
239
|
+
|
|
240
|
+
def _judge(self, token: Token, challenge_id: str, presented: dict[str, Any], *, act: str,
|
|
241
|
+
subject: str, destination: str | None, delta: list[str], origin: str | None,
|
|
242
|
+
biometric_only: bool, fresh_sign_in: bool) -> str | None:
|
|
243
|
+
record = self.state.spend_challenge(challenge_id) # spent now, whatever is decided below
|
|
244
|
+
if terminal_of(token) is not None:
|
|
245
|
+
# identity.md §5: a terminal's token concludes no confirm, by either proof, whatever
|
|
246
|
+
# `confirm.allow_button` says and whatever credentials the person has.
|
|
247
|
+
return "terminal"
|
|
248
|
+
if record is None:
|
|
249
|
+
return "stale"
|
|
250
|
+
if record.get("spent"):
|
|
251
|
+
return "spent"
|
|
252
|
+
if _epoch(record["expires_at"]) <= self.clock():
|
|
253
|
+
return "stale"
|
|
254
|
+
if record["principal"] != token.id:
|
|
255
|
+
return "foreign"
|
|
256
|
+
if (record["act"], record["subject"], record["destination"]) != (act, subject, destination):
|
|
257
|
+
return "mismatch"
|
|
258
|
+
if record["delta"] != sorted(delta):
|
|
259
|
+
return "delta_changed"
|
|
260
|
+
person = person_of(token)
|
|
261
|
+
if presented["proof"] == "button":
|
|
262
|
+
# Off by config, off for a person who has registered a credential (identity.md §5),
|
|
263
|
+
# and off for the acts that take a biometric only (removing a credential).
|
|
264
|
+
if biometric_only or not self.config("confirm.allow_button"):
|
|
265
|
+
return "button_off"
|
|
266
|
+
if self.credentials(person):
|
|
267
|
+
return "button_off"
|
|
268
|
+
if fresh_sign_in and not self.fresh(token):
|
|
269
|
+
return "not_fresh"
|
|
270
|
+
return None
|
|
271
|
+
return self._assert(person, presented.get("assertion"), challenge_id, origin)
|
|
272
|
+
|
|
273
|
+
def fresh(self, token: Token) -> bool:
|
|
274
|
+
"""rest.md §4.3's fresh sign-in: the provider token's newest `amr` time at most
|
|
275
|
+
`FRESH_SIGN_IN_SECONDS` old, and not ahead of this clock by more than check 4's skew. A
|
|
276
|
+
container `Token` carries no sign-in, so it is never fresh (a1r on #290)."""
|
|
277
|
+
signed_in = getattr(token, "auth_time", None)
|
|
278
|
+
return signed_in is not None and (
|
|
279
|
+
-SKEW_SECONDS <= self.clock() - signed_in <= FRESH_SIGN_IN_SECONDS)
|
|
280
|
+
|
|
281
|
+
def _assert(self, person: str, assertion: Any, challenge_id: str,
|
|
282
|
+
origin: str | None) -> str | None:
|
|
283
|
+
rp_id = rp_of(origin)
|
|
284
|
+
if not isinstance(assertion, dict) or rp_id is None:
|
|
285
|
+
return "assertion"
|
|
286
|
+
raw_id = assertion.get("id")
|
|
287
|
+
match = next((c for c in self.credentials(person, rp_id)
|
|
288
|
+
if c["credential_id"] == raw_id), None)
|
|
289
|
+
if match is None:
|
|
290
|
+
return "assertion"
|
|
291
|
+
try:
|
|
292
|
+
verified = verify_authentication_response(
|
|
293
|
+
credential=assertion,
|
|
294
|
+
expected_challenge=challenge_id.encode(),
|
|
295
|
+
expected_rp_id=rp_id,
|
|
296
|
+
expected_origin=origin,
|
|
297
|
+
credential_public_key=_unb64(match["public_key"]),
|
|
298
|
+
credential_current_sign_count=match["sign_count"],
|
|
299
|
+
require_user_verification=True,
|
|
300
|
+
)
|
|
301
|
+
except Exception: # noqa: BLE001 — any verification failure is one reason, no detail
|
|
302
|
+
return "assertion"
|
|
303
|
+
self.state.put_credential({**match, "sign_count": verified.new_sign_count,
|
|
304
|
+
"last_used": now_iso()})
|
|
305
|
+
return None
|
|
306
|
+
|
|
307
|
+
def last_step_up_seq(self) -> int | None:
|
|
308
|
+
tail = self.ledger.tail(1)
|
|
309
|
+
return tail[-1]["seq"] if tail else None
|
|
310
|
+
|
|
311
|
+
# -- registration (rest.md §4.3) --------------------------------------------------------------
|
|
312
|
+
def begin_registration(self, token: Token, *, origin: str, name: str) -> dict[str, Any]:
|
|
313
|
+
"""The registration's first leg: creation options under a challenge bound to this person
|
|
314
|
+
and relying party, and, for a person who already has a credential, the assertion's own
|
|
315
|
+
challenge (an existing credential must agree to a new one). Never to a terminal's token:
|
|
316
|
+
a confirm credential is kept from a browser (rest.md §4.3)."""
|
|
317
|
+
if terminal_of(token) is not None:
|
|
318
|
+
raise PermissionError("a confirm credential is registered from a browser")
|
|
319
|
+
person, rp_id = person_of(token), rp_of(origin)
|
|
320
|
+
challenge = self._challenge(token, act="register", subject=person, destination=rp_id,
|
|
321
|
+
delta=[])
|
|
322
|
+
existing = self.credentials(person, rp_id)
|
|
323
|
+
options = generate_registration_options(
|
|
324
|
+
rp_id=rp_id,
|
|
325
|
+
rp_name=RP_NAME,
|
|
326
|
+
user_name=name,
|
|
327
|
+
# Salted per container, so no two containers hand an authenticator the same handle
|
|
328
|
+
# for one person (a1r on #290).
|
|
329
|
+
user_id=hashlib.sha256(f"{self.salt()}|{person}".encode()).digest()[:32],
|
|
330
|
+
user_display_name=name,
|
|
331
|
+
challenge=challenge["id"].encode(),
|
|
332
|
+
authenticator_selection=AuthenticatorSelectionCriteria(
|
|
333
|
+
resident_key=ResidentKeyRequirement.PREFERRED,
|
|
334
|
+
user_verification=UserVerificationRequirement.REQUIRED,
|
|
335
|
+
),
|
|
336
|
+
exclude_credentials=[
|
|
337
|
+
PublicKeyCredentialDescriptor(id=_unb64(c["credential_id"])) for c in existing
|
|
338
|
+
],
|
|
339
|
+
)
|
|
340
|
+
out: dict[str, Any] = {
|
|
341
|
+
"result": "register",
|
|
342
|
+
"challenge": challenge["id"],
|
|
343
|
+
"webauthn": json.loads(options_to_json(options)),
|
|
344
|
+
"expires_at": challenge["expires_at"],
|
|
345
|
+
}
|
|
346
|
+
# The proof the second leg carries: an existing credential's biometric, whose options
|
|
347
|
+
# list the person's credentials, or for a first credential the button (`webauthn` null).
|
|
348
|
+
agree = self._challenge(token, act="credential.add", subject=person, destination=rp_id,
|
|
349
|
+
delta=[])
|
|
350
|
+
out["confirm"] = {
|
|
351
|
+
"challenge": agree["id"],
|
|
352
|
+
"webauthn": self._request_options(person, rp_id, agree["id"]),
|
|
353
|
+
}
|
|
354
|
+
return out
|
|
355
|
+
|
|
356
|
+
def finish_registration(
|
|
357
|
+
self,
|
|
358
|
+
token: Token,
|
|
359
|
+
*,
|
|
360
|
+
origin: str,
|
|
361
|
+
challenge_id: str,
|
|
362
|
+
attestation: Any,
|
|
363
|
+
presented: Any,
|
|
364
|
+
name: str,
|
|
365
|
+
fresh: bool,
|
|
366
|
+
owner_surface: bool,
|
|
367
|
+
) -> tuple[ConfirmCredential | None, str | None]:
|
|
368
|
+
"""The second leg: the proof first (an existing credential's biometric, or for a first
|
|
369
|
+
credential the button and a fresh sign-in), then the attestation. Returns the stored
|
|
370
|
+
credential, or the reason it was refused; `identity.credential` records which. Never from
|
|
371
|
+
a terminal's token, as the first leg (rest.md §4.3)."""
|
|
372
|
+
if terminal_of(token) is not None:
|
|
373
|
+
raise PermissionError("a confirm credential is registered from a browser")
|
|
374
|
+
person, rp_id = person_of(token), rp_of(origin)
|
|
375
|
+
reason = self._add_proof(token, presented, person=person, rp_id=rp_id, origin=origin,
|
|
376
|
+
fresh=fresh, owner_surface=owner_surface)
|
|
377
|
+
credential: ConfirmCredential | None = None
|
|
378
|
+
if reason is None:
|
|
379
|
+
record = self.state.spend_challenge(challenge_id)
|
|
380
|
+
if record is None or _epoch(record["expires_at"]) <= self.clock():
|
|
381
|
+
reason = "stale"
|
|
382
|
+
elif record.get("spent"):
|
|
383
|
+
reason = "stale"
|
|
384
|
+
elif (record["principal"], record["act"], record["subject"], record["destination"]) != (
|
|
385
|
+
token.id, "register", person, rp_id
|
|
386
|
+
):
|
|
387
|
+
reason = "stale"
|
|
388
|
+
else:
|
|
389
|
+
credential, reason = self._attest(person, rp_id, origin, challenge_id,
|
|
390
|
+
attestation, name)
|
|
391
|
+
details: dict[str, Any] = {"op": "add", "outcome": "refused" if reason else "added"}
|
|
392
|
+
if reason:
|
|
393
|
+
details["reason"] = reason
|
|
394
|
+
else:
|
|
395
|
+
details["credential"] = credential["id"]
|
|
396
|
+
self.ledger.append("identity.credential", actor=token.owner, principal=token.principal,
|
|
397
|
+
subject=person, **details)
|
|
398
|
+
return credential, reason
|
|
399
|
+
|
|
400
|
+
def _add_proof(self, token: Token, presented: Any, *, person: str, rp_id: str | None,
|
|
401
|
+
origin: str, fresh: bool, owner_surface: bool) -> str | None:
|
|
402
|
+
"""rest.md §4.3: a person with a credential adds another only with a biometric proof from
|
|
403
|
+
an existing one; a first credential needs the button and a fresh sign-in, or, where
|
|
404
|
+
buttons are off, the owner's own surface (the lifeboat or the CLI with the owner `Token`;
|
|
405
|
+
never the REST door). Every proof presented is concluded, so it leaves its `step_up`."""
|
|
406
|
+
existing = bool(self.credentials(person))
|
|
407
|
+
if not existing and not self.config("confirm.allow_button") and owner_surface:
|
|
408
|
+
return None # buttons off: the owner's own surface, which presents no proof
|
|
409
|
+
if not isinstance(presented, dict):
|
|
410
|
+
return "no_proof"
|
|
411
|
+
reason = self.conclude(token, presented, act="credential.add", subject=person,
|
|
412
|
+
destination=rp_id, delta=[], origin=origin,
|
|
413
|
+
biometric_only=existing)
|
|
414
|
+
if reason is not None:
|
|
415
|
+
return ADD_REASONS.get(reason, "stale")
|
|
416
|
+
if not existing and not (fresh or owner_surface):
|
|
417
|
+
return "not_fresh"
|
|
418
|
+
return None
|
|
419
|
+
|
|
420
|
+
def _attest(self, person: str, rp_id: str, origin: str, challenge_id: str, attestation: Any,
|
|
421
|
+
name: str) -> tuple[ConfirmCredential | None, str | None]:
|
|
422
|
+
if not isinstance(attestation, dict):
|
|
423
|
+
return None, "attestation"
|
|
424
|
+
try:
|
|
425
|
+
verified = verify_registration_response(
|
|
426
|
+
credential=attestation,
|
|
427
|
+
expected_challenge=challenge_id.encode(),
|
|
428
|
+
expected_rp_id=rp_id,
|
|
429
|
+
expected_origin=origin,
|
|
430
|
+
require_user_verification=True,
|
|
431
|
+
)
|
|
432
|
+
except Exception: # noqa: BLE001 — any verification failure is one reason, no detail
|
|
433
|
+
return None, "attestation"
|
|
434
|
+
credential: ConfirmCredential = {
|
|
435
|
+
"id": ulid(),
|
|
436
|
+
"person": person,
|
|
437
|
+
"credential_id": _b64(verified.credential_id),
|
|
438
|
+
"public_key": _b64(verified.credential_public_key),
|
|
439
|
+
"sign_count": verified.sign_count,
|
|
440
|
+
"rp_id": rp_id,
|
|
441
|
+
"name": name,
|
|
442
|
+
"created_at": now_iso(),
|
|
443
|
+
"last_used": None,
|
|
444
|
+
"removed": False,
|
|
445
|
+
}
|
|
446
|
+
self.state.put_credential(credential)
|
|
447
|
+
return credential, None
|
|
448
|
+
|
|
449
|
+
def remove(self, token: Token, credential: ConfirmCredential) -> None:
|
|
450
|
+
"""Mark a credential removed and record it (`identity.credential`, `op: remove`). The
|
|
451
|
+
caller has judged the biometric proof, or holds the owner token (the recovery path)."""
|
|
452
|
+
self.state.put_credential({**credential, "removed": True})
|
|
453
|
+
self.ledger.append("identity.credential", actor=token.owner, principal=token.principal,
|
|
454
|
+
subject=credential["person"], op="remove", outcome="removed",
|
|
455
|
+
credential=credential["id"])
|