@open-wa/mcp 5.11.1 → 5.12.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/index.cjs CHANGED
@@ -598,6 +598,7 @@ const HEARTBEAT_MS = {
598
598
  };
599
599
  const VERIFICATIONS_PER_HOST_PER_MINUTE = 10;
600
600
  const MAINTENANCE_MS = 3e4;
601
+ const OWN_SEND_GRACE_MS = 3e3;
601
602
  const object = (value) => value && typeof value === "object" ? value : {};
602
603
  const messageId = (kind) => `msg_${kind ? `${kind}_` : ""}${(0, node_crypto.randomBytes)(16).toString("hex")}`;
603
604
  const iso = (ms) => ms === void 0 ? null : new Date(ms).toISOString();
@@ -611,6 +612,8 @@ var McpEventsService = class {
611
612
  this.verificationBudget = /* @__PURE__ */ new Map();
612
613
  this.streams = /* @__PURE__ */ new Set();
613
614
  this.lastMaintenance = 0;
615
+ this.paused = /* @__PURE__ */ new Map();
616
+ this.ownSends = /* @__PURE__ */ new Map();
614
617
  this.closing = false;
615
618
  this.store = new McpEventStore(options.storePath);
616
619
  this.post = options.post ?? postCallback;
@@ -925,7 +928,68 @@ var McpEventsService = class {
925
928
  body: JSON.stringify(this.occurrence(event))
926
929
  });
927
930
  }
