@leg3ndy/otto-bridge 0.5.8 → 0.5.12

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.
@@ -0,0 +1,79 @@
1
+ import { mkdir, readFile, rm, writeFile } from "node:fs/promises";
2
+ import path from "node:path";
3
+ import { getBridgeHomeDir } from "./config.js";
4
+ export const MANAGED_BRIDGE_EXTENSIONS = {
5
+ whatsappweb: {
6
+ displayName: "WhatsApp Web",
7
+ setupUrl: "https://web.whatsapp.com",
8
+ sessionMode: "safari_managed_tab",
9
+ },
10
+ };
11
+ export function isManagedBridgeExtensionSlug(value) {
12
+ return Object.prototype.hasOwnProperty.call(MANAGED_BRIDGE_EXTENSIONS, value);
13
+ }
14
+ export function getManagedBridgeExtensionDefinition(slug) {
15
+ return MANAGED_BRIDGE_EXTENSIONS[slug];
16
+ }
17
+ export function getBridgeExtensionsDir() {
18
+ return path.join(getBridgeHomeDir(), "extensions");
19
+ }
20
+ function getManagedExtensionStatePath(slug) {
21
+ return path.join(getBridgeExtensionsDir(), `${slug}.json`);
22
+ }
23
+ export async function ensureBridgeExtensionsDir() {
24
+ await mkdir(getBridgeExtensionsDir(), { recursive: true });
25
+ }
26
+ export async function loadManagedBridgeExtensionState(slug) {
27
+ try {
28
+ const raw = await readFile(getManagedExtensionStatePath(slug), "utf8");
29
+ const parsed = JSON.parse(raw);
30
+ if (!parsed || typeof parsed !== "object") {
31
+ return null;
32
+ }
33
+ if (parsed.slug !== slug) {
34
+ return null;
35
+ }
36
+ return parsed;
37
+ }
38
+ catch {
39
+ return null;
40
+ }
41
+ }
42
+ export async function saveManagedBridgeExtensionState(slug, state) {
43
+ await ensureBridgeExtensionsDir();
44
+ await writeFile(getManagedExtensionStatePath(slug), `${JSON.stringify(state, null, 2)}\n`, "utf8");
45
+ }
46
+ export async function removeManagedBridgeExtensionState(slug) {
47
+ await rm(getManagedExtensionStatePath(slug), { force: true });
48
+ }
49
+ export async function buildInstalledManagedExtensionState(slug) {
50
+ const definition = getManagedBridgeExtensionDefinition(slug);
51
+ const existing = await loadManagedBridgeExtensionState(slug);
52
+ return {
53
+ slug,
54
+ displayName: definition.displayName,
55
+ setupUrl: definition.setupUrl,
56
+ sessionMode: definition.sessionMode,
57
+ status: existing?.status || "installed_needs_setup",
58
+ installedAt: existing?.installedAt || new Date().toISOString(),
59
+ lastSetupAt: existing?.lastSetupAt,
60
+ lastStatusCheckAt: existing?.lastStatusCheckAt,
61
+ notes: existing?.notes,
62
+ };
63
+ }
64
+ export function formatManagedBridgeExtensionStatus(status) {
65
+ switch (status) {
66
+ case "installed_needs_setup":
67
+ return "instalada, falta setup";
68
+ case "waiting_login":
69
+ return "aguardando login";
70
+ case "connected":
71
+ return "conectada";
72
+ case "session_expired":
73
+ return "sessao expirada";
74
+ case "not_open":
75
+ return "instalada, aba nao aberta";
76
+ default:
77
+ return status;
78
+ }
79
+ }
package/dist/main.js CHANGED
@@ -2,6 +2,7 @@
2
2
  import { spawn } from "node:child_process";
3
3
  import process from "node:process";
4
4
  import { clearBridgeConfig, getBridgeConfigPath, loadBridgeConfig, normalizeInstalledExtensions, resolveApiBaseUrl, resolveExecutorConfig, saveBridgeConfig, } from "./config.js";
