File size: 38,484 Bytes
2e7e617
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
971c29d
2e7e617
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
28e1ab6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2e7e617
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
971c29d
 
 
2e7e617
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f11e183
 
 
 
2e7e617
 
f11e183
2e7e617
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
971c29d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
674f3d8
971c29d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
816fa8a
 
971c29d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2e7e617
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
971c29d
 
 
 
 
2e7e617
 
 
 
 
 
 
 
 
 
 
 
 
 
 
971c29d
2e7e617
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
"""Hash-only OAuth 2.1-style authorization for the existing remote MCP resource.

The authorization endpoint is the only browser-session step.  Code exchange, refresh, bearer
verification, and disconnect resolve from opaque tokens and fresh tenant state without a cookie.
Public clients use PKCE S256 and have no shared client secret to leak or impersonate a user.
"""
from __future__ import annotations

import base64
from dataclasses import dataclass
import hashlib
import hmac
import secrets
import time
from urllib.parse import urlsplit, urlunsplit

from core import external_access, perm_scope, perms, registry, shares, user_tables, users


BUCKET = "external_oauth"
ALGORITHM = "sha256-salt-v1"
CODE_TTL_SECONDS = 5 * 60
ACCESS_TTL_SECONDS = 60 * 60
REFRESH_TTL_SECONDS = 30 * 24 * 60 * 60
MAX_REFRESH_ROTATIONS = 256
MAX_REDIRECT_URIS = 10
SCOPES = ("mcp:read", "mcp:write", "offline_access")
AUTH_ERROR = external_access.AUTH_ERROR
_STAMP_EVERY = 900.0
_DUMMY_SALT = bytes(32)
_DUMMY_HASH = hashlib.sha256(_DUMMY_SALT + b"invalid").hexdigest()
_UNSET = object()


class ExternalOAuthError(external_access.ExternalAccessError):
    """Stable OAuth refusal; HTTP vocabulary belongs to the API route."""


class ExternalOAuthAuthError(ExternalOAuthError):
    """Uniform bearer refusal with no tenant, client, or grant oracle."""


@dataclass(frozen=True)
class VerifiedOAuth:
    tenant: str
    grant_id: str
    client_id: str
    user: dict
    runtime: object
    access: str
    databases: object
    scopes: tuple[str, ...]
    resource: str


@dataclass(frozen=True)
class DisconnectedOAuth:
    """Safe attribution plus public metadata for one token-authenticated disconnect."""

    tenant: str
    username: str
    connection: dict


def _now(now=None) -> float:
    return time.time() if now is None else float(now)


def _iso(epoch: float | None) -> str | None:
    if epoch is None:
        return None
    return time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime(epoch))


def _digest(salt: bytes, secret: str) -> str:
    return hashlib.sha256(salt + secret.encode("utf-8")).hexdigest()


def _state_digest(state: str) -> str:
    return hashlib.sha256(state.encode("utf-8")).hexdigest()


def _pkce_challenge(verifier: str) -> str:
    return base64.urlsafe_b64encode(hashlib.sha256(verifier.encode("ascii")).digest()).rstrip(b"=").decode("ascii")


def _book(st, *, fresh=True) -> dict:
    try:
        value = st.get(BUCKET, fresh=fresh)
    except Exception as exc:
        raise ExternalOAuthError("oauth_unavailable") from exc
    if value is None:
        return {"clients": {}, "codes": {}, "states": {}, "grants": {}}
    if not isinstance(value, dict):
        raise ExternalOAuthError("oauth_unavailable")
    out = {}
    for key in ("clients", "codes", "states", "grants"):
        child = value.get(key, {})
        if not isinstance(child, dict):
            raise ExternalOAuthError("oauth_unavailable")
        out[key] = child
    return out


def _normalise_redirect_uris(value) -> tuple[str, ...]:
    if not isinstance(value, (list, tuple)) or not 1 <= len(value) <= MAX_REDIRECT_URIS:
        raise ExternalOAuthError("oauth_redirect_uri_invalid")
    clean = []
    for raw in value:
        if not isinstance(raw, str) or not raw.strip() or len(raw.strip()) > 1000:
            raise ExternalOAuthError("oauth_redirect_uri_invalid")
        uri = raw.strip()
        parsed = urlsplit(uri)
        loopback = parsed.scheme == "http" and (parsed.hostname or "").lower() in {
            "localhost", "127.0.0.1", "::1",
        }
        if (parsed.fragment or parsed.username or parsed.password or not parsed.netloc
                or (parsed.scheme != "https" and not loopback)):
            raise ExternalOAuthError("oauth_redirect_uri_invalid")
        clean.append(uri)
    return tuple(dict.fromkeys(clean))