931
+ /** Records a message open-wa sent itself, so it isn't mistaken for a person replying. */
932
+ noteOwnSend(messageId) {
933
+ const now = Date.now();
934
+ this.ownSends.set(messageId, now + 6e5);
935
+ if (this.ownSends.size > 5e3) {
936
+ for (const [id, expiry] of this.ownSends) if (expiry <= now || this.ownSends.size > 5e3) this.ownSends.delete(id);
937
+ }
938
+ }
939
+ pauseChat(chatId, ms = this.options.operatorPauseMs ?? 18e5, reason = "operator") {
940
+ if (ms > 0) this.paused.set(chatId, {
941
+ until: Date.now() + ms,
942
+ reason
943
+ });
944
+ }
945
+ resumeChat(chatId) {
946
+ this.paused.delete(chatId);
947
+ }
948
+ chatStatus(chatId) {
949
+ const pause = this.pausedFor(chatId);
950
+ return {
951
+ chatId,
952
+ paused: Boolean(pause),
953
+ until: pause ? new Date(pause.until).toISOString() : null,
954
+ reason: pause?.reason ?? null
955
+ };
956
+ }
957
+ pausedFor(chatId) {
958
+ if (typeof chatId !== "string") return;
959
+ const pause = this.paused.get(chatId);
960
+ if (pause && pause.until <= Date.now()) {
961
+ this.paused.delete(chatId);
962
+ return;
963
+ }
964
+ return pause;
965
+ }
966
+ /**
967
+ * A message from this account that open-wa didn't send was typed by a person in a WhatsApp app.
968
+ * WhatsApp marks messages created on open-wa's own linked device as local, which also covers REST sends.
969
+ * Without that flag, wait briefly: WhatsApp reports a send before the send call returns its ID.
970
+ */
971
+ observeOwnMessage(payload) {
972
+ if ((this.options.operatorPauseMs ?? 18e5) <= 0) return;
973
+ const message = object(object(payload).message);
974
+ if (message.fromMe !== true || typeof message.id !== "string" || message.local === true) return;
975
+ const id = message.id;
976
+ const chatId = typeof message.chatId === "string" ? message.chatId : typeof message.to === "string" ? message.to : void 0;
977
+ if (!chatId) return;
978
+ const decide = () => {
979
+ if (this.closing) return;
980
+ const expiry = this.ownSends.get(id);
981
+ if (expiry !== void 0 && expiry > Date.now()) return;
982
+ this.pauseChat(chatId, void 0, "operator");
983
+ this.log("mcp_event_operator_pause", "message.any");
984
+ };
985
+ if (message.local === false) decide();
986
+ else setTimeout(decide, OWN_SEND_GRACE_MS).unref?.();
987
+ }
928
988
  publish(name, payload) {
989
+ if (name === "message.any") {
990
+ this.observeOwnMessage(payload);
991
+ return;
992
+ }
929
993
  const owner = this.options.owner();
930
994
  const contract = (0, _open_wa_schema.getEventContract)(name);
931
995
  if (this.closing || !owner || !contract?.mcp) return;
@@ -935,6 +999,7 @@ var McpEventsService = class {
935
999
  return;
936
1000
  }
937
1001
  const data = projected.data;
1002
+ if (name === "message.received" && this.pausedFor(data.chatId)) return;
938
1003
  const runtime = object(payload);
939
1004
  const occurredAt = object(runtime.ctx).ts ?? runtime.ts;
940
1005
  if (typeof occurredAt !== "number" || !Number.isFinite(occurredAt)) {
@@ -1084,8 +1149,748 @@ var McpEventsService = class {
1084
1149
  }
1085
1150
  };
1086
1151
  //#endregion
1152
+ //#region src/oauth/oauth.ts
1153
+ const SCOPE = "mcp";
1154
+ const CODE_TTL_MS = 6e5;
1155
+ const ACCESS_TTL_MS = 36e5;
1156
+ const REFRESH_TTL_MS = 2592e6;
1157
+ const MAX_CLIENTS = 200;
1158
+ const KEY_ATTEMPTS_PER_MINUTE = 10;
1159
+ const APPROVAL_TTL_MS = 6e5;
1160
+ const APPROVAL_ATTEMPTS = 5;
1161
+ const CODES_PER_IP_PER_10_MINUTES = 5;
1162
+ const CODES_PER_HOUR = 30;
1163
+ /** Unambiguous characters: no 0/O, 1/I/L or U. Eight of them give about 39 bits. */
1164
+ const CODE_ALPHABET = "ABCDEFGHJKMNPQRSTVWXYZ23456789";
1165
+ const pick = (length) => Array.from({ length }, () => CODE_ALPHABET[(0, node_crypto.randomInt)(30)]).join("");
1166
+ const normalizeCode = (value) => value.toUpperCase().replace(/[^A-Z0-9]/g, "");
1167
+ /** The shared open-wa palette (docs and dashboard: packages/ui-components/src/theme.css), laid out after the ui-sdk.dev sink. */
1168
+ const PAGE_CSS = `:root{--paper:#f9fcff;--raised:#fff;--muted:#eef4fd;--selected:#dde8ff;--ink:#162748;--ink-2:#56647f;--ink-3:#8190ab;--rule:#dde6f3;--accent:#214be6;--accent-ink:#fff;--ring:#5c86f3;--danger:#c63e5c;
1169
+ --shadow:0 1px 2px #1627480f,0 12px 32px -16px #16274833;--sans:"Geist","DM Sans",ui-sans-serif,system-ui,-apple-system,"Segoe UI",sans-serif;--mono:"Geist Mono",ui-monospace,"SF Mono",Menlo,Consolas,monospace}
1170
+ @media (prefers-color-scheme:dark){:root{--paper:#0c1832;--raised:#122343;--muted:#162b50;--selected:#1d3564;--ink:#eaf1ff;--ink-2:#9eb0d2;--ink-3:#7389b0;--rule:#284570;--accent:#8cb0ff;--accent-ink:#0c1832;--ring:#8cb0ff;--danger:#ff7690;--shadow:0 12px 32px -14px #000a}}
1171
+ *{box-sizing:border-box}
1172
+ body{margin:0;min-height:100vh;display:flex;flex-direction:column;align-items:center;justify-content:center;gap:14px;padding:32px 16px;background:var(--paper);color:var(--ink);font:15px/1.5 var(--sans);-webkit-font-smoothing:antialiased}
1173
+ .card{width:100%;max-width:420px;background:var(--raised);border:1px solid var(--rule);border-radius:16px;box-shadow:var(--shadow);padding:28px}
1174
+ .brand{display:flex;align-items:center;gap:8px;color:var(--ink-3);font-size:13px;font-weight:500;margin-bottom:18px}
1175
+ .brand i{width:22px;height:22px;border-radius:7px;background:var(--accent);display:inline-grid;place-items:center;color:var(--accent-ink);font:600 12px var(--mono);font-style:normal}
1176
+ h1{font-size:22px;line-height:1.25;letter-spacing:-.01em;margin:0 0 6px}
1177
+ .lede{color:var(--ink-2);margin:0 0 14px}
1178
+ .perms{list-style:none;padding:12px 14px;margin:0 0 18px;border:1px solid var(--rule);border-radius:12px;background:var(--muted);display:grid;gap:6px;font-size:14px}
1179
+ .perms li{display:flex;gap:8px;align-items:baseline}.perms li::before{content:"";flex:none;width:6px;height:6px;border-radius:50%;background:var(--accent);transform:translateY(-2px)}
1180
+ .step{display:grid;gap:10px}
1181
+ .step-head{display:flex;justify-content:space-between;align-items:center;gap:8px}
1182
+ .label{font-size:13px;font-weight:600}
1183
+ .badge{font:500 12px var(--mono);padding:2px 8px;border-radius:999px;border:1px solid var(--rule);color:var(--ink-2)}
1184
+ .hint{margin:0;color:var(--ink-2);font-size:13.5px}
1185
+ .input{width:100%;height:40px;border:1px solid var(--rule);background:var(--raised);color:var(--ink);border-radius:10px;padding:0 12px;font:14px var(--sans);outline:none;transition:border-color .12s,box-shadow .12s}
1186
+ .input::placeholder{color:var(--ink-3)}
1187
+ .input:focus-visible{border-color:var(--ring);box-shadow:0 0 0 3px color-mix(in oklab,var(--ring) 25%,transparent)}
1188
+ .input.code{height:52px;text-align:center;font:600 22px var(--mono);letter-spacing:.18em;text-transform:uppercase}
1189
+ .btn{display:inline-flex;align-items:center;justify-content:center;gap:6px;height:36px;padding:0 14px;border:1px solid var(--rule);background:var(--raised);color:var(--ink);border-radius:10px;font:500 14px var(--sans);cursor:pointer;white-space:nowrap;transition:background .12s,border-color .12s,transform .12s cubic-bezier(.22,1,.36,1)}
1190
+ .btn:hover{border-color:var(--ink-3)}.btn:active{transform:scale(.97)}
1191
+ .btn:focus-visible{outline:2px solid var(--ring);outline-offset:2px}
1192
+ .btn.primary{background:var(--accent);border-color:var(--accent);color:var(--accent-ink)}
1193
+ .btn.primary:hover{background:color-mix(in oklch,var(--accent) 88%,var(--ink))}
1194
+ .btn.ghost{background:transparent;border-color:transparent;color:var(--ink-2)}
1195
+ .btn.ghost:hover{background:color-mix(in oklab,var(--ink) 7%,transparent);color:var(--ink)}
1196
+ .btn.danger{color:var(--danger)}
1197
+ .btn.wide{width:100%;height:40px}
1198
+ .alert{margin:0 0 14px;padding:10px 12px;border-radius:10px;font-size:13.5px;font-weight:500;color:var(--danger);background:color-mix(in oklab,var(--danger) 10%,transparent);border:1px solid color-mix(in oklab,var(--danger) 30%,transparent)}
1199
+ .alt{margin-top:16px;border-top:1px solid var(--rule);padding-top:12px}
1200
+ .alt summary{cursor:pointer;color:var(--ink-2);font-size:13.5px;list-style:none;display:flex;align-items:center;gap:6px}
1201
+ .alt summary::-webkit-details-marker{display:none}
1202
+ .alt summary::before{content:"›";display:inline-block;transition:transform .12s;font-size:16px;line-height:1}
1203
+ .alt[open] summary::before{transform:rotate(90deg)}
1204
+ .alt[open]{display:grid;gap:10px}
1205
+ .warn{margin:0;font-size:12.5px;color:var(--ink-2);padding:8px 10px;border-radius:10px;background:var(--selected)}
1206
+ .row{display:flex;justify-content:space-between;align-items:center;gap:8px;margin-top:16px}
1207
+ .return{font-size:12.5px;color:var(--ink-3)}
1208
+ code{font:12.5px var(--mono);color:var(--ink-2)}
1209
+ .foot{margin:0;font-size:12px;color:var(--ink-3);text-align:center}`;
1210
+ const BRAND = "<div class=\"brand\"><i>wa</i>open-wa</div>";
1211
+ const random = (bytes = 32) => (0, node_crypto.randomBytes)(bytes).toString("base64url");
1212
+ const digest = (value) => (0, node_crypto.createHash)("sha256").update(value).digest("hex");
1213
+ const s256 = (verifier) => (0, node_crypto.createHash)("sha256").update(verifier).digest("base64url");
1214
+ const escape = (value) => value.replace(/[&<>"']/g, (ch) => `&#${ch.charCodeAt(0)};`);
1215
+ function sameSecret(a, b) {
1216
+ const left = Buffer.from(digest(a));
1217
+ const right = Buffer.from(digest(b));
1218
+ return (0, node_crypto.timingSafeEqual)(left, right);
1219
+ }
1220
+ function allowedRedirect(value) {
1221
+ if (typeof value !== "string") return false;
1222
+ try {
1223
+ const url = new URL(value);
1224
+ if (url.hash) return false;
1225
+ if (url.protocol === "https:") return true;
1226
+ return url.protocol === "http:" && [
1227
+ "localhost",
1228
+ "127.0.0.1",
1229
+ "[::1]"
1230
+ ].includes(url.hostname);
1231
+ } catch {
1232
+ return false;
1233
+ }
1234
+ }
1235
+ var McpOAuth = class {
1236
+ constructor(options) {
1237
+ this.options = options;
1238
+ this.attempts = /* @__PURE__ */ new Map();
1239
+ this.approvals = /* @__PURE__ */ new Map();
1240
+ this.codeRequests = /* @__PURE__ */ new Map();
1241
+ this.codesIssued = [];
1242
+ (0, node_fs.mkdirSync)((0, node_path.dirname)(options.storePath), {
1243
+ recursive: true,
1244
+ mode: 448
1245
+ });
1246
+ this.db = new node_sqlite.DatabaseSync(options.storePath);
1247
+ (0, node_fs.chmodSync)(options.storePath, 384);
1248
+ this.db.exec(`
1249
+ PRAGMA journal_mode=WAL;
1250
+ CREATE TABLE IF NOT EXISTS oauth_clients (
1251
+ client_id TEXT PRIMARY KEY, secret_hash TEXT, redirect_uris TEXT NOT NULL, client_name TEXT,
1252
+ auth_method TEXT NOT NULL, created_at INTEGER NOT NULL
1253
+ );
1254
+ CREATE TABLE IF NOT EXISTS oauth_codes (
1255
+ code_hash TEXT PRIMARY KEY, client_id TEXT NOT NULL, redirect_uri TEXT NOT NULL, challenge TEXT NOT NULL,
1256
+ scope TEXT NOT NULL, resource TEXT NOT NULL, owner TEXT NOT NULL, expires_at INTEGER NOT NULL
1257
+ );
1258
+ CREATE TABLE IF NOT EXISTS oauth_tokens (
1259
+ token_hash TEXT PRIMARY KEY, kind TEXT NOT NULL, client_id TEXT NOT NULL, scope TEXT NOT NULL,
1260
+ resource TEXT NOT NULL, owner TEXT NOT NULL, expires_at INTEGER NOT NULL
1261
+ );
1262
+ `);
1263
+ }
1264
+ /** The public origin clients see, for metadata and token audience. */
1265
+ base(c) {
1266
+ if (this.options.publicUrl) return this.options.publicUrl.replace(/\/+$/, "");
1267
+ const url = new URL(c.req.url);
1268
+ return `${c.req.header("x-forwarded-proto")?.split(",")[0]?.trim() || url.protocol.replace(":", "")}://${c.req.header("x-forwarded-host")?.split(",")[0]?.trim() || c.req.header("host") || url.host}`;
1269
+ }
1270
+ resource(c) {
1271
+ return `${this.base(c)}${this.options.mcpPath}`;
1272
+ }
1273
+ /** The `WWW-Authenticate` challenge that sends a client to the protected-resource metadata. */
1274
+ challenge(c) {
1275
+ return `Bearer resource_metadata="${this.base(c)}/.well-known/oauth-protected-resource${this.options.mcpPath}", scope="${SCOPE}"`;
1276
+ }
1277
+ /** True when the request carries a live access token for this owner and resource. */
1278
+ verify(c) {
1279
+ const header = c.req.header("authorization") ?? "";
1280
+ const match = /^Bearer\s+(\S+)$/i.exec(header);
1281
+ if (!match) return false;
1282
+ const row = this.db.prepare("SELECT * FROM oauth_tokens WHERE token_hash=? AND kind='access'").get(digest(match[1]));
1283
+ return Boolean(row && row.expires_at > Date.now() && row.owner === this.options.owner() && row.resource === this.resource(c));
1284
+ }
1285
+ routes(app) {
1286
+ const protectedResource = (c) => c.json({
1287
+ resource: this.resource(c),
1288
+ authorization_servers: [this.base(c)],
1289
+ bearer_methods_supported: ["header"],
1290
+ scopes_supported: [SCOPE],
1291
+ resource_name: "open-wa"
1292
+ });
1293
+ const serverMetadata = (c) => {
1294
+ const base = this.base(c);
1295
+ return c.json({
1296
+ issuer: base,
1297
+ authorization_endpoint: `${base}/oauth/authorize`,
1298
+ token_endpoint: `${base}/oauth/token`,
1299
+ registration_endpoint: `${base}/oauth/register`,
1300
+ revocation_endpoint: `${base}/oauth/revoke`,
1301
+ response_types_supported: ["code"],
1302
+ grant_types_supported: ["authorization_code", "refresh_token"],
1303
+ code_challenge_methods_supported: ["S256"],
1304
+ scopes_supported: [SCOPE],
1305
+ token_endpoint_auth_methods_supported: [
1306
+ "none",
1307
+ "client_secret_post",
1308
+ "client_secret_basic"
1309
+ ]
1310
+ });
1311
+ };
1312
+ app.get("/.well-known/oauth-protected-resource", protectedResource);
1313
+ app.get(`/.well-known/oauth-protected-resource${this.options.mcpPath}`, protectedResource);
1314
+ app.get("/.well-known/oauth-authorization-server", serverMetadata);
1315
+ app.get("/.well-known/openid-configuration", serverMetadata);
1316
+ app.post("/oauth/register", (c) => this.register(c));
1317
+ app.get("/oauth/authorize", (c) => this.authorizePage(c));
1318
+ app.post("/oauth/authorize", (c) => this.authorizeDecision(c));
1319
+ app.post("/oauth/token", (c) => this.token(c));
1320
+ app.post("/oauth/revoke", (c) => this.revoke(c));
1321
+ }
1322
+ async register(c) {
1323
+ let body;
1324
+ try {
1325
+ body = await c.req.json();
1326
+ } catch {
1327
+ return c.json({
1328
+ error: "invalid_client_metadata",
1329
+ error_description: "Send client metadata as JSON"
1330
+ }, 400);
1331
+ }
1332
+ const redirectUris = Array.isArray(body.redirect_uris) ? body.redirect_uris : [];
1333
+ if (!redirectUris.length || !redirectUris.every(allowedRedirect)) return c.json({
1334
+ error: "invalid_redirect_uri",
1335
+ error_description: "Redirect URIs must be HTTPS, or HTTP on a loopback address"
1336
+ }, 400);
1337
+ const method = typeof body.token_endpoint_auth_method === "string" ? body.token_endpoint_auth_method : "none";
1338
+ if (![
1339
+ "none",
1340
+ "client_secret_post",
1341
+ "client_secret_basic"
1342
+ ].includes(method)) return c.json({
1343
+ error: "invalid_client_metadata",
1344
+ error_description: "Unsupported token_endpoint_auth_method"
1345
+ }, 400);
1346
+ if (Number(this.db.prepare("SELECT COUNT(*) AS n FROM oauth_clients").get().n) >= MAX_CLIENTS) this.db.prepare(`DELETE FROM oauth_clients WHERE client_id = (SELECT client_id FROM oauth_clients
1347
+ WHERE client_id NOT IN (SELECT client_id FROM oauth_tokens WHERE expires_at > ?) ORDER BY created_at LIMIT 1)`).run(Date.now());
1348
+ const clientId = `owa_client_${random(16)}`;
1349
+ const secret = method === "none" ? void 0 : `owa_cs_${random()}`;
1350
+ const clientName = typeof body.client_name === "string" ? body.client_name.slice(0, 120) : null;
1351
+ this.db.prepare("INSERT INTO oauth_clients VALUES (?,?,?,?,?,?)").run(clientId, secret ? digest(secret) : null, JSON.stringify(redirectUris), clientName, method, Date.now());
1352
+ return c.json({
1353
+ client_id: clientId,
1354
+ client_id_issued_at: Math.floor(Date.now() / 1e3),
1355
+ redirect_uris: redirectUris,
1356
+ token_endpoint_auth_method: method,
1357
+ grant_types: ["authorization_code", "refresh_token"],
1358
+ response_types: ["code"],
1359
+ ...clientName ? { client_name: clientName } : {},
1360
+ ...secret ? {
1361
+ client_secret: secret,
1362
+ client_secret_expires_at: 0
1363
+ } : {}
1364
+ }, 201);
1365
+ }
1366
+ client(clientId) {
1367
+ if (typeof clientId !== "string") return;
1368
+ const row = this.db.prepare("SELECT * FROM oauth_clients WHERE client_id=?").get(clientId);
1369
+ return row ? {
1370
+ ...row,
1371
+ redirects: JSON.parse(row.redirect_uris)
1372
+ } : void 0;
1373
+ }
1374
+ request(params, c) {
1375
+ const client = this.client(params.client_id);
1376
+ if (!client) return { fatal: "This app is not registered with this open-wa server." };
1377
+ if (!params.redirect_uri || !client.redirects.includes(params.redirect_uri)) return { fatal: "The redirect address does not match the app registration." };
1378
+ const fail = (error, description) => ({ redirect: this.redirect(params.redirect_uri, {
1379
+ error,
1380
+ error_description: description,
1381
+ state: params.state
1382
+ }, c) });
1383
+ if (params.response_type !== "code") return fail("unsupported_response_type", "Only the code response type is supported");
1384
+ if (!params.code_challenge || params.code_challenge_method !== "S256") return fail("invalid_request", "PKCE with S256 is required");
1385
+ const resource = params.resource || this.resource(c);
1386
+ if (resource !== this.resource(c)) return fail("invalid_target", "Unknown resource");
1387
+ const scope = params.scope?.split(" ").includes(SCOPE) || !params.scope ? SCOPE : "";
1388
+ if (!scope) return fail("invalid_scope", `Request the ${SCOPE} scope`);
1389
+ return {
1390
+ client,
1391
+ redirectUri: params.redirect_uri,
1392
+ challenge: params.code_challenge,
1393
+ state: params.state,
1394
+ scope,
1395
+ resource
1396
+ };
1397
+ }
1398
+ redirect(target, params, c) {
1399
+ const url = new URL(target);
1400
+ for (const [key, value] of Object.entries(params)) if (value !== void 0) url.searchParams.set(key, value);
1401
+ url.searchParams.set("iss", this.base(c));
1402
+ return url.toString();
1403
+ }
1404
+ /**
1405
+ * `redirectOrigin` is the client's registered redirect origin. Browsers apply `form-action` to the redirect
1406
+ * that follows the form post too, so without it the approval would never reach the client.
1407
+ */
1408
+ page(c, title, body, status = 200, redirectOrigin) {
1409
+ c.header("X-Frame-Options", "DENY");
1410
+ c.header("Content-Security-Policy", `default-src 'none'; style-src 'unsafe-inline'; form-action 'self'${redirectOrigin ? ` ${redirectOrigin}` : ""}; frame-ancestors 'none'`);
1411
+ c.header("Cache-Control", "no-store");
1412
+ c.header("Referrer-Policy", "no-referrer");
1413
+ return c.html(`<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
1414
+ <meta name="color-scheme" content="light dark"><title>${escape(title)}</title><style>${PAGE_CSS}</style></head>
1415
+ <body><main class="card">${BRAND}${body}</main><p class="foot">open-wa · this page is served by the WhatsApp session itself</p></body></html>`, status);
1416
+ }
1417
+ consent(c, params, error, status = 200, sent) {
1418
+ const req = this.request(params, c);
1419
+ if ("fatal" in req) return this.page(c, "Sign-in failed", `<h1>Sign-in failed</h1><p class="lede">${escape(req.fatal)}</p>`, 400);
1420
+ if ("redirect" in req) return c.redirect(req.redirect);
1421
+ const name = req.client.client_name || "An MCP client";
1422
+ const host = new URL(req.redirectUri).host;
1423
+ const requestId = sent ?? params.request_id;
1424
+ const waiting = Boolean(requestId && this.approvals.has(requestId));
1425
+ const hidden = [
1426
+ "client_id",
1427
+ "redirect_uri",
1428
+ "response_type",
1429
+ "code_challenge",
1430
+ "code_challenge_method",
1431
+ "state",
1432
+ "scope",
1433
+ "resource"
1434
+ ].map((key) => params[key] === void 0 ? "" : `<input type="hidden" name="${key}" value="${escape(params[key])}">`).join("");
1435
+ const codeStep = waiting ? `<section class="step">
1436
+ <div class="step-head"><span class="label">One-time code</span><span class="badge">Request ${escape(requestId)}</span></div>
1437
+ <p class="hint">Find the code for request ${escape(requestId)} where this server sends approval codes: its log, its webhook, or its own WhatsApp chat.</p>
1438
+ <input type="hidden" name="request_id" value="${escape(requestId)}">
1439
+ <input class="input code" id="approval_code" name="approval_code" autocomplete="one-time-code" autocapitalize="characters" spellcheck="false" placeholder="XXXX-XXXX" maxlength="9" aria-label="One-time code" autofocus>
1440
+ <button class="btn primary wide" type="submit" name="decision" value="approve">Approve</button>
1441
+ <button class="btn ghost wide" type="submit" name="decision" value="send_code">Send a new code</button>
1442
+ </section>` : `<section class="step">
1443
+ <p class="hint">Approve with a one-time code. open-wa sends it to the person running this server, never to this page.</p>
1444
+ <button class="btn primary wide" type="submit" name="decision" value="send_code">Get a one-time code</button>
1445
+ </section>`;
1446
+ return this.page(c, `Connect ${name} to open-wa`, `<h1>Connect ${escape(name)}</h1>
1447
+ <p class="lede">${escape(name)} wants to use this WhatsApp session.</p>
1448
+ <ul class="perms"><li>Read messages and chats</li><li>Send messages as this account</li><li>Receive new message events</li></ul>
1449
+ ${error ? `<p class="alert" role="alert">${escape(error)}</p>` : ""}
1450
+ <form method="post" action="/oauth/authorize">${hidden}
1451
+ ${codeStep}
1452
+ <details class="alt"${params.api_key !== void 0 && !waiting ? " open" : ""}><summary>Approve with the Easy API key instead</summary>
1453
+ <p class="warn">Only on a connection you trust. A proxy or tunnel in front of open-wa can read what you type here.</p>
1454
+ <input class="input" id="api_key" name="api_key" type="password" autocomplete="current-password" placeholder="Easy API key" aria-label="Easy API key">
1455
+ <button class="btn wide" type="submit" name="decision" value="approve">Approve with key</button>
1456
+ </details>
1457
+ <div class="row"><span class="return">Returns to <code>${escape(host)}</code></span><button class="btn ghost danger" type="submit" name="decision" value="deny">Deny</button></div>
1458
+ </form>`, status, new URL(req.redirectUri).origin);
1459
+ }
1460
+ authorizePage(c) {
1461
+ return this.consent(c, c.req.query());
1462
+ }
1463
+ clientIp(c) {
1464
+ return c.req.header("cf-connecting-ip") || c.req.header("x-forwarded-for")?.split(",")[0]?.trim() || "local";
1465
+ }
1466
+ /** Ties a code to the exact authorization request, so it can't approve another client or flow. */
1467
+ binding(req) {
1468
+ return digest([
1469
+ req.client.client_id,
1470
+ req.redirectUri,
1471
+ req.challenge,
1472
+ req.state ?? "",
1473
+ req.resource
1474
+ ].join("\0"));
1475
+ }
1476
+ sendCode(c, form, req) {
1477
+ const now = Date.now();
1478
+ for (const [id, pending] of this.approvals) if (pending.expiresAt <= now) this.approvals.delete(id);
1479
+ const ip = this.clientIp(c);
1480
+ const recent = (this.codeRequests.get(ip) ?? []).filter((at) => at > now - 6e5);
1481
+ this.codesIssued = this.codesIssued.filter((at) => at > now - 36e5);
1482
+ if (recent.length >= CODES_PER_IP_PER_10_MINUTES || this.codesIssued.length >= CODES_PER_HOUR) return this.consent(c, {
1483
+ ...form,
1484
+ request_id: void 0
1485
+ }, "Too many codes were requested. Wait a few minutes and try again.", 429);
1486
+ this.codeRequests.set(ip, [...recent, now]);
1487
+ if (this.codeRequests.size > 1e3) this.codeRequests.delete(this.codeRequests.keys().next().value);
1488
+ this.codesIssued.push(now);
1489
+ if (form.request_id) this.approvals.delete(form.request_id);
1490
+ const requestId = pick(4);
1491
+ const code = pick(8);
1492
+ const expiresAt = now + APPROVAL_TTL_MS;
1493
+ this.approvals.set(requestId, {
1494
+ codeHash: digest(code),
1495
+ binding: this.binding(req),
1496
+ attempts: 0,
1497
+ expiresAt
1498
+ });
1499
+ try {
1500
+ this.options.onApprovalCode?.({
1501
+ requestId,
1502
+ code: `${code.slice(0, 4)}-${code.slice(4)}`,
1503
+ clientName: req.client.client_name || "An MCP client",
1504
+ redirectHost: new URL(req.redirectUri).host,
1505
+ expiresAt
1506
+ });
1507
+ } catch {}
1508
+ return this.consent(c, form, void 0, 200, requestId);
1509
+ }
1510
+ checkCode(form, req) {
1511
+ const pending = form.request_id ? this.approvals.get(form.request_id) : void 0;
1512
+ if (!pending || pending.expiresAt <= Date.now() || pending.binding !== this.binding(req)) {
1513
+ if (form.request_id) this.approvals.delete(form.request_id);
1514
+ return "That code has expired or belongs to another request. Get a new code.";
1515
+ }
1516
+ pending.attempts += 1;
1517
+ if ((0, node_crypto.timingSafeEqual)(Buffer.from(digest(normalizeCode(form.approval_code ?? ""))), Buffer.from(pending.codeHash))) {
1518
+ this.approvals.delete(form.request_id);
1519
+ return;
1520
+ }
1521
+ if (pending.attempts >= APPROVAL_ATTEMPTS) {
1522
+ this.approvals.delete(form.request_id);
1523
+ return "That code is not right, and this request has no attempts left. Get a new code.";
1524
+ }
1525
+ return "That code is not right.";
1526
+ }
1527
+ async authorizeDecision(c) {
1528
+ const form = Object.fromEntries(Object.entries(await c.req.parseBody()).map(([key, value]) => [key, typeof value === "string" ? value : void 0]));
1529
+ const req = this.request(form, c);
1530
+ if ("fatal" in req || "redirect" in req) return this.consent(c, form);
1531
+ if (form.decision === "send_code") return this.sendCode(c, form, req);
1532
+ if (form.decision !== "approve") return c.redirect(this.redirect(req.redirectUri, {
1533
+ error: "access_denied",
1534
+ state: req.state
1535
+ }, c));
1536
+ const ip = this.clientIp(c);
1537
+ const now = Date.now();
1538
+ const recent = (this.attempts.get(ip) ?? []).filter((at) => at > now - 6e4);
1539
+ if (recent.length >= KEY_ATTEMPTS_PER_MINUTE) return this.consent(c, form, "Too many attempts. Wait a minute and try again.", 429);
1540
+ const failed = (message) => {
1541
+ this.attempts.set(ip, [...recent, now]);
1542
+ if (this.attempts.size > 1e3) this.attempts.delete(this.attempts.keys().next().value);
1543
+ return this.consent(c, form, message, 401);
1544
+ };
1545
+ if (form.approval_code?.trim()) {
1546
+ const problem = this.checkCode(form, req);
1547
+ if (problem) return failed(problem);
1548
+ } else {
1549
+ const apiKey = this.options.apiKey();
1550
+ if (!form.api_key) return this.consent(c, form, "Enter the one-time code, or approve with the Easy API key.", 401);
1551
+ if (!apiKey || !sameSecret(form.api_key, apiKey)) return failed("That key is not this server’s Easy API key.");
1552
+ }
1553
+ const code = random();
1554
+ this.db.prepare("INSERT INTO oauth_codes VALUES (?,?,?,?,?,?,?,?)").run(digest(code), req.client.client_id, req.redirectUri, req.challenge, req.scope, req.resource, this.options.owner(), now + CODE_TTL_MS);
1555
+ return c.redirect(this.redirect(req.redirectUri, {
1556
+ code,
1557
+ state: req.state
1558
+ }, c));
1559
+ }
1560
+ authenticateClient(c, form) {
1561
+ let clientId = form.client_id;
1562
+ let secret = form.client_secret;
1563
+ const basic = /^Basic\s+(\S+)$/i.exec(c.req.header("authorization") ?? "");
1564
+ if (basic) {
1565
+ const [id, pass] = Buffer.from(basic[1], "base64").toString("utf8").split(":");
1566
+ clientId = decodeURIComponent(id ?? "");
1567
+ secret = decodeURIComponent(pass ?? "");
1568
+ }
1569
+ const client = this.client(clientId);
1570
+ if (!client) return;
1571
+ if (client.auth_method === "none") return client;
1572
+ return secret && client.secret_hash && sameSecret(digest(secret), client.secret_hash) ? client : void 0;
1573
+ }
1574
+ issue(clientId, scope, resource, owner) {
1575
+ const access = `owa_at_${random()}`;
1576
+ const refresh = `owa_rt_${random()}`;
1577
+ const insert = this.db.prepare("INSERT INTO oauth_tokens VALUES (?,?,?,?,?,?,?)");
1578
+ insert.run(digest(access), "access", clientId, scope, resource, owner, Date.now() + ACCESS_TTL_MS);
1579
+ insert.run(digest(refresh), "refresh", clientId, scope, resource, owner, Date.now() + REFRESH_TTL_MS);
1580
+ this.db.prepare("DELETE FROM oauth_tokens WHERE expires_at <= ?").run(Date.now());
1581
+ return {
1582
+ access_token: access,
1583
+ token_type: "Bearer",
1584
+ expires_in: ACCESS_TTL_MS / 1e3,
1585
+ refresh_token: refresh,
1586
+ scope
1587
+ };
1588
+ }
1589
+ async token(c) {
1590
+ c.header("Cache-Control", "no-store");
1591
+ const form = Object.fromEntries(Object.entries(await c.req.parseBody()).map(([key, value]) => [key, typeof value === "string" ? value : void 0]));
1592
+ const client = this.authenticateClient(c, form);
1593
+ if (!client) return c.json({ error: "invalid_client" }, 401);
1594
+ const owner = this.options.owner();
1595
+ if (!owner) return c.json({
1596
+ error: "invalid_grant",
1597
+ error_description: "The server has no Easy API key"
1598
+ }, 400);
1599
+ if (form.grant_type === "authorization_code") {
1600
+ const hash = digest(form.code ?? "");
1601
+ const row = this.db.prepare("SELECT * FROM oauth_codes WHERE code_hash=?").get(hash);
1602
+ this.db.prepare("DELETE FROM oauth_codes WHERE code_hash=? OR expires_at <= ?").run(hash, Date.now());
1603
+ if (!row || row.expires_at <= Date.now() || row.client_id !== client.client_id || row.redirect_uri !== form.redirect_uri || !form.code_verifier || s256(form.code_verifier) !== row.challenge || row.owner !== owner || form.resource && form.resource !== row.resource) return c.json({ error: "invalid_grant" }, 400);
1604
+ return c.json(this.issue(client.client_id, row.scope, row.resource, owner));
1605
+ }
1606
+ if (form.grant_type === "refresh_token") {
1607
+ const hash = digest(form.refresh_token ?? "");
1608
+ const row = this.db.prepare("SELECT * FROM oauth_tokens WHERE token_hash=? AND kind='refresh'").get(hash);
1609
+ if (!row || row.expires_at <= Date.now() || row.client_id !== client.client_id || row.owner !== owner) return c.json({ error: "invalid_grant" }, 400);
1610
+ this.db.prepare("DELETE FROM oauth_tokens WHERE token_hash=?").run(hash);
1611
+ return c.json(this.issue(client.client_id, row.scope, row.resource, owner));
1612
+ }
1613
+ return c.json({ error: "unsupported_grant_type" }, 400);
1614
+ }
1615
+ async revoke(c) {
1616
+ const form = Object.fromEntries(Object.entries(await c.req.parseBody()).map(([key, value]) => [key, typeof value === "string" ? value : void 0]));
1617
+ const client = this.authenticateClient(c, form);
1618
+ if (!client) return c.json({ error: "invalid_client" }, 401);
1619
+ if (form.token) this.db.prepare("DELETE FROM oauth_tokens WHERE token_hash=? AND client_id=?").run(digest(form.token), client.client_id);
1620
+ return c.body(null, 200);
1621
+ }
1622
+ close() {
1623
+ this.db.close();
1624
+ }
1625
+ };
1626
+ //#endregion
1627
+ //#region src/oauth/approval-delivery.ts
1628
+ const APPROVAL_EVENT = "mcp.oauth.approval_requested";
1629
+ /**
1630
+ * Delivers one-time approval codes only to channels the session owner controls: the local log, the owner's
1631
+ * webhook, and the account's own "Message yourself" chat. Never through MCP events or the dashboard socket,
1632
+ * because a connected client could then approve new clients itself.
1633
+ */
1634
+ function createApprovalDelivery(options) {
1635
+ const write = options.write ?? ((line) => console.log(line));
1636
+ const time = (at) => new Date(at).toLocaleTimeString([], {
1637
+ hour: "2-digit",
1638
+ minute: "2-digit"
1639
+ });
1640
+ return (request) => {
1641
+ const summary = `${request.clientName} (${request.redirectHost}) wants MCP access. Request ${request.requestId}, one-time code ${request.code}, valid until ${time(request.expiresAt)}.`;
1642
+ if (options.log) write(`[open-wa] ${summary}`);
1643
+ if (options.webhookUrl) {
1644
+ const id = `msg_${(0, node_crypto.randomUUID)()}`;
1645
+ const timestamp = /* @__PURE__ */ new Date();
1646
+ const body = JSON.stringify({
1647
+ type: APPROVAL_EVENT,
1648
+ timestamp: timestamp.toISOString(),
1649
+ data: {
1650
+ sessionId: options.sessionId,
1651
+ ...request,
1652
+ expiresAt: new Date(request.expiresAt).toISOString()
1653
+ }
1654
+ });
1655
+ const headers = {
1656
+ "content-type": "application/json",
1657
+ "webhook-id": id,
1658
+ "webhook-timestamp": String(Math.floor(timestamp.getTime() / 1e3))
1659
+ };
1660
+ if (options.webhookSecret) headers["webhook-signature"] = new standardwebhooks.Webhook(options.webhookSecret).sign(id, timestamp, body);
1661
+ fetch(options.webhookUrl, {
1662
+ method: "POST",
1663
+ headers,
1664
+ body,
1665
+ signal: AbortSignal.timeout(1e4)
1666
+ }).then((res) => {
1667
+ if (!res.ok) write(`[open-wa] The approval code webhook answered ${res.status}.`);
1668
+ }).catch((error) => write(`[open-wa] Could not send the approval code webhook: ${error instanceof Error ? error.message : String(error)}`));
1669
+ }
1670
+ if (options.sendToSelf) (async () => {
1671
+ const host = await options.invoke("getHostNumber", {});
1672
+ if (!host.success || typeof host.data !== "string" || !host.data) throw new Error(host.error ?? "this account's number is not available yet");
1673
+ const sent = await options.invoke("sendText", {
1674
+ to: `${host.data.replace(/\D/g, "")}@c.us`,
1675
+ content: `🔐 ${request.clientName} wants access to this WhatsApp through open-wa.\n\nRequest ${request.requestId}\nCode: ${request.code}\n\nEnter the code on the approval page only if you started this. It expires at ${time(request.expiresAt)}.`
1676
+ });
1677
+ if (!sent.success) throw new Error(sent.error ?? "sending failed");
1678
+ if (typeof sent.data === "string") options.noteOwnSend?.(sent.data);
1679
+ })().catch((error) => write(`[open-wa] Could not send the approval code to this account's own chat: ${error instanceof Error ? error.message : String(error)}`));
1680
+ };
1681
+ }
1682
+ //#endregion
1683
+ //#region src/adapter/chat-tools.ts
1684
+ const MAX_MEDIA_BYTES = 15728640;
1685
+ const chatId = {
1686
+ type: "string",
1687
+ description: "Conversation ID from a message event, such as 447700900123@c.us"
1688
+ };
1689
+ const chatToolDefinitions = [
1690
+ {
1691
+ name: "media.getForMessage",
1692
+ description: "Open the photo, voice note, video or document attached to a WhatsApp message, by message ID. Images and audio are returned as content you can view or listen to.",
1693
+ inputSchema: {
1694
+ type: "object",
1695
+ properties: { messageId: {
1696
+ type: "string",
1697
+ description: "messageId from a message event"
1698
+ } },
1699
+ required: ["messageId"],
1700
+ additionalProperties: false
1701
+ },
1702
+ annotations: {
1703
+ readOnlyHint: true,
1704
+ openWorldHint: false,
1705
+ destructiveHint: false
1706
+ }
1707
+ },
1708
+ {
1709
+ name: "messages.sendAttachment",
1710
+ description: "Send a file you hold, such as an image you created or one the user shared, to a WhatsApp chat. Images and videos are shown inline; other files arrive as documents.",
1711
+ inputSchema: {
1712
+ type: "object",
1713
+ properties: {
1714
+ to: chatId,
1715
+ file: {
1716
+ type: "object",
1717
+ properties: {
1718
+ download_url: { type: "string" },
1719
+ file_id: { type: "string" },
1720
+ mime_type: { type: "string" },
1721
+ file_name: { type: "string" }
1722
+ },
1723
+ required: ["download_url", "file_id"],
1724
+ additionalProperties: false
1725
+ },
1726
+ caption: {
1727
+ type: "string",
1728
+ description: "Optional caption"
1729
+ }
1730
+ },
1731
+ required: ["to", "file"],
1732
+ additionalProperties: false
1733
+ },
1734
+ annotations: {
1735
+ readOnlyHint: false,
1736
+ openWorldHint: true,
1737
+ destructiveHint: false
1738
+ },
1739
+ _meta: { "openai/fileParams": ["file"] }
1740
+ },
1741
+ {
1742
+ name: "automation.getStatus",
1743
+ description: "Check whether automation is paused for a chat because a person replied from the WhatsApp app. Message events for a paused chat are not delivered until it resumes.",
1744
+ inputSchema: {
1745
+ type: "object",
1746
+ properties: { chatId },
1747
+ required: ["chatId"],
1748
+ additionalProperties: false
1749
+ },
1750
+ annotations: {
1751
+ readOnlyHint: true,
1752
+ openWorldHint: false,
1753
+ destructiveHint: false
1754
+ }
1755
+ },
1756
+ {
1757
+ name: "automation.pause",
1758
+ description: "Pause message events for a chat, for example when a person should take over.",
1759
+ inputSchema: {
1760
+ type: "object",
1761
+ properties: {
1762
+ chatId,
1763
+ minutes: {
1764
+ type: "number",
1765
+ minimum: 1,
1766
+ maximum: 10080,
1767
+ description: "How long to pause; defaults to the server setting"
1768
+ }
1769
+ },
1770
+ required: ["chatId"],
1771
+ additionalProperties: false
1772
+ },
1773
+ annotations: {
1774
+ readOnlyHint: false,
1775
+ openWorldHint: false,
1776
+ destructiveHint: false
1777
+ }
1778
+ },
1779
+ {
1780
+ name: "automation.resume",
1781
+ description: "Resume message events for a chat that was paused.",
1782
+ inputSchema: {
1783
+ type: "object",
1784
+ properties: { chatId },
1785
+ required: ["chatId"],
1786
+ additionalProperties: false
1787
+ },
1788
+ annotations: {
1789
+ readOnlyHint: false,
1790
+ openWorldHint: false,
1791
+ destructiveHint: false
1792
+ }
1793
+ }
1794
+ ];
1795
+ const text = (value) => ({
1796
+ type: "text",
1797
+ text: typeof value === "string" ? value : JSON.stringify(value ?? null, null, 2)
1798
+ });
1799
+ const failure = (message) => ({
1800
+ isError: true,
1801
+ content: [text(message)]
1802
+ });
1803
+ const record = (value) => value && typeof value === "object" ? value : {};
1804
+ const string = (value) => typeof value === "string" && value.trim() ? value.trim() : void 0;
1805
+ /** Turns a data URL into MCP content an assistant can view or play; other values stay text. */
1806
+ function mediaContent(value, label = "media") {
1807
+ const raw = typeof value === "string" ? value : string(record(value).data) ?? string(record(value).dataUrl);
1808
+ const match = raw ? /^data:([\w.+-]+\/[\w.+-]+)(?:;[^,]*)?;base64,(.+)$/s.exec(raw) : null;
1809
+ if (!match) return;
1810
+ const [, mimeType, data] = match;
1811
+ const bytes = Math.floor(data.length * 3 / 4);
1812
+ if (bytes > MAX_MEDIA_BYTES) return [text(`The ${label} is ${Math.round(bytes / 1048576)} MB, more than the ${MAX_MEDIA_BYTES / 1048576} MB that can be returned here.`)];
1813
+ const summary = text({
1814
+ mimeType,
1815
+ bytes
1816
+ });
1817
+ const kind = mimeType.split("/")[0];
1818
+ if (kind === "image") return [summary, {
1819
+ type: "image",
1820
+ data,
1821
+ mimeType
1822
+ }];
1823
+ if (kind === "audio") return [summary, {
1824
+ type: "audio",
1825
+ data,
1826
+ mimeType
1827
+ }];
1828
+ return [summary, {
1829
+ type: "resource",
1830
+ resource: {
1831
+ uri: `openwa:media/${label}`,
1832
+ mimeType,
1833
+ blob: data
1834
+ }
1835
+ }];
1836
+ }
1837
+ async function callChatTool(name, args, invoke, events) {
1838
+ switch (name) {
1839
+ case "media.getForMessage": {
1840
+ const messageId = string(args.messageId);
1841
+ if (!messageId) return failure("messageId is required");
1842
+ const message = await invoke("getMessageById", { messageId });
1843
+ if (!message.success || !message.data) return failure(message.error ?? "Message not found");
1844
+ const type = string(record(message.data).type);
1845
+ if (!type || ![
1846
+ "image",
1847
+ "audio",
1848
+ "ptt",
1849
+ "video",
1850
+ "document",
1851
+ "sticker"
1852
+ ].includes(type)) return failure(`Message ${messageId} has no media (type ${type ?? "unknown"})`);
1853
+ const media = await invoke("decryptMedia", { message: message.data });
1854
+ if (!media.success) return failure(media.error ?? "Could not download the media");
1855
+ return { content: mediaContent(media.data, messageId) ?? [text("The media could not be read as a file")] };
1856
+ }
1857
+ case "messages.sendAttachment": {
1858
+ const to = string(args.to);
1859
+ const file = record(args.file);
1860
+ const url = string(file.download_url);
1861
+ if (!to || !url) return failure("to and file.download_url are required");
1862
+ if (!/^https:\/\//i.test(url)) return failure("file.download_url must be an HTTPS URL");
1863
+ const filename = string(file.file_name) ?? `attachment.${(string(file.mime_type)?.split("/")[1] ?? "bin").replace(/[^a-z0-9]/gi, "")}`;
1864
+ const caption = string(args.caption);
1865
+ const sent = await invoke("sendFileFromUrl", {
1866
+ to,
1867
+ url,
1868
+ filename,
1869
+ options: {
1870
+ type: "auto",
1871
+ ...caption ? { caption } : {}
1872
+ }
1873
+ });
1874
+ if (!sent.success) return failure(sent.error ?? "Sending failed");
1875
+ if (typeof sent.data === "string") events?.noteOwnSend(sent.data);
1876
+ return { content: [text({ messageId: sent.data ?? null })] };
1877
+ }
1878
+ case "automation.getStatus":
1879
+ case "automation.pause":
1880
+ case "automation.resume": {
1881
+ if (!events) return failure("MCP Events are disabled on this server");
1882
+ const chat = string(args.chatId);
1883
+ if (!chat) return failure("chatId is required");
1884
+ if (name === "automation.pause") events.pauseChat(chat, typeof args.minutes === "number" ? args.minutes * 6e4 : void 0, "assistant");
1885
+ if (name === "automation.resume") events.resumeChat(chat);
1886
+ return { content: [text(events.chatStatus(chat))] };
1887
+ }
1888
+ default: return;
1889
+ }
1890
+ }
1891
+ //#endregion
1087
1892
  //#region package.json
1088
- var version = "5.11.1";
1893
+ var version = "5.12.0";
1089
1894
  //#endregion
1090
1895
  //#region src/adapter/hono-mcp.ts
1091
1896
  /** Easy API's authenticated MCP 2.0 tools and webhook event endpoint. */
@@ -1103,8 +1908,35 @@ function createHonoMcpAdapter(options) {
1103
1908
  storePath: eventConfig?.storePath ?? (0, node_path.join)(".open-wa", `mcp-events-${owner().slice(0, 24)}.sqlite`),
1104
1909
  lifetimeMs: eventConfig?.lifetimeMs ?? 864e5,
1105
1910
  retentionMs: eventConfig?.retentionMs ?? 9e5,
1911
+ operatorPauseMs: eventConfig?.operatorPauseMs ?? 18e5,
1106
1912
  log: (data) => elasticEmitter?.log(data)
1107
1913
  });
1914
+ const mcpPath = config.mcp?.path || "/mcp";
1915
+ const invoke = (functionName, payload) => executeCapability({
1916
+ client: clientSource(),
1917
+ definition: executionDefinitions.get(functionName),
1918
+ payload,
1919
+ elasticEmitter,
1920
+ sessionId: config.sessionId
1921
+ });
1922
+ const oauthConfig = config.mcp?.oauth;
1923
+ const approval = oauthConfig?.approvalCode;
1924
+ const oauth = oauthConfig?.enabled === false ? void 0 : new McpOAuth({
1925
+ storePath: oauthConfig?.storePath ?? (0, node_path.join)(".open-wa", `mcp-oauth-${owner().slice(0, 24)}.sqlite`),
1926
+ mcpPath,
1927
+ apiKey: () => config.apiKey,
1928
+ owner,
1929
+ publicUrl: oauthConfig?.publicUrl,
1930
+ onApprovalCode: createApprovalDelivery({
1931
+ sessionId: config.sessionId ?? "",
1932
+ log: approval?.log ?? true,
1933
+ webhookUrl: approval?.webhook ?? true ? approval?.webhookUrl ?? config.webhook : void 0,
1934
+ webhookSecret: approval?.webhookSecret,
1935
+ sendToSelf: approval?.sendToSelf ?? false,
1936
+ invoke,
1937
+ noteOwnSend: (id) => events?.noteOwnSend(id)
1938
+ })
1939
+ });
1108
1940
  const handler = (0, _modelcontextprotocol_server.createMcpHandler)(() => {
1109
1941
  const capabilities = {
1110
1942
  tools: {},
@@ -1122,7 +1954,10 @@ function createHonoMcpAdapter(options) {
1122
1954
  description: def.description,
1123
1955
  inputSchema: (0, _open_wa_schema.eventJsonSchema)(def.inputSchema),
1124
1956
  annotations: def.annotations
1125
- })) }));
1957
+ })).concat(chatToolDefinitions.map((def) => ({
1958
+ ...def,
1959
+ inputSchema: def.inputSchema
1960
+ }))) }));
1126
1961
  server.setRequestHandler("tools/call", async (request) => {
1127
1962
  const { name, arguments: args } = request.params;
1128
1963
  const definition = toolMap.get(name);
@@ -1133,19 +1968,17 @@ function createHonoMcpAdapter(options) {
1133
1968
  text
1134
1969
  }]
1135
1970
  });
