resource-engine-fastapi 0.1.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.
Files changed (39) hide show
  1. resource_engine_fastapi/__init__.py +39 -0
  2. resource_engine_fastapi/access.py +110 -0
  3. resource_engine_fastapi/asyncapi.py +47 -0
  4. resource_engine_fastapi/auth.py +158 -0
  5. resource_engine_fastapi/authz.py +100 -0
  6. resource_engine_fastapi/caching.py +111 -0
  7. resource_engine_fastapi/docs.py +77 -0
  8. resource_engine_fastapi/documents.py +219 -0
  9. resource_engine_fastapi/email_events.py +85 -0
  10. resource_engine_fastapi/errors.py +178 -0
  11. resource_engine_fastapi/events.py +109 -0
  12. resource_engine_fastapi/explorer/__init__.py +441 -0
  13. resource_engine_fastapi/explorer/assets/auth.js +171 -0
  14. resource_engine_fastapi/explorer/assets/console.js +340 -0
  15. resource_engine_fastapi/explorer/assets/events.js +189 -0
  16. resource_engine_fastapi/explorer/assets/explorer.css +156 -0
  17. resource_engine_fastapi/explorer/assets/explorer.js +275 -0
  18. resource_engine_fastapi/explorer/assets/jobs.js +143 -0
  19. resource_engine_fastapi/explorer/assets/messages.js +85 -0
  20. resource_engine_fastapi/explorer/assets/publish.js +117 -0
  21. resource_engine_fastapi/explorer/data.py +84 -0
  22. resource_engine_fastapi/explorer/events.py +182 -0
  23. resource_engine_fastapi/explorer/jobs.py +167 -0
  24. resource_engine_fastapi/explorer/labels.py +198 -0
  25. resource_engine_fastapi/explorer/locale/ca/LC_MESSAGES/explorer.mo +0 -0
  26. resource_engine_fastapi/explorer/locale/ca/LC_MESSAGES/explorer.po +417 -0
  27. resource_engine_fastapi/explorer/locale/es/LC_MESSAGES/explorer.mo +0 -0
  28. resource_engine_fastapi/explorer/locale/es/LC_MESSAGES/explorer.po +417 -0
  29. resource_engine_fastapi/explorer/messages.py +73 -0
  30. resource_engine_fastapi/explorer/publish.py +85 -0
  31. resource_engine_fastapi/exports.py +186 -0
  32. resource_engine_fastapi/i18n.py +76 -0
  33. resource_engine_fastapi/py.typed +0 -0
  34. resource_engine_fastapi/router.py +1031 -0
  35. resource_engine_fastapi/versioning.py +49 -0
  36. resource_engine_fastapi-0.1.0.dist-info/METADATA +32 -0
  37. resource_engine_fastapi-0.1.0.dist-info/RECORD +39 -0
  38. resource_engine_fastapi-0.1.0.dist-info/WHEEL +4 -0
  39. resource_engine_fastapi-0.1.0.dist-info/licenses/LICENSE +202 -0