def _normalise_state(value) -> str:
    if not isinstance(value, str) or not 16 <= len(value) <= 512 or any(ord(c) < 32 for c in value):
        raise ExternalOAuthError("oauth_state_invalid")
    return value


def _normalise_challenge(value, method) -> str:
    if method != "S256" or not isinstance(value, str) or not 43 <= len(value) <= 128:
        raise ExternalOAuthError("oauth_pkce_required")
    allowed = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"
    if any(char not in allowed for char in value):
        raise ExternalOAuthError("oauth_pkce_required")
    return value


def _normalise_verifier(value) -> str:
    if not isinstance(value, str) or not 43 <= len(value) <= 128:
        raise ExternalOAuthError("oauth_invalid_grant")
    allowed = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~"
    if any(char not in allowed for char in value):
        raise ExternalOAuthError("oauth_invalid_grant")
    return value


def _normalise_scopes(value, access: str) -> tuple[str, ...]:
    requested = str(value or "mcp:read offline_access").split()
    requested = list(dict.fromkeys(requested))
    if (not requested or any(scope not in SCOPES for scope in requested)
            or "mcp:read" not in requested
            or ("mcp:write" in requested and access != external_access.ACCESS_READWRITE)):
        raise ExternalOAuthError("oauth_scope_invalid")
    return tuple(requested)


def normalise_resource(value) -> str:
    """Canonicalise one RFC 8707 audience URI while rejecting ambiguous targets."""
    if not isinstance(value, str) or not value.strip() or len(value.strip()) > 1000:
        raise ExternalOAuthError("oauth_resource_invalid")
    parsed = urlsplit(value.strip())
    if (parsed.scheme.lower() not in {"http", "https"} or not parsed.netloc
            or parsed.fragment or parsed.username or parsed.password):
        raise ExternalOAuthError("oauth_resource_invalid")
    try:
        port = parsed.port
    except ValueError as exc:
        raise ExternalOAuthError("oauth_resource_invalid") from exc
    hostname = (parsed.hostname or "").lower()
    if not hostname:
        raise ExternalOAuthError("oauth_resource_invalid")
    host = f"[{hostname}]" if ":" in hostname else hostname
    netloc = host + (f":{port}" if port is not None else "")
    return urlunsplit((parsed.scheme.lower(), netloc, parsed.path, parsed.query, ""))


def _comparison_material(record, prefix: str) -> tuple[bool, bytes, str]:
    usable = isinstance(record, dict) and record.get("algo") == ALGORITHM
    if usable:
        try:
            salt = bytes.fromhex(str(record.get(prefix + "_salt") or ""))
            expected = str(record.get(prefix + "_hash") or "")
            if len(salt) != 32 or len(expected) != 64:
                raise ValueError("bad digest")
            int(expected, 16)
            return True, salt, expected
        except (TypeError, ValueError):
            pass
    return False, _DUMMY_SALT, _DUMMY_HASH


def _used_refresh_history(record, secret: str) -> tuple[bool, list[dict], bool]:
    """Validate and compare every consumed token retained for this live family."""
    rows = record.get("used_refresh", ()) if isinstance(record, dict) else ()
    if not isinstance(rows, list) or len(rows) > MAX_REFRESH_ROTATIONS:
        return False, [], False
    valid = True
    matched = False
    for item in rows:
        usable, salt, expected = _comparison_material({
            "algo": item.get("algo") if isinstance(item, dict) else None,
            "used_salt": item.get("salt") if isinstance(item, dict) else None,
            "used_hash": item.get("hash") if isinstance(item, dict) else None,
        }, "used")
        valid = valid and usable
        matched = hmac.compare_digest(_digest(salt, secret), expected) and usable or matched
    return valid, list(rows), matched


def _token(prefix: str, tenant: str, identifier: str, secret: str) -> str:
    return f"{prefix}.{tenant}.{identifier}.{secret}"


def _parse_token(token, prefixes) -> tuple[str, str, str, str]:
    parts = str(token or "").strip().split(".")
    if (len(parts) != 4 or parts[0] not in prefixes or not all(parts[1:])
            or len(parts[1]) > 128 or len(parts[2]) > 128 or len(parts[3]) > 256):
        raise ExternalOAuthAuthError(AUTH_ERROR)
    return parts[0], parts[1].lower(), parts[2], parts[3]


def _metadata(record: dict, client: dict | None = None) -> dict:
    return {
        "id": record.get("id"),
        "client_id": record.get("client_id"),
        "label": (client or {}).get("label"),
        "created": _iso(record.get("created_at")),
        "last_used": _iso(record.get("last_used_at")),
        "expires_at": _iso(record.get("refresh_expires_at")),
        "disconnected_at": _iso(record.get("disconnected_at")),
        "access": record.get("access", external_access.ACCESS_READ),
        "databases": (external_access.ALL_DATABASES if record.get("databases") == external_access.ALL_DATABASES
                      else list(record.get("databases") or [])),
        "scopes": list(record.get("scopes") or ()),
    }


