@swimmesberger/elarion-pwa 0.2.22-preview.190.1 → 0.3.0

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.
package/README.md CHANGED
@@ -10,6 +10,10 @@ loads its assets from the cache, and moves to a new deploy without throwing away
10
10
  - **Updates** — `createUpdateWatcher({ currentVersion })` asks the server which web build is live when the app returns
11
11
  to the foreground and reloads into a new one **on the next navigation that changed the path**, never on the
12
12
  foreground return itself, never while a dialog is open or a field is focused, at most once a minute.
13
+ - **Session renewal** — `createSessionRenewal()` for an app behind an authenticating proxy (Cloudflare Access, IAP,
14
+ oauth2-proxy): its `fetch` (for the JSON-RPC client) marks calls so the proxy answers an expired session with `401`
15
+ instead of a login redirect, its `eventSource` (for the client-events client) probes a failing stream, and an
16
+ expired session reloads the page once so the proxy renews it — at most once a minute, then `onSignedOut`.
13
17
  - **Registration** — `registerServiceWorker('/sw.js')` with `updateViaCache: 'none'`; resolves `null` instead of
14
18
  throwing where there is no service worker.
15
19
  - **`/sw`** — `registerShellRouter(self, …)`: network-only or network-first navigations, cache-first hashed assets,
@@ -22,7 +26,7 @@ loads its assets from the cache, and moves to a new deploy without throwing away
22
26
  ## Page
23
27
 
24
28
  ```ts
25
- import { createInstallPrompt, createUpdateWatcher, registerServiceWorker } from '@swimmesberger/elarion-pwa'
29
+ import { createInstallPrompt, createSessionRenewal, createUpdateWatcher, registerServiceWorker } from '@swimmesberger/elarion-pwa'
26
30
 
27
31
  if (import.meta.env.PROD) void registerServiceWorker('/sw.js')
28
32
 
@@ -30,6 +34,11 @@ export const install = createInstallPrompt() // at module load: the prompt event
30
34
 
31
35
  export const updates = createUpdateWatcher({ currentVersion: __APP_VERSION__, enabled: import.meta.env.PROD })
32
36
  router.subscribe('onResolved', (event) => updates.navigationResolved({ pathChanged: event.pathChanged }))
37
+
38
+ // Behind an authenticating proxy:
39
+ const session = createSessionRenewal({ onSignedOut: () => showSignedOut() })
40
+ export const rpc = createRpcApi({ url: '/rpc', fetch: session.fetch })
41
+ export const events = createElarionEvents({ url: '/events', eventSource: session.eventSource })
33
42
  ```
34
43
 
35
44
  ## Service worker
package/dist/index.d.ts CHANGED
@@ -1,3 +1,4 @@
1
1
  export { createInstallPrompt, installOption, isAppleTouchDevice, isStandalone, readInstallEnvironment, type InstallEnvironment, type InstallOption, type InstallPromptController, type InstallPromptOptions, type InstallPromptOutcome, } from './install.js';
2
+ export { createSessionRenewal, DEFAULT_SESSION_PROBE_INTERVAL_MS, DEFAULT_SESSION_RENEWAL_GUARD_MS, DEFAULT_SESSION_RENEWAL_STORAGE_KEY, isSessionExpired, SESSION_REQUEST_HEADERS, type SessionEventSource, type SessionRenewal, type SessionRenewalOptions, } from './session.js';
2
3
  export { registerServiceWorker, type RegisterServiceWorkerOptions, type ServiceWorkerContainerLike } from './register.js';
3
4
  export { BUSY_SELECTOR, createUpdateWatcher, currentEntryScript, DEFAULT_CHECK_INTERVAL_MS, DEFAULT_RELOAD_GUARD_MS, DEFAULT_RELOAD_STORAGE_KEY, DEFAULT_VERSION_URL, entryScriptVersionSource, isDocumentBusy, isTextEntry, jsonVersionSource, parseEntryScript, parseServedVersion, shouldCheckForUpdate, shouldReloadOnNavigation, updateDecision, type BusyDocument, type FocusTarget, type ReloadGuardStorage, type UpdateDecision, type UpdateWatcher, type UpdateWatcherOptions, type VersionSource, type VisibilityDocument, } from './update.js';
