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