def _client_metadata(record: dict) -> dict:
    access, databases = external_access.scope_of(record)
    return {
        "id": record.get("id"), "label": record.get("label"),
        "redirect_uris": list(record.get("redirect_uris") or []),
        "created": _iso(record.get("created_at")), "revoked_at": _iso(record.get("revoked_at")),
        "access": access,
        "databases": (external_access.ALL_DATABASES if databases == external_access.ALL_DATABASES
                      else list(databases)),
        "token_endpoint_auth_method": "none", "pkce": "S256",
    }


def register_client(st, username: str, tenant: str, label, redirect_uris, *, access=None,
                    databases=None) -> dict:
    owner, tenant_key = external_access._normalise_owner(username, tenant)
    external_access._assert_bound_runtime(st, tenant_key)
    external_access.resolve_active_user(owner, tenant_key)
    clean_label = external_access._normalise_label(label)
    redirects = _normalise_redirect_uris(redirect_uris)
    clean_access = external_access.normalise_access(access)
    clean_databases = external_access.normalise_databases(databases)
    created = _now()
    made = {}

    def _set(value):
        book = _book_value(value)
        clients = dict(book["clients"])
        client_id = "lpc_" + secrets.token_urlsafe(18)
        while client_id in clients:
            client_id = "lpc_" + secrets.token_urlsafe(18)
        record = {
            "id": client_id, "username": owner, "tenant": tenant_key, "label": clean_label,
            "redirect_uris": list(redirects), "access": clean_access,
            "databases": (external_access.ALL_DATABASES if clean_databases == external_access.ALL_DATABASES
                          else list(clean_databases)),
            "created_at": created, "revoked_at": None,
        }
        clients[client_id] = record
        book["clients"] = clients
        made["record"] = record
        return book

    _update(st, _set)
    return _client_metadata(made["record"])


def adopt_dynamic_client(st, username: str, tenant: str, client_id: str, label,
                         redirect_uris, *, access, databases) -> dict:
    """Bind a dynamically registered public client to the user who approved it (HOTFIX 2026-09-24).

    RFC 7591 registration happens before anyone signs in, so it carries no tenant and no owner:
    the route mints a SIGNED client id and stores nothing. The consent screen is the first moment
    both are known, and this writes the ordinary client record under them, so `exchange_code`,
    `refresh` and `verify_access` read it exactly as they read a client made in the AI API pane.
    ⛔ An id already bound to ANOTHER user is refused, never taken over.
    """
    owner, tenant_key = external_access._normalise_owner(username, tenant)
    external_access._assert_bound_runtime(st, tenant_key)
    external_access.resolve_active_user(owner, tenant_key)
    clean_label = external_access._normalise_label(label)
    redirects = _normalise_redirect_uris(redirect_uris)
    clean_access = external_access.normalise_access(access)
    clean_databases = external_access.normalise_databases(databases)
    stored = (external_access.ALL_DATABASES if clean_databases == external_access.ALL_DATABASES
              else list(clean_databases))
    made = {}

    def _set(value):
        book = _book_value(value)
        clients = dict(book["clients"])
        current = clients.get(client_id)
        if isinstance(current, dict) and (current.get("username") != owner
                                          or current.get("tenant") != tenant_key
                                          or current.get("revoked_at")):
            raise ExternalOAuthError("oauth_client_invalid")
        record = dict(current) if isinstance(current, dict) else {
            "id": client_id, "username": owner, "tenant": tenant_key, "created_at": _now(),
            "revoked_at": None, "dynamic": True,
        }
        record.update({"label": clean_label, "redirect_uris": list(redirects),
                       "access": clean_access, "databases": stored})
        clients[client_id] = record
        book["clients"] = clients
        made["record"] = record
        return book

    _update(st, _set)
    return _client_metadata(made["record"])


def list_clients(st, username: str, tenant: str) -> list[dict]:
    owner, tenant_key = external_access._normalise_owner(username, tenant)
    external_access._assert_bound_runtime(st, tenant_key)
    return sorted([
        _client_metadata(row) for row in _book(st)["clients"].values()
        if isinstance(row, dict) and row.get("username") == owner
        and row.get("tenant") == tenant_key and not row.get("revoked_at")
    ], key=lambda row: str(row.get("created") or ""), reverse=True)


