multicorn-shield 0.9.0 → 0.11.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
@@ -287,6 +287,39 @@ function hasScope(grantedScopes, requested) {
287
287
  );
288
288
  }
289
289
 
290
+ // src/scopes/content-review-detector.ts
291
+ function requiresContentReview(scope) {
292
+ if (scope.service === "web" && scope.permissionLevel === "publish") {
293
+ return true;
294
+ }
295
+ if (scope.service === "public_content" && scope.permissionLevel === "create") {
296
+ return true;
297
+ }
298
+ return false;
299
+ }
300
+ function isPublicContentAction(toolName, service) {
301
+ const lowerToolName = toolName.toLowerCase();
302
+ const lowerService = service.toLowerCase();
303
+ if (lowerService === "web" || lowerService === "public_content") {
304
+ return true;
305
+ }
306
+ const publicContentIndicators = [
307
+ "publish",
308
+ "public",
309
+ "web",
310
+ "blog",
311
+ "post",
312
+ "article",
313
+ "social",
314
+ "twitter",
315
+ "facebook",
316
+ "linkedin",
317
+ "github_pages",
318
+ "deploy"
319
+ ];
320
+ return publicContentIndicators.some((indicator) => lowerToolName.includes(indicator));
321
+ }
322
+
290
323
  // src/consent/scope-labels.ts
