@lobu/runtime-device 24.1.0 → 24.2.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/dist/component.json +1 -1
- package/dist/dependencies.bun.lock +26 -28
- package/npm-shrinkwrap.json +155 -172
- package/package.json +1 -1
- package/vendor/cli/dist/bundled-skills/lobu/SKILL.md +14 -5
- package/vendor/cli/dist/chrome-extension/accessibility-tree.js +834 -0
- package/vendor/cli/dist/chrome-extension/ambient-context.js +53 -0
- package/vendor/cli/dist/chrome-extension/auth-refresh.js +167 -0
- package/vendor/cli/dist/chrome-extension/automation-run.js +13 -0
- package/vendor/cli/dist/chrome-extension/background.js +1155 -0
- package/vendor/cli/dist/chrome-extension/bridge.js +140 -0
- package/vendor/cli/dist/chrome-extension/browser-origin-policy.js +62 -0
- package/vendor/cli/dist/chrome-extension/browser-recovery.js +260 -0
- package/vendor/cli/dist/chrome-extension/browser-url-sanitizer.js +284 -0
- package/vendor/cli/dist/chrome-extension/completion-response.js +12 -0
- package/vendor/cli/dist/chrome-extension/config.js +144 -0
- package/vendor/cli/dist/chrome-extension/connector-manifests/chrome.json +1516 -0
- package/vendor/cli/dist/chrome-extension/connector-manifests/chrome_bookmarks.json +84 -0
- package/vendor/cli/dist/chrome-extension/connector-manifests/chrome_downloads.json +86 -0
- package/vendor/cli/dist/chrome-extension/connector-manifests/chrome_history.json +78 -0
- package/vendor/cli/dist/chrome-extension/connector-manifests.js +1767 -0
- package/vendor/cli/dist/chrome-extension/console-capture.js +627 -0
- package/vendor/cli/dist/chrome-extension/control-activity.js +70 -0
- package/vendor/cli/dist/chrome-extension/debugger-lease.js +439 -0
- package/vendor/cli/dist/chrome-extension/feed-listener.js +488 -0
- package/vendor/cli/dist/chrome-extension/feed-transaction.js +48 -0
- package/vendor/cli/dist/chrome-extension/feeds.js +632 -0
- package/vendor/cli/dist/chrome-extension/focus-tab.js +25 -0
- package/vendor/cli/dist/chrome-extension/fonts/dm-mono-latin-500-normal.woff2 +0 -0
- package/vendor/cli/dist/chrome-extension/fonts/dm-sans-latin-400-normal.woff2 +0 -0
- package/vendor/cli/dist/chrome-extension/fonts/dm-sans-latin-600-normal.woff2 +0 -0
- package/vendor/cli/dist/chrome-extension/heartbeat.js +140 -0
- package/vendor/cli/dist/chrome-extension/icons/icon-128-rec.png +0 -0
- package/vendor/cli/dist/chrome-extension/icons/icon-128.png +0 -0
- package/vendor/cli/dist/chrome-extension/icons/icon-16-rec.png +0 -0
- package/vendor/cli/dist/chrome-extension/icons/icon-16.png +0 -0
- package/vendor/cli/dist/chrome-extension/icons/icon-32-rec.png +0 -0
- package/vendor/cli/dist/chrome-extension/icons/icon-32.png +0 -0
- package/vendor/cli/dist/chrome-extension/icons/icon-48-rec.png +0 -0
- package/vendor/cli/dist/chrome-extension/icons/icon-48.png +0 -0
- package/vendor/cli/dist/chrome-extension/lens-page.js +135 -0
- package/vendor/cli/dist/chrome-extension/lens-target.js +20 -0
- package/vendor/cli/dist/chrome-extension/manifest.json +76 -0
- package/vendor/cli/dist/chrome-extension/network-intercept.js +657 -0
- package/vendor/cli/dist/chrome-extension/page-activation.js +120 -0
- package/vendor/cli/dist/chrome-extension/page-dialogs.js +125 -0
- package/vendor/cli/dist/chrome-extension/page-url.js +11 -0
- package/vendor/cli/dist/chrome-extension/panel-session.js +184 -0
- package/vendor/cli/dist/chrome-extension/poll-auth.js +85 -0
- package/vendor/cli/dist/chrome-extension/poll-backoff.js +22 -0
- package/vendor/cli/dist/chrome-extension/run-fence.js +117 -0
- package/vendor/cli/dist/chrome-extension/setup-status.js +71 -0
- package/vendor/cli/dist/chrome-extension/side-panel-action-click.js +65 -0
- package/vendor/cli/dist/chrome-extension/sidepanel-context.js +50 -0
- package/vendor/cli/dist/chrome-extension/sidepanel.html +680 -0
- package/vendor/cli/dist/chrome-extension/sidepanel.js +1643 -0
- package/vendor/cli/dist/chrome-extension/tab-labels.js +233 -0
- package/vendor/cli/dist/chrome-extension/tools.js +3354 -0
- package/vendor/cli/dist/chrome-extension/watch-observer.js +354 -0
- package/vendor/cli/dist/chrome-extension/watch-redact.js +96 -0
- package/vendor/cli/dist/chrome-extension/watch.js +348 -0
- package/vendor/cli/dist/commands/_lib/apply/desired-state.d.ts +6 -4
- package/vendor/cli/dist/commands/_lib/apply/desired-state.js +5 -3
- package/vendor/cli/dist/commands/_lib/apply/diff.js +4 -3
- package/vendor/cli/dist/commands/_lib/apply/render.js +4 -14
- package/vendor/cli/dist/commands/_lib/chrome-for-testing.d.ts +13 -0
- package/vendor/cli/dist/commands/_lib/chrome-for-testing.js +226 -0
- package/vendor/cli/dist/commands/_lib/device-credential.d.ts +34 -0
- package/vendor/cli/dist/commands/_lib/device-credential.js +157 -0
- package/vendor/cli/dist/commands/_lib/device-wizard.d.ts +17 -0
- package/vendor/cli/dist/commands/_lib/device-wizard.js +11 -2
- package/vendor/cli/dist/commands/_lib/native-messaging.d.ts +7 -0
- package/vendor/cli/dist/commands/_lib/native-messaging.js +40 -0
- package/vendor/cli/dist/commands/browser.d.ts +23 -0
- package/vendor/cli/dist/commands/browser.js +492 -0
- package/vendor/cli/dist/commands/call.d.ts +12 -0
- package/vendor/cli/dist/commands/call.js +48 -26
- package/vendor/cli/dist/commands/context.d.ts +3 -1
- package/vendor/cli/dist/commands/context.js +13 -2
- package/vendor/cli/dist/commands/daemon.js +2 -152
- package/vendor/cli/dist/commands/memory/_lib/errors.d.ts +4 -1
- package/vendor/cli/dist/commands/memory/_lib/errors.js +9 -1
- package/vendor/cli/dist/commands/memory/_lib/mcp.d.ts +0 -9
- package/vendor/cli/dist/commands/memory/_lib/mcp.js +1 -23
- package/vendor/cli/dist/commands/memory/_lib/memory-auth.d.ts +20 -4
- package/vendor/cli/dist/commands/memory/_lib/memory-auth.js +21 -17
- package/vendor/cli/dist/commands/memory/_lib/seed-cmd.js +6 -17
- package/vendor/cli/dist/commands/memory/run.js +4 -25
- package/vendor/cli/dist/connectors/google_gmail.ts +70 -41
- package/vendor/cli/dist/connectors/google_gmail_references.ts +406 -0
- package/vendor/cli/dist/connectors/linkedin-inbox-adapter.js +107 -36
- package/vendor/cli/dist/connectors/linkedin-inbox.ts +13 -0
- package/vendor/cli/dist/connectors/linkedin.ts +1 -1
- package/vendor/cli/dist/connectors/postgres.ts +5 -3
- package/vendor/cli/dist/connectors/reddit.ts +171 -5
- package/vendor/cli/dist/connectors/whatsapp-web-adapter.js +147 -61
- package/vendor/cli/dist/connectors/whatsapp-web-helpers.ts +6 -2
- package/vendor/cli/dist/connectors/whatsapp_web.ts +48 -17
- package/vendor/cli/dist/connectors/x-dm-adapter.js +252 -35
- package/vendor/cli/dist/connectors/x.ts +189 -13
- package/vendor/cli/dist/index.js +46 -6
- package/vendor/cli/dist/internal/device-state.d.ts +2 -0
- package/vendor/cli/dist/internal/device-state.js +4 -0
- package/vendor/cli/dist/runtime-components.json +4 -4
- package/vendor/cli/dist/templates/AGENTS.md.tmpl +3 -1
- package/vendor/cli/dist/templates/TESTING.md.tmpl +8 -8
- package/vendor/cli/package.json +1 -1
- package/vendor/connector-sdk/dist/browser-requirement.js +1 -1
- package/vendor/connector-sdk/dist/connector-types.d.ts +5 -1
- package/vendor/connector-sdk/package.json +1 -1
- package/vendor/connector-worker/dist/agent-turn/gateway-tools.d.ts +9 -0
- package/vendor/connector-worker/dist/agent-turn/gateway-tools.js +23 -2
- package/vendor/connector-worker/dist/agent-turn/guest-entry.js +14 -6
- package/vendor/connector-worker/dist/agent-turn/guest.bundle.js +62 -25
- package/vendor/connector-worker/dist/agent-turn/media-tools.d.ts +1 -0
- package/vendor/connector-worker/dist/agent-turn/media-tools.js +5 -2
- package/vendor/connector-worker/dist/bin.js +2 -0
- package/vendor/connector-worker/dist/daemon/agent-turn.js +52 -17
- package/vendor/connector-worker/dist/daemon/automation.js +2 -12
- package/vendor/connector-worker/dist/daemon/client.d.ts +8 -2
- package/vendor/connector-worker/dist/daemon/client.js +8 -1
- package/vendor/connector-worker/dist/daemon/interactive-session.js +29 -6
- package/vendor/connector-worker/dist/daemon/poll-loop.js +23 -1
- package/vendor/connector-worker/dist/daemon/terminal-delivery.d.ts +5 -10
- package/vendor/connector-worker/dist/daemon/terminal-delivery.js +55 -23
- package/vendor/connector-worker/dist/daemon/terminal-failure.js +2 -2
- package/vendor/connector-worker/dist/executor/isolate.js +3 -0
- package/vendor/connector-worker/package.json +1 -1
- package/vendor/core/dist/agent-tooling.d.ts +8 -0
- package/vendor/core/dist/agent-tooling.js +9 -1
- package/vendor/core/dist/capabilities.d.ts +1 -1
- package/vendor/core/dist/capabilities.js +5 -0
- package/vendor/core/dist/contracts/entity-reference.d.ts +3 -0
- package/vendor/core/dist/contracts/entity-reference.js +31 -0
- package/vendor/core/dist/contracts/tools/manage-automations.d.ts +3 -0
- package/vendor/core/dist/contracts/tools/manage-automations.js +3 -0
- package/vendor/core/dist/contracts/tools/manage-connections.js +1 -1
- package/vendor/core/dist/contracts/tools/manage-entity-schema.js +1 -1
- package/vendor/core/dist/contracts/tools/manage-entity.d.ts +113 -34
- package/vendor/core/dist/contracts/tools/manage-entity.js +41 -14
- package/vendor/core/dist/contracts/tools/manage-operations.d.ts +13 -4
- package/vendor/core/dist/contracts/tools/manage-operations.js +19 -7
- package/vendor/core/dist/contracts/tools/read-knowledge.d.ts +6 -1
- package/vendor/core/dist/contracts/tools/read-knowledge.js +20 -1
- package/vendor/core/dist/contracts/tools/view-attach.d.ts +1 -1
- package/vendor/core/dist/contracts/tools/view-runtime.d.ts +2 -0
- package/vendor/core/dist/contracts/tools/view-runtime.js +3 -1
- package/vendor/core/dist/contracts/worker/device-automation.d.ts +4 -9
- package/vendor/core/dist/contracts/worker/device-automation.js +10 -15
- package/vendor/core/dist/contracts/worker/protocol.d.ts +20 -0
- package/vendor/core/dist/contracts/worker/protocol.js +20 -0
- package/vendor/core/dist/reserved.d.ts +6 -3
- package/vendor/core/dist/reserved.js +6 -3
- package/vendor/core/dist/worker/auth.d.ts +3 -2
- package/vendor/core/package.json +6 -1
- package/vendor/postgres/cf/src/query.js +3 -1
- package/vendor/postgres/cjs/src/query.js +3 -1
- package/vendor/postgres/src/query.js +3 -1
- /package/vendor/postgres/{.bun-tag-2f292c6554a8475e → .bun-tag-22d644c2873790db} +0 -0
|
@@ -0,0 +1,1643 @@
|
|
|
1
|
+
import {
|
|
2
|
+
createContextPublisher,
|
|
3
|
+
resolveBridgeReplyTarget,
|
|
4
|
+
} from "./sidepanel-context.js";
|
|
5
|
+
import { CONTROL_ACTIVITY_KEY } from "./control-activity.js";
|
|
6
|
+
import {
|
|
7
|
+
GRANTED_SCOPE_KEY,
|
|
8
|
+
grantedScopeUpdate,
|
|
9
|
+
NATIVE_HANDSHAKE_TIMEOUT_MS,
|
|
10
|
+
NATIVE_HOST,
|
|
11
|
+
nativeBridgeHandshake as nativeBridgeHandshakeWith,
|
|
12
|
+
needsAccessReapproval,
|
|
13
|
+
PANEL_SESSION_KEY,
|
|
14
|
+
panelSignInToken,
|
|
15
|
+
nativePairStorage,
|
|
16
|
+
readNativePairResponse,
|
|
17
|
+
refreshDesktopPanelSession,
|
|
18
|
+
WELCOME_PENDING_KEY,
|
|
19
|
+
} from "./panel-session.js";
|
|
20
|
+
|
|
21
|
+
// Sidepanel shell. Three views in one panel:
|
|
22
|
+
// - app: iframe mounting owletto's root (shown when paired)
|
|
23
|
+
// - pair: URL entry → OAuth device-code / local-init / native auto-pair
|
|
24
|
+
// - permissions: opt-in capability toggles + server change
|
|
25
|
+
//
|
|
26
|
+
// The pairing logic lives here so the user never gets bounced to a full
|
|
27
|
+
// Chrome tab. The OAuth verification_uri *does* open in a tab (the user has
|
|
28
|
+
// to authorize on the server's web page) but everything else stays in the
|
|
29
|
+
// panel. chrome.permissions.request() must be called from extension-context
|
|
30
|
+
// JS — the embedded iframe can't trigger native consent — so we keep it
|
|
31
|
+
// here and only postMessage results to the iframe via the existing bridge.
|
|
32
|
+
|
|
33
|
+
import {
|
|
34
|
+
DEFAULT_GATEWAY_URL,
|
|
35
|
+
getGatewayUrl,
|
|
36
|
+
isActionGrantEnabled,
|
|
37
|
+
normalizeGatewayBase,
|
|
38
|
+
STORAGE_KEY_GATEWAY_URL,
|
|
39
|
+
serverBlocksExtension,
|
|
40
|
+
setActionGrantEnabled,
|
|
41
|
+
TABS_MANAGE_SCOPE,
|
|
42
|
+
} from "./config.js";
|
|
43
|
+
|
|
44
|
+
// Show which extension build is loaded, under the server in Settings. An
|
|
45
|
+
// unpacked extension loaded from a stale worktree (or not reloaded after a fix)
|
|
46
|
+
// is otherwise indistinguishable from current — you only notice via broken
|
|
47
|
+
// automation. The manifest version is always available; an optional generated
|
|
48
|
+
// build-info.json (gitignored locally, stamped into Web Store packages) adds the
|
|
49
|
+
// git SHA/date without forcing a stale generated file into source control.
|
|
50
|
+
{
|
|
51
|
+
const stamp = document.getElementById("build-stamp");
|
|
52
|
+
if (stamp) {
|
|
53
|
+
const version = chrome.runtime.getManifest().version;
|
|
54
|
+
const render = (build) => {
|
|
55
|
+
stamp.textContent = build?.sha
|
|
56
|
+
? `v${version} · ${build.sha}${build.dirty ? "+" : ""}`
|
|
57
|
+
: `v${version}`;
|
|
58
|
+
if (build) {
|
|
59
|
+
stamp.dataset.dirty = String(Boolean(build.dirty));
|
|
60
|
+
stamp.title = `Build ${build.sha ?? "unknown"}${
|
|
61
|
+
build.dirty ? " (uncommitted)" : ""
|
|
62
|
+
} · ${build.date ?? "unknown"}`;
|
|
63
|
+
} else {
|
|
64
|
+
delete stamp.dataset.dirty;
|
|
65
|
+
stamp.removeAttribute("title");
|
|
66
|
+
}
|
|
67
|
+
};
|
|
68
|
+
|
|
69
|
+
render(null);
|
|
70
|
+
fetch(chrome.runtime.getURL("build-info.json"), { cache: "no-store" })
|
|
71
|
+
.then((res) => (res.ok ? res.json() : null))
|
|
72
|
+
.then((build) => {
|
|
73
|
+
if (build && typeof build === "object") render(build);
|
|
74
|
+
})
|
|
75
|
+
.catch(() => {
|
|
76
|
+
// Unstamped unpacked trees simply show the manifest version.
|
|
77
|
+
});
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
const STORAGE_KEYS = {
|
|
82
|
+
workerId: "owletto.workerId",
|
|
83
|
+
accessToken: "owletto.accessToken",
|
|
84
|
+
refreshToken: "owletto.refreshToken",
|
|
85
|
+
clientId: "owletto.clientId",
|
|
86
|
+
clientSecret: "owletto.clientSecret",
|
|
87
|
+
pairedAt: "owletto.pairedAt",
|
|
88
|
+
};
|
|
89
|
+
|
|
90
|
+
// The side panel embeds the signed-in web app, and the gateway only mints a web
|
|
91
|
+
// session from a device-code grant that carries mcp:admin (/api/extension-session).
|
|
92
|
+
const SCOPE = "device_worker:run profile:read mcp:read mcp:admin";
|
|
93
|
+
|
|
94
|
+
// The desktop bridge only exists on macOS, so we only point users at the Mac
|
|
95
|
+
// app download when auto-pair fails on a Mac. Elsewhere the URL-entry fallback
|
|
96
|
+
// stands alone.
|
|
97
|
+
const IS_MAC = /Mac/i.test(
|
|
98
|
+
navigator.userAgentData?.platform || navigator.platform || "",
|
|
99
|
+
);
|
|
100
|
+
// Set true once the native host sends any frame back — distinguishes "Owletto
|
|
101
|
+
// Mac app not running/installed" (no frame) from "running but not signed in".
|
|
102
|
+
let macBridgeReachable = false;
|
|
103
|
+
|
|
104
|
+
// ── DOM ─────────────────────────────────────────────────────────────────
|
|
105
|
+
const frame = document.getElementById("app");
|
|
106
|
+
const statusLabel = document.getElementById("status-label");
|
|
107
|
+
const topbarAction = document.getElementById("topbar-action");
|
|
108
|
+
const reloadAppBtn = document.getElementById("reload-app");
|
|
109
|
+
|
|
110
|
+
const pairView = document.getElementById("pair-view");
|
|
111
|
+
const pairSetup = document.getElementById("pair-setup");
|
|
112
|
+
const macAppHint = document.getElementById("mac-app-hint");
|
|
113
|
+
const allowServerBtn = document.getElementById("allow-server");
|
|
114
|
+
const pairCode = document.getElementById("pair-code");
|
|
115
|
+
const gatewayUrlInput = document.getElementById("gateway-url");
|
|
116
|
+
const selfHostedFields = document.getElementById("self-hosted-fields");
|
|
117
|
+
const serverKindInputs = document.querySelectorAll('input[name="server-kind"]');
|
|
118
|
+
const verifyUrlBtn = document.getElementById("verify-url");
|
|
119
|
+
const setupStatus = document.getElementById("setup-status");
|
|
120
|
+
const codeEl = document.getElementById("user-code");
|
|
121
|
+
const pollStatus = document.getElementById("poll-status");
|
|
122
|
+
const cancelPairBtn = document.getElementById("cancel-pair");
|
|
123
|
+
const pairCodeTitle = document.getElementById("pair-code-title");
|
|
124
|
+
const pairCodeDetail = document.getElementById("pair-code-detail");
|
|
125
|
+
const pairCodeActions = document.getElementById("pair-code-actions");
|
|
126
|
+
const reopenApprovalBtn = document.getElementById("reopen-approval");
|
|
127
|
+
|
|
128
|
+
const permsView = document.getElementById("permissions-view");
|
|
129
|
+
const permsTitle = document.getElementById("perms-title");
|
|
130
|
+
const permsLede = document.getElementById("perms-lede");
|
|
131
|
+
const permContinueRow = document.getElementById("perm-continue-row");
|
|
132
|
+
document
|
|
133
|
+
.getElementById("perm-continue")
|
|
134
|
+
.addEventListener("click", () => void exitPermissions());
|
|
135
|
+
const serverUrlDisplay = document.getElementById("server-url-display");
|
|
136
|
+
const changeServerPermBtn = document.getElementById("change-server-perm");
|
|
137
|
+
const permStatus = document.getElementById("perm-status");
|
|
138
|
+
const toggleAllsitesBtn = document.getElementById("toggle-allsites");
|
|
139
|
+
const siteUrlInput = document.getElementById("site-url");
|
|
140
|
+
const addSiteBtn = document.getElementById("add-site");
|
|
141
|
+
const siteList = document.getElementById("site-list");
|
|
142
|
+
const siteMode = document.getElementById("site-mode");
|
|
143
|
+
const siteSpecific = document.getElementById("site-specific");
|
|
144
|
+
|
|
145
|
+
const healthBanner = document.getElementById("health-banner");
|
|
146
|
+
const healthMessage = document.getElementById("health-message");
|
|
147
|
+
const healthAction = document.getElementById("health-action");
|
|
148
|
+
|
|
149
|
+
// Show stale run failures only while fresh — an error from an hour ago that's
|
|
150
|
+
// since recovered shouldn't linger in the banner.
|
|
151
|
+
const RUN_ERROR_TTL_MS = 10 * 60 * 1000;
|
|
152
|
+
const HEALTH_KEY = "owletto.health";
|
|
153
|
+
|
|
154
|
+
// ── State ───────────────────────────────────────────────────────────────
|
|
155
|
+
let embeddedOrigin = null;
|
|
156
|
+
let gatewayUrl = null;
|
|
157
|
+
// In-flight OAuth device flows (see waitForDeviceTokens): the pair view's,
|
|
158
|
+
// and the banner's re-approval, which runs while the app stays mounted.
|
|
159
|
+
let pairFlow = null;
|
|
160
|
+
let reapproveFlow = null;
|
|
161
|
+
// Session key (gateway|worker|pairedAt) of the iframe currently mounted, or
|
|
162
|
+
// null when not mounted. Keyed on the PAIRING, never the access token: the
|
|
163
|
+
// topbar "Done" back action and a background access-token refresh must both
|
|
164
|
+
// leave the mounted iframe untouched (a remount tears down its session and, on
|
|
165
|
+
// a refresh loop, never finishes loading). See mountEmbeddedApp.
|
|
166
|
+
let mountedEmbeddedKey = null;
|
|
167
|
+
// Cached result of tryNativeAutoPair() for this browser session. The handshake
|
|
168
|
+
// takes up to NATIVE_HANDSHAKE_TIMEOUT_MS when the host manifest is missing
|
|
169
|
+
// on some platforms; cache the negative so re-entering the pair flow within
|
|
170
|
+
// the same session is instant.
|
|
171
|
+
let nativeAutoPairAttempted = false;
|
|
172
|
+
// The sign-in page URL of the device flow in progress, for "Reopen sign-in tab".
|
|
173
|
+
let pendingApprovalUrl = null;
|
|
174
|
+
let desktopSessionRefreshAttempted = false;
|
|
175
|
+
|
|
176
|
+
// ── View routing ────────────────────────────────────────────────────────
|
|
177
|
+
function show(mode) {
|
|
178
|
+
// mode: "app" | "pair" | "permissions" | "welcome"
|
|
179
|
+
// "welcome" is Settings shown once right after a pairing.
|
|
180
|
+
const settings = mode === "permissions" || mode === "welcome";
|
|
181
|
+
frame.hidden = mode !== "app";
|
|
182
|
+
if (mode === "app") void publishActiveContext();
|
|
183
|
+
pairView.hidden = mode !== "pair";
|
|
184
|
+
permsView.hidden = !settings;
|
|
185
|
+
permsTitle.textContent = mode === "welcome" ? "You're connected" : "Settings";
|
|
186
|
+
permsLede.textContent =
|
|
187
|
+
mode === "welcome"
|
|
188
|
+
? "Review what Lobu can use in this browser. You can change these permissions any time from Settings."
|
|
189
|
+
: "Choose which websites and optional browser features Lobu can use.";
|
|
190
|
+
permContinueRow.hidden = mode !== "welcome";
|
|
191
|
+
// The reload escape hatch only makes sense once the app is mounted.
|
|
192
|
+
if (reloadAppBtn) reloadAppBtn.hidden = mode !== "app";
|
|
193
|
+
|
|
194
|
+
if (mode !== "pair") {
|
|
195
|
+
// Leaving the pair flow mid-OAuth → cancel the token poll so it doesn't
|
|
196
|
+
// keep hitting the token_endpoint in the background.
|
|
197
|
+
cancelDeviceFlow(pairFlow);
|
|
198
|
+
pairFlow = null;
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
if (settings) {
|
|
202
|
+
topbarAction.textContent = "Done";
|
|
203
|
+
topbarAction.dataset.mode = "back";
|
|
204
|
+
void refreshPermissions();
|
|
205
|
+
} else {
|
|
206
|
+
topbarAction.textContent = "Settings";
|
|
207
|
+
topbarAction.dataset.mode = "permissions";
|
|
208
|
+
}
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
topbarAction.addEventListener("click", (ev) => {
|
|
212
|
+
ev.preventDefault();
|
|
213
|
+
if (topbarAction.dataset.mode === "permissions") {
|
|
214
|
+
show("permissions");
|
|
215
|
+
} else {
|
|
216
|
+
void exitPermissions();
|
|
217
|
+
}
|
|
218
|
+
});
|
|
219
|
+
|
|
220
|
+
// Force-reload the embedded app. mountEmbeddedApp() normally NO-OPs when the
|
|
221
|
+
// pairing session is unchanged (so a background token refresh doesn't tear the
|
|
222
|
+
// iframe down). That same guard means a panel stuck on a stale app build never
|
|
223
|
+
// refreshes on its own. This blanks the frame and clears mountedEmbeddedKey so
|
|
224
|
+
// the next mount always re-bootstraps — a genuine cross-document navigation
|
|
225
|
+
// that re-fetches the (no-store) bootstrap + index.html, picking up the current
|
|
226
|
+
// app bundle.
|
|
227
|
+
if (reloadAppBtn) {
|
|
228
|
+
reloadAppBtn.addEventListener("click", async (ev) => {
|
|
229
|
+
ev.preventDefault();
|
|
230
|
+
const workerId = (await chrome.storage.local.get(STORAGE_KEYS.workerId))[
|
|
231
|
+
STORAGE_KEYS.workerId
|
|
232
|
+
];
|
|
233
|
+
if (!workerId) {
|
|
234
|
+
// Not paired — nothing to reload; send them through the pair flow.
|
|
235
|
+
await enterPairFlow();
|
|
236
|
+
return;
|
|
237
|
+
}
|
|
238
|
+
mountedEmbeddedKey = null;
|
|
239
|
+
embeddedOrigin = null;
|
|
240
|
+
frame.src = "about:blank";
|
|
241
|
+
await mountEmbeddedApp(workerId);
|
|
242
|
+
});
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
async function exitPermissions() {
|
|
246
|
+
// If we already have an embedded app mounted, just reveal it — don't
|
|
247
|
+
// reset frame.src or we'll lose iframe state (whatever page/chat the
|
|
248
|
+
// user was on inside owletto).
|
|
249
|
+
if (mountedEmbeddedKey) {
|
|
250
|
+
show("app");
|
|
251
|
+
return;
|
|
252
|
+
}
|
|
253
|
+
await enterPairFlow();
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
// Compact "Ns ago" / "Nm ago" / "Nh ago" for the topbar label + tooltip.
|
|
257
|
+
function relTime(ts) {
|
|
258
|
+
if (typeof ts !== "number") return null;
|
|
259
|
+
const s = Math.max(0, Math.round((Date.now() - ts) / 1000));
|
|
260
|
+
if (s < 60) return `${s}s ago`;
|
|
261
|
+
const m = Math.round(s / 60);
|
|
262
|
+
if (m < 60) return `${m}m ago`;
|
|
263
|
+
const h = Math.round(m / 60);
|
|
264
|
+
if (h < 24) return `${h}h ago`;
|
|
265
|
+
return `${Math.round(h / 24)}d ago`;
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
// Repurpose the topbar "Lobu" label as a live status line: connection state
|
|
269
|
+
// + freshness of the last successful poll. The full detail (server, last sync,
|
|
270
|
+
// last job) rides in the title tooltip so the visible string stays short. The
|
|
271
|
+
// label is clickable when connected — it points the embedded iframe at this
|
|
272
|
+
// browser's device page (see openDeviceView).
|
|
273
|
+
//
|
|
274
|
+
// While an agent drives this browser the same line shows the action instead,
|
|
275
|
+
// so the panel layout never shifts; the requester detail rides in the tooltip
|
|
276
|
+
// and a click opens the run's source in Lobu.
|
|
277
|
+
let lastHealth = {};
|
|
278
|
+
let controlActivities = [];
|
|
279
|
+
|
|
280
|
+
function renderStatusLabel() {
|
|
281
|
+
if (!statusLabel) return;
|
|
282
|
+
const active = controlActivities;
|
|
283
|
+
if (active.length > 0) {
|
|
284
|
+
statusLabel.textContent =
|
|
285
|
+
active.length === 1
|
|
286
|
+
? `Browser in use · ${active[0].operation}`
|
|
287
|
+
: `Browser in use · ${active.length} actions`;
|
|
288
|
+
statusLabel.title = active.map((a) => `${a.detail}\n${a.operation}`).join("\n\n");
|
|
289
|
+
statusLabel.setAttribute("aria-label", statusLabel.title);
|
|
290
|
+
statusLabel.dataset.active = "true";
|
|
291
|
+
const url = active.length === 1 ? active[0].url : null;
|
|
292
|
+
statusLabel.dataset.href = url ?? "";
|
|
293
|
+
statusLabel.dataset.clickable = url ? "true" : "false";
|
|
294
|
+
statusLabel.disabled = !url;
|
|
295
|
+
statusLabel.style.cursor = url ? "pointer" : "default";
|
|
296
|
+
return;
|
|
297
|
+
}
|
|
298
|
+
statusLabel.dataset.active = "false";
|
|
299
|
+
statusLabel.removeAttribute("aria-label");
|
|
300
|
+
statusLabel.dataset.href = "";
|
|
301
|
+
const h = lastHealth;
|
|
302
|
+
const connected = h.connected !== false;
|
|
303
|
+
const synced = relTime(h.lastSyncOkAt);
|
|
304
|
+
if (!connected && h.reason && h.reason !== "ok") {
|
|
305
|
+
statusLabel.textContent =
|
|
306
|
+
h.reason === "auth-lost"
|
|
307
|
+
? "Lobu · disconnected"
|
|
308
|
+
: h.reason === "update-required"
|
|
309
|
+
? "Lobu · update required"
|
|
310
|
+
: h.reason === "reconnecting"
|
|
311
|
+
? "Lobu · reconnecting…"
|
|
312
|
+
: "Lobu · offline";
|
|
313
|
+
} else if (synced) {
|
|
314
|
+
statusLabel.textContent = `Lobu · synced ${synced}`;
|
|
315
|
+
} else {
|
|
316
|
+
statusLabel.textContent = "Lobu";
|
|
317
|
+
}
|
|
318
|
+
|
|
319
|
+
const lines = [];
|
|
320
|
+
if (h.host) lines.push(`Server: ${h.host}`);
|
|
321
|
+
if (synced) lines.push(`Synced: ${synced}`);
|
|
322
|
+
if (h.lastRun) {
|
|
323
|
+
const mark = h.lastRun.status === "success" ? "✓" : "✕";
|
|
324
|
+
lines.push(
|
|
325
|
+
`Last job: ${h.lastRun.label ?? "run"} ${mark} ${relTime(h.lastRun.at) ?? ""}`.trim(),
|
|
326
|
+
);
|
|
327
|
+
}
|
|
328
|
+
statusLabel.title = connected
|
|
329
|
+
? `${lines.join("\n")}\n\nClick to open this browser's device page`
|
|
330
|
+
: lines.join("\n");
|
|
331
|
+
|
|
332
|
+
statusLabel.style.cursor = connected ? "pointer" : "default";
|
|
333
|
+
statusLabel.dataset.clickable = connected ? "true" : "false";
|
|
334
|
+
statusLabel.disabled = !connected;
|
|
335
|
+
}
|
|
336
|
+
|
|
337
|
+
if (statusLabel) {
|
|
338
|
+
statusLabel.addEventListener("click", () => {
|
|
339
|
+
if (statusLabel.dataset.clickable !== "true") return;
|
|
340
|
+
const href = statusLabel.dataset.href;
|
|
341
|
+
if (href) window.open(href, "_blank", "noopener,noreferrer");
|
|
342
|
+
else void openDeviceView();
|
|
343
|
+
});
|
|
344
|
+
}
|
|
345
|
+
|
|
346
|
+
// ── Worker health banner ─────────────────────────────────────────────────
|
|
347
|
+
// The service worker writes its poll/run outcomes to chrome.storage.local
|
|
348
|
+
// (HEALTH_KEY). Mirror them in a banner so failures the SW used to swallow
|
|
349
|
+
// (CORS-blocked polls, lost auth, failed runs) are visible in the panel
|
|
350
|
+
// instead of only in the SW console.
|
|
351
|
+
function renderHealth(health) {
|
|
352
|
+
const h = health ?? {};
|
|
353
|
+
lastHealth = h;
|
|
354
|
+
renderStatusLabel();
|
|
355
|
+
if (!healthBanner) return;
|
|
356
|
+
// "reconnecting" is the worker quietly self-healing through a transient
|
|
357
|
+
// gateway/OAuth blip — it keeps its credentials and retries, so show it as a
|
|
358
|
+
// soft warning with no action rather than a red "disconnected" error. If it
|
|
359
|
+
// can't recover within the budget the SW escalates to "auth-lost", which falls
|
|
360
|
+
// into the error branch below and surfaces the Reconnect CTA.
|
|
361
|
+
if (h.connected === false && h.reason === "reconnecting") {
|
|
362
|
+
healthBanner.dataset.severity = "warn";
|
|
363
|
+
healthMessage.textContent = h.message || "Reconnecting to Lobu…";
|
|
364
|
+
healthAction.hidden = true;
|
|
365
|
+
healthAction.dataset.action = "";
|
|
366
|
+
healthBanner.hidden = false;
|
|
367
|
+
return;
|
|
368
|
+
}
|
|
369
|
+
// Disconnected states take priority — the worker isn't reaching the gateway.
|
|
370
|
+
if (h.connected === false && h.reason && h.reason !== "ok") {
|
|
371
|
+
healthBanner.dataset.severity = "error";
|
|
372
|
+
healthMessage.textContent = h.message || "Lobu isn't connected.";
|
|
373
|
+
if (h.reason === "needs-permission") {
|
|
374
|
+
healthAction.hidden = false;
|
|
375
|
+
healthAction.textContent = "Grant access";
|
|
376
|
+
healthAction.dataset.action = "grant";
|
|
377
|
+
} else if (h.reason === "auth-lost") {
|
|
378
|
+
healthAction.hidden = false;
|
|
379
|
+
healthAction.textContent = "Reconnect";
|
|
380
|
+
healthAction.dataset.action = "reconnect";
|
|
381
|
+
} else if (h.reason === "update-required") {
|
|
382
|
+
healthAction.hidden = false;
|
|
383
|
+
healthAction.textContent = "Update";
|
|
384
|
+
healthAction.dataset.action = "update";
|
|
385
|
+
} else {
|
|
386
|
+
healthAction.hidden = true;
|
|
387
|
+
healthAction.dataset.action = "";
|
|
388
|
+
}
|
|
389
|
+
healthBanner.hidden = false;
|
|
390
|
+
return;
|
|
391
|
+
}
|
|
392
|
+
// Connected through a read-only OAuth grant, which the gateway is phasing
|
|
393
|
+
// out for sign-in. Only a fresh approval upgrades it (refresh never widens a
|
|
394
|
+
// grant), so offer it before the app stops opening.
|
|
395
|
+
if (accessReapprovalNeeded) {
|
|
396
|
+
healthBanner.dataset.severity = "warn";
|
|
397
|
+
healthMessage.textContent =
|
|
398
|
+
reapprovalStatus ??
|
|
399
|
+
"Lobu for Chrome was approved with limited access. Re-approve it with full access to keep opening the app here.";
|
|
400
|
+
healthAction.hidden = reapproveFlow !== null;
|
|
401
|
+
healthAction.textContent = "Re-approve";
|
|
402
|
+
healthAction.dataset.action = "reapprove";
|
|
403
|
+
healthBanner.hidden = false;
|
|
404
|
+
return;
|
|
405
|
+
}
|
|
406
|
+
// A run needed a site this profile hasn't granted. The grant needs a user
|
|
407
|
+
// gesture, so offer it here; the agent was told to retry once it's allowed.
|
|
408
|
+
const site = h.siteAccessNeeded;
|
|
409
|
+
if (site && typeof site.at === "number" && Date.now() - site.at < RUN_ERROR_TTL_MS) {
|
|
410
|
+
healthBanner.dataset.severity = "warn";
|
|
411
|
+
healthMessage.textContent = `${site.requester ?? "An agent"} needs access to ${new URL(site.origin).host}. Allow it, then tell the agent to try again.`;
|
|
412
|
+
healthAction.hidden = false;
|
|
413
|
+
healthAction.textContent = "Allow";
|
|
414
|
+
healthAction.dataset.action = "allow-site";
|
|
415
|
+
healthBanner.hidden = false;
|
|
416
|
+
return;
|
|
417
|
+
}
|
|
418
|
+
// Connected, but a recent run failed — surface it as a softer warning.
|
|
419
|
+
const e = h.lastRunError;
|
|
420
|
+
if (e && typeof e.at === "number" && Date.now() - e.at < RUN_ERROR_TTL_MS) {
|
|
421
|
+
healthBanner.dataset.severity = "warn";
|
|
422
|
+
healthMessage.textContent = `Last task failed${e.label ? ` (${e.label})` : ""}: ${e.message}`;
|
|
423
|
+
healthAction.hidden = true;
|
|
424
|
+
healthAction.dataset.action = "";
|
|
425
|
+
healthBanner.hidden = false;
|
|
426
|
+
return;
|
|
427
|
+
}
|
|
428
|
+
healthBanner.hidden = true;
|
|
429
|
+
}
|
|
430
|
+
|
|
431
|
+
if (healthAction) {
|
|
432
|
+
healthAction.addEventListener("click", () => {
|
|
433
|
+
const action = healthAction.dataset.action;
|
|
434
|
+
if (action === "grant") {
|
|
435
|
+
void grantFromBanner();
|
|
436
|
+
} else if (action === "reconnect") {
|
|
437
|
+
void enterPairFlow();
|
|
438
|
+
} else if (action === "update") {
|
|
439
|
+
void updateExtension();
|
|
440
|
+
} else if (action === "reapprove") {
|
|
441
|
+
void reapproveAccess();
|
|
442
|
+
} else if (action === "allow-site") {
|
|
443
|
+
void allowSiteFromBanner();
|
|
444
|
+
}
|
|
445
|
+
});
|
|
446
|
+
}
|
|
447
|
+
|
|
448
|
+
// permissions.request must be the first await so it keeps the click's gesture.
|
|
449
|
+
async function allowSiteFromBanner() {
|
|
450
|
+
const origin = lastHealth.siteAccessNeeded?.origin;
|
|
451
|
+
if (!origin) return;
|
|
452
|
+
if (await chrome.permissions.request({ origins: [`${origin}/*`] })) {
|
|
453
|
+
await clearSiteAccessNeeded();
|
|
454
|
+
}
|
|
455
|
+
}
|
|
456
|
+
|
|
457
|
+
// The failed run's lastRunError is the same failure, so it goes too.
|
|
458
|
+
async function clearSiteAccessNeeded() {
|
|
459
|
+
const h = (await chrome.storage.local.get(HEALTH_KEY))[HEALTH_KEY] ?? {};
|
|
460
|
+
if (!h.siteAccessNeeded) return;
|
|
461
|
+
const { siteAccessNeeded: _, ...rest } = h;
|
|
462
|
+
await chrome.storage.local.set({
|
|
463
|
+
[HEALTH_KEY]: { ...rest, lastRunError: null, updatedAt: Date.now() },
|
|
464
|
+
});
|
|
465
|
+
}
|
|
466
|
+
|
|
467
|
+
// A grant made from Settings ("Access all sites" or a single site) also
|
|
468
|
+
// resolves the request.
|
|
469
|
+
chrome.permissions.onAdded.addListener(async () => {
|
|
470
|
+
const origin = lastHealth.siteAccessNeeded?.origin;
|
|
471
|
+
if (origin && (await chrome.permissions.contains({ origins: [`${origin}/*`] }))) {
|
|
472
|
+
await clearSiteAccessNeeded();
|
|
473
|
+
}
|
|
474
|
+
});
|
|
475
|
+
|
|
476
|
+
// Ask Chrome for the store update now instead of waiting for its own check,
|
|
477
|
+
// and restart into it when one is ready.
|
|
478
|
+
async function updateExtension() {
|
|
479
|
+
let result;
|
|
480
|
+
try {
|
|
481
|
+
result = await chrome.runtime.requestUpdateCheck();
|
|
482
|
+
} catch {
|
|
483
|
+
result = null;
|
|
484
|
+
}
|
|
485
|
+
if (result?.status === "update_available") {
|
|
486
|
+
// Chrome downloads it in the background; restart once it's ready, or
|
|
487
|
+
// we'd come back up on the old version.
|
|
488
|
+
healthMessage.textContent = "Downloading the update…";
|
|
489
|
+
healthAction.hidden = true;
|
|
490
|
+
chrome.runtime.onUpdateAvailable.addListener(() => chrome.runtime.reload());
|
|
491
|
+
return;
|
|
492
|
+
}
|
|
493
|
+
healthMessage.textContent =
|
|
494
|
+
result?.status === "throttled"
|
|
495
|
+
? "Chrome checked for updates recently. Try again in a few minutes."
|
|
496
|
+
: "No update is available yet. Chrome installs it automatically once the Chrome Web Store has it.";
|
|
497
|
+
healthAction.hidden = true;
|
|
498
|
+
}
|
|
499
|
+
|
|
500
|
+
let accessReapprovalNeeded = false;
|
|
501
|
+
// Progress text while a re-approval is running; null when idle.
|
|
502
|
+
let reapprovalStatus = null;
|
|
503
|
+
|
|
504
|
+
async function refreshAccessReapproval() {
|
|
505
|
+
const stored = await chrome.storage.local.get([
|
|
506
|
+
STORAGE_KEYS.refreshToken,
|
|
507
|
+
GRANTED_SCOPE_KEY,
|
|
508
|
+
]);
|
|
509
|
+
accessReapprovalNeeded = needsAccessReapproval(
|
|
510
|
+
stored,
|
|
511
|
+
STORAGE_KEYS.refreshToken,
|
|
512
|
+
);
|
|
513
|
+
await refreshHealth();
|
|
514
|
+
}
|
|
515
|
+
|
|
516
|
+
function setReapprovalStatus(text) {
|
|
517
|
+
reapprovalStatus = text;
|
|
518
|
+
void refreshHealth();
|
|
519
|
+
}
|
|
520
|
+
|
|
521
|
+
// Re-run the OAuth device approval for an existing pairing, keeping its
|
|
522
|
+
// worker. The new grant asks for the panel's full SCOPE; on approval the
|
|
523
|
+
// panel re-signs in with it and the old grant is revoked.
|
|
524
|
+
async function reapproveAccess() {
|
|
525
|
+
if (reapproveFlow) return;
|
|
526
|
+
const flow = { timer: null, cancelled: false, resolve: null };
|
|
527
|
+
reapproveFlow = flow;
|
|
528
|
+
try {
|
|
529
|
+
const base = normalizeGatewayBase(await getGatewayUrl());
|
|
530
|
+
if (!base) return;
|
|
531
|
+
const startedFor = (await chrome.storage.local.get(STORAGE_KEYS.clientId))[
|
|
532
|
+
STORAGE_KEYS.clientId
|
|
533
|
+
];
|
|
534
|
+
const device = await requestDeviceCode(base, setReapprovalStatus);
|
|
535
|
+
const approveHint = "Approve Lobu for Chrome in the tab that just opened.";
|
|
536
|
+
setReapprovalStatus(approveHint);
|
|
537
|
+
const tokens = await waitForDeviceTokens(device, flow, (text) => {
|
|
538
|
+
setReapprovalStatus(text === "Waiting for approval…" ? approveHint : text);
|
|
539
|
+
});
|
|
540
|
+
if (!tokens) return;
|
|
541
|
+
// The user may have re-paired or changed server while approving. Only
|
|
542
|
+
// upgrade the pairing this flow started from (its OAuth client; token
|
|
543
|
+
// refreshes keep it), never a different one.
|
|
544
|
+
const current = await chrome.storage.local.get([
|
|
545
|
+
STORAGE_KEY_GATEWAY_URL,
|
|
546
|
+
STORAGE_KEYS.refreshToken,
|
|
547
|
+
STORAGE_KEYS.clientId,
|
|
548
|
+
STORAGE_KEYS.clientSecret,
|
|
549
|
+
]);
|
|
550
|
+
if (
|
|
551
|
+
flow.cancelled ||
|
|
552
|
+
normalizeGatewayBase(current[STORAGE_KEY_GATEWAY_URL]) !== base ||
|
|
553
|
+
current[STORAGE_KEYS.clientId] !== startedFor
|
|
554
|
+
) {
|
|
555
|
+
setReapprovalStatus(null);
|
|
556
|
+
return;
|
|
557
|
+
}
|
|
558
|
+
await chrome.storage.local.set(deviceTokenStorage(device.client, tokens));
|
|
559
|
+
void revokeRefreshToken(device.discovery, current);
|
|
560
|
+
} catch (err) {
|
|
561
|
+
setReapprovalStatus(`Re-approval failed: ${err.message}`);
|
|
562
|
+
return;
|
|
563
|
+
} finally {
|
|
564
|
+
if (reapproveFlow === flow) reapproveFlow = null;
|
|
565
|
+
void refreshHealth();
|
|
566
|
+
}
|
|
567
|
+
setReapprovalStatus(null);
|
|
568
|
+
}
|
|
569
|
+
|
|
570
|
+
// Best-effort revocation of a replaced grant (RFC 7009); it expires anyway.
|
|
571
|
+
async function revokeRefreshToken(discovery, previous) {
|
|
572
|
+
const token = previous[STORAGE_KEYS.refreshToken];
|
|
573
|
+
const clientId = previous[STORAGE_KEYS.clientId];
|
|
574
|
+
if (!discovery.revocation_endpoint || !token || !clientId) return;
|
|
575
|
+
try {
|
|
576
|
+
await fetch(discovery.revocation_endpoint, {
|
|
577
|
+
method: "POST",
|
|
578
|
+
headers: { "content-type": "application/x-www-form-urlencoded" },
|
|
579
|
+
body: new URLSearchParams({
|
|
580
|
+
token,
|
|
581
|
+
token_type_hint: "refresh_token",
|
|
582
|
+
client_id: clientId,
|
|
583
|
+
...(previous[STORAGE_KEYS.clientSecret]
|
|
584
|
+
? { client_secret: previous[STORAGE_KEYS.clientSecret] }
|
|
585
|
+
: {}),
|
|
586
|
+
}).toString(),
|
|
587
|
+
});
|
|
588
|
+
} catch {
|
|
589
|
+
// The old grant lapses on its own.
|
|
590
|
+
}
|
|
591
|
+
}
|
|
592
|
+
|
|
593
|
+
async function grantFromBanner() {
|
|
594
|
+
const base = await getGatewayUrl();
|
|
595
|
+
if (!base) return;
|
|
596
|
+
const granted = await chrome.permissions.request({ origins: [`${base}/*`] });
|
|
597
|
+
if (!granted) return;
|
|
598
|
+
await chrome.storage.local.set({ [STORAGE_KEY_GATEWAY_URL]: base });
|
|
599
|
+
// The SW clears health on its next poll; mount the app right away. Force a
|
|
600
|
+
// fresh bootstrap: we're recovering from a permission-blocked state where the
|
|
601
|
+
// iframe couldn't load, so a stale matching key must not short-circuit the
|
|
602
|
+
// mount.
|
|
603
|
+
mountedEmbeddedKey = null;
|
|
604
|
+
const workerId = (await chrome.storage.local.get(STORAGE_KEYS.workerId))[
|
|
605
|
+
STORAGE_KEYS.workerId
|
|
606
|
+
];
|
|
607
|
+
if (workerId) await mountEmbeddedApp(workerId);
|
|
608
|
+
}
|
|
609
|
+
|
|
610
|
+
async function refreshHealth() {
|
|
611
|
+
renderHealth((await chrome.storage.local.get(HEALTH_KEY))[HEALTH_KEY]);
|
|
612
|
+
}
|
|
613
|
+
|
|
614
|
+
function renderControlActivity(activities) {
|
|
615
|
+
controlActivities = Array.isArray(activities) ? activities : [];
|
|
616
|
+
renderStatusLabel();
|
|
617
|
+
}
|
|
618
|
+
|
|
619
|
+
chrome.storage.onChanged.addListener((changes, area) => {
|
|
620
|
+
if (area === "session" && changes[CONTROL_ACTIVITY_KEY]) {
|
|
621
|
+
renderControlActivity(changes[CONTROL_ACTIVITY_KEY].newValue);
|
|
622
|
+
}
|
|
623
|
+
if (area === "local" && changes[HEALTH_KEY]) {
|
|
624
|
+
renderHealth(changes[HEALTH_KEY].newValue);
|
|
625
|
+
}
|
|
626
|
+
if (
|
|
627
|
+
area === "local" &&
|
|
628
|
+
(changes[GRANTED_SCOPE_KEY] || changes[STORAGE_KEYS.refreshToken])
|
|
629
|
+
) {
|
|
630
|
+
void refreshAccessReapproval();
|
|
631
|
+
}
|
|
632
|
+
});
|
|
633
|
+
|
|
634
|
+
// ── Boot ────────────────────────────────────────────────────────────────
|
|
635
|
+
void renderInitialView().catch((err) => {
|
|
636
|
+
// Last-resort boundary: never leave the panel showing only its topbar.
|
|
637
|
+
console.error("[owletto] side panel failed to start", err);
|
|
638
|
+
show("pair");
|
|
639
|
+
pairCode.hidden = true;
|
|
640
|
+
pairSetup.hidden = false;
|
|
641
|
+
setupStatus.textContent =
|
|
642
|
+
"Lobu couldn't start. Close and reopen this panel; if it keeps happening, reload the extension.";
|
|
643
|
+
});
|
|
644
|
+
void refreshAccessReapproval();
|
|
645
|
+
void chrome.storage.session.get(CONTROL_ACTIVITY_KEY).then((stored) => renderControlActivity(stored[CONTROL_ACTIVITY_KEY]));
|
|
646
|
+
|
|
647
|
+
async function renderInitialView() {
|
|
648
|
+
const stored = await chrome.storage.local.get([
|
|
649
|
+
STORAGE_KEYS.workerId,
|
|
650
|
+
STORAGE_KEYS.accessToken,
|
|
651
|
+
]);
|
|
652
|
+
const gatewayBase = await getGatewayUrl();
|
|
653
|
+
if (stored[STORAGE_KEYS.accessToken] && gatewayBase) {
|
|
654
|
+
// Canonicalize storage so future reads + the toolbar badge check agree on
|
|
655
|
+
// the https origin (the next pair-save would otherwise be the only fixup).
|
|
656
|
+
await chrome.storage.local.set({ [STORAGE_KEY_GATEWAY_URL]: gatewayBase });
|
|
657
|
+
await mountEmbeddedApp(stored[STORAGE_KEYS.workerId]);
|
|
658
|
+
return;
|
|
659
|
+
}
|
|
660
|
+
await enterPairFlow();
|
|
661
|
+
}
|
|
662
|
+
|
|
663
|
+
// Mount owletto in the side-panel iframe, signed in.
|
|
664
|
+
//
|
|
665
|
+
// The iframe runs on the gateway origin but its top-level is this
|
|
666
|
+
// chrome-extension:// page, so it's a CROSS-SITE context: it can't see the
|
|
667
|
+
// extension's stored PAT, the user's main-tab session, or rely on a session
|
|
668
|
+
// cookie. We mount the gateway's /api/extension-bootstrap page, which exchanges
|
|
669
|
+
// the token for a Better Auth session token, stashes it in sessionStorage for
|
|
670
|
+
// the SPA to send as Authorization: Bearer, and redirects to the app. The PAT
|
|
671
|
+
// rides in the URL fragment — never sent to a server, stripped from history
|
|
672
|
+
// immediately by the bootstrap page — so it never lands in a request URL or
|
|
673
|
+
// history entry.
|
|
674
|
+
async function mountEmbeddedApp(workerId) {
|
|
675
|
+
const base = await getGatewayUrl();
|
|
676
|
+
if (!base) return;
|
|
677
|
+
const cleanBase = base.replace(/\/$/, "");
|
|
678
|
+
embeddedOrigin = new URL(cleanBase).origin;
|
|
679
|
+
const stored = await chrome.storage.local.get([
|
|
680
|
+
STORAGE_KEYS.accessToken,
|
|
681
|
+
PANEL_SESSION_KEY,
|
|
682
|
+
STORAGE_KEYS.pairedAt,
|
|
683
|
+
]);
|
|
684
|
+
// Mount identity = the pairing SESSION, not the access token. The token is a
|
|
685
|
+
// one-time bootstrap credential exchanged for the iframe's Better Auth session
|
|
686
|
+
// token; once the iframe holds that session, a later access-token refresh must
|
|
687
|
+
// NOT reload it — doing so re-runs the bootstrap and, when the token churns,
|
|
688
|
+
// leaves the iframe perpetually reloading. `pairedAt` is written on every pair
|
|
689
|
+
// path but never on refresh,
|
|
690
|
+
// so it distinguishes "new pairing → re-bootstrap" from "same session, SW
|
|
691
|
+
// token refreshed → leave the iframe alone".
|
|
692
|
+
const key = `${cleanBase}|${workerId}|${stored[STORAGE_KEYS.pairedAt] ?? ""}`;
|
|
693
|
+
if (mountedEmbeddedKey === key) {
|
|
694
|
+
// Same pairing — already mounted. Don't touch frame.src (a token refresh
|
|
695
|
+
// fires this while the user may be in Permissions), and don't force a view
|
|
696
|
+
// change. A failed first bootstrap recovers on next panel open, which
|
|
697
|
+
// re-mounts with the current token.
|
|
698
|
+
return;
|
|
699
|
+
}
|
|
700
|
+
const token = panelSignInToken(stored, STORAGE_KEYS.accessToken);
|
|
701
|
+
const url = new URL(`${cleanBase}/api/extension-bootstrap`);
|
|
702
|
+
// No `worker` in the hash: bootstrap forwards it into its post-auth redirect,
|
|
703
|
+
// and we want the default mount to land on the app root (dashboard), not the
|
|
704
|
+
// device page. The device page is reached only via openDeviceView() on an
|
|
705
|
+
// explicit topbar click.
|
|
706
|
+
url.hash = `token=${encodeURIComponent(token ?? "")}`;
|
|
707
|
+
frame.src = url.toString();
|
|
708
|
+
mountedEmbeddedKey = key;
|
|
709
|
+
// Right after a pairing, open Settings once while the app loads behind it,
|
|
710
|
+
// so the user picks what Lobu may use before the first agent run needs it.
|
|
711
|
+
// The flag is stored, so a background pairing gets the welcome too.
|
|
712
|
+
const welcome = (await chrome.storage.local.get(WELCOME_PENDING_KEY))[
|
|
713
|
+
WELCOME_PENDING_KEY
|
|
714
|
+
];
|
|
715
|
+
if (welcome) await chrome.storage.local.remove(WELCOME_PENDING_KEY);
|
|
716
|
+
show(welcome ? "welcome" : "app");
|
|
717
|
+
}
|
|
718
|
+
|
|
719
|
+
// Point the embedded iframe at this browser's device page. We re-run the
|
|
720
|
+
// bootstrap with the worker id in the hash; bootstrap redirects to
|
|
721
|
+
// `/#worker=<id>`, which the app's root route resolves to
|
|
722
|
+
// `/$owner/connectors/device/{id}` (it knows the signed-in org; the extension
|
|
723
|
+
// does not). The route matches the device by its stable `worker_id` as well as
|
|
724
|
+
// its surrogate id. A deliberate click is the only path that re-bootstraps the
|
|
725
|
+
// iframe — mountedEmbeddedKey stays the normal pairing key so a later token
|
|
726
|
+
// refresh won't fight it back to the dashboard.
|
|
727
|
+
async function openDeviceView() {
|
|
728
|
+
const base = await getGatewayUrl();
|
|
729
|
+
if (!base) return;
|
|
730
|
+
const cleanBase = base.replace(/\/$/, "");
|
|
731
|
+
const stored = await chrome.storage.local.get([
|
|
732
|
+
STORAGE_KEYS.accessToken,
|
|
733
|
+
PANEL_SESSION_KEY,
|
|
734
|
+
STORAGE_KEYS.workerId,
|
|
735
|
+
STORAGE_KEYS.pairedAt,
|
|
736
|
+
]);
|
|
737
|
+
const token = panelSignInToken(stored, STORAGE_KEYS.accessToken);
|
|
738
|
+
const workerId = stored[STORAGE_KEYS.workerId];
|
|
739
|
+
if (!token || !workerId) return;
|
|
740
|
+
const url = new URL(`${cleanBase}/api/extension-bootstrap`);
|
|
741
|
+
url.hash = `token=${encodeURIComponent(token)}&worker=${encodeURIComponent(workerId)}`;
|
|
742
|
+
frame.src = url.toString();
|
|
743
|
+
mountedEmbeddedKey = `${cleanBase}|${workerId}|${stored[STORAGE_KEYS.pairedAt] ?? ""}`;
|
|
744
|
+
show("app");
|
|
745
|
+
}
|
|
746
|
+
|
|
747
|
+
async function enterPairFlow() {
|
|
748
|
+
cancelDeviceFlow(reapproveFlow);
|
|
749
|
+
show("pair");
|
|
750
|
+
// Tear the embedded iframe down: drop the session key so the next pair forces
|
|
751
|
+
// a fresh bootstrap, AND blank the frame so a hidden, still-authenticated
|
|
752
|
+
// iframe doesn't linger after token loss / unpair (we only reach here when
|
|
753
|
+
// not mounted — exitPermissions reveals the live app instead of calling us).
|
|
754
|
+
mountedEmbeddedKey = null;
|
|
755
|
+
embeddedOrigin = null;
|
|
756
|
+
frame.src = "about:blank";
|
|
757
|
+
pairSetup.hidden = true;
|
|
758
|
+
pairCode.hidden = true;
|
|
759
|
+
|
|
760
|
+
// Try native auto-pair first — skips both the URL-setup step and OAuth
|
|
761
|
+
// when the Owletto desktop bridge is installed + signed in. Only attempt
|
|
762
|
+
// once per session: a failed handshake takes up to NATIVE_HANDSHAKE_TIMEOUT_MS,
|
|
763
|
+
// and the answer is unlikely to change without a reload.
|
|
764
|
+
if (!nativeAutoPairAttempted) {
|
|
765
|
+
nativeAutoPairAttempted = true;
|
|
766
|
+
setupStatus.textContent = "Connecting…";
|
|
767
|
+
// A failed auto-pair must fall through to manual pairing. Every pair
|
|
768
|
+
// sub-view is hidden at this point, so an escaping rejection would leave
|
|
769
|
+
// the panel blank.
|
|
770
|
+
const auto = await tryNativeAutoPair().catch(() => false);
|
|
771
|
+
if (auto) {
|
|
772
|
+
showPairWaiting({ title: "Signing in through the Lobu desktop app…" });
|
|
773
|
+
pollStatus.textContent = "Connected ✓";
|
|
774
|
+
// storage onChanged listener below swaps us into the embedded iframe.
|
|
775
|
+
return;
|
|
776
|
+
}
|
|
777
|
+
}
|
|
778
|
+
|
|
779
|
+
setupStatus.textContent = "";
|
|
780
|
+
const existing = await getGatewayUrl();
|
|
781
|
+
selectServerKind(
|
|
782
|
+
existing && existing !== DEFAULT_GATEWAY_URL ? "self-hosted" : "cloud",
|
|
783
|
+
existing,
|
|
784
|
+
);
|
|
785
|
+
if (existing) {
|
|
786
|
+
gatewayUrl = existing;
|
|
787
|
+
pairSetup.hidden = false;
|
|
788
|
+
} else {
|
|
789
|
+
// Fell through to manual entry. On a Mac whose desktop bridge never
|
|
790
|
+
// answered, point at the app that would have connected automatically.
|
|
791
|
+
macAppHint.hidden = !(
|
|
792
|
+
IS_MAC &&
|
|
793
|
+
nativeAutoPairAttempted &&
|
|
794
|
+
!macBridgeReachable
|
|
795
|
+
);
|
|
796
|
+
pairSetup.hidden = false;
|
|
797
|
+
}
|
|
798
|
+
}
|
|
799
|
+
|
|
800
|
+
function serverKind() {
|
|
801
|
+
return document.querySelector('input[name="server-kind"]:checked')?.value;
|
|
802
|
+
}
|
|
803
|
+
|
|
804
|
+
// Lobu Cloud needs no URL; the field only appears for a self-hosted server.
|
|
805
|
+
function selectServerKind(kind, url = "") {
|
|
806
|
+
for (const input of serverKindInputs) input.checked = input.value === kind;
|
|
807
|
+
selfHostedFields.hidden = kind !== "self-hosted";
|
|
808
|
+
if (kind === "self-hosted") {
|
|
809
|
+
if (url) gatewayUrlInput.value = url;
|
|
810
|
+
gatewayUrlInput.focus();
|
|
811
|
+
gatewayUrlInput.select();
|
|
812
|
+
}
|
|
813
|
+
}
|
|
814
|
+
|
|
815
|
+
for (const input of serverKindInputs) {
|
|
816
|
+
input.addEventListener("change", () => selectServerKind(input.value));
|
|
817
|
+
}
|
|
818
|
+
|
|
819
|
+
// React to storage updates: pairing completes (token arrives) → swap to
|
|
820
|
+
// embedded app; "Change server" clears creds → swap back to pair flow.
|
|
821
|
+
chrome.storage.onChanged.addListener(async (changes, area) => {
|
|
822
|
+
if (area !== "local") return;
|
|
823
|
+
if (changes[STORAGE_KEYS.accessToken]) {
|
|
824
|
+
if (changes[STORAGE_KEYS.accessToken].newValue) {
|
|
825
|
+
const workerId =
|
|
826
|
+
changes[STORAGE_KEYS.workerId]?.newValue ??
|
|
827
|
+
(await chrome.storage.local.get(STORAGE_KEYS.workerId))[
|
|
828
|
+
STORAGE_KEYS.workerId
|
|
829
|
+
];
|
|
830
|
+
if ((await getGatewayUrl()) && workerId) {
|
|
831
|
+
await mountEmbeddedApp(workerId);
|
|
832
|
+
}
|
|
833
|
+
} else {
|
|
834
|
+
await enterPairFlow();
|
|
835
|
+
}
|
|
836
|
+
}
|
|
837
|
+
});
|
|
838
|
+
|
|
839
|
+
// ── Pair: URL setup ─────────────────────────────────────────────────────
|
|
840
|
+
verifyUrlBtn.addEventListener("click", () => {
|
|
841
|
+
void verifyAndSaveGatewayUrl();
|
|
842
|
+
});
|
|
843
|
+
gatewayUrlInput.addEventListener("keydown", (ev) => {
|
|
844
|
+
if (ev.key === "Enter") void verifyAndSaveGatewayUrl();
|
|
845
|
+
});
|
|
846
|
+
async function verifyAndSaveGatewayUrl() {
|
|
847
|
+
const raw =
|
|
848
|
+
serverKind() === "cloud" ? DEFAULT_GATEWAY_URL : gatewayUrlInput.value.trim();
|
|
849
|
+
if (!raw) {
|
|
850
|
+
setupStatus.textContent = "Enter a URL.";
|
|
851
|
+
return;
|
|
852
|
+
}
|
|
853
|
+
// normalizeGatewayBase: validates http(s), strips trailing path, and
|
|
854
|
+
// upgrades non-loopback http→https. The host permission we request and
|
|
855
|
+
// the value we store must both be the form fetches will actually use.
|
|
856
|
+
const cleanBase = normalizeGatewayBase(raw);
|
|
857
|
+
if (!cleanBase) {
|
|
858
|
+
setupStatus.textContent =
|
|
859
|
+
"That doesn't look like a valid http:// or https:// URL.";
|
|
860
|
+
return;
|
|
861
|
+
}
|
|
862
|
+
|
|
863
|
+
verifyUrlBtn.disabled = true;
|
|
864
|
+
allowServerBtn.hidden = true;
|
|
865
|
+
setupStatus.textContent = "Checking the server…";
|
|
866
|
+
let discovery;
|
|
867
|
+
try {
|
|
868
|
+
const res = await fetch(
|
|
869
|
+
`${cleanBase}/.well-known/oauth-authorization-server`,
|
|
870
|
+
{ headers: { accept: "application/json" } },
|
|
871
|
+
);
|
|
872
|
+
if (!res.ok) throw new Error(`${cleanBase} returned ${res.status}`);
|
|
873
|
+
discovery = await res.json();
|
|
874
|
+
} catch (err) {
|
|
875
|
+
verifyUrlBtn.disabled = false;
|
|
876
|
+
if (await serverBlocksExtension(cleanBase)) {
|
|
877
|
+
// A site grant lets Chrome skip the refused CORS check; it needs a click.
|
|
878
|
+
allowServerBtn.dataset.base = cleanBase;
|
|
879
|
+
allowServerBtn.hidden = false;
|
|
880
|
+
setupStatus.textContent = `${new URL(cleanBase).host} is reachable but isn't allowing this extension to connect. Try allowing access.`;
|
|
881
|
+
return;
|
|
882
|
+
}
|
|
883
|
+
setupStatus.textContent = `Couldn't reach a Lobu server at ${cleanBase}: ${
|
|
884
|
+
err instanceof Error ? err.message : String(err)
|
|
885
|
+
}`;
|
|
886
|
+
return;
|
|
887
|
+
}
|
|
888
|
+
if (!discovery.device_authorization_endpoint) {
|
|
889
|
+
setupStatus.textContent =
|
|
890
|
+
"That server doesn't advertise device authorization — wrong URL?";
|
|
891
|
+
verifyUrlBtn.disabled = false;
|
|
892
|
+
return;
|
|
893
|
+
}
|
|
894
|
+
|
|
895
|
+
await chrome.storage.local.set({ [STORAGE_KEY_GATEWAY_URL]: cleanBase });
|
|
896
|
+
gatewayUrl = cleanBase;
|
|
897
|
+
try {
|
|
898
|
+
await pair((text) => {
|
|
899
|
+
setupStatus.textContent = text;
|
|
900
|
+
});
|
|
901
|
+
} catch (err) {
|
|
902
|
+
pairCode.hidden = true;
|
|
903
|
+
pairSetup.hidden = false;
|
|
904
|
+
setupStatus.textContent = err instanceof Error ? err.message : String(err);
|
|
905
|
+
} finally {
|
|
906
|
+
verifyUrlBtn.disabled = false;
|
|
907
|
+
}
|
|
908
|
+
}
|
|
909
|
+
|
|
910
|
+
// ── Pair: OAuth + local-init ────────────────────────────────────────────
|
|
911
|
+
allowServerBtn.addEventListener("click", async () => {
|
|
912
|
+
const base = allowServerBtn.dataset.base;
|
|
913
|
+
if (!base) return;
|
|
914
|
+
if (await chrome.permissions.request({ origins: [`${base}/*`] })) {
|
|
915
|
+
allowServerBtn.hidden = true;
|
|
916
|
+
await verifyAndSaveGatewayUrl();
|
|
917
|
+
}
|
|
918
|
+
});
|
|
919
|
+
|
|
920
|
+
cancelPairBtn.addEventListener("click", () => {
|
|
921
|
+
cancelDeviceFlow(pairFlow);
|
|
922
|
+
pairFlow = null;
|
|
923
|
+
pairCode.hidden = true;
|
|
924
|
+
pairSetup.hidden = false;
|
|
925
|
+
setupStatus.textContent = "";
|
|
926
|
+
});
|
|
927
|
+
|
|
928
|
+
reopenApprovalBtn.addEventListener("click", () => {
|
|
929
|
+
if (pendingApprovalUrl) void chrome.tabs.create({ url: pendingApprovalUrl });
|
|
930
|
+
});
|
|
931
|
+
|
|
932
|
+
// The waiting screen. Without an approval URL it is a bare progress screen
|
|
933
|
+
// (desktop auto-pair); with one it shows the code to match and the reopen link.
|
|
934
|
+
function showPairWaiting({ title, code = null, approvalUrl = null }) {
|
|
935
|
+
pairSetup.hidden = true;
|
|
936
|
+
pairCode.hidden = false;
|
|
937
|
+
pairCodeTitle.textContent = title;
|
|
938
|
+
pairCodeDetail.hidden = !code;
|
|
939
|
+
codeEl.textContent = code ?? "";
|
|
940
|
+
pendingApprovalUrl = approvalUrl;
|
|
941
|
+
pairCodeActions.hidden = !approvalUrl;
|
|
942
|
+
reopenApprovalBtn.hidden = !approvalUrl;
|
|
943
|
+
pollStatus.textContent = "Waiting…";
|
|
944
|
+
}
|
|
945
|
+
|
|
946
|
+
async function pair(onStatus) {
|
|
947
|
+
if (!gatewayUrl) {
|
|
948
|
+
throw new Error("Lobu server URL not set.");
|
|
949
|
+
}
|
|
950
|
+
|
|
951
|
+
// Zero-config local-runner short-circuit. If the gateway is loopback,
|
|
952
|
+
// POST /api/local-init first: on an empty embedded-Postgres deployment
|
|
953
|
+
// the server mints a worker-scoped PAT and we skip the OAuth dance entirely.
|
|
954
|
+
if (isLoopbackUrl(gatewayUrl)) {
|
|
955
|
+
onStatus("Trying local sign-in…");
|
|
956
|
+
const local = await tryLocalInit(gatewayUrl);
|
|
957
|
+
if (local) {
|
|
958
|
+
onStatus("Connected locally ✓");
|
|
959
|
+
// storage onChanged swaps us into the embedded iframe.
|
|
960
|
+
return;
|
|
961
|
+
}
|
|
962
|
+
}
|
|
963
|
+
|
|
964
|
+
const device = await requestDeviceCode(gatewayUrl, onStatus);
|
|
965
|
+
|
|
966
|
+
showPairWaiting({
|
|
967
|
+
title: "Approve in the new tab",
|
|
968
|
+
code: device.authz.user_code,
|
|
969
|
+
approvalUrl: device.approvalUrl,
|
|
970
|
+
});
|
|
971
|
+
|
|
972
|
+
cancelDeviceFlow(pairFlow);
|
|
973
|
+
const flow = { timer: null, cancelled: false, resolve: null };
|
|
974
|
+
pairFlow = flow;
|
|
975
|
+
const tokens = await waitForDeviceTokens(device, flow, (text) => {
|
|
976
|
+
pollStatus.textContent = text;
|
|
977
|
+
});
|
|
978
|
+
if (pairFlow === flow) pairFlow = null;
|
|
979
|
+
if (!tokens) {
|
|
980
|
+
// Expired or refused: the sign-in link is dead, so send the user back to
|
|
981
|
+
// the start with the reason. A Cancel has already gone back on its own.
|
|
982
|
+
if (!flow.cancelled) throw new Error(pollStatus.textContent);
|
|
983
|
+
return;
|
|
984
|
+
}
|
|
985
|
+
|
|
986
|
+
const workerId =
|
|
987
|
+
(await chrome.storage.local.get(STORAGE_KEYS.workerId))[
|
|
988
|
+
STORAGE_KEYS.workerId
|
|
989
|
+
] ?? crypto.randomUUID();
|
|
990
|
+
|
|
991
|
+
// storage.onChanged mounts the iframe, which signs itself in from inside
|
|
992
|
+
// its own partition via /api/extension-bootstrap (see mountEmbeddedApp).
|
|
993
|
+
await chrome.storage.local.set({
|
|
994
|
+
[STORAGE_KEYS.workerId]: workerId,
|
|
995
|
+
...deviceTokenStorage(device.client, tokens),
|
|
996
|
+
[WELCOME_PENDING_KEY]: true,
|
|
997
|
+
});
|
|
998
|
+
pollStatus.textContent = "Connected ✓";
|
|
999
|
+
}
|
|
1000
|
+
|
|
1001
|
+
// Register this extension and start an OAuth device authorization, opening
|
|
1002
|
+
// the approval page in a real tab (the user consents on the server's web UI).
|
|
1003
|
+
async function requestDeviceCode(base, onStatus) {
|
|
1004
|
+
onStatus("Contacting Lobu…");
|
|
1005
|
+
const discovery = await getJson(
|
|
1006
|
+
`${base}/.well-known/oauth-authorization-server`,
|
|
1007
|
+
);
|
|
1008
|
+
|
|
1009
|
+
onStatus("Registering this extension…");
|
|
1010
|
+
const client = await postJson(discovery.registration_endpoint, {
|
|
1011
|
+
client_name: "Lobu for Chrome",
|
|
1012
|
+
software_id: "owletto-chrome",
|
|
1013
|
+
software_version: chrome.runtime.getManifest().version,
|
|
1014
|
+
grant_types: [
|
|
1015
|
+
"urn:ietf:params:oauth:grant-type:device_code",
|
|
1016
|
+
"refresh_token",
|
|
1017
|
+
],
|
|
1018
|
+
token_endpoint_auth_method: "none",
|
|
1019
|
+
scope: SCOPE,
|
|
1020
|
+
});
|
|
1021
|
+
|
|
1022
|
+
onStatus("Requesting code…");
|
|
1023
|
+
const authz = await postJson(discovery.device_authorization_endpoint, {
|
|
1024
|
+
client_id: client.client_id,
|
|
1025
|
+
scope: SCOPE,
|
|
1026
|
+
});
|
|
1027
|
+
|
|
1028
|
+
const approvalUrl = authz.verification_uri_complete ?? authz.verification_uri;
|
|
1029
|
+
if (approvalUrl) await chrome.tabs.create({ url: approvalUrl });
|
|
1030
|
+
return { discovery, client, authz, approvalUrl };
|
|
1031
|
+
}
|
|
1032
|
+
|
|
1033
|
+
// Poll the token endpoint until the user approves. Resolves to the token
|
|
1034
|
+
// response, or null when the code expires, the server refuses, or the flow is
|
|
1035
|
+
// cancelled (cancelDeviceFlow).
|
|
1036
|
+
function waitForDeviceTokens({ discovery, client, authz }, flow, onStatus) {
|
|
1037
|
+
const deadline = Date.now() + (authz.expires_in ?? 600) * 1000;
|
|
1038
|
+
let intervalMs = Math.max((authz.interval ?? 5) * 1000, 1000);
|
|
1039
|
+
return new Promise((resolve) => {
|
|
1040
|
+
flow.resolve = resolve;
|
|
1041
|
+
const tick = async () => {
|
|
1042
|
+
if (flow.cancelled) return;
|
|
1043
|
+
if (Date.now() > deadline) {
|
|
1044
|
+
onStatus("Code expired. Try again.");
|
|
1045
|
+
resolve(null);
|
|
1046
|
+
return;
|
|
1047
|
+
}
|
|
1048
|
+
let response;
|
|
1049
|
+
try {
|
|
1050
|
+
response = await fetchJson(discovery.token_endpoint, {
|
|
1051
|
+
grant_type: "urn:ietf:params:oauth:grant-type:device_code",
|
|
1052
|
+
client_id: client.client_id,
|
|
1053
|
+
device_code: authz.device_code,
|
|
1054
|
+
...(client.client_secret
|
|
1055
|
+
? { client_secret: client.client_secret }
|
|
1056
|
+
: {}),
|
|
1057
|
+
});
|
|
1058
|
+
} catch (err) {
|
|
1059
|
+
onStatus(`Failed: ${err.message}`);
|
|
1060
|
+
schedule();
|
|
1061
|
+
return;
|
|
1062
|
+
}
|
|
1063
|
+
if (flow.cancelled) return;
|
|
1064
|
+
if (response.status === "pending") {
|
|
1065
|
+
onStatus("Waiting for approval…");
|
|
1066
|
+
if (response.error === "slow_down") intervalMs += 5000;
|
|
1067
|
+
schedule();
|
|
1068
|
+
return;
|
|
1069
|
+
}
|
|
1070
|
+
if (response.status !== "ok") {
|
|
1071
|
+
onStatus(
|
|
1072
|
+
response.error === "access_denied"
|
|
1073
|
+
? "Sign-in was denied. Try again."
|
|
1074
|
+
: `Sign-in failed: ${response.error ?? response.status}`,
|
|
1075
|
+
);
|
|
1076
|
+
resolve(null);
|
|
1077
|
+
return;
|
|
1078
|
+
}
|
|
1079
|
+
resolve(response.tokens);
|
|
1080
|
+
};
|
|
1081
|
+
const schedule = () => {
|
|
1082
|
+
if (!flow.cancelled) flow.timer = setTimeout(tick, intervalMs);
|
|
1083
|
+
};
|
|
1084
|
+
schedule();
|
|
1085
|
+
});
|
|
1086
|
+
}
|
|
1087
|
+
|
|
1088
|
+
function cancelDeviceFlow(flow) {
|
|
1089
|
+
if (!flow) return;
|
|
1090
|
+
flow.cancelled = true;
|
|
1091
|
+
clearTimeout(flow.timer);
|
|
1092
|
+
flow.resolve?.(null);
|
|
1093
|
+
}
|
|
1094
|
+
|
|
1095
|
+
function deviceTokenStorage(client, tokens) {
|
|
1096
|
+
return {
|
|
1097
|
+
[STORAGE_KEYS.accessToken]: tokens.access_token,
|
|
1098
|
+
[PANEL_SESSION_KEY]: null,
|
|
1099
|
+
[STORAGE_KEYS.refreshToken]: tokens.refresh_token ?? null,
|
|
1100
|
+
[GRANTED_SCOPE_KEY]: null,
|
|
1101
|
+
...grantedScopeUpdate(tokens),
|
|
1102
|
+
[STORAGE_KEYS.clientId]: client.client_id,
|
|
1103
|
+
[STORAGE_KEYS.clientSecret]: client.client_secret ?? null,
|
|
1104
|
+
[STORAGE_KEYS.pairedAt]: Date.now(),
|
|
1105
|
+
};
|
|
1106
|
+
}
|
|
1107
|
+
|
|
1108
|
+
// ── Native auto-pair ────────────────────────────────────────────────────
|
|
1109
|
+
|
|
1110
|
+
// Single-shot native-messaging handshake against the Owletto Mac bridge.
|
|
1111
|
+
// Resolves to the bridge response (`{gateway_url, worker_id, access_token,
|
|
1112
|
+
// session_token?}`) or null if the host isn't installed/reachable/responsive
|
|
1113
|
+
// within NATIVE_HANDSHAKE_TIMEOUT_MS. Disconnects the port either way.
|
|
1114
|
+
// The worker_id is absent on a first-ever pair (storage empty) → the server
|
|
1115
|
+
// mints fresh; tearDownPairing keeps it across auth-loss so a re-pair after
|
|
1116
|
+
// auth-loss still reuses it.
|
|
1117
|
+
function nativeBridgeHandshake() {
|
|
1118
|
+
return nativeBridgeHandshakeWith({
|
|
1119
|
+
connectNative: () => chrome.runtime.connectNative(NATIVE_HOST),
|
|
1120
|
+
readWorkerId: async () =>
|
|
1121
|
+
(await chrome.storage.local.get(STORAGE_KEYS.workerId))[
|
|
1122
|
+
STORAGE_KEYS.workerId
|
|
1123
|
+
],
|
|
1124
|
+
timeoutMs: NATIVE_HANDSHAKE_TIMEOUT_MS,
|
|
1125
|
+
onReply: () => {
|
|
1126
|
+
macBridgeReachable = true;
|
|
1127
|
+
},
|
|
1128
|
+
});
|
|
1129
|
+
}
|
|
1130
|
+
|
|
1131
|
+
async function tryNativeAutoPair() {
|
|
1132
|
+
const pair = readNativePairResponse(await nativeBridgeHandshake());
|
|
1133
|
+
const gatewayBase = pair && normalizeGatewayBase(pair.gatewayUrl);
|
|
1134
|
+
if (!gatewayBase) return false;
|
|
1135
|
+
// storage.onChanged mounts the iframe, which signs itself in from inside its
|
|
1136
|
+
// own partition via /api/extension-bootstrap (see mountEmbeddedApp).
|
|
1137
|
+
await chrome.storage.local.set(
|
|
1138
|
+
nativePairStorage({
|
|
1139
|
+
pair,
|
|
1140
|
+
gatewayBase,
|
|
1141
|
+
keys: STORAGE_KEYS,
|
|
1142
|
+
gatewayKey: STORAGE_KEY_GATEWAY_URL,
|
|
1143
|
+
}),
|
|
1144
|
+
);
|
|
1145
|
+
return true;
|
|
1146
|
+
}
|
|
1147
|
+
|
|
1148
|
+
// ── local-init ─────────────────────────────────────────────────────────
|
|
1149
|
+
async function tryLocalInit(baseUrl) {
|
|
1150
|
+
let res;
|
|
1151
|
+
try {
|
|
1152
|
+
res = await fetch(`${baseUrl}/api/local-init`, {
|
|
1153
|
+
method: "POST",
|
|
1154
|
+
headers: {
|
|
1155
|
+
"X-Lobu-Client": "chrome-extension",
|
|
1156
|
+
accept: "application/json",
|
|
1157
|
+
},
|
|
1158
|
+
});
|
|
1159
|
+
} catch {
|
|
1160
|
+
return null;
|
|
1161
|
+
}
|
|
1162
|
+
if (!res.ok) return null;
|
|
1163
|
+
let body;
|
|
1164
|
+
try {
|
|
1165
|
+
body = await res.json();
|
|
1166
|
+
} catch {
|
|
1167
|
+
return null;
|
|
1168
|
+
}
|
|
1169
|
+
// device_token is a worker-scoped PAT; session_token is a Better Auth session
|
|
1170
|
+
// token. Both resolve to the user via the deep-link path /api/extension-session
|
|
1171
|
+
// uses (the iframe bootstrap) — so either works as the stored credential.
|
|
1172
|
+
const token = body?.device_token ?? body?.session_token;
|
|
1173
|
+
if (!token) return null;
|
|
1174
|
+
|
|
1175
|
+
const workerId =
|
|
1176
|
+
(await chrome.storage.local.get(STORAGE_KEYS.workerId))[
|
|
1177
|
+
STORAGE_KEYS.workerId
|
|
1178
|
+
] ?? crypto.randomUUID();
|
|
1179
|
+
|
|
1180
|
+
// storage.onChanged mounts the iframe, which signs itself in from inside its
|
|
1181
|
+
// own partition via /api/extension-bootstrap (see mountEmbeddedApp).
|
|
1182
|
+
await chrome.storage.local.set({
|
|
1183
|
+
[STORAGE_KEYS.workerId]: workerId,
|
|
1184
|
+
[STORAGE_KEYS.accessToken]: token,
|
|
1185
|
+
[PANEL_SESSION_KEY]: null,
|
|
1186
|
+
[STORAGE_KEYS.refreshToken]: null,
|
|
1187
|
+
[GRANTED_SCOPE_KEY]: null,
|
|
1188
|
+
[STORAGE_KEYS.clientId]: null,
|
|
1189
|
+
[STORAGE_KEYS.clientSecret]: null,
|
|
1190
|
+
[STORAGE_KEYS.pairedAt]: Date.now(),
|
|
1191
|
+
[WELCOME_PENDING_KEY]: true,
|
|
1192
|
+
});
|
|
1193
|
+
return { workerId, token };
|
|
1194
|
+
}
|
|
1195
|
+
|
|
1196
|
+
function isLoopbackUrl(url) {
|
|
1197
|
+
try {
|
|
1198
|
+
const { hostname } = new URL(url);
|
|
1199
|
+
return (
|
|
1200
|
+
hostname === "localhost" ||
|
|
1201
|
+
hostname === "127.0.0.1" ||
|
|
1202
|
+
hostname === "::1" ||
|
|
1203
|
+
hostname === "[::1]"
|
|
1204
|
+
);
|
|
1205
|
+
} catch {
|
|
1206
|
+
return false;
|
|
1207
|
+
}
|
|
1208
|
+
}
|
|
1209
|
+
|
|
1210
|
+
async function getJson(url) {
|
|
1211
|
+
const res = await fetch(url, { headers: { accept: "application/json" } });
|
|
1212
|
+
if (!res.ok) throw new Error(`${url} → ${res.status}`);
|
|
1213
|
+
return res.json();
|
|
1214
|
+
}
|
|
1215
|
+
|
|
1216
|
+
async function postJson(url, body) {
|
|
1217
|
+
const res = await fetch(url, {
|
|
1218
|
+
method: "POST",
|
|
1219
|
+
headers: {
|
|
1220
|
+
"content-type": "application/json",
|
|
1221
|
+
accept: "application/json",
|
|
1222
|
+
},
|
|
1223
|
+
body: JSON.stringify(body),
|
|
1224
|
+
});
|
|
1225
|
+
if (!res.ok) {
|
|
1226
|
+
const text = await res.text().catch(() => "");
|
|
1227
|
+
throw new Error(`${url} → ${res.status} ${text.slice(0, 200)}`);
|
|
1228
|
+
}
|
|
1229
|
+
return res.json();
|
|
1230
|
+
}
|
|
1231
|
+
|
|
1232
|
+
async function fetchJson(url, body) {
|
|
1233
|
+
const res = await fetch(url, {
|
|
1234
|
+
method: "POST",
|
|
1235
|
+
headers: {
|
|
1236
|
+
"content-type": "application/json",
|
|
1237
|
+
accept: "application/json",
|
|
1238
|
+
},
|
|
1239
|
+
body: JSON.stringify(body),
|
|
1240
|
+
});
|
|
1241
|
+
const data = await res.json().catch(() => ({}));
|
|
1242
|
+
if (res.ok) return { status: "ok", tokens: data };
|
|
1243
|
+
if (data?.error === "authorization_pending" || data?.error === "slow_down") {
|
|
1244
|
+
return { status: "pending", error: data.error };
|
|
1245
|
+
}
|
|
1246
|
+
return { status: "error", error: data?.error ?? String(res.status) };
|
|
1247
|
+
}
|
|
1248
|
+
|
|
1249
|
+
// ── Permissions view ───────────────────────────────────────────────────
|
|
1250
|
+
const permRows = Array.from(permsView.querySelectorAll(".perm-row[data-perm]"));
|
|
1251
|
+
const actionGrantRows = Array.from(
|
|
1252
|
+
permsView.querySelectorAll(".perm-row[data-action-grant]"),
|
|
1253
|
+
);
|
|
1254
|
+
async function refreshServerRow() {
|
|
1255
|
+
const url = await getGatewayUrl();
|
|
1256
|
+
serverUrlDisplay.textContent = url ?? "(not set)";
|
|
1257
|
+
}
|
|
1258
|
+
|
|
1259
|
+
async function refreshPermRow(row) {
|
|
1260
|
+
const perm = row.dataset.perm;
|
|
1261
|
+
const button = row.querySelector(".toggle");
|
|
1262
|
+
const granted = await chrome.permissions.contains({ permissions: [perm] });
|
|
1263
|
+
button.dataset.granted = String(granted);
|
|
1264
|
+
button.textContent = granted ? "Revoke" : "Grant";
|
|
1265
|
+
}
|
|
1266
|
+
|
|
1267
|
+
async function refreshActionGrantRow(row) {
|
|
1268
|
+
const scope = row.dataset.actionGrant;
|
|
1269
|
+
const button = row.querySelector(".toggle");
|
|
1270
|
+
const granted = await isActionGrantEnabled(chrome, scope);
|
|
1271
|
+
button.dataset.granted = String(granted);
|
|
1272
|
+
button.textContent = granted ? "Revoke" : "Grant";
|
|
1273
|
+
}
|
|
1274
|
+
|
|
1275
|
+
async function refreshPermissions() {
|
|
1276
|
+
await refreshServerRow();
|
|
1277
|
+
await refreshSiteAccess();
|
|
1278
|
+
for (const row of permRows) await refreshPermRow(row);
|
|
1279
|
+
for (const row of actionGrantRows) await refreshActionGrantRow(row);
|
|
1280
|
+
}
|
|
1281
|
+
|
|
1282
|
+
// ── Site (host) access ─────────────────────────────────────────────────
|
|
1283
|
+
// Connectors that visit sites the user hasn't pre-approved need a host
|
|
1284
|
+
// permission for that origin. The manifest no longer hardcodes any site —
|
|
1285
|
+
// chrome.permissions.request() must come from a user gesture, and headless
|
|
1286
|
+
// poll-loop runs have none, so the grant happens HERE (a panel click): either
|
|
1287
|
+
// <all_urls> via the toggle, or one origin at a time. The background worker
|
|
1288
|
+
// then finds the grant via chrome.permissions.contains() on its next run.
|
|
1289
|
+
const ALL_URLS = "<all_urls>";
|
|
1290
|
+
|
|
1291
|
+
// "https://example.com/*" → "https://example.com"
|
|
1292
|
+
function siteLabelFromPattern(pattern) {
|
|
1293
|
+
return pattern.replace(/\/\*$/, "");
|
|
1294
|
+
}
|
|
1295
|
+
|
|
1296
|
+
async function refreshAllSitesToggle() {
|
|
1297
|
+
const granted = await chrome.permissions.contains({ origins: [ALL_URLS] });
|
|
1298
|
+
toggleAllsitesBtn.dataset.granted = String(granted);
|
|
1299
|
+
toggleAllsitesBtn.textContent = granted ? "Revoke" : "Allow all sites";
|
|
1300
|
+
// With every site allowed, per-site grants change nothing, so hide them.
|
|
1301
|
+
siteMode.textContent = granted
|
|
1302
|
+
? "Your agent can open and act on any website."
|
|
1303
|
+
: "Lobu asks you the first time an agent needs a site. Allow all sites, or add sites ahead of time.";
|
|
1304
|
+
siteSpecific.hidden = granted;
|
|
1305
|
+
}
|
|
1306
|
+
|
|
1307
|
+
async function refreshSiteList() {
|
|
1308
|
+
const all = await chrome.permissions.getAll();
|
|
1309
|
+
const gatewayBase = await getGatewayUrl();
|
|
1310
|
+
// The gateway origin is granted during pairing and shown in the server row —
|
|
1311
|
+
// exclude it (and <all_urls>, which the toggle owns) so the list is only the
|
|
1312
|
+
// per-site connector grants the user added here.
|
|
1313
|
+
const gatewayPattern = gatewayBase ? `${gatewayBase}/*` : null;
|
|
1314
|
+
const origins = (all.origins ?? []).filter(
|
|
1315
|
+
(o) => o !== ALL_URLS && o !== gatewayPattern,
|
|
1316
|
+
);
|
|
1317
|
+
siteList.replaceChildren();
|
|
1318
|
+
for (const pattern of origins) {
|
|
1319
|
+
const li = document.createElement("li");
|
|
1320
|
+
const label = document.createElement("span");
|
|
1321
|
+
label.textContent = siteLabelFromPattern(pattern);
|
|
1322
|
+
const revoke = document.createElement("button");
|
|
1323
|
+
revoke.textContent = "Revoke";
|
|
1324
|
+
revoke.addEventListener("click", async () => {
|
|
1325
|
+
revoke.disabled = true;
|
|
1326
|
+
try {
|
|
1327
|
+
await chrome.permissions.remove({ origins: [pattern] });
|
|
1328
|
+
} finally {
|
|
1329
|
+
await refreshSiteAccess();
|
|
1330
|
+
}
|
|
1331
|
+
});
|
|
1332
|
+
li.append(label, revoke);
|
|
1333
|
+
siteList.append(li);
|
|
1334
|
+
}
|
|
1335
|
+
}
|
|
1336
|
+
|
|
1337
|
+
async function refreshSiteAccess() {
|
|
1338
|
+
await refreshAllSitesToggle();
|
|
1339
|
+
await refreshSiteList();
|
|
1340
|
+
}
|
|
1341
|
+
|
|
1342
|
+
toggleAllsitesBtn.addEventListener("click", async () => {
|
|
1343
|
+
const granted = toggleAllsitesBtn.dataset.granted === "true";
|
|
1344
|
+
toggleAllsitesBtn.disabled = true;
|
|
1345
|
+
permStatus.textContent = "";
|
|
1346
|
+
try {
|
|
1347
|
+
if (granted) {
|
|
1348
|
+
const ok = await chrome.permissions.remove({ origins: [ALL_URLS] });
|
|
1349
|
+
permStatus.textContent = ok
|
|
1350
|
+
? "Revoked all-sites access."
|
|
1351
|
+
: "Couldn't revoke — try chrome://extensions.";
|
|
1352
|
+
} else {
|
|
1353
|
+
const ok = await chrome.permissions.request({ origins: [ALL_URLS] });
|
|
1354
|
+
permStatus.textContent = ok
|
|
1355
|
+
? "Granted access to all sites."
|
|
1356
|
+
: "Permission declined.";
|
|
1357
|
+
}
|
|
1358
|
+
} catch (err) {
|
|
1359
|
+
permStatus.textContent = `Failed: ${
|
|
1360
|
+
err instanceof Error ? err.message : String(err)
|
|
1361
|
+
}`;
|
|
1362
|
+
} finally {
|
|
1363
|
+
await refreshSiteAccess();
|
|
1364
|
+
toggleAllsitesBtn.disabled = false;
|
|
1365
|
+
}
|
|
1366
|
+
});
|
|
1367
|
+
|
|
1368
|
+
addSiteBtn.addEventListener("click", () => void addSite());
|
|
1369
|
+
siteUrlInput.addEventListener("keydown", (ev) => {
|
|
1370
|
+
if (ev.key === "Enter") void addSite();
|
|
1371
|
+
});
|
|
1372
|
+
|
|
1373
|
+
async function addSite() {
|
|
1374
|
+
const raw = siteUrlInput.value.trim();
|
|
1375
|
+
if (!raw) {
|
|
1376
|
+
permStatus.textContent = "Enter a site URL.";
|
|
1377
|
+
return;
|
|
1378
|
+
}
|
|
1379
|
+
// Same normalization the gateway URL uses: strip path, upgrade non-loopback
|
|
1380
|
+
// http→https, so the granted pattern matches what fetches/navigations hit.
|
|
1381
|
+
const base = normalizeGatewayBase(raw);
|
|
1382
|
+
if (!base) {
|
|
1383
|
+
permStatus.textContent = "That doesn't look like a valid http(s) URL.";
|
|
1384
|
+
return;
|
|
1385
|
+
}
|
|
1386
|
+
addSiteBtn.disabled = true;
|
|
1387
|
+
permStatus.textContent = "";
|
|
1388
|
+
try {
|
|
1389
|
+
const ok = await chrome.permissions.request({ origins: [`${base}/*`] });
|
|
1390
|
+
if (ok) {
|
|
1391
|
+
siteUrlInput.value = "";
|
|
1392
|
+
permStatus.textContent = `Allowed ${new URL(base).host}.`;
|
|
1393
|
+
} else {
|
|
1394
|
+
permStatus.textContent = "Permission declined.";
|
|
1395
|
+
}
|
|
1396
|
+
} catch (err) {
|
|
1397
|
+
permStatus.textContent = `Failed: ${
|
|
1398
|
+
err instanceof Error ? err.message : String(err)
|
|
1399
|
+
}`;
|
|
1400
|
+
} finally {
|
|
1401
|
+
await refreshSiteAccess();
|
|
1402
|
+
addSiteBtn.disabled = false;
|
|
1403
|
+
}
|
|
1404
|
+
}
|
|
1405
|
+
|
|
1406
|
+
for (const row of permRows) {
|
|
1407
|
+
const button = row.querySelector(".toggle");
|
|
1408
|
+
button.addEventListener("click", async () => {
|
|
1409
|
+
const perm = row.dataset.perm;
|
|
1410
|
+
const granted = button.dataset.granted === "true";
|
|
1411
|
+
button.disabled = true;
|
|
1412
|
+
permStatus.textContent = "";
|
|
1413
|
+
try {
|
|
1414
|
+
if (granted) {
|
|
1415
|
+
const ok = await chrome.permissions.remove({ permissions: [perm] });
|
|
1416
|
+
permStatus.textContent = ok
|
|
1417
|
+
? `Revoked ${perm}.`
|
|
1418
|
+
: `Couldn't revoke ${perm} — try chrome://extensions.`;
|
|
1419
|
+
} else {
|
|
1420
|
+
const ok = await chrome.permissions.request({ permissions: [perm] });
|
|
1421
|
+
permStatus.textContent = ok
|
|
1422
|
+
? `Granted ${perm}. Advertised on next poll.`
|
|
1423
|
+
: `Permission declined.`;
|
|
1424
|
+
}
|
|
1425
|
+
} catch (err) {
|
|
1426
|
+
permStatus.textContent = `Failed: ${
|
|
1427
|
+
err instanceof Error ? err.message : String(err)
|
|
1428
|
+
}`;
|
|
1429
|
+
} finally {
|
|
1430
|
+
await refreshPermRow(row);
|
|
1431
|
+
button.disabled = false;
|
|
1432
|
+
}
|
|
1433
|
+
});
|
|
1434
|
+
}
|
|
1435
|
+
|
|
1436
|
+
for (const row of actionGrantRows) {
|
|
1437
|
+
const button = row.querySelector(".toggle");
|
|
1438
|
+
button.addEventListener("click", async () => {
|
|
1439
|
+
const scope = row.dataset.actionGrant;
|
|
1440
|
+
const granted = button.dataset.granted === "true";
|
|
1441
|
+
button.disabled = true;
|
|
1442
|
+
permStatus.textContent = "";
|
|
1443
|
+
try {
|
|
1444
|
+
await setActionGrantEnabled(chrome, scope, !granted);
|
|
1445
|
+
const label = scope === TABS_MANAGE_SCOPE ? "Manage open tabs" : scope;
|
|
1446
|
+
permStatus.textContent = granted
|
|
1447
|
+
? `Revoked ${label}.`
|
|
1448
|
+
: `Granted ${label}. Agents can use close_user_tabs.`;
|
|
1449
|
+
} catch (err) {
|
|
1450
|
+
permStatus.textContent = `Failed: ${
|
|
1451
|
+
err instanceof Error ? err.message : String(err)
|
|
1452
|
+
}`;
|
|
1453
|
+
} finally {
|
|
1454
|
+
await refreshActionGrantRow(row);
|
|
1455
|
+
button.disabled = false;
|
|
1456
|
+
}
|
|
1457
|
+
});
|
|
1458
|
+
}
|
|
1459
|
+
|
|
1460
|
+
changeServerPermBtn.addEventListener("click", async () => {
|
|
1461
|
+
// Clear everything tied to the current pairing. When a token existed,
|
|
1462
|
+
// removing it fires storage.onChanged → enterPairFlow (don't also call
|
|
1463
|
+
// renderInitialView/enterPairFlow here, or we double-fire enterPairFlow +
|
|
1464
|
+
// native auto-pair). But when the server is already unset (no token), there
|
|
1465
|
+
// is nothing to remove and no change event fires — so the click would do
|
|
1466
|
+
// nothing. Navigate to the pair flow directly in that case.
|
|
1467
|
+
gatewayUrl = null;
|
|
1468
|
+
mountedEmbeddedKey = null;
|
|
1469
|
+
cancelDeviceFlow(reapproveFlow);
|
|
1470
|
+
const { [STORAGE_KEYS.accessToken]: hadToken } =
|
|
1471
|
+
await chrome.storage.local.get(STORAGE_KEYS.accessToken);
|
|
1472
|
+
await chrome.storage.local.remove([
|
|
1473
|
+
STORAGE_KEY_GATEWAY_URL,
|
|
1474
|
+
STORAGE_KEYS.workerId,
|
|
1475
|
+
STORAGE_KEYS.accessToken,
|
|
1476
|
+
PANEL_SESSION_KEY,
|
|
1477
|
+
STORAGE_KEYS.refreshToken,
|
|
1478
|
+
GRANTED_SCOPE_KEY,
|
|
1479
|
+
STORAGE_KEYS.clientId,
|
|
1480
|
+
STORAGE_KEYS.clientSecret,
|
|
1481
|
+
STORAGE_KEYS.pairedAt,
|
|
1482
|
+
]);
|
|
1483
|
+
if (!hadToken) await enterPairFlow();
|
|
1484
|
+
});
|
|
1485
|
+
|
|
1486
|
+
chrome.permissions.onAdded.addListener(() => {
|
|
1487
|
+
for (const row of permRows) void refreshPermRow(row);
|
|
1488
|
+
void refreshSiteAccess();
|
|
1489
|
+
});
|
|
1490
|
+
chrome.permissions.onRemoved.addListener(() => {
|
|
1491
|
+
for (const row of permRows) void refreshPermRow(row);
|
|
1492
|
+
void refreshSiteAccess();
|
|
1493
|
+
});
|
|
1494
|
+
|
|
1495
|
+
// ── Live input context toggle ────────────────────────────────────────
|
|
1496
|
+
const watchToggle = document.getElementById("toggle-watch");
|
|
1497
|
+
|
|
1498
|
+
async function refreshWatchState() {
|
|
1499
|
+
if (!watchToggle) return;
|
|
1500
|
+
const reply = await new Promise((resolve) =>
|
|
1501
|
+
chrome.runtime.sendMessage({ op: "watch-status" }, (r) =>
|
|
1502
|
+
resolve(r ?? { watching: false }),
|
|
1503
|
+
),
|
|
1504
|
+
);
|
|
1505
|
+
const on = Boolean(reply?.watching);
|
|
1506
|
+
watchToggle.textContent = on ? "On" : "Off";
|
|
1507
|
+
watchToggle.dataset.granted = String(on);
|
|
1508
|
+
}
|
|
1509
|
+
void refreshWatchState();
|
|
1510
|
+
|
|
1511
|
+
watchToggle?.addEventListener("click", async () => {
|
|
1512
|
+
watchToggle.disabled = true;
|
|
1513
|
+
const status = await new Promise((resolve) =>
|
|
1514
|
+
chrome.runtime.sendMessage({ op: "watch-status" }, (r) =>
|
|
1515
|
+
resolve(r ?? { watching: false }),
|
|
1516
|
+
),
|
|
1517
|
+
);
|
|
1518
|
+
const turnOn = !status?.watching;
|
|
1519
|
+
await new Promise((resolve) =>
|
|
1520
|
+
chrome.runtime.sendMessage(
|
|
1521
|
+
{ op: turnOn ? "watch-start" : "watch-stop" },
|
|
1522
|
+
resolve,
|
|
1523
|
+
),
|
|
1524
|
+
);
|
|
1525
|
+
watchToggle.disabled = false;
|
|
1526
|
+
permStatus.textContent = turnOn
|
|
1527
|
+
? "Live input context on. Non-sensitive form inputs + submits are captured across the tab you're actively using — password/OTP/card fields are redacted. A red recording dot shows on the Lobu extension icon."
|
|
1528
|
+
: "Live input context off.";
|
|
1529
|
+
await refreshWatchState();
|
|
1530
|
+
});
|
|
1531
|
+
|
|
1532
|
+
// Single target-resolution path for everything posted to the embedded app:
|
|
1533
|
+
// the ambient-context publisher and the service-worker bridge replies share
|
|
1534
|
+
// it, so a blanked/hidden/remounted frame reads the same way everywhere.
|
|
1535
|
+
const getEmbeddedTarget = () =>
|
|
1536
|
+
embeddedOrigin && !frame.hidden && frame.contentWindow
|
|
1537
|
+
? { origin: embeddedOrigin, window: frame.contentWindow }
|
|
1538
|
+
: null;
|
|
1539
|
+
|
|
1540
|
+
const publishActiveContext = createContextPublisher({
|
|
1541
|
+
queryTabs: (query) => chrome.tabs.query(query),
|
|
1542
|
+
getTarget: getEmbeddedTarget,
|
|
1543
|
+
});
|
|
1544
|
+
frame.addEventListener("load", () => void publishActiveContext());
|
|
1545
|
+
chrome.tabs.onActivated.addListener(() => void publishActiveContext());
|
|
1546
|
+
chrome.tabs.onUpdated.addListener((_id, change) => {
|
|
1547
|
+
if (change.url || change.status) void publishActiveContext();
|
|
1548
|
+
});
|
|
1549
|
+
chrome.windows.onFocusChanged.addListener(() => void publishActiveContext());
|
|
1550
|
+
document.addEventListener("visibilitychange", () => {
|
|
1551
|
+
if (document.visibilityState === "visible") void publishActiveContext();
|
|
1552
|
+
});
|
|
1553
|
+
|
|
1554
|
+
// ── iframe ↔ service-worker bridge ─────────────────────────────────────
|
|
1555
|
+
const port = chrome.runtime.connect({ name: "owletto.sidepanel" });
|
|
1556
|
+
|
|
1557
|
+
const pending = new Map();
|
|
1558
|
+
let nextId = 1;
|
|
1559
|
+
|
|
1560
|
+
window.addEventListener("message", (ev) => {
|
|
1561
|
+
if (
|
|
1562
|
+
!embeddedOrigin ||
|
|
1563
|
+
ev.origin !== embeddedOrigin ||
|
|
1564
|
+
ev.source !== frame.contentWindow
|
|
1565
|
+
)
|
|
1566
|
+
return;
|
|
1567
|
+
if (ev.data?.owletto === "ambient-context-request") {
|
|
1568
|
+
void publishActiveContext();
|
|
1569
|
+
return;
|
|
1570
|
+
}
|
|
1571
|
+
// The bootstrap error page (served at the gateway origin inside the iframe)
|
|
1572
|
+
// can't reach the panel's Settings view itself; when its Retry keeps failing
|
|
1573
|
+
// it asks us to open Settings so a stuck user can change server / re-pair.
|
|
1574
|
+
if (ev.data?.owletto === "open-settings") {
|
|
1575
|
+
show("permissions");
|
|
1576
|
+
return;
|
|
1577
|
+
}
|
|
1578
|
+
// The gateway refused the panel's sign-in (expired session, or a credential
|
|
1579
|
+
// without full access). A desktop pairing can get a fresh one from the app;
|
|
1580
|
+
// try once per panel load so a persistent refusal can't loop.
|
|
1581
|
+
if (ev.data?.owletto === "session-rejected") {
|
|
1582
|
+
// The bootstrap page waits for us before showing its error: either we
|
|
1583
|
+
// store a fresh pairing (which remounts the frame) or we say we can't.
|
|
1584
|
+
const frameWindow = ev.source;
|
|
1585
|
+
const reportFailure = () => {
|
|
1586
|
+
try {
|
|
1587
|
+
frameWindow?.postMessage(
|
|
1588
|
+
{ owletto: "session-refresh-failed" },
|
|
1589
|
+
embeddedOrigin,
|
|
1590
|
+
);
|
|
1591
|
+
} catch {}
|
|
1592
|
+
};
|
|
1593
|
+
if (desktopSessionRefreshAttempted) {
|
|
1594
|
+
reportFailure();
|
|
1595
|
+
return;
|
|
1596
|
+
}
|
|
1597
|
+
desktopSessionRefreshAttempted = true;
|
|
1598
|
+
void getGatewayUrl()
|
|
1599
|
+
.then((gatewayBase) =>
|
|
1600
|
+
refreshDesktopPanelSession({
|
|
1601
|
+
storage: chrome.storage.local,
|
|
1602
|
+
keys: STORAGE_KEYS,
|
|
1603
|
+
gatewayBase,
|
|
1604
|
+
handshake: nativeBridgeHandshake,
|
|
1605
|
+
normalizeGatewayBase,
|
|
1606
|
+
}),
|
|
1607
|
+
)
|
|
1608
|
+
.then((refreshed) => {
|
|
1609
|
+
if (!refreshed) reportFailure();
|
|
1610
|
+
}, reportFailure);
|
|
1611
|
+
return;
|
|
1612
|
+
}
|
|
1613
|
+
const { id: requestedId, op, params } = ev.data ?? {};
|
|
1614
|
+
if (typeof op !== "string") return;
|
|
1615
|
+
const id = `req-${nextId++}`;
|
|
1616
|
+
pending.set(id, { requestedId, source: ev.source });
|
|
1617
|
+
port.postMessage({ id, op, params, origin: embeddedOrigin });
|
|
1618
|
+
});
|
|
1619
|
+
|
|
1620
|
+
port.onMessage.addListener((msg) => {
|
|
1621
|
+
const entry = pending.get(msg.id);
|
|
1622
|
+
if (!entry) return;
|
|
1623
|
+
pending.delete(msg.id);
|
|
1624
|
+
// The frame may have been blanked or remounted while the service worker
|
|
1625
|
+
// was handling the op. Resolve the target fresh through the same
|
|
1626
|
+
// getTarget() the ambient-context publisher uses and drop the reply when
|
|
1627
|
+
// it no longer points at the requesting document — posting with a stale
|
|
1628
|
+
// gateway target origin throws.
|
|
1629
|
+
const target = resolveBridgeReplyTarget({
|
|
1630
|
+
getTarget: getEmbeddedTarget,
|
|
1631
|
+
source: entry.source,
|
|
1632
|
+
});
|
|
1633
|
+
if (!target) return;
|
|
1634
|
+
target.window.postMessage(
|
|
1635
|
+
{
|
|
1636
|
+
id: entry.requestedId,
|
|
1637
|
+
ok: msg.ok,
|
|
1638
|
+
result: msg.result,
|
|
1639
|
+
error: msg.error,
|
|
1640
|
+
},
|
|
1641
|
+
target.origin,
|
|
1642
|
+
);
|
|
1643
|
+
});
|