def edit_client(st, username: str, tenant: str, client_id: str, *, label=_UNSET,
                redirect_uris=_UNSET, access=_UNSET, databases=_UNSET) -> dict:
    owner, tenant_key = external_access._normalise_owner(username, tenant)
    external_access._assert_bound_runtime(st, tenant_key)
    external_access.resolve_active_user(owner, tenant_key)
    if label is redirect_uris is access is databases is _UNSET:
        raise ExternalOAuthError("oauth_edit_empty")
    clean_label = external_access._normalise_label(label) if label is not _UNSET else _UNSET
    clean_redirects = _normalise_redirect_uris(redirect_uris) if redirect_uris is not _UNSET else _UNSET
    clean_access = external_access.normalise_access(access) if access is not _UNSET else _UNSET
    clean_databases = external_access.normalise_databases(databases) if databases is not _UNSET else _UNSET
    edited = {}

    def _set(value):
        book = _book_value(value)
        clients = dict(book["clients"])
        current = clients.get(client_id)
        if (not isinstance(current, dict) or current.get("username") != owner
                or current.get("tenant") != tenant_key or current.get("revoked_at")):
            raise ExternalOAuthError("oauth_client_not_found")
        row = dict(current)
        if clean_label is not _UNSET:
            row["label"] = clean_label
        if clean_redirects is not _UNSET:
            row["redirect_uris"] = list(clean_redirects)
        if clean_access is not _UNSET:
            row["access"] = clean_access
        if clean_databases is not _UNSET:
            row["databases"] = (external_access.ALL_DATABASES
                                if clean_databases == external_access.ALL_DATABASES
                                else list(clean_databases))
        clients[client_id] = row
        book["clients"] = clients
        edited["record"] = row
        return book

    _update(st, _set)
    return _client_metadata(edited["record"])


def authorize(st, username: str, tenant: str, *, client_id, redirect_uri, state,
              code_challenge, code_challenge_method, resource, scope=None, response_type="code",
              now=None) -> dict:
    owner, tenant_key = external_access._normalise_owner(username, tenant)
    external_access._assert_bound_runtime(st, tenant_key)
    external_access.resolve_active_user(owner, tenant_key)
    if response_type != "code":
        raise ExternalOAuthError("oauth_response_type_invalid")
    clean_state = _normalise_state(state)
    challenge = _normalise_challenge(code_challenge, code_challenge_method)
    audience = normalise_resource(resource)
    issued_at = _now(now)
    code_id, secret, salt = secrets.token_urlsafe(18), secrets.token_urlsafe(32), secrets.token_bytes(32)
    issued = {}

    def _set(value):
        book = _book_value(value)
        client = book["clients"].get(client_id)
        if (not isinstance(client, dict) or client.get("username") != owner
                or client.get("tenant") != tenant_key or client.get("revoked_at")):
            raise ExternalOAuthError("oauth_client_invalid")
        if redirect_uri not in (client.get("redirect_uris") or []):
            raise ExternalOAuthError("oauth_redirect_uri_invalid")
        # R15/C5: approval delegates the live account authority. Saved client settings and
        # old grants remain readable metadata, never a cap on a future Manage users change.
        access, databases = external_access.ACCESS_READWRITE, external_access.ALL_DATABASES
        scopes = _normalise_scopes(scope, access)
        states = {key: row for key, row in book["states"].items()
                  if isinstance(row, dict) and float(row.get("expires_at") or 0) >= issued_at}
        state_id = hashlib.sha256(f"{tenant_key}\0{owner}\0{client_id}\0{clean_state}".encode()).hexdigest()
        if state_id in states:
            raise ExternalOAuthError("oauth_state_replayed")
        states[state_id] = {"expires_at": issued_at + CODE_TTL_SECONDS}
        codes = {key: row for key, row in book["codes"].items()
                 if isinstance(row, dict) and float(row.get("expires_at") or 0) >= issued_at - CODE_TTL_SECONDS}
        row = {
            "id": code_id, "tenant": tenant_key, "username": owner, "client_id": client_id,
            "redirect_uri": redirect_uri, "state_hash": _state_digest(clean_state),
            "code_challenge": challenge, "resource": audience,
            "scopes": list(scopes), "access": access,
            "databases": (external_access.ALL_DATABASES if databases == external_access.ALL_DATABASES
                          else list(databases)),
            "code_salt": salt.hex(), "code_hash": _digest(salt, secret), "algo": ALGORITHM,
            "created_at": issued_at, "expires_at": issued_at + CODE_TTL_SECONDS,
            "consumed_at": None,
        }
        codes[code_id] = row
        book.update({"states": states, "codes": codes})
        issued["record"] = row
        return book

    _update(st, _set)
    return {"redirect_uri": redirect_uri, "state": clean_state,
            "code": _token("lpc1", tenant_key, code_id, secret),
            "expires_in": CODE_TTL_SECONDS}