@@ -0,0 +1,441 @@
1
+ """The explorer: try the running application from the browser, like FastAPI's
2
+ ``/docs`` but for the whole application (docs/explorer.md).
3
+
4
+ ```python
5
+ from resource_engine_fastapi.explorer import mount_explorer
6
+
7
+ if settings.explorer: # off unless you turn it on
8
+ mount_explorer(app, manager, actor_dependency=actor, events=hub, activity=log)
9
+ # http://localhost:8000/explorer/
10
+ ```
11
+
12
+ Laid out like Swagger UI: a section per resource, a row per verb.
13
+
14
+ - ``GET`` ``POST`` ``PUT`` ``PATCH`` ``DELETE``: every HTTP operation, with its form.
15
+ - ``SUB``: each event type a resource publishes, live (``events=`` an
16
+ ``EventHub``), and which consumers handled each one (``activity=`` an
17
+ ``ActivityLog``).
18
+ - ``CRON`` (``jobs=True``, with ``activity``): each timed transition, and each
19
+ worker job with its runs and "run now".
20
+ - ``PUB`` (``publish=`` an ``EventPublishing``): each event the application
21
+ lets people publish by hand, with a dry run.
22
+ - ``OUTBOX`` and ``DLQ`` (``outbox=True``): messages not sent yet, the ones
23
+ consumers gave up on (with ``activity``), and "send again".
24
+
25
+ Everything calls the running API with the visitor's own token: they see and
26
+ do exactly what they may. Reads only, until they tick "Allow changes". The
27
+ explorer's own endpoints live under ``api_prefix`` (``/_explorer``), out of
28
+ the application's OpenAPI document (they are a tool, not its API), behind
29
+ their permissions (``register_explorer`` adds them to the catalogue) and
30
+ audited. Without an authorizer they are refused, unless ``open=True`` (local
31
+ development only).
32
+
33
+ The documentation site (``resource-engine docs site``, ``mount_docs``) is the
34
+ functional documentation and links the API's documents; the explorer is
35
+ where the API is tried.
36
+ """
37
+
38
+ from __future__ import annotations
39
+
40
+ import hashlib
41
+ import html
42
+ import json
43
+ from dataclasses import dataclass
44
+ from functools import cache
45
+ from importlib.resources import files
46
+ from typing import TYPE_CHECKING, Any
47
+
48
+ from fastapi import APIRouter, FastAPI, Request
49
+ from fastapi.responses import HTMLResponse, Response
50
+
51
+ from resource_engine_fastapi.explorer import data, labels
52
+ from resource_engine_fastapi.explorer.data import console_data
53
+ from resource_engine_fastapi.explorer.labels import locales
54
+
55
+ if TYPE_CHECKING:
56
+ from resource_engine import ResourceManager
57
+ from resource_engine.messaging import EventHub, EventPublishing
58
+ from resource_engine.ports.activity import ActivityLog
59
+
60
+ from resource_engine_fastapi.router import ActorDependency
61
+
62
+ #: The explorer page holds the caller's token: only its own scripts and
63
+ #: styles run (no inline code, no CDN), and other sites can't frame it.
64
+ CSP = (
65
+ "default-src 'self'; script-src 'self'; style-src 'self'; img-src 'self' data:; "
66
+ "connect-src 'self'; frame-ancestors 'self'; base-uri 'none'; form-action 'none'; "
67
+ "object-src 'none'"
68
+ )
69
+
70
+
71
+ @dataclass(frozen=True)
72
+ class OidcSignIn:
73
+ """The explorer's "Authorize": signing in with the application's OpenID
74
+ Connect provider (authorization code with PKCE, as a public client), so
75
+ nobody pastes tokens. The token is renewed while the page is open.
76
+
77
+ Args:
78
+ issuer: The provider's issuer URL
79
+ (``https://sso.example.com/realms/acme``); its discovery document
80
+ gives the endpoints.
81
+ client_id: A public client that allows PKCE and redirects to the
82
+ explorer's page (``http://localhost:*`` in development).
83
+ scope: The scopes to ask for.
84
+ """
85
+
86
+ issuer: str
87
+ client_id: str
88
+ scope: str = "openid"
89
+
90
+ def origin(self) -> str:
91
+ """The scheme and host of the provider (``issuer``)."""
92
+ from urllib.parse import urlsplit
93
+
94
+ parts = urlsplit(self.issuer)
95
+ return f"{parts.scheme}://{parts.netloc}"
96
+
97
+
98
+ ASSETS = (
99
+ "console.js",
100
+ "auth.js",
101
+ "events.js",
102
+ "jobs.js",
103
+ "publish.js",
104
+ "messages.js",
105
+ "explorer.js",
106
+ "explorer.css",
107
+ )
108
+
109
+
110
+ @cache
111
+ def assets_version() -> str:
112
+ """A hash of the assets: their URLs change with them, so browsers never
113
+ keep an old script after an upgrade."""
114
+ digest = hashlib.sha256()
115
+ for name in ASSETS:
116
+ digest.update(asset(name).encode("utf-8"))
117
+ return digest.hexdigest()[:12]
118
+
119
+
120
+ def asset(name: str) -> str:
121
+ """One of the explorer's assets (``console.js``...), as text."""
122
+ return (files(__package__) / "assets" / name).read_text(encoding="utf-8")
123
+
124
+
125
+ def _no_actor() -> None:
126
+ return None
127
+
128
+
129
+ def event_types(registry: Any) -> list[dict[str, Any]]:
130
+ """Event types the application publishes, with their schema versions."""
131
+ from resource_engine.integration import engine_events
132
+
133
+ found: dict[str, Any] = dict(engine_events())
134
+ for event in registry.event_types():
135
+ found[event.__name__] = event
136
+ out = []
137
+ for name, event in sorted(found.items()):
138
+ current = int(getattr(event, "schema_version", 1))
139
+ older = sorted(int(v) for v in (getattr(event, "previous_versions", None) or {}))
140
+ out.append({"type": name, "versions": [str(v) for v in [*older, current]]})
141
+ return out
142
+
143
+
144
+ def _first_line(text: str | None) -> str:
145
+ return (text or "").strip().split("\n\n")[0].replace("\n", " ").strip()
146
+
147
+
148
+ def event_channels(registry: Any) -> dict[str, list[dict[str, Any]]]:
149
+ """The event types each resource publishes (its AsyncAPI channel): the
150
+ explorer's SUB rows. Only resources whose records can be read."""
151
+ from resource_engine.messaging import asyncapi_document
152
+
153
+ document = asyncapi_document(registry)
154
+ messages = document.get("components", {}).get("messages", {})
155
+ out: dict[str, list[dict[str, Any]]] = {}
156
+ for name, channel in document.get("channels", {}).items():
157
+ if name not in registry or not registry.get(name).exposed("get"):
158
+ continue
159
+ rows = []
160
+ for ref in channel.get("messages", {}).values():
161
+ message = messages.get(str(ref.get("$ref", "")).rsplit("/", 1)[-1], {})
162
+ headers = message.get("headers", {}).get("properties", {})
163
+ rows.append(
164
+ {
165
+ "type": message.get("name"),
166
+ "version": str(headers.get("schema_version", {}).get("const", "1")),
167
+ "summary": message.get("summary") or "",
168
+ "deprecated": "x-deprecation" in message,
169
+ }
170
+ )
171
+ out[name] = rows
172
+ return out
173
+
174
+
175
+ def timer_rows(registry: Any) -> dict[str, list[dict[str, Any]]]:
176
+ """Each resource's timed transitions: the explorer's CRON rows."""
177
+ return {
178
+ d.name: [
179
+ {
180
+ "event": t.event,
181
+ "after_seconds": t.after.total_seconds(),
182
+ "since": t.since,
183
+ "states": [str(getattr(s, "value", s)) for s in t.states],
184
+ "description": t.description,
185
+ }
186
+ for t in d.timers
187
+ ]
188
+ for d in registry
189
+ if d.timers
190
+ }
191
+
192
+
193
+ def explorer_config(
194
+ app: Any,
195
+ manager: Any,
196
+ *,
197
+ api_prefix: str,
198
+ events: bool,
199
+ deliveries: bool,
200
+ locale: str | None,
201
+ jobs: bool = False,
202
+ publish: Any = None,
203
+ oidc: OidcSignIn | None = None,
204
+ outbox: bool = False,
205
+ ) -> dict[str, Any]:
206
+ """What the explorer's scripts read as ``window.CONSOLE``."""
207
+ openapi = app.openapi()
208
+ names = [d.name for d in manager.registry]
209
+ config = console_data(openapi, names)
210
+ config.update(
211
+ api="",
212
+ me="/authz/me" in openapi.get("paths", {}),
213
+ labels=labels.labels(locale),
214
+ groups=[{"name": d.name, "summary": _first_line(d.description)} for d in manager.registry],
215
+ )
216
+ if events:
217
+ config["events"] = {
218
+ "stream": f"{api_prefix}/events/stream",
219
+ "deliveries": f"{api_prefix}/events/{{message_id}}/deliveries" if deliveries else None,
220
+ "resources": [d.name for d in manager.registry if d.exposed("get")],
221
+ "types": event_types(manager.registry),
222
+ "channels": event_channels(manager.registry),
223
+ }
224
+ if jobs:
225
+ config["jobs"] = {
226
+ "list": f"{api_prefix}/jobs",
227
+ "runs": f"{api_prefix}/jobs/{{name}}/runs",
228
+ "run": f"{api_prefix}/jobs/{{name}}/run",
229
+ "request": f"{api_prefix}/jobs/requests/{{id}}",
230
+ "timers": f"{api_prefix}/timers/{{resource}}/{{id}}",
231
+ "timer_resources": [d.name for d in manager.registry if d.timers],
232
+ "timers_by_resource": timer_rows(manager.registry),
233
+ }
234
+ if publish is not None:
235
+ from resource_engine_fastapi.explorer.publish import publish_config
236
+
237
+ config["publish"] = publish_config(publish, api_prefix)
238
+ if oidc is not None:
239
+ config["oidc"] = {"issuer": oidc.issuer, "client_id": oidc.client_id, "scope": oidc.scope}
240
+ if outbox:
241
+ config["messages"] = {
242
+ "outbox": f"{api_prefix}/outbox",
243
+ "dead_letters": f"{api_prefix}/dead-letters",
244
+ "send_again": f"{api_prefix}/outbox/{{id}}/send-again",
245
+ }
246
+ return config
247
+
248
+
249
+ def _locale(request: Request) -> str | None:
250
+ """``?lang=``, else the browser's first offered language we have."""
251
+ offered = locales()
252
+ wanted = request.query_params.get("lang")
253
+ candidates = [wanted] if wanted else []
254
+ for part in request.headers.get("accept-language", "").split(","):
255
+ candidates.append(part.split(";")[0].strip())
256
+ for candidate in candidates:
257
+ if not candidate:
258
+ continue
259
+ base = candidate.lower().split("-")[0]
260
+ if base in offered:
261
+ return base
262
+ return None
263
+
264
+
265
+ def _page(title: str, locale: str | None, root: str) -> str:
266
+ label = labels.labels(locale)
267
+ config = f"config.js?lang={html.escape(locale)}" if locale else "config.js"
268
+ version = assets_version()
269
+ scripts = "\n".join(
270
+ f'<script src="{root}/{name}"></script>'
271
+ for name in (
272
+ config,
273
+ f"assets/console.js?v={version}",
274
+ f"assets/auth.js?v={version}",
275
+ f"assets/events.js?v={version}",
276
+ f"assets/jobs.js?v={version}",
277
+ f"assets/publish.js?v={version}",
278
+ f"assets/messages.js?v={version}",
279
+ f"assets/explorer.js?v={version}",
280
+ )
281
+ )
282
+ return f"""<!doctype html>
283
+ <html lang="{html.escape(locale or "en")}">
284
+ <head>
285
+ <meta charset="utf-8">
286
+ <meta name="viewport" content="width=device-width, initial-scale=1">
287
+ <title>{html.escape(label["explorer"])} · {html.escape(title)}</title>
288
+ <link rel="stylesheet" href="{root}/assets/explorer.css?v={version}">
289
+ </head>
290
+ <body>
291
+ <header><h1>{html.escape(label["explorer"])}</h1>
292
+ <span class="app">{html.escape(title)}</span></header>
293
+ <main><div id="explorer" class="console"></div></main>
294
+ {scripts}
295
+ </body>
296
+ </html>
297
+ """
298
+
299
+
300
+ def mount_explorer(
301
+ app: FastAPI,
302
+ manager: ResourceManager,
303
+ *,
304
+ path: str = "/explorer",
305
+ api_prefix: str = "/_explorer",
306
+ actor_dependency: ActorDependency = _no_actor,
307
+ events: EventHub | None = None,
308
+ activity: ActivityLog | None = None,
309
+ jobs: bool = False,
310
+ publish: EventPublishing | None = None,
311
+ oidc: OidcSignIn | None = None,
312
+ outbox: bool = False,
313
+ open: bool = False,
314
+ title: str | None = None,
315
+ csp: str | None = CSP,
316
+ ) -> None:
317
+ """Serve the explorer at ``path`` and its endpoints at ``api_prefix``.
318
+
319
+ Args:
320
+ actor_dependency: The same dependency as ``mount_resources``'s.
321
+ events: An ``EventHub`` fed with committed events: the ``SUB`` rows.
322
+ activity: An ``ActivityLog``: which consumers handled each event, and
323
+ (with ``jobs``) the workers' jobs and runs.
324
+ jobs: The ``CRON`` rows: needs ``activity``, and workers built with
325
+ ``JobRunner(activity=...)`` on the same log.
326
+ publish: An ``EventPublishing``: the ``PUB`` rows (a dry run, and
327
+ publishing when it allows it).
328
+ oidc: An ``OidcSignIn``: the "Authorize" button (sign in with the
329
+ identity provider instead of pasting a token).
330
+ outbox: The outbox and dead letters (dead letters need ``activity``,
331
+ the log the consumers report to).
332
+ open: Allow the explorer's endpoints without an authorizer (local
333
+ development only: anyone could see every event).
334
+ csp: Content-Security-Policy of the page.
335
+ """
336
+ api = APIRouter(prefix=api_prefix, include_in_schema=False)
337
+ if events is not None:
338
+ from resource_engine_fastapi.explorer.events import build_events_router
339
+
340
+ api.include_router(
341
+ build_events_router(
342
+ manager, events, actor_dependency=actor_dependency, activity=activity, open=open
343
+ )
344
+ )
345
+ if jobs:
346
+ if activity is None:
347
+ from resource_engine.errors import ConfigurationError
348
+
349
+ raise ConfigurationError(
350
+ "The explorer's jobs need the activity log the workers write to",
351
+ hint="mount_explorer(..., jobs=True, activity=SqlAlchemyActivityLog(...)) and "
352
+ "JobRunner(activity=<the same log>).",
353
+ doc="docs/explorer.md#jobs",
354
+ )
355
+ from resource_engine_fastapi.explorer.jobs import build_jobs_router
356
+
357
+ api.include_router(
358
+ build_jobs_router(manager, activity, actor_dependency=actor_dependency, open=open)
359
+ )
360
+ if outbox:
361
+ from resource_engine.messaging import MessagingInspector
362
+
363
+ from resource_engine_fastapi.explorer.messages import build_messages_router
364
+
365
+ api.include_router(
366
+ build_messages_router(
367
+ MessagingInspector(manager, activity, open=open),
368
+ actor_dependency=actor_dependency,
369
+ )
370
+ )
371
+ if publish is not None:
372
+ from resource_engine_fastapi.explorer.publish import build_publish_router
373
+
374
+ api.include_router(build_publish_router(publish, actor_dependency=actor_dependency))
375
+ app.include_router(api)
376
+ root = path.rstrip("/")
377
+ page_title = title or getattr(app, "title", None) or "API"
378
+ headers = {"X-Content-Type-Options": "nosniff", "Referrer-Policy": "no-referrer"}
379
+ if csp and oidc is not None: # the page talks to the provider: discovery, tokens
380
+ csp = csp.replace("connect-src 'self'", f"connect-src 'self' {oidc.origin()}")
381
+ if csp:
382
+ headers["Content-Security-Policy"] = csp
383
+ ui_router = APIRouter(prefix=root, include_in_schema=False)
384
+
385
+ @ui_router.get("/", response_class=HTMLResponse)
386
+ async def page(request: Request) -> HTMLResponse:
387
+ return HTMLResponse(
388
+ _page(page_title, _locale(request), root),
389
+ headers={**headers, "Cache-Control": "no-store"},
390
+ )
391
+
392
+ @ui_router.get("/config.js")
393
+ async def config(request: Request) -> Response:
394
+ payload = explorer_config(
395
+ app,
396
+ manager,
397
+ api_prefix=api_prefix,
398
+ events=events is not None,
399
+ deliveries=activity is not None,
400
+ locale=_locale(request),
401
+ jobs=jobs,
402
+ publish=publish,
403
+ oidc=oidc,
404
+ outbox=outbox,
405
+ )
406
+ body = json.dumps(payload, ensure_ascii=False).replace("</", "<\\/")
407
+ return Response(
408
+ f"window.CONSOLE = {body};\n",
409
+ media_type="text/javascript",
410
+ headers={**headers, "Cache-Control": "no-store"},
411
+ )
412
+
413
+ @ui_router.get("/assets/{name}")
414
+ async def assets(name: str, request: Request) -> Response:
415
+ if name not in ASSETS:
416
+ return Response(status_code=404)
417
+ kind = "text/css" if name.endswith(".css") else "text/javascript"
418
+ # versioned URLs (?v=<hash>) change with the content: cache them for good
419
+ caching = (
420
+ "public, max-age=31536000, immutable" if request.query_params.get("v") else "no-cache"
421
+ )
422
+ return Response(asset(name), media_type=kind, headers={**headers, "Cache-Control": caching})
423
+
424
+ app.include_router(ui_router)
425
+ if root: # /explorer → /explorer/
426
+
427
+ async def redirect() -> Response:
428
+ return Response(status_code=307, headers={"Location": f"{root}/"})
429
+
430
+ app.add_api_route(root, redirect, methods=["GET"], include_in_schema=False)
431
+
432
+
433
+ __all__ = [
434
+ "OidcSignIn",
435
+ "asset",
436
+ "data",
437
+ "event_types",
438
+ "explorer_config",
439
+ "labels",
440
+ "mount_explorer",
441
+ ]
@@ -0,0 +1,171 @@
1
+ /* "Authorize": signing in with the application's OpenID Connect provider
2
+ (authorization code with PKCE, a public client), instead of pasting a
3
+ token. The token goes where the console reads it (this tab only) and is
4
+ renewed with the refresh token while the page is open.
5
+ R.ready resolves once a sign-in coming back from the provider is done;
6
+ R.auth.box() is the button, or who is signed in. */
7
+ (function () {
8
+ var R = window.ResourceExplorer;
9
+ if (!R) return;
10
+ if (!R.config.oidc) { R.ready = Promise.resolve(); return; }
11
+ var O = R.config.oidc, L = R.labels, el = R.el;
12
+ var KEY = "re-oidc", FLOW = "re-oidc-flow";
13
+ var lang = document.documentElement.lang || "";
14
+
15
+ function b64url(bytes) {
16
+ var text = "";
17
+ bytes.forEach(function (b) { text += String.fromCharCode(b); });
18
+ return btoa(text).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
19
+ }
20
+ function random(size) {
21
+ var bytes = new Uint8Array(size);
22
+ crypto.getRandomValues(bytes);
23
+ return b64url(bytes);
24
+ }
25
+ function sha256(text) {
26
+ return crypto.subtle.digest("SHA-256", new TextEncoder().encode(text)).then(function (hash) {
27
+ return b64url(new Uint8Array(hash));
28
+ });
29
+ }
30
+ function read(key) {
31
+ try { return JSON.parse(sessionStorage.getItem(key) || "null"); } catch (e) { return null; }
32
+ }
33
+ function write(key, value) {
34
+ try {
35
+ if (value === null) sessionStorage.removeItem(key);
36
+ else sessionStorage.setItem(key, JSON.stringify(value));
37
+ } catch (e) { /* private mode */ }
38
+ }
39
+
40
+ var discovery = null;
41
+ function discover() {
42
+ if (!discovery) {
43
+ discovery = fetch(O.issuer.replace(/\/$/, "") + "/.well-known/openid-configuration")
44
+ .then(function (response) { return response.json(); });
45
+ }
46
+ return discovery;
47
+ }
48
+ function redirectUri() { return location.origin + location.pathname; }
49
+
50
+ function tokenRequest(params) {
51
+ return discover().then(function (d) {
52
+ return fetch(d.token_endpoint, { method: "POST",
53
+ headers: { "Content-Type": "application/x-www-form-urlencoded" },
54
+ body: new URLSearchParams(params) });
55
+ }).then(function (response) {
56
+ return response.json().then(function (data) {
57
+ if (!response.ok) throw new Error(data.error_description || data.error || response.status);
58
+ return data;
59
+ });
60
+ });
61
+ }
62
+
63
+ function signIn() {
64
+ var verifier = random(48), state = random(16);
65
+ write(FLOW, { verifier: verifier, state: state, back: location.search + location.hash });
66
+ Promise.all([discover(), sha256(verifier)]).then(function (both) {
67
+ var query = new URLSearchParams({
68
+ response_type: "code", client_id: O.client_id, redirect_uri: redirectUri(),
69
+ scope: O.scope, state: state, code_challenge: both[1], code_challenge_method: "S256",
70
+ });
71
+ if (lang) query.set("ui_locales", lang);
72
+ location.assign(both[0].authorization_endpoint + "?" + query);
73
+ }, function (error) { R.authError = L.sign_in_failed + " (" + error.message + ")"; redraw(); });
74
+ }
75
+
76
+ var timer = null;
77
+ function store(tokens) {
78
+ R.save("re-console-token", tokens.access_token);
79
+ var previous = read(KEY) || {};
80
+ write(KEY, {
81
+ refresh: tokens.refresh_token || previous.refresh,
82
+ id_token: tokens.id_token || previous.id_token,
83
+ expires: Date.now() + (tokens.expires_in || 300) * 1000,
84
+ });
85
+ schedule();
86
+ window.dispatchEvent(new Event("re-token"));
87
+ }
88
+ function schedule() {
89
+ clearTimeout(timer);
90
+ var state = read(KEY);
91
+ if (!state || !state.refresh) return;
92
+ timer = setTimeout(renew, Math.max(5000, state.expires - Date.now() - 30000));
93
+ }
94
+ function renew() {
95
+ var state = read(KEY);
96
+ if (!state) return;
97
+ tokenRequest({ grant_type: "refresh_token", refresh_token: state.refresh,
98
+ client_id: O.client_id }).then(store, function () { forget(); redraw(); });
99
+ }
100
+ function forget() {
101
+ write(KEY, null);
102
+ R.save("re-console-token", "");
103
+ window.dispatchEvent(new Event("re-token"));
104
+ }
105
+ function signOut() {
106
+ var state = read(KEY);
107
+ forget();
108
+ discover().then(function (d) {
109
+ if (d.end_session_endpoint && state && state.id_token) {
110
+ var query = new URLSearchParams({ client_id: O.client_id, id_token_hint: state.id_token,
111
+ post_logout_redirect_uri: redirectUri() + location.search + location.hash });
112
+ location.assign(d.end_session_endpoint + "?" + query);
113
+ } else {
114
+ redraw();
115
+ }
116
+ }, redraw);
117
+ }
118
+
119
+ // back from the provider: ?code=...&state=...
120
+ function callback() {
121
+ var params = new URLSearchParams(location.search);
122
+ if (!params.get("code") && !params.get("error")) return Promise.resolve();
123
+ var flow = read(FLOW);
124
+ write(FLOW, null);
125
+ history.replaceState(null, "", location.pathname + (flow ? flow.back : ""));
126
+ if (params.get("error") || !flow || flow.state !== params.get("state")) {
127
+ R.authError = L.sign_in_failed + (params.get("error_description") ?
128
+ " (" + params.get("error_description") + ")" : "");
129
+ return Promise.resolve();
130
+ }
131
+ return tokenRequest({ grant_type: "authorization_code", code: params.get("code"),
132
+ redirect_uri: redirectUri(), client_id: O.client_id, code_verifier: flow.verifier })
133
+ .then(store, function (error) { R.authError = L.sign_in_failed + " (" + error.message + ")"; });
134
+ }
135
+
136
+ function claims() {
137
+ var token = R.load("re-console-token");
138
+ try {
139
+ return JSON.parse(decodeURIComponent(escape(atob(
140
+ token.split(".")[1].replace(/-/g, "+").replace(/_/g, "/")))));
141
+ } catch (e) { return null; }
142
+ }
143
+
144
+ var holder = null;
145
+ function redraw() { if (holder) fill(holder); }
146
+ function fill(target) {
147
+ target.textContent = "";
148
+ var who = read(KEY) ? claims() : null;
149
+ if (who) {
150
+ target.appendChild(el("span", { className: "who",
151
+ text: L.signed_in_as.replace("{name}", who.preferred_username || who.email || who.sub) }));
152
+ var out = el("button", { type: "button", className: "secondary", text: L.sign_out });
153
+ out.addEventListener("click", signOut);
154
+ target.appendChild(out);
155
+ } else {
156
+ var button = el("button", { type: "button", className: "execute authorize", text: L.authorize });
157
+ button.addEventListener("click", signIn);
158
+ target.appendChild(button);
159
+ target.appendChild(el("span", { className: "note", text: " " + L.authorize_note }));
160
+ }
161
+ if (R.authError) target.appendChild(el("p", { className: "console-status fail", text: R.authError }));
162
+ }
163
+ function box() {
164
+ holder = el("div", { className: "signin" });
165
+ fill(holder);
166
+ return holder;
167
+ }
168
+
169
+ R.auth = { box: box };
170
+ R.ready = callback().then(schedule);
171
+ })();