5
+ import { buildInstalledManagedExtensionState, formatManagedBridgeExtensionStatus, getManagedBridgeExtensionDefinition, isManagedBridgeExtensionSlug, loadManagedBridgeExtensionState, removeManagedBridgeExtensionState, saveManagedBridgeExtensionState, } from "./extensions.js";
5
6
  import { pairDevice } from "./pairing.js";
6
7
  import { BridgeRuntime } from "./runtime.js";
7
8
  import { BRIDGE_PACKAGE_NAME, BRIDGE_VERSION, DEFAULT_PAIR_TIMEOUT_SECONDS, DEFAULT_POLL_INTERVAL_MS, } from "./types.js";
@@ -58,6 +59,8 @@ function printUsage() {
58
59
  otto-bridge status
59
60
  otto-bridge extensions --list
60
61
  otto-bridge extensions --install github
62
+ otto-bridge extensions --setup whatsappweb
63
+ otto-bridge extensions --status whatsappweb
61
64
  otto-bridge extensions --uninstall github
62
65
  otto-bridge version
63
66
  otto-bridge update [--tag latest|next] [--dry-run]
@@ -66,7 +69,9 @@ function printUsage() {
66
69
  Examples:
67
70
  otto-bridge pair --api https://api.leg3ndy.com.br --code ABC123
68
71
  otto-bridge run
69
- otto-bridge extensions --install github
72
+ otto-bridge extensions --install whatsappweb
73
+ otto-bridge extensions --setup whatsappweb
74
+ otto-bridge extensions --status whatsappweb
70
75
  otto-bridge extensions --list
71
76
  otto-bridge version
72
77
  otto-bridge update
@@ -94,6 +99,162 @@ function runChildCommand(command, args) {
94
99
  });
95
100
  });
96
101
  }