def exchange_code(code, *, client_id, redirect_uri, code_verifier, resource,
                  runtime_resolver, now=None) -> dict:
    _, tenant_key, code_id, secret = _parse_token(code, {"lpc1"})
    verifier = _normalise_verifier(code_verifier)
    audience = normalise_resource(resource)
    try:
        st = runtime_resolver(tenant_key)
        external_access._assert_bound_runtime(st, tenant_key)
    except (KeyError, external_access.ExternalAccessError) as exc:
        raise ExternalOAuthError("oauth_invalid_grant") from exc
    snapshot = _book(st)
    candidate = snapshot["codes"].get(code_id)
    if isinstance(candidate, dict):
        try:
            external_access.resolve_active_user(candidate.get("username"), tenant_key)
        except external_access.ExternalAccessError as exc:
            raise ExternalOAuthError("oauth_invalid_grant") from exc
    issued_at = _now(now)
    access_secret, refresh_secret = secrets.token_urlsafe(32), secrets.token_urlsafe(32)
    access_salt, refresh_salt = secrets.token_bytes(32), secrets.token_bytes(32)
    grant_id = secrets.token_urlsafe(18)
    result = {}

    def _set(value):
        book = _book_value(value)
        row = book["codes"].get(code_id)
        usable, salt, expected = _comparison_material(row, "code")
        matched = hmac.compare_digest(_digest(salt, secret), expected)
        client = book["clients"].get(client_id)
        if (not usable or not matched or not isinstance(row, dict) or row.get("consumed_at")
                or float(row.get("expires_at") or 0) < issued_at
                or row.get("tenant") != tenant_key or row.get("client_id") != client_id
                or row.get("redirect_uri") != redirect_uri
                or row.get("resource") != audience
                or not isinstance(client, dict) or client.get("revoked_at")
                or client.get("username") != row.get("username")
                or not hmac.compare_digest(_pkce_challenge(verifier), str(row.get("code_challenge") or ""))):
            raise ExternalOAuthError("oauth_invalid_grant")
        grants = dict(book["grants"])
        while grant_id in grants:
            raise ExternalOAuthError("oauth_unavailable")
        grant = {
            "id": grant_id, "tenant": tenant_key, "username": row["username"],
            "client_id": client_id, "resource": audience,
            "access": row["access"], "databases": row["databases"],
            "scopes": list(row["scopes"]), "algo": ALGORITHM,
            "access_salt": access_salt.hex(), "access_hash": _digest(access_salt, access_secret),
            "refresh_salt": refresh_salt.hex(), "refresh_hash": _digest(refresh_salt, refresh_secret),
            "used_refresh": [], "refresh_generation": 0,
            "created_at": issued_at, "access_expires_at": issued_at + ACCESS_TTL_SECONDS,
            "refresh_expires_at": issued_at + REFRESH_TTL_SECONDS,
            "last_used_at": None, "disconnected_at": None,
        }
        grants[grant_id] = grant
        codes = dict(book["codes"])
        consumed = dict(row)
        consumed["consumed_at"] = issued_at
        codes[code_id] = consumed
        book.update({"codes": codes, "grants": grants})
        result["grant"] = grant
        return book

    _update(st, _set)
    grant = result["grant"]
    return {
        "token_type": "Bearer", "access_token": _token("lpo1", tenant_key, grant_id, access_secret),
        "expires_in": ACCESS_TTL_SECONDS,
        "refresh_token": _token("lpr1", tenant_key, grant_id, refresh_secret),
        "scope": " ".join(grant["scopes"]),
    }


