@hosty-sdk/app 0.18.0 → 0.20.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
@@ -1,8 +1,7 @@
1
1
  # @hosty-sdk/app
2
2
 
3
3
  Auth and host integration for [Hosty](https://github.com/alex-de-haas/docker-host) runtime
4
- apps: the app-session state machine, silent session recovery, Core revalidation, and the
5
- embedder responder for shells.
4
+ apps: app-session classification, Core-owned sign-in, app-local request transport and revalidation.
6
5
 
7
6
  ```
8
7
  npm install @hosty-sdk/app
@@ -12,8 +11,9 @@ npm install @hosty-sdk/app
12
11
  | --- | --- | --- |
13
12
  | `@hosty-sdk/app` | anywhere | status taxonomy, recovery decision, `hosty:auth-required` and `hosty:request-delegated-token` schemas, URL/env helpers |
14
13
  | `@hosty-sdk/app/server` | server only | Core revalidation with caching, cookie helpers, the app-code route factory, the app secrets client |
15
- | `@hosty-sdk/app/react` | client | `<AppIdentityBridge />` — probe, silent recovery, fallback cards |
16
- | `@hosty-sdk/app/embedder` | client | verified responders — launch-code recovery and delegated tokens — plus the theme sender half, for anything that embeds Hosty apps |
14
+ | `@hosty-sdk/app/react` | client | `<AppIdentityBridge />` — probe, Core popup/navigation recovery, content gate |
15
+ | `@hosty-sdk/app/embedder` | client | theme sender and legacy embedder message parsers; Shell no longer mints app credentials |
16
+ | `@hosty-sdk/app/browser-auth` | client | `appFetch` for app-local API requests and bound Core popup sign-in |
17
17
  | `@hosty-sdk/app/providers` | anywhere | permission state, provider descriptors, speech contract types |
18
18
  | `@hosty-sdk/app/providers/server` | server only | `ProviderClient`: discovery, speech recognition, assistant handoffs and live credential validation |
19
19
  | `@hosty-sdk/app/theme` | anywhere | the shell→app theme protocol: constants, `resolveTheme`, `applyTheme`, `parseShellThemeMessage`, `themeBootstrapScript` / `createThemeBootstrapScript` |
@@ -23,7 +23,7 @@ Minimal Next.js wiring:
23
23
  ```tsx
24
24
  // app/layout.tsx
25
25
  import { AppIdentityBridge } from "@hosty-sdk/app/react";
26
- // mount <AppIdentityBridge /> at the top of <body>
26
+ // wrap protected client content: <AppIdentityBridge>{children}</AppIdentityBridge>
27
27
 
28
28
  // app/api/auth/app-code/route.ts
29
29
  import { createAppCodeRouteHandler } from "@hosty-sdk/app/server";
@@ -81,36 +81,26 @@ await setAppSecret("trakt.connection.1.tokens", refreshed, config);
81
81
  Reads are served from a write-through cache, namespaced by Core origin and app id; pass
82
82
  `{ refresh: true }` to force a live read.
83
83
 
84
- Delegated tokens — the credential a browser client (Shell) presents when calling a system
85
- app's API directly. Core signs them (ECDSA P-256, 5-minute TTL) and injects the verification
86
- key as `HOSTY_DELEGATED_TOKEN_PUBLIC_KEY`, so validation is fully local — no Core round-trip:
84
+ Protected browser requests use the app-only credential held by the bridge:
87
85
 
88
86
  ```ts
89
- import { validateDelegatedToken } from "@hosty-sdk/app/server";
90
-
91
- // null for anything invalid (bad signature, wrong audience, expired) — treat like a missing token.
92
- const claims = validateDelegatedToken(bearerToken);
93
- if (claims?.role !== "host.admin") { /* 401/403 */ }
87
+ import { appFetch } from "@hosty-sdk/app/browser-auth";
88
+ const response = await appFetch("/api/items");
94
89
  ```
95
90
 
96
- An embedded page cannot mint a delegated token itself — that needs the user's Core session in a
97
- first-party context — so it asks whoever embeds it:
91
+ The server must accept the explicit app bearer as well as its cookie (`readAppIdentityToken`), then
92
+ revalidate it with the app service token. This supports embedded browsers that block cookie access.
93
+ The bridge retains the grant only in memory and never sends it to Shell. `appFetch` rejects foreign
94
+ origins and redirects; 401 starts recovery, while 503 preserves the credential. Custom bridge views
95
+ must call `state.signIn` from a click and display `state.error` if present.
98
96
 
99
- ```ts
100
- import { DELEGATED_TOKEN_REQUEST_TYPE, DELEGATED_TOKEN_TYPE } from "@hosty-sdk/app";
101
- import { parseActiveFrameDelegatedTokenRequest } from "@hosty-sdk/app/embedder";
102
-
103
- // In the embedder, per app frame. A verified request says who asked, never whether to answer: the
104
- // token is user-scoped, so grant it only to apps you decided to grant it to, and post it to that
105
- // frame's own origin — never "*". Attach the listener before the frame can run (apps ask as soon as
106
- // their document does, and they re-ask until answered), and honour `refresh`: it means the token the
107
- // app holds was refused, so a cached mint must not be handed back.
108
- const intent = parseActiveFrameDelegatedTokenRequest(event, frame.contentWindow, frame.src);
109
- if (intent) {
110
- const { token, expiresAt } = await mintDelegatedTokenFromCore(appId, { force: intent.refresh });
111
- frame.contentWindow.postMessage({ type: DELEGATED_TOKEN_TYPE, token, expiresAt }, frameOrigin);
112
- }
113
- ```
97
+ Embedded recovery opens Core in a popup and accepts a one-time code only from that window, the exact
98
+ Core origin and matching random state. The app exchanges and validates the code on its own server.
99
+ Standalone recovery uses Core navigation. No Core session credential is copied into either app.
100
+
101
+ Legacy signed clients can still use `validateDelegatedToken` from `@hosty-sdk/app/delegated` for
102
+ local signature/audience/expiry checking. An app login is not permission to mint cross-app MCP
103
+ tokens. Do not ask Shell for a delegated token; its old responder is disabled.
114
104
 
115
105
  The design contract lives in the Hosty repository:
116
106
  [`docs/features/hosty-app-sdk/feature.md`](https://github.com/alex-de-haas/docker-host/blob/main/docs/features/hosty-app-sdk/feature.md).
@@ -121,7 +111,7 @@ License: AGPL-3.0-only.
121
111
 
122
112
  Declare `"corePermissions": ["apps.install"]` in the manifest and have an administrator approve
123
113
  that permission when installing/updating your app. This grants the ability to **request** an
124
- installation; it never grants the ability to approve it on the user's behalf.
114
+ installation, update or removal; it never grants the ability to approve it on the user's behalf.
125
115
 
126
116
  Mount an app-local handler using the existing Hosty identity-cookie configuration:
127
117
 
@@ -174,15 +164,27 @@ Open an empty confirmation window synchronously in the click handler with
174
164
  `showInstallationConfirmation(popup, pending)`. Always retain a visible new-tab link for popup
175
165
  blocking. No installation-specific Shell messages or shared administrative credentials are needed.
176
166
  `prepare({ updateAppId, planDigest })` similarly requests approval of a reviewed update for clients
177
- with `apps.update`. A transport override supports existing Core operator clients:
167
+ with `apps.install`. A transport override supports existing Core operator clients:
178
168
  `createInstallationClient({ baseUrl: coreOrigin + "/api/installations", request: sendCsrfJson })`.
179
169
 
170
+ Removal uses the same flow: `prepare({ removeAppId, removalOptions: { deleteData: true,
171
+ deleteBackups: false } })`, then `submit(draft.id, {}, false)`, Core confirmation and status polling.
172
+ Core freezes the target installation and cleanup options during preparation; later payloads cannot
173
+ change them. `deleteRuntimeState` defaults to true; `deleteData`, `deleteBackups`, `deleteSource`
174
+ and `ignoreRuntimeErrors` default to false. Only report removal after status is `succeeded`.
175
+ App credentials cannot call the direct removal endpoint, even with `apps.install`.
176
+
180
177
  Core's final page cannot be embedded or replaced by a custom permission-grant dialog. It requires
181
178
  an administrator browser login issued on a dedicated Core hostname, separate from app cookie
182
179
  hosts. Existing sessions need a fresh login. Requests expire after 15 minutes and Core restart
183
180
  invalidates them. Closing your UI does not cancel a confirmed operation; status is the authority.
184
181
  Never automatically retry an execution after a lost response.
185
182
 
183
+ Optional permission choices belong exclusively to the Core confirmation page. The client cannot
184
+ preselect them: `submit` accepts only the request ID, settings and autostart. Core starts new optional
185
+ rights unchecked and checks rights already granted to that app. The user can grant or revoke them
186
+ there. App settings should display grants read-only and link to Core to change permissions.
187
+
186
188
  ## Assistant handoffs
187
189
 
188
190
  `@hosty-sdk/app/assistant` exposes the version-1 client. Discover the confirmed assistant's
@@ -221,3 +223,23 @@ PCM16 WAV. Browser microphone consent is separate from Core permission.
221
223
  `assistant(selected, getUserToken)` returns the existing `AssistantClient` with bounded provider
222
224
  credentials and the acting user's access. It does not expose general agent execution.
223
225
  See [Provider consumption](../../docs/features/provider-consumption/feature.md) for the full contract.
226
+
227
+ ### Assistant MCP credentials
228
+
229
+ MCP handlers use `introspectMcpToken` from `@hosty-sdk/app/scoped-token` for online validation of
230
+ external scoped tokens and Core's assistant-only `hosty_mcp.1` tokens. The latter require explicit
231
+ Core assistant-to-target grants and include `callerAppId` in the result. Require `mcp:read` for
232
+ reads or `mcp:invoke` for assistant mutations, then apply your application's user permissions.
233
+ Do not cache validation. Keep `introspectScopedToken` on ordinary APIs: it does not opt into accepting
234
+ MCP-only credentials. Neither token permits skipping the application's own authorization.
235
+
236
+ ## Privileged activity renewal
237
+
238
+ Identity probes used by `AppIdentityBridge` pass `activeUntil` and `activityRequired` through from
239
+ `resolveAppSession().identity`. Keep app APIs on `appFetch`; a 401 can then request a user-click
240
+ Core popup, exchange a code on the same origin and retry once without replacing mounted content.
241
+ For another UI framework, use `configureAppActivity` with an app-owned `exchangeCode` function,
242
+ listen for `APP_SESSION_ENDED`, and call `renewAppActivity` directly from a click. Do not navigate
243
+ or reload to renew access. `appActivityNeedsRenewal()` supports proactive click renewal near expiry.
244
+ See [the activity contract](../../docs/features/app-activity-window/feature.md), including the
245
+ separate Core-approved assistant session leases.
@@ -0,0 +1,7 @@
1
+ /** Keep mounted beside app content so expiry never discards drafts or component state. */
2
+ export declare function AppActivityBridge({ openUrl, appCodePath, activeUntil, activityRequired }: {
3
+ openUrl: string;
4
+ appCodePath: string;
5
+ activeUntil?: string | null;
6
+ activityRequired?: boolean;
7
+ }): import("react").JSX.Element | null;
@@ -0,0 +1,44 @@
1
+ "use client";
2
+ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
3
+ import { useEffect, useState } from "react";
4
+ import { AuthNotice, AuthNoticeButton } from "./auth-notice.js";
5
+ import { APP_SESSION_ENDED, APP_ACTIVITY_RENEWED, appActivityNeedsRenewal, configureAppActivity, updateAppActivity, renewAppActivity, cancelActivityRenewal } from "./browser-auth.js";
6
+ /** Keep mounted beside app content so expiry never discards drafts or component state. */
7
+ export function AppActivityBridge({ openUrl, appCodePath, activeUntil, activityRequired = false }) {
8
+ const [needed, setNeeded] = useState(false);
9
+ const [pending, setPending] = useState(false);
10
+ const [error, setError] = useState("");
11
+ const renew = () => {
12
+ const operation = renewAppActivity();
13
+ setPending(true);
14
+ setError("");
15
+ void operation.catch(e => { setNeeded(true); setError(String(e.message ?? e)); }).finally(() => setPending(false));
16
+ };
17
+ useEffect(() => {
18
+ const cleanup = configureAppActivity({ openUrl, exchangeCode: async (code) => {
19
+ const response = await fetch(appCodePath, { method: "POST", credentials: "same-origin", redirect: "error",
20
+ headers: { "Content-Type": "application/json" }, body: JSON.stringify({ code }) });
21
+ const body = await response.json();
22
+ if (!response.ok)
23
+ throw new Error(body.message ?? "Could not renew app activity.");
24
+ return body;
25
+ } });
26
+ const expired = () => setNeeded(true);
27
+ const renewed = () => { setNeeded(false); setError(""); };
28
+ const click = (event) => {
29
+ if (event.target instanceof Element && event.target.closest("[data-hosty-activity-control]"))
30
+ return;
31
+ if (event.isTrusted && appActivityNeedsRenewal()) {
32
+ void renewAppActivity().catch(e => { setNeeded(true); setError(String(e.message ?? e)); });
33
+ }
34
+ };
35
+ window.addEventListener(APP_SESSION_ENDED, expired);
36
+ window.addEventListener(APP_ACTIVITY_RENEWED, renewed);
37
+ document.addEventListener("click", click, true);
38
+ return () => { cleanup(); window.removeEventListener(APP_SESSION_ENDED, expired); window.removeEventListener(APP_ACTIVITY_RENEWED, renewed); document.removeEventListener("click", click, true); };
39
+ }, [openUrl, appCodePath]);
40
+ useEffect(() => { updateAppActivity(activeUntil, activityRequired); }, [activeUntil, activityRequired, openUrl, appCodePath]);
41
+ if (!needed)
42
+ return null;
43
+ return _jsxs(AuthNotice, { children: [_jsx("span", { children: error || "Renew access through Core to continue. Your work stays on this page." }), _jsx(AuthNoticeButton, { disabled: pending, onClick: renew, children: pending ? "Waiting for Core…" : "Renew access" }), _jsx(AuthNoticeButton, { secondary: true, onClick: () => { cancelActivityRenewal(); setNeeded(false); }, children: "Later" })] });
44
+ }
@@ -1,3 +1,9 @@
1
+ /** Preserve provider refusal details through app-owned server transports. */
2
+ export declare class AssistantError extends Error {
3
+ readonly code: string;
4
+ readonly status: number;
5
+ constructor(code: string, message: string, status: number);
6
+ }
1
7
  /** Version 1 of the manifest-discovered assistant handoff. */
2
8
  export type AssistantContract = {
3
9
  version?: number | null;
package/dist/assistant.js CHANGED
@@ -1,3 +1,13 @@
1
+ /** Preserve provider refusal details through app-owned server transports. */
2
+ export class AssistantError extends Error {
3
+ code;
4
+ status;
5
+ constructor(code, message, status) {
6
+ super(message);
7
+ this.code = code;
8
+ this.status = status;
9
+ }
10
+ }
1
11
  export function assistantContractError(contract) {
2
12
  return contract.version !== 1 || !Array.isArray(contract.capabilities)
3
13
  ? "This assistant does not support the required assistant interface version 1." : null;
@@ -56,7 +66,7 @@ export class AssistantClient {
56
66
  continue;
57
67
  const body = await response.json().catch(() => null);
58
68
  if (!response.ok)
59
- throw new Error(body?.message || `Assistant request failed (${response.status}).`);
69
+ throw new AssistantError(body?.code ?? "assistant_failed", body?.message || `Assistant request failed (${response.status}).`, response.status);
60
70
  return body;
61
71
  }
62
72
  throw new Error("Assistant authorization expired.");
@@ -0,0 +1,9 @@
1
+ import type { ButtonHTMLAttributes, CSSProperties, ReactNode } from "react";
2
+ /** Shared SDK chrome for sign-in and renewal, independent of the app's CSS framework. */
3
+ export declare function AuthNotice({ children }: {
4
+ children: ReactNode;
5
+ }): import("react").JSX.Element;
6
+ export declare function AuthNoticeButton({ secondary, disabled, ...props }: ButtonHTMLAttributes<HTMLButtonElement> & {
7
+ secondary?: boolean;
8
+ }): import("react").JSX.Element;
9
+ export declare const authNoticeActionStyle: CSSProperties;
@@ -0,0 +1,48 @@
1
+ "use client";
2
+ import { jsx as _jsx } from "react/jsx-runtime";
3
+ /** Shared SDK chrome for sign-in and renewal, independent of the app's CSS framework. */
4
+ export function AuthNotice({ children }) {
5
+ return _jsx("div", { "data-hosty-activity-control": true, role: "status", style: barStyle, children: children });
6
+ }
7
+ export function AuthNoticeButton({ secondary = false, disabled, ...props }) {
8
+ return _jsx("button", { ...props, type: "button", disabled: disabled, style: {
9
+ ...authNoticeActionStyle,
10
+ ...(secondary ? { background: "transparent", color: "#422006", boxShadow: "inset 0 0 0 1px #a16207" } : {}),
11
+ ...(disabled ? { opacity: 0.65, cursor: "wait" } : {}),
12
+ } });
13
+ }
14
+ const barStyle = {
15
+ position: "fixed",
16
+ insetInline: 0,
17
+ bottom: 0,
18
+ zIndex: 2147483647,
19
+ display: "flex",
20
+ flexWrap: "wrap",
21
+ alignItems: "center",
22
+ justifyContent: "center",
23
+ gap: "12px",
24
+ padding: "12px 16px",
25
+ margin: 0,
26
+ border: 0,
27
+ borderTop: "1px solid #d97706",
28
+ boxSizing: "border-box",
29
+ background: "#fef3c7",
30
+ color: "#422006",
31
+ font: "500 14px/1.4 system-ui, sans-serif",
32
+ textAlign: "center",
33
+ boxShadow: "0 -2px 8px rgba(66,32,6,0.12)",
34
+ };
35
+ export const authNoticeActionStyle = {
36
+ display: "inline-block",
37
+ padding: "6px 14px",
38
+ margin: 0,
39
+ borderRadius: "8px",
40
+ background: "#422006",
41
+ color: "#fffbeb",
42
+ border: "none",
43
+ cursor: "pointer",
44
+ font: "650 14px/1.4 system-ui, sans-serif",
45
+ textDecoration: "none",
46
+ textTransform: "none",
47
+ letterSpacing: "normal",
48
+ };
@@ -0,0 +1,31 @@
1
+ export declare const APP_SESSION_ENDED = "hosty:app-session-ended";
2
+ export declare const APP_GRANT_STORAGE_KEY = "hosty.auth.app-grant";
3
+ /** Restore before the first identity probe; standalone documents use their first-party cookie. */
4
+ export declare function restoreAppGrant(): boolean;
5
+ export declare function rememberAppGrant(token: string): void;
6
+ export declare function forgetAppGrant(): void;
7
+ /** Snapshot the grant generation so older probes cannot invalidate a renewed identity. */
8
+ export declare function appGrantRevision(): number;
9
+ /** Activity expiry keeps identity; only explicit identity rejection discards the credential. */
10
+ export declare function forgetRejectedAppGrant(code: unknown, expectedRevision?: number): boolean;
11
+ export declare function appSessionActive(): void;
12
+ /** Use for app-local API calls, including streams. Redirects cannot carry the credential away. */
13
+ export declare function appFetch(input: string | URL, init?: RequestInit, recover?: boolean): Promise<Response>;
14
+ /** Must be called directly from a user gesture. The popup belongs to this app frame, not Shell. */
15
+ export declare function openAppSignIn(openUrl: string, signal?: AbortSignal): Promise<string>;
16
+ export declare const APP_ACTIVITY_RENEWED = "hosty:app-activity-renewed";
17
+ export type AppActivityConfig = {
18
+ openUrl: string;
19
+ activeUntil?: string | null;
20
+ activityRequired?: boolean;
21
+ exchangeCode: (code: string) => Promise<{
22
+ accessToken?: string;
23
+ activeUntil?: string | null;
24
+ }>;
25
+ };
26
+ export declare function configureAppActivity(config: AppActivityConfig): () => void;
27
+ export declare function updateAppActivity(activeUntil?: string | null, activityRequired?: boolean): void;
28
+ export declare function cancelActivityRenewal(): void;
29
+ /** Call only in response to a user gesture. The original page is never navigated or reloaded. */
30
+ export declare function renewAppActivity(): Promise<void>;
31
+ export declare function appActivityNeedsRenewal(now?: number): boolean;
@@ -0,0 +1,217 @@
1
+ /** App-only credentials. Embedded documents keep them for this tab on the app's own origin. */
2
+ let grant = null;
3
+ let grantRevision = 0;
4
+ let recoveryPending = false;
5
+ export const APP_SESSION_ENDED = "hosty:app-session-ended";
6
+ export const APP_GRANT_STORAGE_KEY = "hosty.auth.app-grant";
7
+ function isEmbedded() {
8
+ try {
9
+ return window.self !== window.top;
10
+ }
11
+ catch {
12
+ return true;
13
+ }
14
+ }
15
+ /** Restore before the first identity probe; standalone documents use their first-party cookie. */
16
+ export function restoreAppGrant() {
17
+ if (typeof window === "undefined")
18
+ return false;
19
+ if (grant?.origin === window.location.origin)
20
+ return true;
21
+ if (!isEmbedded())
22
+ return false;
23
+ try {
24
+ const token = window.sessionStorage.getItem(APP_GRANT_STORAGE_KEY);
25
+ if (token) {
26
+ grant = { token, origin: window.location.origin };
27
+ grantRevision++;
28
+ }
29
+ }
30
+ catch {
31
+ // Blocked storage leaves the in-memory transport available.
32
+ }
33
+ return grant?.origin === window.location.origin;
34
+ }
35
+ export function rememberAppGrant(token) {
36
+ grant = { token, origin: window.location.origin };
37
+ grantRevision++;
38
+ recoveryPending = false;
39
+ if (isEmbedded()) {
40
+ try {
41
+ window.sessionStorage.setItem(APP_GRANT_STORAGE_KEY, token);
42
+ }
43
+ catch { /* In-memory fallback. */ }
44
+ }
45
+ }
46
+ export function forgetAppGrant() {
47
+ if (grant)
48
+ grantRevision++;
49
+ grant = null;
50
+ recoveryPending = false;
51
+ if (typeof window !== "undefined") {
52
+ try {
53
+ window.sessionStorage.removeItem(APP_GRANT_STORAGE_KEY);
54
+ }
55
+ catch { /* In-memory fallback. */ }
56
+ }
57
+ }
58
+ /** Snapshot the grant generation so older probes cannot invalidate a renewed identity. */
59
+ export function appGrantRevision() { return grantRevision; }
60
+ /** Activity expiry keeps identity; only explicit identity rejection discards the credential. */
61
+ export function forgetRejectedAppGrant(code, expectedRevision = grantRevision) {
62
+ if (expectedRevision !== grantRevision)
63
+ return false;
64
+ if (typeof code !== "string" || !["token_invalid", "token_revoked", "token_expired", "token_app_mismatch"].includes(code))
65
+ return false;
66
+ forgetAppGrant();
67
+ return true;
68
+ }
69
+ export function appSessionActive() { recoveryPending = false; }
70
+ /** Use for app-local API calls, including streams. Redirects cannot carry the credential away. */
71
+ export async function appFetch(input, init = {}, recover = true) {
72
+ if (typeof window === "undefined")
73
+ return fetch(input, init);
74
+ const url = new URL(input, window.location.href);
75
+ if (url.origin !== window.location.origin || url.username || url.password)
76
+ throw new Error("App API requests must stay on this app's origin.");
77
+ const current = grant?.origin === url.origin ? grant : null;
78
+ const headers = new Headers(init.headers);
79
+ if (current)
80
+ headers.set("authorization", `Bearer ${current.token}`);
81
+ const response = await fetch(input, { ...init, headers, credentials: "same-origin", redirect: "error" });
82
+ if ((response.status === 401 || response.status === 403) && grant === current && !init.signal?.aborted) {
83
+ const revision = grantRevision;
84
+ const body = await response.clone().json().catch(() => null);
85
+ if (grant !== current || grantRevision !== revision || init.signal?.aborted)
86
+ return response;
87
+ // Identity probes disable recovery, but a rejected grant must still be forgotten. Activity
88
+ // expiry is different: the identity remains valid and the popup renews the same session.
89
+ const rejected = forgetRejectedAppGrant(body?.code);
90
+ if (response.status !== 401)
91
+ return response;
92
+ if (!rejected && recover && body?.code !== "reauth_required" && current)
93
+ forgetAppGrant();
94
+ if (!recover)
95
+ return response;
96
+ if (activityConfig) {
97
+ const renewed = waitForActivity(init.signal);
98
+ window.dispatchEvent(new Event(APP_SESSION_ENDED));
99
+ // A response may arrive while the originating click still has browser activation.
100
+ // Otherwise the inline button owns the next attempt; background work never opens a popup.
101
+ if (navigator.userActivation?.isActive)
102
+ void renewAppActivity().catch(() => undefined);
103
+ if (await renewed)
104
+ return appFetch(input, init, false);
105
+ }
106
+ else if (!recoveryPending) {
107
+ recoveryPending = true;
108
+ window.dispatchEvent(new Event(APP_SESSION_ENDED));
109
+ }
110
+ }
111
+ return response;
112
+ }
113
+ /** Must be called directly from a user gesture. The popup belongs to this app frame, not Shell. */
114
+ export function openAppSignIn(openUrl, signal) {
115
+ const url = new URL(openUrl);
116
+ if (!["http:", "https:"].includes(url.protocol) || url.username || url.password)
117
+ return Promise.reject(new Error("Hosty sign-in URL is invalid."));
118
+ const state = Array.from(crypto.getRandomValues(new Uint8Array(32)), b => b.toString(16).padStart(2, "0")).join("");
119
+ url.searchParams.set("responseMode", "web_message");
120
+ url.searchParams.set("state", state);
121
+ return new Promise((resolve, reject) => {
122
+ let popup = null;
123
+ let settled = false;
124
+ const finish = (code, error) => {
125
+ if (settled)
126
+ return;
127
+ settled = true;
128
+ window.removeEventListener("message", receive);
129
+ signal?.removeEventListener("abort", abort);
130
+ window.clearTimeout(timer);
131
+ clearInterval(closedCheck);
132
+ popup?.close();
133
+ if (code)
134
+ resolve(code);
135
+ else
136
+ reject(new Error(error ?? "Sign-in was cancelled."));
137
+ };
138
+ const receive = (event) => {
139
+ if (!popup || event.source !== popup || event.origin !== url.origin)
140
+ return;
141
+ const data = event.data;
142
+ if (data?.type !== "hosty:app-auth-code" || data.state !== state ||
143
+ typeof data.code !== "string" || !data.code || data.code.length > 4096)
144
+ return;
145
+ finish(data.code);
146
+ };
147
+ const abort = () => finish();
148
+ const timer = window.setTimeout(() => finish(undefined, "Sign-in timed out. Please try again."), 180_000);
149
+ const closedCheck = setInterval(() => { if (popup?.closed)
150
+ finish(); }, 500);
151
+ window.addEventListener("message", receive);
152
+ signal?.addEventListener("abort", abort, { once: true });
153
+ if (signal?.aborted) {
154
+ finish();
155
+ return;
156
+ }
157
+ popup = window.open(url.href, "_blank", "popup,width=520,height=700");
158
+ if (!popup)
159
+ finish(undefined, "Allow the sign-in popup and try again.");
160
+ });
161
+ }
162
+ export const APP_ACTIVITY_RENEWED = "hosty:app-activity-renewed";
163
+ let activityConfig = null;
164
+ let renewal = null;
165
+ const waiting = new Set();
166
+ export function configureAppActivity(config) {
167
+ activityConfig = config;
168
+ return () => { if (activityConfig === config) {
169
+ activityConfig = null;
170
+ cancelActivityRenewal();
171
+ } };
172
+ }
173
+ export function updateAppActivity(activeUntil, activityRequired) {
174
+ if (activityConfig) {
175
+ activityConfig.activeUntil = activeUntil;
176
+ activityConfig.activityRequired = activityRequired;
177
+ }
178
+ }
179
+ export function cancelActivityRenewal() { for (const done of [...waiting])
180
+ done(false); }
181
+ function waitForActivity(signal) {
182
+ return new Promise(resolve => {
183
+ const done = (ok) => { waiting.delete(done); signal?.removeEventListener("abort", abort); resolve(ok); };
184
+ const abort = () => done(false);
185
+ waiting.add(done);
186
+ if (signal?.aborted)
187
+ done(false);
188
+ else
189
+ signal?.addEventListener("abort", abort, { once: true });
190
+ });
191
+ }
192
+ /** Call only in response to a user gesture. The original page is never navigated or reloaded. */
193
+ export function renewAppActivity() {
194
+ if (renewal)
195
+ return renewal;
196
+ const config = activityConfig;
197
+ if (!config)
198
+ return Promise.reject(new Error("App recovery is not configured."));
199
+ const popup = openAppSignIn(config.openUrl);
200
+ renewal = popup.then(async (code) => {
201
+ const result = await config.exchangeCode(code);
202
+ if (result.accessToken)
203
+ rememberAppGrant(result.accessToken);
204
+ config.activeUntil = result.activeUntil;
205
+ recoveryPending = false;
206
+ for (const done of [...waiting])
207
+ done(true);
208
+ window.dispatchEvent(new Event(APP_ACTIVITY_RENEWED));
209
+ }).catch(error => { cancelActivityRenewal(); throw error; }).finally(() => { renewal = null; });
210
+ return renewal;
211
+ }
212
+ export function appActivityNeedsRenewal(now = Date.now()) {
213
+ if (!activityConfig?.activityRequired)
214
+ return false;
215
+ const until = Date.parse(activityConfig.activeUntil ?? "");
216
+ return !Number.isFinite(until) || until - now < 10 * 60_000;
217
+ }
@@ -13,7 +13,8 @@ export type AuthRequiredMessage = EmbedderMessage;
13
13
  * - `event.origin` must match the frame URL's origin (the app itself, not an inner frame);
14
14
  * - the payload's `appId` must match the app the embedder actually mounted there.
15
15
  * No credential crosses the boundary in either direction: the payload is only the app id,
16
- * and the embedder answers by reissuing a code through its own authenticated Core call.
16
+ * and the app owns its direct sign-in with Core. This parser gives the embedder no authority
17
+ * to issue or redeem credentials for the app.
17
18
  */
18
19
  export declare function parseActiveFrameAuthRequired(event: AuthRequiredMessage, activeFrameWindow: unknown, activeFrameUrl: string, expectedAppId: string): boolean;
19
20
  /** A verified request, and the one thing its payload carries. */
@@ -82,3 +83,10 @@ export declare function createReissueRateLimiter(minIntervalMs: number, now?: ()
82
83
  * a listener. Re-derived on every launch and every page switch, so it is never stale.
83
84
  */
84
85
  export declare function appendThemeLaunchParams(redirectUri: string, theme: HostyResolvedTheme, preference: HostyThemePreference): string;
86
+ /** Return the trusted mounted app id, ignoring any id or URL claimed by the payload. */
87
+ export declare function parseActiveFramePermissionReview(event: EmbedderMessage, frame: unknown, url: string, appId: string): string | null;
88
+ /** An assistant frame may request its own session review, never another app's. */
89
+ export declare function parseActiveFrameAssistantReview(event: EmbedderMessage, frame: unknown, url: string, appId: string): {
90
+ appId: string;
91
+ sessionId: string;
92
+ } | null;
package/dist/embedder.js CHANGED
@@ -3,10 +3,10 @@
3
3
  // functions plus a small rate limiter — the embedder wires them to its own DOM, its own "open
4
4
  // this app" flow, and its own Core session.
5
5
  //
6
- // Recovery, in one sentence: on a VERIFIED `hosty:auth-required` from an app you embed,
7
- // re-run your normal open flow for that app (which mints a fresh launch code), rate-limited.
8
- // The re-open must take the full launch-code path — an "already open → reuse the URL
9
- // without a code" optimization must not short-circuit recovery.
6
+ // Authentication belongs to the app frame: it restores its own per-tab grant, tries a silent
7
+ // Core navigation on first load, and opens its own Core popup when interaction is required.
8
+ // An embedder may observe a verified `hosty:auth-required` intent, but never carries or
9
+ // redeems another app's code or grant.
10
10
  //
11
11
  // Delegated tokens, in one sentence: on a VERIFIED `hosty:request-delegated-token` from an app
12
12
  // you have decided to grant one, mint a token from Core with your own session and post it back
@@ -21,7 +21,8 @@ import { THEME_PARAM, THEME_PREFERENCE_PARAM } from "./theme.js";
21
21
  * - `event.origin` must match the frame URL's origin (the app itself, not an inner frame);
22
22
  * - the payload's `appId` must match the app the embedder actually mounted there.
23
23
  * No credential crosses the boundary in either direction: the payload is only the app id,
24
- * and the embedder answers by reissuing a code through its own authenticated Core call.
24
+ * and the app owns its direct sign-in with Core. This parser gives the embedder no authority
25
+ * to issue or redeem credentials for the app.
25
26
  */
26
27
  export function parseActiveFrameAuthRequired(event, activeFrameWindow, activeFrameUrl, expectedAppId) {
27
28
  if (!isActiveFrameMessage(event, activeFrameWindow, activeFrameUrl)) {
@@ -151,3 +152,17 @@ export function appendThemeLaunchParams(redirectUri, theme, preference) {
151
152
  url.searchParams.set(THEME_PREFERENCE_PARAM, preference);
152
153
  return url.toString();
153
154
  }
155
+ /** Return the trusted mounted app id, ignoring any id or URL claimed by the payload. */
156
+ export function parseActiveFramePermissionReview(event, frame, url, appId) {
157
+ if (!isActiveFrameMessage(event, frame, url))
158
+ return null;
159
+ return event.data.type === "hosty:request-permission-review" ? appId : null;
160
+ }
161
+ /** An assistant frame may request its own session review, never another app's. */
162
+ export function parseActiveFrameAssistantReview(event, frame, url, appId) {
163
+ if (!isActiveFrameMessage(event, frame, url))
164
+ return null;
165
+ const data = event.data;
166
+ return data.type === "hosty:request-assistant-authority" && typeof data.sessionId === "string" && /^[a-zA-Z0-9_-]{1,128}$/.test(data.sessionId)
167
+ ? { appId, sessionId: data.sessionId } : null;
168
+ }