1136
- if (!definition) return failure(`Unknown tool: ${name}. Use tools/list to discover available tools.`);
1971
+ const isChatTool = chatToolDefinitions.some((def) => def.name === name);
1972
+ if (!definition && !isChatTool) return failure(`Unknown tool: ${name}. Use tools/list to discover available tools.`);
1137
1973
  if (isSessionConnected && !isSessionConnected() && config.apiLifecycle !== "immediate") return failure("Session is not connected or ready. Tool execution is blocked until the session is fully ready.");
1138
- const result = await executeCapability({
1139
- client: clientSource(),
1140
- definition: executionDefinitions.get(definition.functionName),
1141
- payload: args || {},
1142
- elasticEmitter,
1143
- sessionId: config.sessionId
1144
- });
1145
- return result.success ? { content: [{
1974
+ if (isChatTool) return await callChatTool(name, args || {}, invoke, events);
1975
+ const result = await invoke(definition.functionName, args || {});
1976
+ if (!result.success) return failure(result.error || "Internal Execution Error");
1977
+ if (definition.functionName.startsWith("send") && typeof result.data === "string") events?.noteOwnSend(result.data);
1978
+ return { content: mediaContent(result.data, definition.toolName) ?? [{
1146
1979
  type: "text",
1147
1980
  text: JSON.stringify(result.data ?? null, null, 2)
1148
- }] } : failure(result.error || "Internal Execution Error");
1981
+ }] };
1149
1982
  });
