fsanyoto commited on
Commit
0de30a1
·
verified ·
1 Parent(s): 68bfa0a

Deploy AIOS web (React glide grid + FastAPI slice)

Browse files
RELEASES.json CHANGED
@@ -1,5 +1,5 @@
1
  {
2
- "current": "df68553",
3
  "releases": [
4
  {
5
  "version": "v75",
 
1
  {
2
+ "current": "e60f096",
3
  "releases": [
4
  {
5
  "version": "v75",
VERSION CHANGED
@@ -1 +1 @@
1
- df68553
 
1
+ e60f096
api/routes_external.py CHANGED
@@ -1,6 +1,7 @@
1
  """Per-user credentials, governed reads and explicitly allowed bearer build tools."""
2
 
3
  import base64
 
4
  import copy
5
  import hashlib
6
  import hmac
@@ -1092,7 +1093,7 @@ def _oauth_urls(request: Request) -> dict:
1092
  "issuer": root,
1093
  "authorization_endpoint": root + "/oauth/authorize",
1094
  "token_endpoint": root + "/oauth/token",
1095
- "registration_endpoint": root + "/oauth/clients",
1096
  "revocation_endpoint": root + "/oauth/disconnect",
1097
  "protected_resource": root + "/mcp",
1098
  "metadata": origin + "/.well-known/oauth-authorization-server/api/v1/external",
@@ -1103,6 +1104,10 @@ def _oauth_urls(request: Request) -> dict:
1103
 
1104
  def _require_oauth_resource(request: Request, value) -> str:
1105
  """Bind every grant and token request to this exact remote MCP audience."""
 
 
 
 
1106
  supplied = external_oauth.normalise_resource(value)
1107
  expected = external_oauth.normalise_resource(_oauth_urls(request)["protected_resource"])
1108
  if supplied != expected:
@@ -1119,6 +1124,10 @@ def oauth_server_metadata(request: Request):
1119
  "authorization_endpoint": urls["authorization_endpoint"],
1120
  "token_endpoint": urls["token_endpoint"],
1121
  "revocation_endpoint": urls["revocation_endpoint"],
 
 
 
 
1122
  "response_types_supported": ["code"],
1123
  "grant_types_supported": ["authorization_code", "refresh_token"],
1124
  "token_endpoint_auth_methods_supported": ["none"],
@@ -1202,21 +1211,260 @@ def _oauth_redirect(uri: str, **params):
1202
  return RedirectResponse(location, status_code=302)
1203
 
1204
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1205
  @router.get("/oauth/callback")
1206
  @router.get("/oauth/authorize")
1207
  def oauth_authorize(
1208
  request: Request,
 
1209
  response_type: str,
1210
  client_id: str,
1211
  redirect_uri: str,
1212
  state: str,
1213
  code_challenge: str,
1214
  code_challenge_method: str,
1215
- resource: str,
1216
  scope: str | None = None,
1217
- session: Session = Depends(require_session),
1218
  ):
1219
  """Authorize the signed-in user and redirect an exact registered callback with one code."""
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1220
  session.require("analyst")
1221
  try:
1222
  audience = _require_oauth_resource(request, resource)
@@ -1231,6 +1479,59 @@ def oauth_authorize(
1231
  return _oauth_redirect(result["redirect_uri"], code=result["code"], state=result["state"])
1232
 
1233
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1234
  async def _oauth_token_body(request: Request) -> dict:
1235
  raw = await request.body()
1236
  if len(raw) > 16_384:
 
1
  """Per-user credentials, governed reads and explicitly allowed bearer build tools."""
2
 
3
  import base64
4
+ import html as _html
5
  import copy
6
  import hashlib
7
  import hmac
 
1093
  "issuer": root,
1094
  "authorization_endpoint": root + "/oauth/authorize",
1095
  "token_endpoint": root + "/oauth/token",
1096
+ "registration_endpoint": root + "/oauth/register",
1097
  "revocation_endpoint": root + "/oauth/disconnect",
1098
  "protected_resource": root + "/mcp",
1099
  "metadata": origin + "/.well-known/oauth-authorization-server/api/v1/external",
 
1104
 
1105
  def _require_oauth_resource(request: Request, value) -> str:
1106
  """Bind every grant and token request to this exact remote MCP audience."""
1107
+ if value is None or value == "":
1108
+ # HOTFIX 2026-09-24: this server has ONE audience, so an omitted RFC 8707 `resource`
1109
+ # can only mean it. A DIFFERENT audience is still refused below.
1110
+ value = _oauth_urls(request)["protected_resource"]
1111
  supplied = external_oauth.normalise_resource(value)
1112
  expected = external_oauth.normalise_resource(_oauth_urls(request)["protected_resource"])
1113
  if supplied != expected:
 
1124
  "authorization_endpoint": urls["authorization_endpoint"],
1125
  "token_endpoint": urls["token_endpoint"],
1126
  "revocation_endpoint": urls["revocation_endpoint"],
1127
+ # HOTFIX 2026-09-24 (owner: "it still ask me for the Client ID"). Without this key an MCP
1128
+ # client (ChatGPT, Claude.ai, Codex, Cursor) cannot register itself and falls back to
1129
+ # asking the person for a client id and secret.
1130
+ "registration_endpoint": urls["registration_endpoint"],
1131
  "response_types_supported": ["code"],
1132
  "grant_types_supported": ["authorization_code", "refresh_token"],
1133
  "token_endpoint_auth_methods_supported": ["none"],
 
1211
  return RedirectResponse(location, status_code=302)
1212
 
1213
 
1214
+ # ─────────────────────────────────────────────────────────────────────────────────────────
1215
+ # ⭐⭐ HOTFIX 2026-09-24 — RFC 7591 DYNAMIC CLIENT REGISTRATION, AND THE CONSENT SCREEN IT NEEDS.
1216
+ # Owner: "the ChatGPT AI connection ... still ask me for the Client ID". Discovery named no
1217
+ # `registration_endpoint`, so every MCP client fell back to asking for credentials.
1218
+ #
1219
+ # ⛔ REGISTRATION IS PUBLIC AND THEREFORE STORES NOTHING. It happens before anyone signs in, so
1220
+ # there is no tenant to write into; the client id IS the registration (name + exact callbacks),
1221
+ # HMAC-signed with the session secret. The consent screen, where user and tenant are finally
1222
+ # known, writes the ordinary client record (`external_oauth.adopt_dynamic_client`).
1223
+ # ⛔⛔ AND A DYNAMIC CLIENT NEVER GETS A CODE WITHOUT AN EXPLICIT ALLOW. Anyone can register any
1224
+ # callback, so a silent code (the pane-registered path below) would hand a signed-in person's
1225
+ # access to whoever sent them the link. Owner ruling 2026-09-24: the screen offers Read only or
1226
+ # Read and write, all databases or chosen ones, with Read only and all databases preselected.
1227
+ # ─────────────────────────────────────────────────────────────────────────────────────────
1228
+ _DCR_PREFIX = "lpd_"
1229
+ _DCR_MAX_ID = 2048
1230
+ _CONSENT_TTL = 15 * 60
1231
+
1232
+
1233
+ def _dcr_b64(raw: bytes) -> str:
1234
+ return base64.urlsafe_b64encode(raw).decode("ascii").rstrip("=")
1235
+
1236
+
1237
+ def _dcr_unb64(text: str) -> bytes:
1238
+ return base64.urlsafe_b64decode(text + "=" * (-len(text) % 4))
1239
+
1240
+
1241
+ def _dcr_mac(purpose: bytes, payload: bytes) -> str:
1242
+ return _dcr_b64(hmac.new(aios_session._SECRET, purpose + b"\0" + payload,
1243
+ hashlib.sha256).digest()[:24])
1244
+
1245
+
1246
+ def _dcr_client_id(name: str, redirects) -> str:
1247
+ payload = json.dumps({"n": name, "r": list(redirects), "i": int(time.time()),
1248
+ "k": uuid.uuid4().hex[:12]}, separators=(",", ":")).encode("utf-8")
1249
+ body = _dcr_b64(payload)
1250
+ return f"{_DCR_PREFIX}{body}.{_dcr_mac(b'oauth-dcr', body.encode('ascii'))}"
1251
+
1252
+
1253
+ def _dcr_read(client_id) -> dict | None:
1254
+ """The registration a signed dynamic client id carries, or None for anything else."""
1255
+ if (not isinstance(client_id, str) or not client_id.startswith(_DCR_PREFIX)
1256
+ or len(client_id) > _DCR_MAX_ID or client_id.count(".") != 1):
1257
+ return None
1258
+ body, mac = client_id[len(_DCR_PREFIX):].split(".")
1259
+ try:
1260
+ if not hmac.compare_digest(mac, _dcr_mac(b"oauth-dcr", body.encode("ascii"))):
1261
+ return None
1262
+ meta = json.loads(_dcr_unb64(body))
1263
+ except (ValueError, UnicodeError, TypeError):
1264
+ return None
1265
+ if (not isinstance(meta, dict) or not isinstance(meta.get("n"), str)
1266
+ or not isinstance(meta.get("r"), list)):
1267
+ return None
1268
+ return meta
1269
+
1270
+
1271
+ def _dcr_error(code: str, description: str, status: int = 400) -> JSONResponse:
1272
+ return JSONResponse({"error": code, "error_description": description}, status_code=status,
1273
+ headers={"Cache-Control": "no-store", "Pragma": "no-cache"})
1274
+
1275
+
1276
+ @router.post("/oauth/register", status_code=201)
1277
+ async def oauth_register(request: Request):
1278
+ """Public RFC 7591 registration: a PKCE-only public client, signed, nothing stored."""
1279
+ raw = await request.body()
1280
+ try:
1281
+ if len(raw) > 16_384:
1282
+ raise ValueError("too large")
1283
+ body = json.loads(raw or b"{}")
1284
+ if not isinstance(body, dict):
1285
+ raise ValueError("not an object")
1286
+ except (ValueError, UnicodeError):
1287
+ return _dcr_error("invalid_client_metadata", "Send the client metadata as a JSON object.")
1288
+ try:
1289
+ redirects = external_oauth._normalise_redirect_uris(body.get("redirect_uris"))
1290
+ except external_access.ExternalAccessError:
1291
+ return _dcr_error("invalid_redirect_uri",
1292
+ "Use exact HTTPS callbacks, or an HTTP loopback callback.")
1293
+ name = " ".join(str(body.get("client_name") or "").split())[:80] or "AI app"
1294
+ if any(ord(char) < 32 for char in name) or any(t in name for t in ("lpb1.", "lpo1.", "lpr1.", "lpc1.")):
1295
+ name = "AI app"
1296
+ client_id = _dcr_client_id(name, redirects)
1297
+ if len(client_id) > _DCR_MAX_ID:
1298
+ return _dcr_error("invalid_client_metadata", "The callback list is too long.")
1299
+ return JSONResponse({
1300
+ "client_id": client_id, "client_id_issued_at": int(time.time()),
1301
+ "client_name": name, "redirect_uris": list(redirects),
1302
+ "grant_types": ["authorization_code", "refresh_token"],
1303
+ "response_types": ["code"], "token_endpoint_auth_method": "none",
1304
+ }, status_code=201, headers={"Cache-Control": "no-store", "Pragma": "no-cache"})
1305
+
1306
+
1307
+ def _maybe_session(request: Request, response: Response):
1308
+ try:
1309
+ return require_session(request, response)
1310
+ except HTTPException as exc:
1311
+ if exc.status_code == 401:
1312
+ return None
1313
+ raise
1314
+
1315
+
1316
+ _PAGE_STYLE = """
1317
+ body{margin:0;background:#f6f5fb;font-family:Inter,system-ui,-apple-system,Segoe UI,sans-serif;
1318
+ color:#1d1b2e;display:flex;justify-content:center;padding:48px 16px}
1319
+ .card{background:#fff;border:1px solid #e4e1f0;border-radius:12px;max-width:460px;width:100%;
1320
+ padding:28px;box-shadow:0 1px 3px rgba(20,16,50,.06)}
1321
+ h1{font-size:20px;margin:0 0 8px}p{line-height:1.5;margin:0 0 16px;color:#4a4760}
1322
+ fieldset{border:1px solid #e4e1f0;border-radius:8px;margin:0 0 16px;padding:12px 14px}
1323
+ legend{font-weight:600;padding:0 4px}label{display:block;margin:6px 0;cursor:pointer}
1324
+ small{display:block;color:#6d6a82;margin-left:24px}.dbs{margin:6px 0 0 24px;max-height:220px;
1325
+ overflow:auto}.row{display:flex;gap:10px;justify-content:flex-end;margin-top:8px}
1326
+ button{font:inherit;border-radius:8px;padding:9px 18px;cursor:pointer;border:1px solid #d6d2e8;
1327
+ background:#fff;color:#1d1b2e}button.primary{background:#5b3fd6;border-color:#5b3fd6;color:#fff}
1328
+ .who{font-size:13px;color:#6d6a82;margin-top:16px}
1329
+ """
1330
+
1331
+
1332
+ def _page(title: str, body: str, status: int = 200):
1333
+ from fastapi.responses import HTMLResponse
1334
+ return HTMLResponse(
1335
+ f"<!doctype html><html lang=en><head><meta charset=utf-8>"
1336
+ f"<meta name=viewport content='width=device-width,initial-scale=1'>"
1337
+ f"<title>{_html.escape(title)}</title><style>{_PAGE_STYLE}</style></head>"
1338
+ f"<body><main class=card>{body}</main></body></html>", status_code=status,
1339
+ headers={"Cache-Control": "no-store", "X-Frame-Options": "DENY",
1340
+ "Content-Security-Policy": "frame-ancestors 'none'"})
1341
+
1342
+
1343
+ def _refusal_page(message: str, status: int = 400):
1344
+ return _page("Loopable", f"<h1>This connection cannot continue</h1>"
1345
+ f"<p>{_html.escape(message)}</p>", status)
1346
+
1347
+
1348
+ def _login_bounce():
1349
+ # The shell reads this key after a sign-in and comes back here (`Shell.tsx`, onSignedIn).
1350
+ return _page("Sign in to Loopable", (
1351
+ "<h1>Sign in to Loopable</h1><p>Sign in first, then you will come straight back here.</p>"
1352
+ "<p><a href='/#/login'>Continue to sign in</a></p>"
1353
+ "<script>try{sessionStorage.setItem('aios.oauthReturn',location.href)}catch(e){}"
1354
+ "location.replace('/#/login')</script>"))
1355
+
1356
+
1357
+ def _consent_token(session: Session, fields: dict) -> str:
1358
+ payload = json.dumps({"u": session.uname, "t": session.tenant, "f": fields,
1359
+ "x": int(time.time()) + _CONSENT_TTL},
1360
+ separators=(",", ":"), sort_keys=True).encode("utf-8")
1361
+ body = _dcr_b64(payload)
1362
+ return f"{body}.{_dcr_mac(b'oauth-consent', body.encode('ascii'))}"
1363
+
1364
+
1365
+ def _read_consent_token(session: Session, token) -> dict | None:
1366
+ if not isinstance(token, str) or token.count(".") != 1 or len(token) > 16_384:
1367
+ return None
1368
+ body, mac = token.split(".")
1369
+ try:
1370
+ if not hmac.compare_digest(mac, _dcr_mac(b"oauth-consent", body.encode("ascii"))):
1371
+ return None
1372
+ claims = json.loads(_dcr_unb64(body))
1373
+ except (ValueError, UnicodeError, TypeError):
1374
+ return None
1375
+ if (not isinstance(claims, dict) or claims.get("u") != session.uname
1376
+ or claims.get("t") != session.tenant or int(claims.get("x") or 0) < time.time()
1377
+ or not isinstance(claims.get("f"), dict)):
1378
+ return None
1379
+ return claims["f"]
1380
+
1381
+
1382
+ def _granted_scopes(requested, access: str) -> str:
1383
+ wanted = [s for s in str(requested or "").split() if s in external_oauth.SCOPES]
1384
+ out = ["mcp:read"]
1385
+ if access == external_access.ACCESS_READWRITE and ("mcp:write" in wanted or not wanted):
1386
+ out.append("mcp:write")
1387
+ out.append("offline_access")
1388
+ return " ".join(out)
1389
+
1390
+
1391
+ def _consent_page(request: Request, session: Session, meta: dict, fields: dict):
1392
+ name = _html.escape(meta["n"])
1393
+ host = _html.escape(urlsplit(fields["redirect_uri"]).netloc)
1394
+ try:
1395
+ rows = [row for row in _resolve_external_scope(session) if row.get("permitted")]
1396
+ except Exception:
1397
+ rows = []
1398
+ dbs = "".join(
1399
+ f"<label><input type=checkbox name=database value='{_html.escape(str(row['database']))}'>"
1400
+ f" {_html.escape(str(row.get('label') or row['database']))}</label>" for row in rows)
1401
+ token = _html.escape(_consent_token(session, fields))
1402
+ action = _html.escape(str(request.url.path))
1403
+ return _page(f"Connect {meta['n']} to Loopable", (
1404
+ f"<h1>Connect {name} to Loopable</h1>"
1405
+ f"<p>{name} wants to use your Loopable account. After you choose, you go back to "
1406
+ f"<strong>{host}</strong>.</p>"
1407
+ f"<form method=post action='{action}'>"
1408
+ f"<input type=hidden name=consent value='{token}'>"
1409
+ "<fieldset><legend>Access</legend>"
1410
+ "<label><input type=radio name=access value=read checked> Read only"
1411
+ "<small>It can read the databases you choose.</small></label>"
1412
+ "<label><input type=radio name=access value=readwrite> Read and write"
1413
+ "<small>It can also make the changes you could make yourself.</small></label>"
1414
+ "</fieldset><fieldset><legend>Databases</legend>"
1415
+ "<label><input type=radio name=scope_kind value=all checked> All databases you can see"
1416
+ "</label><label><input type=radio name=scope_kind value=some> Only these databases"
1417
+ f"</label><div class=dbs>{dbs or '<small>No databases are available to you.</small>'}"
1418
+ "</div></fieldset><div class=row>"
1419
+ "<button type=submit name=decision value=deny>Deny</button>"
1420
+ "<button type=submit name=decision value=allow class=primary>Allow</button></div></form>"
1421
+ f"<p class=who>Signed in as {_html.escape(session.uname)}. You can disconnect it at any "
1422
+ "time under AI API.</p>"))
1423
+
1424
+
1425
  @router.get("/oauth/callback")
1426
  @router.get("/oauth/authorize")
1427
  def oauth_authorize(
1428
  request: Request,
1429
+ response: Response,
1430
  response_type: str,
1431
  client_id: str,
1432
  redirect_uri: str,
1433
  state: str,
1434
  code_challenge: str,
1435
  code_challenge_method: str,
1436
+ resource: str | None = None,
1437
  scope: str | None = None,
 
1438
  ):
1439
  """Authorize the signed-in user and redirect an exact registered callback with one code."""
1440
+ meta = _dcr_read(client_id)
1441
+ session = _maybe_session(request, response)
1442
+ if meta is not None:
1443
+ if session is None:
1444
+ return _login_bounce()
1445
+ if redirect_uri not in meta["r"]:
1446
+ return _refusal_page("The app sent a callback it did not register. Start the "
1447
+ "connection again from the app.")
1448
+ try:
1449
+ session.require("analyst")
1450
+ _require_oauth_resource(request, resource)
1451
+ if response_type != "code":
1452
+ raise external_oauth.ExternalOAuthError("oauth_response_type_invalid")
1453
+ external_oauth._normalise_state(state)
1454
+ external_oauth._normalise_challenge(code_challenge, code_challenge_method)
1455
+ except HTTPException:
1456
+ return _refusal_page("Your Loopable role cannot connect AI apps. Ask an "
1457
+ "administrator.", 403)
1458
+ except external_access.ExternalAccessError:
1459
+ return _refusal_page("The app sent an incomplete sign-in request. Start the "
1460
+ "connection again from the app.")
1461
+ fields = {"client_id": client_id, "redirect_uri": redirect_uri, "state": state,
1462
+ "code_challenge": code_challenge,
1463
+ "code_challenge_method": code_challenge_method,
1464
+ "resource": resource or "", "scope": scope or ""}
1465
+ return _consent_page(request, session, meta, fields)
1466
+ if session is None:
1467
+ raise err(401, "no_session", "sign in to continue")
1468
  session.require("analyst")
1469
  try:
1470
  audience = _require_oauth_resource(request, resource)
 
1479
  return _oauth_redirect(result["redirect_uri"], code=result["code"], state=result["state"])
1480
 
1481
 
1482
+ @router.post("/oauth/callback")
1483
+ @router.post("/oauth/authorize")
1484
+ async def oauth_consent(request: Request, session: Session = Depends(require_session)):
1485
+ """The consent screen's answer. Lax cookie + a signed, user-bound token: same-site only."""
1486
+ raw = await request.body()
1487
+ if len(raw) > 65_536:
1488
+ return _refusal_page("That answer was too large.")
1489
+ try:
1490
+ form = parse_qs(raw.decode("utf-8"), keep_blank_values=True)
1491
+ except (UnicodeError, ValueError):
1492
+ return _refusal_page("That answer could not be read.")
1493
+ fields = _read_consent_token(session, (form.get("consent") or [None])[-1])
1494
+ meta = _dcr_read((fields or {}).get("client_id"))
1495
+ if not fields or meta is None or fields.get("redirect_uri") not in meta["r"]:
1496
+ return _refusal_page("This approval expired. Start the connection again from the app.")
1497
+ if (form.get("decision") or [""])[-1] != "allow":
1498
+ return _oauth_redirect(fields["redirect_uri"], error="access_denied",
1499
+ state=fields["state"])
1500
+ access = (external_access.ACCESS_READWRITE
1501
+ if (form.get("access") or [""])[-1] == "readwrite" else external_access.ACCESS_READ)
1502
+ chosen = [value for value in form.get("database") or [] if value]
1503
+ if (form.get("scope_kind") or ["all"])[-1] == "some":
1504
+ if not chosen:
1505
+ return _refusal_page("Choose at least one database, or allow all of them. Go back "
1506
+ "and try again.")
1507
+ databases = chosen
1508
+ else:
1509
+ databases = external_access.ALL_DATABASES
1510
+ try:
1511
+ session.require("analyst")
1512
+ except HTTPException:
1513
+ return _refusal_page("Your Loopable role cannot connect AI apps. Ask an administrator.",
1514
+ 403)
1515
+ try:
1516
+ audience = _require_oauth_resource(request, fields.get("resource"))
1517
+ client = external_oauth.adopt_dynamic_client(
1518
+ session.runtime, session.uname, session.tenant, fields["client_id"], meta["n"],
1519
+ meta["r"], access=access, databases=databases)
1520
+ result = external_oauth.authorize(
1521
+ session.runtime, session.uname, session.tenant, client_id=fields["client_id"],
1522
+ redirect_uri=fields["redirect_uri"], state=fields["state"],
1523
+ code_challenge=fields["code_challenge"],
1524
+ code_challenge_method=fields["code_challenge_method"], resource=audience,
1525
+ scope=_granted_scopes(fields.get("scope"), access), response_type="code",
1526
+ )
1527
+ except external_access.ExternalAccessError:
1528
+ return _refusal_page("Loopable could not finish this connection. Start it again from "
1529
+ "the app.")
1530
+ _credential_audit("config.changed", session, "oauth_client", setting="client_registered",
1531
+ access=client["access"])
1532
+ return _oauth_redirect(result["redirect_uri"], code=result["code"], state=result["state"])
1533
+
1534
+
1535
  async def _oauth_token_body(request: Request) -> dict:
1536
  raw = await request.body()
1537
  if len(raw) > 16_384:
platform/core/external_oauth.py CHANGED
@@ -283,6 +283,50 @@ def register_client(st, username: str, tenant: str, label, redirect_uris, *, acc
283
  return _client_metadata(made["record"])
284
 
285
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
286
  def list_clients(st, username: str, tenant: str) -> list[dict]:
287
  owner, tenant_key = external_access._normalise_owner(username, tenant)
288
  external_access._assert_bound_runtime(st, tenant_key)
 
283
  return _client_metadata(made["record"])
284
 
285
 
286
+ def adopt_dynamic_client(st, username: str, tenant: str, client_id: str, label,
287
+ redirect_uris, *, access, databases) -> dict:
288
+ """Bind a dynamically registered public client to the user who approved it (HOTFIX 2026-09-24).
289
+
290
+ RFC 7591 registration happens before anyone signs in, so it carries no tenant and no owner:
291
+ the route mints a SIGNED client id and stores nothing. The consent screen is the first moment
292
+ both are known, and this writes the ordinary client record under them, so `exchange_code`,
293
+ `refresh` and `verify_access` read it exactly as they read a client made in the AI API pane.
294
+ ⛔ An id already bound to ANOTHER user is refused, never taken over.
295
+ """
296
+ owner, tenant_key = external_access._normalise_owner(username, tenant)
297
+ external_access._assert_bound_runtime(st, tenant_key)
298
+ external_access.resolve_active_user(owner, tenant_key)
299
+ clean_label = external_access._normalise_label(label)
300
+ redirects = _normalise_redirect_uris(redirect_uris)
301
+ clean_access = external_access.normalise_access(access)
302
+ clean_databases = external_access.normalise_databases(databases)
303
+ stored = (external_access.ALL_DATABASES if clean_databases == external_access.ALL_DATABASES
304
+ else list(clean_databases))
305
+ made = {}
306
+
307
+ def _set(value):
308
+ book = _book_value(value)
309
+ clients = dict(book["clients"])
310
+ current = clients.get(client_id)
311
+ if isinstance(current, dict) and (current.get("username") != owner
312
+ or current.get("tenant") != tenant_key
313
+ or current.get("revoked_at")):
314
+ raise ExternalOAuthError("oauth_client_invalid")
315
+ record = dict(current) if isinstance(current, dict) else {
316
+ "id": client_id, "username": owner, "tenant": tenant_key, "created_at": _now(),
317
+ "revoked_at": None, "dynamic": True,
318
+ }
319
+ record.update({"label": clean_label, "redirect_uris": list(redirects),
320
+ "access": clean_access, "databases": stored})
321
+ clients[client_id] = record
322
+ book["clients"] = clients
323
+ made["record"] = record
324
+ return book
325
+
326
+ _update(st, _set)
327
+ return _client_metadata(made["record"])
328
+
329
+
330
  def list_clients(st, username: str, tenant: str) -> list[dict]:
331
  owner, tenant_key = external_access._normalise_owner(username, tenant)
332
  external_access._assert_bound_runtime(st, tenant_key)
web/public/AIOS_DEPLOY_RECEIPT CHANGED
@@ -1 +1 @@
1
- 0144152dddb2b5892d9f27e555accc9818fbc6c892bd010ce1f71394a69bc33f
 
1
+ 4fecb566f7ed03ef9116291760b9f8beb2c7c6c8812734f419470e260ddd7182
web/src/shell/Shell.tsx CHANGED
@@ -817,6 +817,27 @@ const APP_BASE =
817
 
818
  /** X5's hash route. Also the route an unauthenticated shell is pinned to. */
819
  const LOGIN_ROUTE = "login";
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
820
  /** A stable identity for "no nav yet" — see its use below. */
821
  const NO_ENTRIES: NavEntry[] = [];
822
 
@@ -2979,6 +3000,9 @@ function ShellFrame() {
2979
  return (
2980
  <LoginPage
2981
  onSignedIn={(user) => {
 
 
 
2982
  // Same rule as sign-out, from the other side: a fresh session never
2983
  // reads the previous session's cached rows.
2984
  clearCustomersCache();
 
817
 
818
  /** X5's hash route. Also the route an unauthenticated shell is pinned to. */
819
  const LOGIN_ROUTE = "login";
820
+
821
+ /** HOTFIX 2026-09-24: the same-origin OAuth approval a sign-in interrupted, resumed once. */
822
+ function resumeOAuthApproval(): boolean {
823
+ let saved: string | null = null;
824
+ try {
825
+ saved = window.sessionStorage.getItem("aios.oauthReturn");
826
+ window.sessionStorage.removeItem("aios.oauthReturn");
827
+ } catch {
828
+ return false;
829
+ }
830
+ if (!saved) return false;
831
+ try {
832
+ const url = new URL(saved, window.location.origin);
833
+ if (url.origin !== window.location.origin || url.pathname !== "/api/v1/external/oauth/authorize")
834
+ return false;
835
+ window.location.assign(url.href);
836
+ return true;
837
+ } catch {
838
+ return false;
839
+ }
840
+ }
841
  /** A stable identity for "no nav yet" — see its use below. */
842
  const NO_ENTRIES: NavEntry[] = [];
843
 
 
3000
  return (
3001
  <LoginPage
3002
  onSignedIn={(user) => {
3003
+ // HOTFIX 2026-09-24: an AI app's OAuth approval sent a signed-out visitor here
3004
+ // (`routes_external.py::_login_bounce`). Go back to that approval, and only to it.
3005
+ if (resumeOAuthApproval()) return;
3006
  // Same rule as sign-out, from the other side: a fresh session never
3007
  // reads the previous session's cached rows.
3008
  clearCustomersCache();