def refresh(refresh_token, *, client_id, resource, runtime_resolver, now=None) -> dict:
    _, tenant_key, grant_id, secret = _parse_token(refresh_token, {"lpr1"})
    try:
        st = runtime_resolver(tenant_key)
        external_access._assert_bound_runtime(st, tenant_key)
    except (KeyError, external_access.ExternalAccessError) as exc:
        raise ExternalOAuthError("oauth_invalid_grant") from exc
    snapshot = _book(st)
    candidate = snapshot["grants"].get(grant_id)
    if isinstance(candidate, dict):
        try:
            external_access.resolve_active_user(candidate.get("username"), tenant_key)
        except external_access.ExternalAccessError as exc:
            raise ExternalOAuthError("oauth_invalid_grant") from exc
    issued_at = _now(now)
    audience = normalise_resource(resource)
    next_access, next_refresh = secrets.token_urlsafe(32), secrets.token_urlsafe(32)
    next_access_salt, next_refresh_salt = secrets.token_bytes(32), secrets.token_bytes(32)
    result = {}

    def _set(value):
        book = _book_value(value)
        grants = dict(book["grants"])
        row = grants.get(grant_id)
        current_ok, current_salt, current_hash = _comparison_material(row, "refresh")
        current_match = hmac.compare_digest(_digest(current_salt, secret), current_hash)
        history_ok, used, used_match = _used_refresh_history(row, secret)
        if (isinstance(row, dict) and not history_ok and not row.get("disconnected_at")):
            corrupted = dict(row)
            corrupted["disconnected_at"] = issued_at
            grants[grant_id] = corrupted
            book["grants"] = grants
            result["error"] = "oauth_invalid_grant"
            return book
        if (isinstance(row, dict) and used_match and not row.get("disconnected_at")):
            replayed = dict(row)
            replayed["disconnected_at"] = issued_at
            grants[grant_id] = replayed
            book["grants"] = grants
            result["error"] = "oauth_refresh_replayed"
            return book
        # HOTFIX 2026-09-24: a public client that omits client_id on refresh is the client the
        # grant was issued to; the refresh token, matched below, is the credential.
        named = client_id or (row.get("client_id") if isinstance(row, dict) else None)
        client = book["clients"].get(named)
        if (not current_ok or not current_match or not isinstance(row, dict)
                or row.get("disconnected_at") or row.get("tenant") != tenant_key
                or row.get("client_id") != named
                or row.get("resource") != audience
                or float(row.get("refresh_expires_at") or 0) < issued_at
                or not isinstance(client, dict) or client.get("revoked_at")
                or client.get("username") != row.get("username")):
            raise ExternalOAuthError("oauth_invalid_grant")
        generation = int(row.get("refresh_generation") or 0)
        if generation >= MAX_REFRESH_ROTATIONS or len(used) >= MAX_REFRESH_ROTATIONS:
            exhausted = dict(row)
            exhausted["disconnected_at"] = issued_at
            grants[grant_id] = exhausted
            book["grants"] = grants
            result["error"] = "oauth_refresh_exhausted"
            return book
        used.append({"salt": row.get("refresh_salt"), "hash": row.get("refresh_hash"),
                     "algo": ALGORITHM})
        rotated = dict(row)
        rotated.update({
            "used_refresh": used,
            "refresh_generation": generation + 1,
            "access_salt": next_access_salt.hex(),
            "access_hash": _digest(next_access_salt, next_access),
            "refresh_salt": next_refresh_salt.hex(),
            "refresh_hash": _digest(next_refresh_salt, next_refresh),
            "access_expires_at": issued_at + ACCESS_TTL_SECONDS,
            "last_used_at": None,
        })
        grants[grant_id] = rotated
        book["grants"] = grants
        result["grant"] = rotated
        return book

    _update(st, _set)
    if result.get("error"):
        raise ExternalOAuthError(result["error"])
    grant = result["grant"]
    return {
        "token_type": "Bearer", "access_token": _token("lpo1", tenant_key, grant_id, next_access),
        "expires_in": ACCESS_TTL_SECONDS,
        "refresh_token": _token("lpr1", tenant_key, grant_id, next_refresh),
        "scope": " ".join(grant["scopes"]),
    }


def _intersect_databases(left, right):
    if left == external_access.ALL_DATABASES:
        return right
    if right == external_access.ALL_DATABASES:
        return left
    allowed = set(right or ())
    return tuple(item for item in (left or ()) if item in allowed)


def _live_permission_user(username: str, tenant: str) -> dict:
    """Read and validate the raw account before its public projection can discard bad perms."""
    records = users.registry()
    record = records.get(username) if isinstance(records, dict) else None
    if not isinstance(record, dict) or record.get("active", True) is not True:
        raise ExternalOAuthAuthError(AUTH_ERROR)
    version = record.get("perms_v", 0)
    if type(version) is not int or version < 0:
        raise ExternalOAuthAuthError(AUTH_ERROR)
    block = record.get("perms", {})
    if not isinstance(block, dict):
        raise ExternalOAuthAuthError(AUTH_ERROR)
    for key, entry in block.items():
        if not isinstance(key, str) or not key or not isinstance(entry, dict):
            raise ExternalOAuthAuthError(AUTH_ERROR)
        if "access" in entry and type(entry["access"]) is not bool:
            raise ExternalOAuthAuthError(AUTH_ERROR)
        if "metrics" in entry and type(entry["metrics"]) is not bool:
            raise ExternalOAuthAuthError(AUTH_ERROR)
        tree = entry.get("filter")
        if tree is not None and (not isinstance(tree, dict)
                or not isinstance(tree.get("nodes"), list)
                or tree.get("conj", "and") not in {"and", "or"}):
            raise ExternalOAuthAuthError(AUTH_ERROR)
        if "hiddenFields" in entry and (not isinstance(entry["hiddenFields"], list)
                or any(not isinstance(field, str) for field in entry["hiddenFields"])):
            raise ExternalOAuthAuthError(AUTH_ERROR)
    modules = record.get("modules", "all")
    if modules != "all" and (not isinstance(modules, (list, tuple))
            or any(not isinstance(key, str) or not key for key in modules)):
        raise ExternalOAuthAuthError(AUTH_ERROR)
    public = users._public(username, record)
    if public.get("tenant") != tenant:
        raise ExternalOAuthAuthError(AUTH_ERROR)
    return public