package/dist/index.js CHANGED
@@ -1,10 +1,12 @@
1
1
  // The page half of the Elarion installable-app shell (ADR-0083): how the app can be installed (the deferred
2
2
  // `beforeinstallprompt` prompt, or the iOS share-sheet instructions), reloading into a new deploy at a safe moment,
3
- // and registering the service worker. Framework-neutral: subscribe/snapshot pairs plug into React's
4
- // `useSyncExternalStore`, and the update watcher takes navigation events from any router.
3
+ // renewing an expired authenticating-proxy session, and registering the service worker. Framework-neutral:
4
+ // subscribe/snapshot pairs plug into React's `useSyncExternalStore`, and the update watcher takes navigation events
5
+ // from any router.
5
6
  //
6
7
  // The service-worker half (the shell router and its caching strategies) is the `/sw` sub-export; the Vite plugin
7
8
  // that publishes the build version is `/vite`.
8
9
  export { createInstallPrompt, installOption, isAppleTouchDevice, isStandalone, readInstallEnvironment, } from './install.js';
10
+ export { createSessionRenewal, DEFAULT_SESSION_PROBE_INTERVAL_MS, DEFAULT_SESSION_RENEWAL_GUARD_MS, DEFAULT_SESSION_RENEWAL_STORAGE_KEY, isSessionExpired, SESSION_REQUEST_HEADERS, } from './session.js';
9
11
  export { registerServiceWorker } from './register.js';
10
12
  export { BUSY_SELECTOR, createUpdateWatcher, currentEntryScript, DEFAULT_CHECK_INTERVAL_MS, DEFAULT_RELOAD_GUARD_MS, DEFAULT_RELOAD_STORAGE_KEY, DEFAULT_VERSION_URL, entryScriptVersionSource, isDocumentBusy, isTextEntry, jsonVersionSource, parseEntryScript, parseServedVersion, shouldCheckForUpdate, shouldReloadOnNavigation, updateDecision, } from './update.js';