102
+ function runChildCommandCapture(command, args, options) {
103
+ return new Promise((resolve, reject) => {
104
+ const child = spawn(command, args, {
105
+ stdio: "pipe",
106
+ env: process.env,
107
+ });
108
+ let stdout = "";
109
+ let stderr = "";
110
+ child.stdout?.setEncoding("utf8");
111
+ child.stderr?.setEncoding("utf8");
112
+ child.stdout?.on("data", (chunk) => {
113
+ stdout += String(chunk);
114
+ });
115
+ child.stderr?.on("data", (chunk) => {
116
+ stderr += String(chunk);
117
+ });
118
+ child.on("error", (error) => {
119
+ reject(error);
120
+ });
121
+ child.on("exit", (code) => {
122
+ if (code === 0) {
123
+ resolve({ stdout, stderr });
124
+ return;
125
+ }
126
+ const detail = stderr.trim() || stdout.trim();
127
+ reject(new Error(detail || `${command} exited with code ${code ?? "unknown"}`));
128
+ });
129
+ if (options?.stdin !== undefined) {
130
+ child.stdin?.write(options.stdin);
131
+ }
132
+ child.stdin?.end();
133
+ });
134
+ }
135
+ function escapeAppleScript(value) {
136
+ return value
137
+ .replace(/\\/g, "\\\\")
138
+ .replace(/"/g, '\\"')
139
+ .replace(/\r/g, "\\r")
140
+ .replace(/\n/g, "\\n");
141
+ }
142
+ async function openManagedExtensionSetup(slug) {
143
+ const definition = getManagedBridgeExtensionDefinition(slug);
144
+ if (process.platform !== "darwin") {
145
+ throw new Error(`${definition.displayName} setup automatico esta disponivel apenas no macOS no momento.`);
146
+ }
147
+ await runChildCommand("open", ["-a", "Safari", definition.setupUrl]);
148
+ }
149
+ async function detectManagedWhatsAppWebStatus() {
150
+ if (process.platform !== "darwin") {
151
+ return {
152
+ status: "installed_needs_setup",
153
+ notes: "Status automatico do WhatsApp Web ainda esta disponivel apenas no macOS.",
154
+ };
155
+ }
156
+ const jsCode = `
157
+ (function(){
158
+ const qrVisible = Boolean(
159
+ document.querySelector('[data-testid="qrcode"], canvas[aria-label*="Scan"], canvas[aria-label*="scan"], div[data-ref] canvas')
160
+ );
161
+ const paneVisible = Boolean(document.querySelector('#pane-side, [data-testid="chat-list"]'));
162
+ const searchVisible = Boolean(document.querySelector('[data-testid="chat-list-search"] [contenteditable="true"], div[contenteditable="true"][role="textbox"]'));
163
+ const composerVisible = Boolean(document.querySelector('footer [contenteditable="true"], [data-testid="conversation-compose-box-input"]'));
164
+ return JSON.stringify({
165
+ ok: true,
166
+ title: document.title || '',
167
+ href: location.href || '',
168
+ qrVisible,
169
+ paneVisible,
170
+ searchVisible,
171
+ composerVisible
172
+ });
173
+ })()
174
+ `;
175
+ const script = `
176
+ set targetUrlIncludes to "web.whatsapp.com"
177
+ tell application "Safari"
178
+ if (count of windows) = 0 then return "{\\"ok\\":false,\\"reason\\":\\"not_open\\"}"
179
+ set targetTab to missing value
180
+ repeat with safariWindow in windows
181
+ repeat with safariTab in tabs of safariWindow
182
+ set tabUrl to ""
183
+ try
184
+ set tabUrl to URL of safariTab
185
+ end try
186
+ if tabUrl contains targetUrlIncludes then
187
+ set targetTab to safariTab
188
+ exit repeat
189
+ end if
190
+ end repeat
191
+ if targetTab is not missing value then exit repeat
192
+ end repeat
193
+ if targetTab is missing value then return "{\\"ok\\":false,\\"reason\\":\\"not_open\\"}"
194
+ set scriptResult to do JavaScript "${escapeAppleScript(jsCode)}" in targetTab
195
+ end tell
196
+ return scriptResult
197
+ `;
198
+ try {
199
+ const { stdout } = await runChildCommandCapture("osascript", ["-e", script]);
200
+ const parsed = JSON.parse(stdout.trim() || "{}");
201
+ if (parsed.ok !== true) {
202
+ return {
203
+ status: "not_open",
204
+ notes: "Nenhuma aba do WhatsApp Web foi encontrada no Safari.",
205
+ };
206
+ }
207
+ const qrVisible = parsed.qrVisible === true;
208
+ const paneVisible = parsed.paneVisible === true;
209
+ const searchVisible = parsed.searchVisible === true;
210
+ const composerVisible = parsed.composerVisible === true;
211
+ const title = typeof parsed.title === "string" ? parsed.title : "";
212
+ if (paneVisible || searchVisible || composerVisible) {
213
+ return {
214
+ status: "connected",
215
+ notes: title ? `Sessao conectada em "${title}".` : "Sessao conectada.",
216
+ };
217
+ }
218
+ if (qrVisible) {
219
+ return {
220
+ status: "waiting_login",
221
+ notes: "QR code visivel. Escaneie com o celular para concluir o login.",
222
+ };
223
+ }
224
+ return {
225
+ status: "waiting_login",
226
+ notes: title ? `Aba aberta em "${title}", mas o login ainda nao foi confirmado.` : "Aba aberta, mas o login ainda nao foi confirmado.",
227
+ };
228
+ }
229
+ catch (error) {
230
+ const detail = error instanceof Error ? error.message : String(error);
231
+ if (detail.toLowerCase().includes("allow javascript from apple events")) {
232
+ return {
233
+ status: "waiting_login",
234
+ notes: "Ative 'Allow JavaScript from Apple Events' no Safari para o bridge verificar o status automaticamente.",
235
+ };
236
+ }
237
+ throw error;
238
+ }
239
+ }
240
+ async function detectManagedExtensionStatus(slug, currentState) {
241
+ if (slug === "whatsappweb") {
242
+ const detected = await detectManagedWhatsAppWebStatus();
243
+ const shouldMarkExpired = (detected.status === "waiting_login"
244
+ && (currentState?.status === "connected" || currentState?.status === "session_expired"));
245
+ if (!shouldMarkExpired) {
246
+ return detected;
247
+ }
248
+ return {
249
+ status: "session_expired",
250
+ notes: "A sessao do WhatsApp Web expirou. Rode `otto-bridge extensions --setup whatsappweb` para abrir o QR code novamente.",
251
+ };
252
+ }
253
+ return {
254
+ status: "installed_needs_setup",
255
+ notes: "Esta extensao gerenciada ainda nao possui verificador automatico de status.",
256
+ };
257
+ }
97
258
  async function runPairCommand(args) {
98
259
  const code = option(args, "code");
99
260
  if (!code) {
@@ -153,14 +314,25 @@ async function runStatusCommand() {
153
314
  async function runExtensionsCommand(args) {
154
315
  const config = await loadRequiredBridgeConfig();
155
316
  const installValue = option(args, "install");
317
+ const setupValue = option(args, "setup");
318
+ const statusValue = option(args, "status");
156
319
  const uninstallValue = option(args, "uninstall");
157
- if (installValue && uninstallValue) {
158
- throw new Error("Use apenas uma acao por vez: --install ou --uninstall.");
320
+ const wantsList = args.options.has("list");
321
+ const requestedActions = [
322
+ installValue ? "install" : null,
323
+ setupValue ? "setup" : null,
324
+ statusValue ? "status" : null,
325
+ uninstallValue ? "uninstall" : null,
326
+ wantsList ? "list" : null,
327
+ ].filter(Boolean);
328
+ if (requestedActions.length > 1) {
329
+ throw new Error("Use apenas uma acao por vez: --install, --setup, --status, --uninstall ou --list.");
159
330
  }
160
331
  if (installValue) {
332
+ const installSlugs = normalizeInstalledExtensions(installValue.split(","));
161
333
  const nextExtensions = normalizeInstalledExtensions([
162
334
  ...config.installedExtensions,
163
- ...installValue.split(","),
335
+ ...installSlugs,
164
336
  ]);
165
337
  const added = nextExtensions.filter((item) => !config.installedExtensions.includes(item));
166
338
  if (!added.length) {
@@ -171,10 +343,74 @@ async function runExtensionsCommand(args) {
171
343
  ...config,
172
344
  installedExtensions: nextExtensions,
173
345
  });
346
+ for (const extension of added) {
347
+ if (!isManagedBridgeExtensionSlug(extension)) {
348
+ continue;
349
+ }
350
+ const state = await buildInstalledManagedExtensionState(extension);
351
+ await saveManagedBridgeExtensionState(extension, state);
352
+ }
174
353
  console.log(`[otto-bridge] extensoes instaladas: ${added.join(", ")}`);
354
+ for (const extension of added) {
355
+ if (!isManagedBridgeExtensionSlug(extension)) {
356
+ continue;
357
+ }
358
+ console.log(`[otto-bridge] proximo passo para ${extension}: otto-bridge extensions --setup ${extension}`);
359
+ }
175
360
  console.log("[otto-bridge] rode `otto-bridge run` novamente se quiser sincronizar agora com a web");
176
361
  return;
177
362
  }
363
+ if (setupValue) {
364
+ const slug = normalizeInstalledExtensions([setupValue])[0];
365
+ if (!slug) {
366
+ throw new Error("Informe uma extensao valida em --setup <slug>.");
367
+ }
368
+ if (!config.installedExtensions.includes(slug)) {
369
+ throw new Error(`A extensao ${slug} nao esta instalada. Rode \`otto-bridge extensions --install ${slug}\` primeiro.`);
370
+ }
371
+ if (!isManagedBridgeExtensionSlug(slug)) {
372
+ throw new Error(`A extensao ${slug} nao possui setup interativo gerenciado no bridge.`);
373
+ }
374
+ const definition = getManagedBridgeExtensionDefinition(slug);
375
+ const currentState = await buildInstalledManagedExtensionState(slug);
376
+ await saveManagedBridgeExtensionState(slug, {
377
+ ...currentState,
378
+ status: "waiting_login",
379
+ lastSetupAt: new Date().toISOString(),
380
+ notes: `Setup iniciado para ${definition.displayName}. Escaneie o QR code no Safari e depois rode \`otto-bridge extensions --status ${slug}\`.`,
381
+ });
382
+ await openManagedExtensionSetup(slug);
383
+ console.log(`[otto-bridge] setup iniciado para ${definition.displayName}`);
384
+ console.log(`[otto-bridge] escaneie o QR code no Safari e depois rode: otto-bridge extensions --status ${slug}`);
385
+ return;
386
+ }
387
+ if (statusValue) {
388
+ const slug = normalizeInstalledExtensions([statusValue])[0];
389
+ if (!slug) {
390
+ throw new Error("Informe uma extensao valida em --status <slug>.");
391
+ }
392
+ if (!config.installedExtensions.includes(slug)) {
393
+ throw new Error(`A extensao ${slug} nao esta instalada neste bridge.`);
394
+ }
395
+ if (!isManagedBridgeExtensionSlug(slug)) {
396
+ console.log(`[otto-bridge] ${slug}: instalada (sem status gerenciado)`);
397
+ return;
398
+ }
399
+ const currentState = await buildInstalledManagedExtensionState(slug);
400
+ const detected = await detectManagedExtensionStatus(slug, currentState);
401
+ const nextState = {
402
+ ...currentState,
403
+ status: detected.status,
404
+ lastStatusCheckAt: new Date().toISOString(),
405
+ notes: detected.notes || currentState.notes,
406
+ };
407
+ await saveManagedBridgeExtensionState(slug, nextState);
408
+ console.log(`[otto-bridge] ${slug}: ${formatManagedBridgeExtensionStatus(nextState.status)}`);
409
+ if (nextState.notes) {
410
+ console.log(`[otto-bridge] ${nextState.notes}`);
411
+ }
412
+ return;
413
+ }
178
414
  if (uninstallValue) {
179
415
  const removeSet = new Set(normalizeInstalledExtensions(uninstallValue.split(",")));
180
416
  const nextExtensions = config.installedExtensions.filter((item) => !removeSet.has(item));
@@ -187,6 +423,11 @@ async function runExtensionsCommand(args) {
187
423
  ...config,
188
424
  installedExtensions: nextExtensions,
189
425
  });
426
+ for (const extension of removed) {
427
+ if (isManagedBridgeExtensionSlug(extension)) {
428
+ await removeManagedBridgeExtensionState(extension);
429
+ }
430
+ }
190
431
  console.log(`[otto-bridge] extensoes removidas: ${removed.join(", ")}`);
191
432
  console.log("[otto-bridge] rode `otto-bridge run` novamente se quiser sincronizar agora com a web");
192
433
  return;
@@ -197,7 +438,13 @@ async function runExtensionsCommand(args) {
197
438
  }
198
439
  console.log("[otto-bridge] extensoes instaladas:");
199
440
  for (const extension of config.installedExtensions) {
200
- console.log(`- ${extension}`);
441
+ if (!isManagedBridgeExtensionSlug(extension)) {
442
+ console.log(`- ${extension}`);
443
+ continue;
444
+ }
445
+ const state = await loadManagedBridgeExtensionState(extension);
446
+ const suffix = state ? ` (${formatManagedBridgeExtensionStatus(state.status)})` : "";
447
+ console.log(`- ${extension}${suffix}`);
201
448
  }
202
449
  }
203
450
  async function runUnpairCommand() {
package/dist/types.js CHANGED
@@ -1,5 +1,5 @@
1
1
  export const BRIDGE_CONFIG_VERSION = 1;
2
- export const BRIDGE_VERSION = "0.5.8";
2
+ export const BRIDGE_VERSION = "0.5.12";
3
3
  export const BRIDGE_PACKAGE_NAME = "@leg3ndy/otto-bridge";
4
4
  export const DEFAULT_API_BASE_URL = "http://localhost:8000";
5
5
  export const DEFAULT_POLL_INTERVAL_MS = 3000;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@leg3ndy/otto-bridge",
3
- "version": "0.5.8",
3
+ "version": "0.5.12",
4
4
  "private": false,
5
5
  "type": "module",
6
6
  "description": "Local companion for Otto Bridge device pairing and WebSocket runtime.",