def _live_permission_scope(user: dict, st) -> tuple[str, object]:
    """C5: resolve this call's database and editor authority, without reading database rows.

    The canonical evaluators preserve migrated topic denies and the distinct ut_* share rule.
    The coarse write capability also permits owned Sheet work; each writer still checks its
    own object, database, row and field authority. Neither client nor grant snapshots enter.
    """
    if perms.is_admin(user):
        return external_access.ACCESS_READWRITE, external_access.ALL_DATABASES
    definitions = st.get_projection(user_tables.STORE_KEY, drop=user_tables.DEF_ONLY_DROPS)
    if definitions is None:
        definitions = {}
    if not isinstance(definitions, dict) or any(
            not isinstance(key, str) or not isinstance(value, dict)
            for key, value in definitions.items()):
        raise ExternalOAuthAuthError(AUTH_ERROR)
    # The native activity database has no stored definition; admit it as every other door does.
    definitions = user_tables._with_activity(definitions)
    grants = st.get(shares.SHARES_KEY, fresh=True)
    if grants is None:
        grants = {}
    if not isinstance(grants, dict):
        raise ExternalOAuthAuthError(AUTH_ERROR)
    if "database" in grants and not isinstance(grants["database"], dict):
        raise ExternalOAuthAuthError(AUTH_ERROR)
    lent = user_tables.lend(st, **{user_tables.STORE_KEY: definitions, shares.SHARES_KEY: grants})
    topics = {row["key"] for row in registry.governable_modules().values()
              if perms.tenant_has_module(st, row["key"])}
    candidates = topics | {key for key in definitions if key.startswith(user_tables.KEY_PREFIX)}
    databases = tuple(key for key in sorted(candidates) if perm_scope.may_read(user, key, st=lent))
    editable = any(key in topics or user_tables.may_edit_database(
        key, user["username"], st=lent) for key in databases)
    editable = editable or (perms.tenant_has_module(st, "sheets")
                            and perm_scope.nav_may_open(user, "sheets", st=lent))
    return (external_access.ACCESS_READWRITE if editable else external_access.ACCESS_READ), databases


def verify_access(token: str, *, resource, runtime_resolver) -> VerifiedOAuth:
    try:
        _, tenant_key, grant_id, secret = _parse_token(token, {"lpo1"})
        try:
            st = runtime_resolver(tenant_key)
            external_access._assert_bound_runtime(st, tenant_key)
        except KeyError as exc:
            raise ExternalOAuthAuthError(AUTH_ERROR) from exc
        book = _book(st)
        audience = normalise_resource(resource)
        row = book["grants"].get(grant_id)
        usable, salt, expected = _comparison_material(row, "access")
        matched = hmac.compare_digest(_digest(salt, secret), expected)
        client = book["clients"].get(row.get("client_id")) if isinstance(row, dict) else None
        now = _now()
        if (not usable or not matched or not isinstance(row, dict) or row.get("disconnected_at")
                or row.get("tenant") != tenant_key or float(row.get("access_expires_at") or 0) < now
                or row.get("resource") != audience
                or not isinstance(client, dict) or client.get("revoked_at")
                or client.get("username") != row.get("username")
                or client.get("tenant") != tenant_key):
            raise ExternalOAuthAuthError(AUTH_ERROR)
        public = _live_permission_user(row["username"], tenant_key)
        access, databases = _live_permission_scope(public, st)
        scopes = ("mcp:read",) + (("mcp:write",) if external_access.may_write(access) else ())
        if "offline_access" in (row.get("scopes") or ()):
            scopes += ("offline_access",)
        if now - float(row.get("last_used_at") or 0) >= _STAMP_EVERY:
            def _stamp(value):
                latest = _book_value(value)
                grants = dict(latest["grants"])
                current = grants.get(grant_id)
                if (not isinstance(current, dict) or current.get("disconnected_at")
                        or current.get("access_hash") != row.get("access_hash")):
                    raise ExternalOAuthAuthError(AUTH_ERROR)
                current = dict(current)
                current["last_used_at"] = now
                grants[grant_id] = current
                latest["grants"] = grants
                return latest
            _update(st, _stamp, auth=True)
        return VerifiedOAuth(tenant_key, grant_id, row["client_id"], public, st, access,
                             databases, scopes, audience)
    except ExternalOAuthAuthError:
        raise
    except Exception as exc:
        raise ExternalOAuthAuthError(AUTH_ERROR) from exc