@@ -0,0 +1,83 @@
1
+ import type { ReloadGuardStorage } from './update.js';
2
+ /** The headers that make authenticating proxies answer an expired session with 401 instead of a login redirect. */
3
+ export declare const SESSION_REQUEST_HEADERS: Readonly<Record<string, string>>;
4
+ /** No second renewal reload within this window: a 401 right after one is not an expiry the reload can renew. */
5
+ export declare const DEFAULT_SESSION_RENEWAL_GUARD_MS = 60000;
6
+ /** The sessionStorage key of the last renewal reload (per tab; it survives the reload itself). */
7
+ export declare const DEFAULT_SESSION_RENEWAL_STORAGE_KEY = "elarion.pwa.sessionRenewedAt";
8
+ /** No second probe of an event stream within this window, however often it reports an error. */
9
+ export declare const DEFAULT_SESSION_PROBE_INTERVAL_MS = 10000;
10
+ /**
11
+ * Whether an API answer means the session expired: a 401, or a redirect (fetched with `redirect: 'manual'`) — an API
12
+ * endpoint never redirects, a proxy sending the browser to its login page does.
13
+ */
14
+ export declare function isSessionExpired(response: Pick<Response, 'status' | 'type'>): boolean;
15
+ /** The parts of the platform `EventSource` the renewal needs — and the shape the generated events client accepts. */
16
+ export interface SessionEventSource {
17
+ addEventListener(type: string, listener: (event: any) => void): void;
18
+ close(): void;
19
+ readonly readyState: number;
20
+ }
21
+ /** Options for {@link createSessionRenewal}. */
22
+ export interface SessionRenewalOptions {
23
+ /** Minimum time between two renewal reloads of this tab. Defaults to 60 s. */
24
+ reloadGuardMs?: number;
25
+ /** The sessionStorage key of the reload guard. Defaults to {@link DEFAULT_SESSION_RENEWAL_STORAGE_KEY}. */
26
+ storageKey?: string;
27
+ /**
28
+ * Where the reload guard is kept. Defaults to `sessionStorage`. `null` disables the automatic reload: without a
29
+ * guard that survives the reload, a proxy that keeps answering 401 would reload the page forever.
30
+ */
31
+ storage?: ReloadGuardStorage | null;
32
+ /**
33
+ * Called when the session expired but the page will not reload — a renewal ran moments ago, or there is no guard
34
+ * storage. The proxy needs a real sign-in: show a "signed out" state with a button that reloads.
35
+ */
36
+ onSignedOut?: () => void;
37
+ /** Minimum time between two probes of an event stream. Defaults to 10 s. */
38
+ probeIntervalMs?: number;
39
+ /** The `fetch` behind {@link SessionRenewal.fetch} and the event-stream probe. Defaults to the global one. */
40
+ fetch?: typeof fetch;
41
+ /** Opens an event stream. Defaults to `new EventSource(url)`. */
42
+ createEventSource?: (url: string) => SessionEventSource;
43
+ /** Reloads the page. Defaults to `location.reload()`. */
44
+ reload?: () => void;
45
+ /** The clock. Defaults to `Date.now`. */
46
+ now?: () => number;
47
+ }
48
+ /** Session renewal for an app behind an authenticating proxy; see {@link createSessionRenewal}. */
49
+ export interface SessionRenewal {
50
+ /**
51
+ * A `fetch` for the app's API — the generated JSON-RPC client's `fetch` option. It adds
52
+ * {@link SESSION_REQUEST_HEADERS} (unless the call sets them) and `redirect: 'manual'` (unless the call sets
53
+ * `redirect`); when the answer means the session expired it reloads the page and never settles, so the page goes
54
+ * away instead of flashing an error first. When it does not reload ({@link SessionRenewalOptions.onSignedOut}) the
55
+ * answer passes through.
56
+ */
57
+ fetch(input: string | URL | Request, init?: RequestInit): Promise<Response>;
58
+ /**
59
+ * Opens an event stream — the generated events client's `eventSource` option. When the stream reports an error it
60
+ * probes the same URL once with {@link SESSION_REQUEST_HEADERS}, and renews the session when the probe says it
61
+ * expired. Network errors (offline, a server restart) are left to the stream's own retries.
62
+ */
63
+ eventSource(url: string): SessionEventSource;
64
+ /**
65
+ * Reloads the page to renew the session, unless a renewal ran within the guard window (then it calls `onSignedOut`).
66
+ * Returns whether it reloaded.
67
+ */
68
+ renew(): boolean;
69
+ }
70
+ /**
71
+ * Creates the session renewal: pass its `fetch` to the JSON-RPC client and its `eventSource` to the client-events
72
+ * client, and an expired proxy session renews itself with one reload.
73
+ *
74
+ * @example
75
+ * ```ts
76
+ * import { createSessionRenewal } from '@swimmesberger/elarion-pwa'
77
+ *
78
+ * const session = createSessionRenewal({ onSignedOut: () => showSignedOutBanner() })
79
+ * export const rpc = createRpcApi({ url: '/rpc', fetch: session.fetch })
80
+ * export const events = createElarionEvents({ url: '/events', eventSource: session.eventSource })
81
+ * ```
82
+ */
83
+ export declare function createSessionRenewal(options?: SessionRenewalOptions): SessionRenewal;
@@ -0,0 +1,148 @@
1
+ // Renew an expired proxy session. An authenticating proxy in front of the app (Cloudflare Access, Google IAP,
2
+ // oauth2-proxy) issues its session for a fixed time and renews it — silently, from its own longer-lived session and
3
+ // the identity provider's — only on a full page load: the redirect chain runs through other origins, which a fetch
4
+ // cannot follow. An installed app is resumed rather than reloaded, so it meets the expiry on an API call instead:
5
+ //
6
+ // fetch the proxy redirects to its login page on another origin, and the browser reports a CORS failure,
7
+ // indistinguishable from being offline. Marked as an XHR (`X-Requested-With: XMLHttpRequest`, which
8
+ // Cloudflare Access, Google IAP and ASP.NET Core's cookie handler honour) or as a JSON call
9
+ // (`Accept: application/json`, oauth2-proxy), it answers 401 instead; with `redirect: 'manual'` a
10
+ // proxy that redirects anyway yields a readable opaque redirect instead of the CORS failure.
11
+ // EventSource cannot send headers. Redirected off-origin it retries forever; answered with a 401 or a login page
12
+ // it gives up. Neither says why.
13
+ //
14
+ // createSessionRenewal turns both into one signal — the session expired — and answers it with a single reload, which
15
+ // lets the proxy renew the session and lands the user where they were. A sessionStorage guard keeps a proxy that
16
+ // answers 401 right after the reload from turning it into a loop.
17
+ /** The headers that make authenticating proxies answer an expired session with 401 instead of a login redirect. */
18
+ export const SESSION_REQUEST_HEADERS = {
19
+ 'X-Requested-With': 'XMLHttpRequest',
20
+ Accept: 'application/json',
21
+ };
22
+ /** No second renewal reload within this window: a 401 right after one is not an expiry the reload can renew. */
23
+ export const DEFAULT_SESSION_RENEWAL_GUARD_MS = 60_000;
24
+ /** The sessionStorage key of the last renewal reload (per tab; it survives the reload itself). */
25
+ export const DEFAULT_SESSION_RENEWAL_STORAGE_KEY = 'elarion.pwa.sessionRenewedAt';
26
+ /** No second probe of an event stream within this window, however often it reports an error. */
27
+ export const DEFAULT_SESSION_PROBE_INTERVAL_MS = 10_000;
28
+ /**
29
+ * Whether an API answer means the session expired: a 401, or a redirect (fetched with `redirect: 'manual'`) — an API
30
+ * endpoint never redirects, a proxy sending the browser to its login page does.
31
+ */
32
+ export function isSessionExpired(response) {
33
+ return response.status === 401 || response.type === 'opaqueredirect';
34
+ }
35
+ /**
36
+ * Creates the session renewal: pass its `fetch` to the JSON-RPC client and its `eventSource` to the client-events
37
+ * client, and an expired proxy session renews itself with one reload.
38
+ *
39
+ * @example
40
+ * ```ts
41
+ * import { createSessionRenewal } from '@swimmesberger/elarion-pwa'
42
+ *
43
+ * const session = createSessionRenewal({ onSignedOut: () => showSignedOutBanner() })
44
+ * export const rpc = createRpcApi({ url: '/rpc', fetch: session.fetch })
45
+ * export const events = createElarionEvents({ url: '/events', eventSource: session.eventSource })
46
+ * ```
47
+ */
48
+ export function createSessionRenewal(options = {}) {
49
+ const guardMs = options.reloadGuardMs ?? DEFAULT_SESSION_RENEWAL_GUARD_MS;
50
+ const storageKey = options.storageKey ?? DEFAULT_SESSION_RENEWAL_STORAGE_KEY;
51
+ const storage = options.storage === undefined ? sessionStorageOrNull() : options.storage;
52
+ const probeIntervalMs = options.probeIntervalMs ?? DEFAULT_SESSION_PROBE_INTERVAL_MS;
53
+ const reload = options.reload ?? (() => globalThis.location.reload());
54
+ const now = options.now ?? Date.now;
55
+ const doFetch = (input, init) => (options.fetch ?? globalThis.fetch)(input, init);
56
+ const createEventSource = options.createEventSource ?? defaultEventSource;
57
+ let reloading = false;
58
+ let probing = false;
59
+ let lastProbeAt = Number.NEGATIVE_INFINITY;
60
+ function renew() {
61
+ if (reloading)
62
+ return true;
63
+ const at = now();
64
+ try {
65
+ if (!storage)
66
+ throw new Error('No reload guard storage.');
67
+ const last = Number(storage.getItem(storageKey));
68
+ if (Number.isFinite(last) && at - last < guardMs)
69
+ throw new Error('Renewed moments ago.');
70
+ storage.setItem(storageKey, String(at));
71
+ }
72
+ catch {
73
+ options.onSignedOut?.();
74
+ return false;
75
+ }
76
+ reloading = true;
77
+ reload();
78
+ return true;
79
+ }
80
+ async function sessionFetch(input, init) {
81
+ const headers = new Headers(init?.headers ?? (isRequest(input) ? input.headers : undefined));
82
+ for (const [name, value] of Object.entries(SESSION_REQUEST_HEADERS)) {
83
+ if (!headers.has(name))
84
+ headers.set(name, value);
85
+ }
86
+ const response = await doFetch(input, { ...init, headers, redirect: init?.redirect ?? 'manual' });
87
+ // The page is going away; settling would only show an error for the moment until it does.
88
+ if (isSessionExpired(response) && renew())
89
+ return new Promise(() => { });
90
+ return response;
91
+ }
92
+ async function probe(url) {
93
+ const at = now();
94
+ if (reloading || probing || at - lastProbeAt < probeIntervalMs)
95
+ return;
96
+ probing = true;
97
+ lastProbeAt = at;
98
+ const controller = new AbortController();
99
+ try {
100
+ const response = await doFetch(url, {
101
+ headers: { ...SESSION_REQUEST_HEADERS, Accept: 'text/event-stream' },
102
+ redirect: 'manual',
103
+ credentials: 'same-origin',
104
+ cache: 'no-store',
105
+ signal: controller.signal,
106
+ });
107
+ if (isSessionExpired(response))
108
+ renew();
109
+ }
110
+ catch {
111
+ // Offline or the server is restarting: the stream's own retries cover that.
112
+ }
113
+ finally {
114
+ // Only the status matters; a stream that did open must not stay open.
115
+ controller.abort();
116
+ probing = false;
117
+ }
118
+ }
119
+ return {
120
+ fetch: sessionFetch,
121
+ eventSource(url) {
122
+ const source = createEventSource(url);
123
+ source.addEventListener('error', () => {
124
+ void probe(url);
125
+ });
126
+ return source;
127
+ },
128
+ renew,
129
+ };
130
+ }
131
+ function isRequest(input) {
132
+ return typeof Request !== 'undefined' && input instanceof Request;
133
+ }
134
+ function defaultEventSource(url) {
135
+ const ctor = globalThis.EventSource;
136
+ if (!ctor)
137
+ throw new Error('No EventSource implementation is available. Pass createEventSource.');
138
+ return new ctor(url);
139
+ }
140
+ function sessionStorageOrNull() {
141
+ try {
142
+ return globalThis.sessionStorage ?? null;
143
+ }
144
+ catch {
145
+ // Reading sessionStorage throws where storage is blocked (sandboxed frames, some privacy modes).
146
+ return null;
147
+ }
148
+ }
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@swimmesberger/elarion-pwa",
3
- "version": "0.2.22-preview.190.1",
4
- "description": "The installable-app shell for Elarion frontends: install-prompt capture with iOS Home Screen instructions, a deploy-update watcher that reloads only on a safe page change, service-worker registration, a /sw module whose shell router never caches the API, HTML, redirects, or no-store answers, and a /vite plugin that publishes the build version.",
3
+ "version": "0.3.0",
4
+ "description": "The installable-app shell for Elarion frontends: install-prompt capture with iOS Home Screen instructions, a deploy-update watcher that reloads only on a safe page change, renewal of an expired authenticating-proxy session, service-worker registration, a /sw module whose shell router never caches the API, HTML, redirects, or no-store answers, and a /vite plugin that publishes the build version.",
5
5
  "license": "Apache-2.0",
6
6
  "type": "module",
7
7
  "exports": {