291
324
  var SERVICE_DISPLAY_NAMES = {
292
325
  gmail: "Gmail",
@@ -399,6 +432,8 @@ function getScopeWarning(scopeString) {
399
432
  const metadata = getScopeMetadata(scopeString);
400
433
  return metadata?.warningMessage;
401
434
  }
435
+
436
+ // src/shared/shield-tokens.ts
402
437
  var SHIELD_COLORS = {
403
438
  bg: "#0d0d14",
404
439
  surface: "#14141f",
@@ -419,6 +454,8 @@ var SHIELD_COLORS = {
419
454
  red: "#ef4444",
420
455
  redDim: "rgba(239, 68, 68, 0.12)"
421
456
  };
457
+
458
+ // src/consent/consent-styles.ts
422
459
  var consentStyles = lit.css`
423
460
  :host {
424
461
  display: block;
@@ -1566,6 +1603,144 @@ exports.MulticornConsent = __decorateClass([
1566
1603
  decorators_js.customElement(CONSENT_ELEMENT_TAG)
1567
1604
  ], exports.MulticornConsent);
1568
1605
 
1606
+ // src/badge/badge-styles.ts
1607
+ var LIGHT_TEXT = "#0f172a";
1608
+ var LIGHT_SURFACE = "#f8fafc";
1609
+ var LIGHT_SURFACE_HOVER = "#f1f5f9";
1610
+ var LIGHT_BORDER = "#e2e8f0";
1611
+ function getBadgeStyleText() {
1612
+ return `
1613
+ :host { display: inline-block; line-height: 0; }
1614
+ .badge {
1615
+ display: inline-flex;
1616
+ align-items: center;
1617
+ justify-content: center;
1618
+ box-sizing: border-box;
1619
+ gap: 6px;
1620
+ min-height: 28px;
1621
+ padding: 4px 10px 4px 8px;
1622
+ border-radius: 9999px;
1623
+ text-decoration: none;
1624
+ font-family: system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
1625
+ font-size: 12px;
1626
+ font-weight: 500;
1627
+ border: 1px solid ${SHIELD_COLORS.border};
1628
+ background: ${SHIELD_COLORS.surface};
1629
+ color: ${SHIELD_COLORS.text};
1630
+ transition: background 0.15s ease, border-color 0.15s ease, box-shadow 0.15s ease;
1631
+ }
1632
+ :host([theme="light"]) .badge {
1633
+ border-color: ${LIGHT_BORDER};
1634
+ background: ${LIGHT_SURFACE};
1635
+ color: ${LIGHT_TEXT};
1636
+ }
1637
+ .badge:hover {
1638
+ background: ${SHIELD_COLORS.surfaceHover};
1639
+ border-color: ${SHIELD_COLORS.accent};
1640
+ box-shadow: 0 0 0 1px ${SHIELD_COLORS.accentDim};
1641
+ }
1642
+ :host([theme="light"]) .badge:hover {
1643
+ background: ${LIGHT_SURFACE_HOVER};
1644
+ border-color: ${SHIELD_COLORS.accent};
1645
+ }
1646
+ .badge:focus-visible {
1647
+ outline: 2px solid ${SHIELD_COLORS.accent};
1648
+ outline-offset: 2px;
1649
+ }
1650
+ .icon { flex-shrink: 0; display: block; }
1651
+ .text { white-space: nowrap; }
1652
+ :host([size="compact"]) .text { display: none; }
1653
+ :host([size="compact"]) .badge { padding: 4px 6px; }
1654
+ @media (prefers-reduced-motion: reduce) { .badge { transition: none; } }
1655
+ `.trim();
1656
+ }
1657
+
1658
+ // src/badge/multicorn-badge.ts
1659
+ var VERIFY_BASE = "https://multicorn.ai/verify/";
1660
+ var BADGE_ELEMENT_TAG = "multicorn-badge";
1661
+ var SHIELD_PATH = "M12 1L3 5v6c0 5.55 3.84 9.95 9 12 5.16-2.05 9-6.45 9-12V5l-9-4z";
1662
+ function parseOptionalCount(raw) {
1663
+ if (raw == null || raw === "") {
1664
+ return void 0;
1665
+ }
1666
+ const n = Number(raw);
1667
+ return Number.isNaN(n) ? void 0 : n;
1668
+ }
1669
+ var MulticornBadge = class extends HTMLElement {
1670
+ #didInjectStyle = false;
1671
+ ensureShadow() {
1672
+ if (this.shadowRoot != null) {
1673
+ return this.shadowRoot;
1674
+ }
1675
+ return this.attachShadow({ mode: "open" });
1676
+ }
1677
+ static get observedAttributes() {
1678
+ return ["agent-id", "size", "theme", "action-count"];
1679
+ }
1680
+ connectedCallback() {
1681
+ this.render();
1682
+ }
1683
+ attributeChangedCallback() {
1684
+ this.render();
1685
+ }
1686
+ render() {
1687
+ const root = this.ensureShadow();
1688
+ if (this.#didInjectStyle) ; else {
1689
+ const style = document.createElement("style");
1690
+ style.textContent = getBadgeStyleText();
1691
+ root.appendChild(style);
1692
+ this.#didInjectStyle = true;
1693
+ }
1694
+ const agentId = (this.getAttribute("agent-id") ?? "").trim();
1695
+ const actionCount = parseOptionalCount(this.getAttribute("action-count"));
1696
+ const prior = root.querySelector("a.badge");
1697
+ if (prior) {
1698
+ prior.remove();
1699
+ }
1700
+ if (agentId === "") {
1701
+ return;
1702
+ }
1703
+ let labelSuffix;
1704
+ let ariaLabel;
1705
+ if (actionCount == null) {
1706
+ labelSuffix = "Secured by Multicorn";
1707
+ ariaLabel = "Secured by Multicorn, verify this agent";
1708
+ } else {
1709
+ const count = actionCount;
1710
+ const countText = String(count);
1711
+ labelSuffix = "Secured by Multicorn \xB7 " + countText + " actions secured";
1712
+ ariaLabel = "Secured by Multicorn \xB7 " + countText + " actions secured, verify this agent";
1713
+ }
1714
+ const href = `${VERIFY_BASE}${encodeURIComponent(agentId)}`;
1715
+ const a = document.createElement("a");
1716
+ a.className = "badge";
1717
+ a.href = href;
1718
+ a.target = "_blank";
1719
+ a.rel = "noopener noreferrer";
1720
+ a.setAttribute("aria-label", ariaLabel);
1721
+ const svgNs = "http://www.w3.org/2000/svg";
1722
+ const svg = document.createElementNS(svgNs, "svg");
1723
+ svg.setAttribute("class", "icon");
1724
+ svg.setAttribute("width", "16");
1725
+ svg.setAttribute("height", "16");
1726
+ svg.setAttribute("viewBox", "0 0 24 24");
1727
+ svg.setAttribute("aria-hidden", "true");
1728
+ const path = document.createElementNS(svgNs, "path");
1729
+ path.setAttribute("d", SHIELD_PATH);
1730
+ path.setAttribute("fill", SHIELD_COLORS.accent);
1731
+ svg.appendChild(path);
1732
+ a.appendChild(svg);
1733
+ const text = document.createElement("span");
1734
+ text.className = "text";
1735
+ text.textContent = labelSuffix;
1736
+ a.appendChild(text);
1737
+ root.appendChild(a);
1738
+ }
1739
+ };
1740
+ if (customElements.get(BADGE_ELEMENT_TAG) === void 0) {
1741
+ customElements.define(BADGE_ELEMENT_TAG, MulticornBadge);
1742
+ }
1743
+
1569
1744
  // src/logger/action-logger.ts
1570
1745
  function createActionLogger(config) {
1571
1746
  if (!config.apiKey || config.apiKey.trim().length === 0) {
@@ -1878,37 +2053,215 @@ function centsToDollars(cents) {
1878
2053
  })}`;
1879
2054
  }
1880
2055
 
1881
- // src/scopes/content-review-detector.ts
1882
- function requiresContentReview(scope) {
1883
- if (scope.service === "web" && scope.permissionLevel === "publish") {
1884
- return true;
2056
+ // src/openclaw/shield-client.ts
2057
+ var REQUEST_TIMEOUT_MS = 5e3;
2058
+ var AUTH_HEADER = "X-Multicorn-Key";
2059
+ var POLL_INTERVAL_MS = 3e3;
2060
+ var MAX_POLLS = 100;
2061
+ var POLL_TIMEOUT_MS = POLL_INTERVAL_MS * MAX_POLLS;
2062
+ var authErrorLogged = false;
2063
+ function isApiSuccess(value) {
2064
+ if (typeof value !== "object" || value === null) return false;
2065
+ const obj = value;
2066
+ return obj["success"] === true;
2067
+ }
2068
+ function isContentReviewStatusResponse(value) {
2069
+ if (typeof value !== "object" || value === null) return false;
2070
+ const obj = value;
2071
+ return typeof obj["id"] === "string" && typeof obj["status"] === "string" && ["pending", "approved", "blocked", "timeout"].includes(obj["status"]);
2072
+ }
2073
+ function readApiErrorCode(body) {
2074
+ if (typeof body !== "object" || body === null) return void 0;
2075
+ const err = body["error"];
2076
+ if (typeof err !== "object" || err === null) return void 0;
2077
+ const code = err["code"];
2078
+ return typeof code === "string" ? code : void 0;
2079
+ }
2080
+ function isPlanTierInsufficientError(status, body) {
2081
+ return status === 403 && readApiErrorCode(body) === "PLAN_TIER_INSUFFICIENT";
2082
+ }
2083
+ function handleHttpError(status, logger, retryDelaySeconds) {
2084
+ if (status === 401 || status === 403) {
2085
+ if (!authErrorLogged) {
2086
+ authErrorLogged = true;
2087
+ const errorMsg = "[multicorn-shield] ERROR: Authentication failed. Your MULTICORN_API_KEY is invalid or expired. Check the key in your OpenClaw config (~/.openclaw/openclaw.json \u2192 plugins.entries.multicorn-shield.env.MULTICORN_API_KEY). Get a valid key from your Multicorn dashboard (Settings \u2192 API Keys).";
2088
+ logger?.error(errorMsg);
2089
+ process.stderr.write(`${errorMsg}
2090
+ `);
2091
+ }
2092
+ return { shouldBlock: true };
2093
+ }
2094
+ if (status === 429) {
2095
+ if (retryDelaySeconds !== void 0) {
2096
+ const rateLimitMsg = `[multicorn-shield] Rate limited by Shield API. Retrying in ${String(retryDelaySeconds)}s.`;
2097
+ logger?.warn(rateLimitMsg);
2098
+ process.stderr.write(`${rateLimitMsg}
2099
+ `);
2100
+ } else {
2101
+ const rateLimitMsg = "[multicorn-shield] Rate limited by Shield API. Action blocked: Shield cannot verify permissions.";
2102
+ logger?.warn(rateLimitMsg);
2103
+ process.stderr.write(`${rateLimitMsg}
2104
+ `);
2105
+ }
2106
+ return { shouldBlock: true };
1885
2107
  }
1886
- if (scope.service === "public_content" && scope.permissionLevel === "create") {
1887
- return true;
2108
+ if (status >= 500 && status < 600) {
2109
+ const serverErrorMsg = `[multicorn-shield] Shield API error (${String(status)}). Action blocked: Shield cannot verify permissions.`;
2110
+ logger?.warn(serverErrorMsg);
2111
+ process.stderr.write(`${serverErrorMsg}
2112
+ `);
2113
+ return { shouldBlock: true };
1888
2114
  }
1889
- return false;
2115
+ return { shouldBlock: true };
1890
2116
  }
1891
- function isPublicContentAction(toolName, service) {
1892
- const lowerToolName = toolName.toLowerCase();
1893
- const lowerService = service.toLowerCase();
1894
- if (lowerService === "web" || lowerService === "public_content") {
1895
- return true;
2117
+ async function pollContentReviewStatus(reviewId, apiKey, baseUrl, logger) {
2118
+ const startTime = Date.now();
2119
+ const logDebug = logger?.debug?.bind(logger);
2120
+ for (let pollCount = 0; pollCount < MAX_POLLS; pollCount++) {
2121
+ if (Date.now() - startTime >= POLL_TIMEOUT_MS) {
2122
+ return { status: "timeout", reason: "decision_window_exceeded", reviewId };
2123
+ }
2124
+ let row = null;
2125
+ for (let retry = 0; retry < 3; retry++) {
2126
+ try {
2127
+ const response = await fetch(`${baseUrl}/api/v1/content-reviews/${reviewId}/status`, {
2128
+ headers: { [AUTH_HEADER]: apiKey },
2129
+ signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS)
2130
+ });
2131
+ if (!response.ok) {
2132
+ if (response.status === 404) {
2133
+ return { status: "blocked", reason: "review_not_found", reviewId };
2134
+ }
2135
+ const errBody = await response.json().catch(() => null);
2136
+ if (isPlanTierInsufficientError(response.status, errBody)) {
2137
+ return { status: "blocked", reason: "plan_tier_insufficient", reviewId };
2138
+ }
2139
+ if (response.status === 401 || response.status === 403) {
2140
+ handleHttpError(response.status, logger);
2141
+ return { status: "blocked", reason: "auth_error", reviewId };
2142
+ }
2143
+ if (response.status === 429 || response.status >= 500 && response.status < 600) {
2144
+ const retryDelay = retry < 2 ? Math.pow(2, retry) : void 0;
2145
+ handleHttpError(response.status, logger, retryDelay);
2146
+ }
2147
+ logDebug?.(
2148
+ `Content review poll ${String(pollCount + 1)} failed: HTTP ${String(response.status)}. Retrying...`
2149
+ );
2150
+ if (retry < 2) {
2151
+ await new Promise((resolve) => setTimeout(resolve, 1e3 * Math.pow(2, retry)));
2152
+ }
2153
+ continue;
2154
+ }
2155
+ const body = await response.json();
2156
+ if (!isApiSuccess(body)) {
2157
+ logDebug?.(
2158
+ `Content review poll ${String(pollCount + 1)} failed: invalid response format. Retrying...`
2159
+ );
2160
+ if (retry < 2) {
2161
+ await new Promise((resolve) => setTimeout(resolve, 1e3 * Math.pow(2, retry)));
2162
+ }
2163
+ continue;
2164
+ }
2165
+ const statusData = body.data;
2166
+ if (!isContentReviewStatusResponse(statusData)) {
2167
+ logDebug?.(
2168
+ `Content review poll ${String(pollCount + 1)} failed: invalid status data. Retrying...`
2169
+ );
2170
+ if (retry < 2) {
2171
+ await new Promise((resolve) => setTimeout(resolve, 1e3 * Math.pow(2, retry)));
2172
+ }
2173
+ continue;
2174
+ }
2175
+ row = statusData;
2176
+ break;
2177
+ } catch (error) {
2178
+ const errorMessage = error instanceof Error ? error.message : String(error);
2179
+ logDebug?.(
2180
+ `Content review poll ${String(pollCount + 1)} failed: ${errorMessage}. Retrying...`
2181
+ );
2182
+ if (retry < 2) {
2183
+ await new Promise((resolve) => setTimeout(resolve, 1e3 * Math.pow(2, retry)));
2184
+ }
2185
+ }
2186
+ }
2187
+ if (row !== null) {
2188
+ if (row.status === "approved") {
2189
+ return { status: "approved", reviewId };
2190
+ }
2191
+ if (row.status === "blocked") {
2192
+ return { status: "blocked", reason: "blocked_by_reviewer", reviewId };
2193
+ }
2194
+ if (row.status === "timeout") {
2195
+ return { status: "timeout", reason: "decision_window_exceeded", reviewId };
2196
+ }
2197
+ if (pollCount < MAX_POLLS - 1) {
2198
+ await new Promise((resolve) => setTimeout(resolve, POLL_INTERVAL_MS));
2199
+ }
2200
+ } else {
2201
+ logDebug?.(
2202
+ `All retries failed for content review poll ${String(pollCount + 1)}. Continuing...`
2203
+ );
2204
+ if (pollCount < MAX_POLLS - 1) {
2205
+ await new Promise((resolve) => setTimeout(resolve, POLL_INTERVAL_MS));
2206
+ }
2207
+ }
2208
+ }
2209
+ return { status: "timeout", reason: "decision_window_exceeded", reviewId };
2210
+ }
2211
+ async function requestContentReview(payload, apiKey, baseUrl, logger) {
2212
+ try {
2213
+ const response = await fetch(`${baseUrl}/api/v1/actions`, {
2214
+ method: "POST",
2215
+ headers: {
2216
+ "Content-Type": "application/json",
2217
+ [AUTH_HEADER]: apiKey
2218
+ },
2219
+ body: JSON.stringify({
2220
+ agent: payload.agent,
2221
+ service: payload.service,
2222
+ actionType: payload.actionType,
2223
+ status: "requires_approval",
2224
+ cost: payload.cost ?? 0,
2225
+ metadata: payload.metadata
2226
+ }),
2227
+ signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS)
2228
+ });
2229
+ const body = await response.json().catch(() => null);
2230
+ if (isPlanTierInsufficientError(response.status, body)) {
2231
+ return { status: "blocked", reason: "plan_tier_insufficient" };
2232
+ }
2233
+ if (response.status === 401 || response.status === 403) {
2234
+ handleHttpError(response.status, logger);
2235
+ return { status: "blocked", reason: "auth_error" };
2236
+ }
2237
+ if (response.status === 429 || response.status >= 500 && response.status < 600) {
2238
+ handleHttpError(response.status, logger);
2239
+ return { status: "blocked", reason: "service_unavailable" };
2240
+ }
2241
+ if (response.status === 202) {
2242
+ if (!isApiSuccess(body)) {
2243
+ return { status: "blocked", reason: "no_review_id" };
2244
+ }
2245
+ const data = body.data;
2246
+ if (typeof data !== "object" || data === null) {
2247
+ return { status: "blocked", reason: "no_review_id" };
2248
+ }
2249
+ const record = data;
2250
+ const rid = record["content_review_id"];
2251
+ const reviewId = typeof rid === "string" ? rid : void 0;
2252
+ if (reviewId === void 0) {
2253
+ return { status: "blocked", reason: "no_review_id" };
2254
+ }
2255
+ const polled = await pollContentReviewStatus(reviewId, apiKey, baseUrl, logger);
2256
+ return { ...polled, reviewId };
2257
+ }
2258
+ if (response.status === 201) {
2259
+ return { status: "blocked", reason: "no_review_id" };
2260
+ }
2261
+ return { status: "blocked", reason: "service_unavailable" };
2262
+ } catch {
2263
+ return { status: "blocked", reason: "network_error" };
1896
2264
  }
1897
- const publicContentIndicators = [
1898
- "publish",
1899
- "public",
1900
- "web",
1901
- "blog",
1902
- "post",
1903
- "article",
1904
- "social",
1905
- "twitter",
1906
- "facebook",
1907
- "linkedin",
1908
- "github_pages",
1909
- "deploy"
1910
- ];
1911
- return publicContentIndicators.some((indicator) => lowerToolName.includes(indicator));
1912
2265
  }
1913
2266
 
1914
2267
  // src/mcp/mcp-adapter.ts
@@ -1985,6 +2338,28 @@ function createMcpAdapter(config) {
1985
2338
  status
1986
2339
  });
1987
2340
  }
2341
+ function mapContentReviewReasonToUserMessage(reason) {
2342
+ switch (reason) {
2343
+ case "plan_tier_insufficient":
2344
+ return "Content review requires an Enterprise plan. Upgrade at app.multicorn.ai/settings.";
2345
+ case "review_not_found":
2346
+ return "Content review no longer exists. It may have been deleted or timed out.";
2347
+ case "decision_window_exceeded":
2348
+ return "Content review timed out before a decision was made.";
2349
+ case "blocked_by_reviewer":
2350
+ return "Content review was blocked by a reviewer.";
2351
+ case "auth_error":
2352
+ return "Content review failed: please verify your Multicorn API key.";
2353
+ case "service_unavailable":
2354
+ return "Content review failed: service unavailable.";
2355
+ case "network_error":
2356
+ return "Content review failed: network error.";
2357
+ case "no_review_id":
2358
+ return "Content review failed: could not start review.";
2359
+ default:
2360
+ return "Content review failed.";
2361
+ }
2362
+ }
1988
2363
  async function checkAutoApproveStatus() {
1989
2364
  if (config.checkAutoApprove !== void 0) {
1990
2365
  const result = config.checkAutoApprove(config.agentId);
@@ -2054,6 +2429,38 @@ function createMcpAdapter(config) {
2054
2429
  arguments: JSON.stringify(toolCall.arguments),
2055
2430
  requiresReview: true
2056
2431
  };
2432
+ if (config.waitForReviewDecision === true) {
2433
+ if (config.baseUrl === void 0 || config.apiKey === void 0) {
2434
+ return {
2435
+ blocked: true,
2436
+ reason: "waitForReviewDecision requires baseUrl and apiKey to poll the content review.",
2437
+ toolName: toolCall.toolName,
2438
+ service: mappedService,
2439
+ action
2440
+ };
2441
+ }
2442
+ const review = await requestContentReview(
2443
+ {
2444
+ agent: config.agentId,
2445
+ service: mappedService,
2446
+ actionType: action,
2447
+ metadata
2448
+ },
2449
+ config.apiKey,
2450
+ config.baseUrl
2451
+ );
2452
+ if (review.status === "approved") {
2453
+ await recordAction(mappedService, action, ACTION_STATUSES.Approved);
2454
+ return handler(toolCall);
2455
+ }
2456
+ return {
2457
+ blocked: true,
2458
+ reason: mapContentReviewReasonToUserMessage(review.reason),
2459
+ toolName: toolCall.toolName,
2460
+ service: mappedService,
2461
+ action
2462
+ };
2463
+ }
2057
2464
  if (config.logger) {
2058
2465
  await config.logger.logAction({
2059
2466
  agent: config.agentId,
@@ -2484,6 +2891,7 @@ exports.ACTION_STATUSES = ACTION_STATUSES;
2484
2891
  exports.AGENT_STATUSES = AGENT_STATUSES;
2485
2892
  exports.BUILT_IN_SERVICES = BUILT_IN_SERVICES;
2486
2893
  exports.CONSENT_ELEMENT_TAG = CONSENT_ELEMENT_TAG;
2894
+ exports.MulticornBadge = MulticornBadge;
2487
2895
  exports.MulticornShield = MulticornShield;
2488
2896
  exports.PERMISSION_LEVELS = PERMISSION_LEVELS;
2489
2897
  exports.SERVICE_NAME_PATTERN = SERVICE_NAME_PATTERN;
@@ -2503,9 +2911,12 @@ exports.getServiceDisplayName = getServiceDisplayName;
2503
2911
  exports.getServiceIcon = getServiceIcon;
2504
2912
  exports.hasScope = hasScope;
2505
2913
  exports.isBlockedResult = isBlockedResult;
2914
+ exports.isPublicContentAction = isPublicContentAction;
2506
2915
  exports.isValidScopeString = isValidScopeString;
2507
2916
  exports.parseScope = parseScope;
2508
2917
  exports.parseScopes = parseScopes;
2918
+ exports.requestContentReview = requestContentReview;
2919
+ exports.requiresContentReview = requiresContentReview;
2509
2920
  exports.tryParseScope = tryParseScope;
2510
2921
  exports.validateAllScopesAccess = validateAllScopesAccess;
2511
2922
  exports.validateScopeAccess = validateScopeAccess;
package/dist/index.d.cts CHANGED
@@ -652,6 +652,42 @@ declare function validateAllScopesAccess(grantedScopes: readonly Scope[], reques
652
652
  */
653
653
  declare function hasScope(grantedScopes: readonly Scope[], requested: Scope): boolean;
654
654
 
655
+ /**
656
+ * Detects if a scope requires content review before execution.
657
+ *
658
+ * Public content scopes that require review:
659
+ * - `publish:web` - publishing content to the web
660
+ * - `create:public_content` - creating public-facing content
661
+ *
662
+ * @module scopes/content-review-detector
663
+ */
664
+
665
+ /**
666
+ * Check if a scope requires content review.
667
+ *
668
+ * @param scope - The scope to check
669
+ * @returns `true` if the scope requires content review
670
+ *
671
+ * @example
672
+ * ```ts
673
+ * requiresContentReview({ service: "web", permissionLevel: "publish" }); // true
674
+ * requiresContentReview({ service: "public_content", permissionLevel: "create" }); // true
675
+ * requiresContentReview({ service: "gmail", permissionLevel: "execute" }); // false
676
+ * ```
677
+ */
678
+ declare function requiresContentReview(scope: Scope): boolean;
679
+ /**
680
+ * Check if a tool name/action indicates public content creation.
681
+ *
682
+ * This is a helper for cases where the service might not be explicitly
683
+ * "web" or "public_content" but the action name indicates public content.
684
+ *
685
+ * @param toolName - The tool name to check
686
+ * @param service - The service name
687
+ * @returns `true` if the tool/action indicates public content
688
+ */
689
+ declare function isPublicContentAction(toolName: string, service: string): boolean;
690
+
655
691
  /**
656
692
  * Custom element tag name for the consent component.
657
693
  */
@@ -1033,6 +1069,29 @@ interface FocusTrap {
1033
1069
  */
1034
1070
  declare function createFocusTrap(container: HTMLElement, initialFocus?: HTMLElement | null): FocusTrap;
1035
1071
 
1072
+ /**
1073
+ * `<multicorn-badge>`: small embeddable trust badge (Shadow DOM).
1074
+ * Implemented as a native custom element to keep the CDN `badge.js` under the
1075
+ * size budget. Styling and tokens align with the Lit-based consent screen.
1076
+ *
1077
+ * @module badge/multicorn-badge
1078
+ */
1079
+ /** Custom element tag for the trust badge. */
1080
+ declare const BADGE_ELEMENT_TAG: "multicorn-badge";
1081
+ declare class MulticornBadge extends HTMLElement {
1082
+ #private;
1083
+ private ensureShadow;
1084
+ static get observedAttributes(): string[];
1085
+ connectedCallback(): void;
1086
+ attributeChangedCallback(): void;
1087
+ private render;
1088
+ }
1089
+ declare global {
1090
+ interface HTMLElementTagNameMap {
1091
+ [BADGE_ELEMENT_TAG]: MulticornBadge;
1092
+ }
1093
+ }
1094
+
1036
1095
  /**
1037
1096
  * Action logging client for Multicorn Shield.
1038
1097
  *
@@ -1775,6 +1834,11 @@ interface McpAdapterConfig {
1775
1834
  * Used with baseUrl to fetch auto-approval status if checkAutoApprove is not provided.
1776
1835
  */
1777
1836
  readonly apiKey?: string;
1837
+ /**
1838
+ * When `true`, blocks until the content review completes (or times out) and forwards the tool call if approved.
1839
+ * Requires `baseUrl` and `apiKey`. Default `false` preserves the existing fast block with `requires_approval` logging only.
1840
+ */
1841
+ readonly waitForReviewDecision?: boolean;
1778
1842
  }
1779
1843
  /**
1780
1844
  * The MCP adapter produced by {@link createMcpAdapter}.
@@ -2179,4 +2243,67 @@ declare class MulticornShield {
2179
2243
  destroy(): void;
2180
2244
  }
2181
2245
 
2182
- export { ACTION_STATUSES, AGENT_STATUSES, type Action, type ActionInput, type ActionLogger, type ActionLoggerConfig, type ActionPayload, type ActionStatus, type Agent, type AgentStatus, type ApiError, BUILT_IN_SERVICES, type BatchModeConfig, type BuiltInServiceName, CONSENT_ELEMENT_TAG, type ConsentDecision, type ConsentDeniedEventDetail, type ConsentEventDetail, type ConsentEventMap, type ConsentEventName, type ConsentGrantedEventDetail, type ConsentOptions, type ConsentPartialEventDetail, type FocusTrap, type McpAdapter, type McpAdapterConfig, type McpAdapterResult, type McpBlockedResult, type McpToolCall, type McpToolHandler, type McpToolResult, MulticornConsent, MulticornShield, type MulticornShieldConfig, PERMISSION_LEVELS, type Permission, type PermissionLevel, type RemainingBudget, SERVICE_NAME_PATTERN, type Scope, ScopeParseError, type ScopeParseResult, type ScopeRegistry, type ScopeRequest, type ServiceDefinition, type SpendCheckResult, type SpendingCheckResult, type SpendingChecker, type SpendingLimit, type SpendingLimits, type SpendingTrackerConfig, type ValidationResult, centsToDollars, createActionLogger, createFocusTrap, createMcpAdapter, createScopeRegistry, createSpendingChecker, dollarsToCents, formatScope, getPermissionLabel, getScopeLabel, getScopeShortLabel, getServiceDisplayName, getServiceIcon, hasScope, isBlockedResult, isValidScopeString, parseScope, parseScopes, tryParseScope, validateAllScopesAccess, validateScopeAccess };
2246
+ /**
2247
+ * Local type definitions for the OpenClaw Plugin SDK.
2248
+ *
2249
+ * Extracted from openclaw/dist/plugin-sdk/plugins/types.d.ts (v2026.2.26).
2250
+ * We define only the subset needed for the Shield plugin so there's no
2251
+ * build-time dependency on the OpenClaw package itself.
2252
+ *
2253
+ * @module openclaw/plugin-sdk.types
2254
+ */
2255
+ interface PluginLogger {
2256
+ debug?: (message: string) => void;
2257
+ info: (message: string) => void;
2258
+ warn: (message: string) => void;
2259
+ error: (message: string) => void;
2260
+ }
2261
+
2262
+ /**
2263
+ * HTTP client for communicating with the Multicorn Shield API.
2264
+ *
2265
+ * Handles agent registration, permission fetching, and action logging.
2266
+ * Follows the same patterns as the MCP proxy client but is self-contained
2267
+ * so the hook has no runtime dependency on proxy internals.
2268
+ *
2269
+ * Security: the API key is passed as a parameter and sent only via the
2270
+ * `X-Multicorn-Key` header over HTTPS. It is never logged or written
2271
+ * to disk.
2272
+ *
2273
+ * @module openclaw/shield-client
2274
+ */
2275
+
2276
+ /**
2277
+ * `data` shape from GET /api/v1/content-reviews/:id/status when `success` is true.
2278
+ */
2279
+ interface ContentReviewStatusResponse {
2280
+ readonly id: string;
2281
+ readonly status: "pending" | "approved" | "blocked" | "timeout";
2282
+ }
2283
+ /**
2284
+ * Result of {@link requestContentReview} or {@link pollContentReviewStatus}.
2285
+ */
2286
+ interface ContentReviewResult {
2287
+ readonly status: "approved" | "blocked" | "timeout";
2288
+ readonly reviewId?: string;
2289
+ readonly reason?: string;
2290
+ }
2291
+ /**
2292
+ * Payload for {@link requestContentReview}. `cost` is optional; the POST body always includes `cost`, defaulting to `0` when omitted (matches {@link LogActionRequest} in the service).
2293
+ */
2294
+ interface ContentReviewRequestPayload {
2295
+ readonly agent: string;
2296
+ readonly service: string;
2297
+ readonly actionType: string;
2298
+ /** Defaults to `0` when omitted. Must be >= 0 if set. */
2299
+ readonly cost?: number;
2300
+ readonly metadata?: Readonly<Record<string, string | number | boolean>>;
2301
+ }
2302
+ /**
2303
+ * Create a content-review request via POST /api/v1/actions with `status: "requires_approval"`, then poll until decided.
2304
+ *
2305
+ * Wire format: response `data.content_review_id` (snake_case) per service Jackson naming.
2306
+ */
2307
+ declare function requestContentReview(payload: ContentReviewRequestPayload, apiKey: string, baseUrl: string, logger?: PluginLogger): Promise<ContentReviewResult>;
2308
+
2309
+ export { ACTION_STATUSES, AGENT_STATUSES, type Action, type ActionInput, type ActionLogger, type ActionLoggerConfig, type ActionPayload, type ActionStatus, type Agent, type AgentStatus, type ApiError, BUILT_IN_SERVICES, type BatchModeConfig, type BuiltInServiceName, CONSENT_ELEMENT_TAG, type ConsentDecision, type ConsentDeniedEventDetail, type ConsentEventDetail, type ConsentEventMap, type ConsentEventName, type ConsentGrantedEventDetail, type ConsentOptions, type ConsentPartialEventDetail, type ContentReviewRequestPayload, type ContentReviewResult, type ContentReviewStatusResponse, type FocusTrap, type McpAdapter, type McpAdapterConfig, type McpAdapterResult, type McpBlockedResult, type McpToolCall, type McpToolHandler, type McpToolResult, MulticornBadge, MulticornConsent, MulticornShield, type MulticornShieldConfig, PERMISSION_LEVELS, type Permission, type PermissionLevel, type RemainingBudget, SERVICE_NAME_PATTERN, type Scope, ScopeParseError, type ScopeParseResult, type ScopeRegistry, type ScopeRequest, type ServiceDefinition, type SpendCheckResult, type SpendingCheckResult, type SpendingChecker, type SpendingLimit, type SpendingLimits, type SpendingTrackerConfig, type ValidationResult, centsToDollars, createActionLogger, createFocusTrap, createMcpAdapter, createScopeRegistry, createSpendingChecker, dollarsToCents, formatScope, getPermissionLabel, getScopeLabel, getScopeShortLabel, getServiceDisplayName, getServiceIcon, hasScope, isBlockedResult, isPublicContentAction, isValidScopeString, parseScope, parseScopes, requestContentReview, requiresContentReview, tryParseScope, validateAllScopesAccess, validateScopeAccess };