def disconnect(token: str, *, runtime_resolver, now=None) -> DisconnectedOAuth:
    prefix, tenant_key, grant_id, secret = _parse_token(token, {"lpo1", "lpr1"})
    try:
        st = runtime_resolver(tenant_key)
        external_access._assert_bound_runtime(st, tenant_key)
    except (KeyError, external_access.ExternalAccessError) as exc:
        raise ExternalOAuthAuthError(AUTH_ERROR) from exc
    stopped = {}
    at = _now(now)
    material = "access" if prefix == "lpo1" else "refresh"

    def _set(value):
        book = _book_value(value)
        grants = dict(book["grants"])
        row = grants.get(grant_id)
        usable, salt, expected = _comparison_material(row, material)
        if (not usable or not hmac.compare_digest(_digest(salt, secret), expected)
                or not isinstance(row, dict) or row.get("tenant") != tenant_key
                or not isinstance(row.get("username"), str) or not row.get("username")):
            raise ExternalOAuthAuthError(AUTH_ERROR)
        disconnected = dict(row)
        if not disconnected.get("disconnected_at"):
            disconnected["disconnected_at"] = at
        grants[grant_id] = disconnected
        book["grants"] = grants
        stopped["record"] = disconnected
        stopped["client"] = book["clients"].get(disconnected.get("client_id"))
        return book

    _update(st, _set, auth=True)
    record = stopped["record"]
    return DisconnectedOAuth(tenant_key, record["username"],
                             _metadata(record, stopped.get("client")))


def disconnect_for_user(st, username: str, tenant: str, grant_id: str) -> dict:
    owner, tenant_key = external_access._normalise_owner(username, tenant)
    external_access._assert_bound_runtime(st, tenant_key)
    stopped = {}
    at = _now()

    def _set(value):
        book = _book_value(value)
        grants = dict(book["grants"])
        row = grants.get(grant_id)
        if (not isinstance(row, dict) or row.get("username") != owner
                or row.get("tenant") != tenant_key):
            raise ExternalOAuthError("oauth_connection_not_found")
        disconnected = dict(row)
        if not disconnected.get("disconnected_at"):
            disconnected["disconnected_at"] = at
        grants[grant_id] = disconnected
        book["grants"] = grants
        stopped["record"] = disconnected
        stopped["client"] = book["clients"].get(disconnected.get("client_id"))
        return book

    _update(st, _set)
    return _metadata(stopped["record"], stopped.get("client"))


def list_connections(st, username: str, tenant: str) -> list[dict]:
    owner, tenant_key = external_access._normalise_owner(username, tenant)
    external_access._assert_bound_runtime(st, tenant_key)
    book = _book(st)
    return sorted([
        _metadata(row, book["clients"].get(row.get("client_id")))
        for row in book["grants"].values()
        if isinstance(row, dict) and row.get("username") == owner
        and row.get("tenant") == tenant_key and not row.get("disconnected_at")
    ], key=lambda row: str(row.get("created") or ""), reverse=True)


def label_for(st, grant_id: str) -> str:
    book = _book(st)
    grant = book["grants"].get(grant_id)
    client = book["clients"].get(grant.get("client_id")) if isinstance(grant, dict) else None
    if (not isinstance(grant, dict) or grant.get("disconnected_at")
            or not isinstance(client, dict) or client.get("revoked_at")):
        raise ExternalOAuthAuthError(AUTH_ERROR)
    label = client.get("label")
    if not isinstance(label, str) or not label:
        raise ExternalOAuthError("oauth_unavailable")
    return label


def _book_value(value) -> dict:
    if value is None:
        return {"clients": {}, "codes": {}, "states": {}, "grants": {}}
    if not isinstance(value, dict):
        raise ExternalOAuthError("oauth_unavailable")
    book = dict(value)
    for key in ("clients", "codes", "states", "grants"):
        child = book.get(key, {})
        if not isinstance(child, dict):
            raise ExternalOAuthError("oauth_unavailable")
        book[key] = dict(child)
    return book


def _update(st, callback, *, auth=False) -> None:
    try:
        st.update(BUCKET, callback, flush="sync")
    except (ExternalOAuthError, ExternalOAuthAuthError):
        raise
    except Exception as exc:
        if auth:
            raise ExternalOAuthAuthError(AUTH_ERROR) from exc
        raise ExternalOAuthError("oauth_unavailable") from exc