1150
1983
  if (events) {
1151
1984
  server.setRequestHandler("events/list", {
@@ -1180,12 +2013,16 @@ function createHonoMcpAdapter(options) {
1180
2013
  }, { legacy: "reject" });
1181
2014
  return {
1182
2015
  mount(app, path) {
2016
+ oauth?.routes(app);
1183
2017
  app.all(path, async (c) => {
1184
2018
  const key = c.req.header("X-API-Key") || c.req.header("api_key") || c.req.header("key");
1185
- if (!config.apiKey || key !== config.apiKey) return c.json({
1186
- error: "Unauthorized",
1187
- details: "Invalid or missing API key for MCP endpoint"
1188
- }, 401);
2019
+ if (!config.apiKey || key !== config.apiKey && !oauth?.verify(c)) {
2020
+ if (oauth) c.header("WWW-Authenticate", oauth.challenge(c));
2021
+ return c.json({
2022
+ error: "Unauthorized",
2023
+ details: "Sign in with OAuth or send the Easy API key in X-API-Key"
2024
+ }, 401);
2025
+ }
1189
2026
  const mismatch = await eventNameMismatch(c.req.raw);
1190
2027
  if (mismatch) return c.json({
1191
2028
  jsonrpc: "2.0",
@@ -1215,6 +2052,7 @@ function createHonoMcpAdapter(options) {
1215
2052
  await handler.close();
1216
2053
  } finally {
1217
2054
  await events?.close();
2055
+ oauth?.close();
1218
2056
  }
1219
2057
  }
1220
2058
  };