UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

10 lines (9 loc) • 12.9 kB
import{l as normalizeOptionalString,o as normalizeLowercaseStringOrEmpty}from"../../string-coerce-CpTFcSwY.mjs";import{r as createLazyRuntimeModule}from"../../lazy-runtime-Ds6M7vp4.mjs";import"../../string-coerce-runtime-BYDH9Quw.mjs";import{t as definePluginEntry}from"../../plugin-entry-DhKiQ4Uu.mjs";import path from"node:path";import{rm}from"node:fs/promises";import os from"node:os";import{isIP}from"node:net"; //!extensions/device-pair/index.ts const loadDevicePairApiModule=createLazyRuntimeModule(()=>import(`./api.js`));const loadNotifyModule=createLazyRuntimeModule(()=>import(`./notify.js`));const loadPairCommandApproveModule=createLazyRuntimeModule(()=>import(`./pair-command-approve.js`));const loadPairCommandAuthModule=createLazyRuntimeModule(()=>import(`./pair-command-auth.js`));function formatDurationMinutes(e){const t=Math.max(0,e-Date.now());const n=Math.max(1,Math.ceil(t/6e4));return`${n} minute${n===1?``:`s`}`}const QR_SUPPORTED_CHANNELS=/* @__PURE__ */ new Set([`telegram`,`discord`,`slack`,`signal`,`imessage`,`whatsapp`]);function describeSecureMobilePairingFix(e){return`Tailscale and public mobile pairing require a secure gateway URL (wss://) or Tailscale Serve/Funnel.`+(e?` Resolved source: ${e}.`:``)+` Fix: use a private LAN address, prefer gateway.tailscale.mode=serve, or set gateway.remote.url / plugins.entries.device-pair.config.publicUrl to a wss:// URL. ws:// setup codes are only valid for localhost/loopback, private LAN addresses, .local hosts, or the Android emulator.`}function normalizeHostForIpCheck(e){let t=normalizeLowercaseStringOrEmpty(e);if(t.startsWith(`[`)&&t.endsWith(`]`))t=t.slice(1,-1);if(t.endsWith(`.`))t=t.slice(0,-1);const n=t.indexOf(`%`);if(n>=0)t=t.slice(0,n);return t}function isLoopbackHost(e){const t=normalizeHostForIpCheck(e);if(!t)return false;if(t===`localhost`)return true;const n=parseIPv4Octets(t);if(n)return n[0]===127;return t===`::1`||t===`0:0:0:0:0:0:0:1`}function parseIPv4Octets(e){const t=e.split(`.`);if(t.length!==4)return null;if(t.some(e=>!/^\d+$/.test(e)))return null;const n=t.map(e=>Number.parseInt(e,10));if(n.some(e=>!Number.isFinite(e)||e<0||e>255))return null;return n}function isPrivateIPv4(e){const t=parseIPv4Octets(e);if(!t)return false;const[n,r]=t;if(n===10)return true;if(n===172&&r>=16&&r<=31)return true;if(n===192&&r===168)return true;return false}function isPrivateLanIPv6(e){if(isIP(e)!==6)return false;const t=e.split(`:`,1)[0]??``;if(!/^[0-9a-f]{4}$/.test(t))return false;const n=Number.parseInt(t,16);return(n&65024)===64512||(n&65472)===65152}function isPrivateLanCleartextHost(e){const t=normalizeHostForIpCheck(e);if(t.endsWith(`.local`))return true;if(isPrivateIPv4(t)||isPrivateLanIPv6(t))return true;const n=parseIPv4Octets(t);if(!n)return false;return n[0]===169&&n[1]===254}function isMobilePairingCleartextAllowedHost(e){const t=normalizeHostForIpCheck(e);return isLoopbackHost(t)||t===`10.0.2.2`||isPrivateLanCleartextHost(t)}function validateMobilePairingUrl(e,t){const n=URL.parse(e);if(!n)return`Resolved mobile pairing URL is invalid.`;const r=n.protocol===`https:`?`wss:`:n.protocol===`http:`?`ws:`:n.protocol;if(r===`wss:`)return null;if(r!==`ws:`||isMobilePairingCleartextAllowedHost(n.hostname))return null;return describeSecureMobilePairingFix(t)}function isFullAccessMobilePairingUrl(e){const t=URL.parse(e);return t?.protocol===`wss:`||t?.protocol===`ws:`&&isLoopbackHost(t.hostname)}async function resolveMobilePairingGatewayUrl(e){const{resolvePairingGatewayUrl:t,runPluginCommandWithTimeout:n}=await loadDevicePairApiModule();const r=e.pluginConfig??{};const i=await t(e.config,{env:process.env,publicUrl:r.publicUrl,urlPathMode:`origin-only`,networkInterfaces:os.networkInterfaces,runCommandWithTimeout:(e,t)=>n({argv:e,timeoutMs:t.timeoutMs})});if(!i.url)return i;const a=validateMobilePairingUrl(i.url,i.source);if(a)return{error:a};return i}function encodeSetupCode(e){return Buffer.from(JSON.stringify(e),`utf8`).toString(`base64url`)}function buildPairingFlowLines(e){return[`1) Open the iOS app → Settings → Gateway`,`2) ${e}`,`3) Back here, run /pair approve`,`4) If this code leaks or you are done, run /pair cleanup`]}function buildSecurityNoticeLines(e){const t=e.markdown?"`/pair cleanup`":`/pair cleanup`;const n=e.markdown?`- `:``;const r=e.markdown?`**Important:** Run ${t} after pairing finishes.`:`IMPORTANT: After pairing finishes, run ${t}.`;return[`${n}Security: single-use bootstrap token`,`${n}Expires: ${formatDurationMinutes(e.expiresAtMs)}`,``,r,`If this ${e.kind} leaks, run ${t} immediately.`]}function buildQrFollowUpLines(e){return e?[`After scanning, wait here for the pairing request ping.`,`I’ll auto-ping here when the pairing request arrives, then auto-disable.`,"If the ping does not arrive, run `/pair approve latest` manually."]:["After scanning, run `/pair approve` to complete pairing."]}function formatSetupReply(e,t){const n=encodeSetupCode(e);return[`Pairing setup code generated.`,``,...buildPairingFlowLines(`Paste the setup code below and tap Connect`),``,`Setup code:`,n,``,`Gateway: ${e.url}`,`Auth: ${t}`,...buildAccessLines(e),...buildSecurityNoticeLines({kind:`setup code`,expiresAtMs:e.expiresAtMs})].join(` `)}function formatSetupInstructions(e){return[`Pairing setup code generated.`,``,...buildPairingFlowLines(`Paste the setup code from my next message and tap Connect`),``,...buildSecurityNoticeLines({kind:`setup code`,expiresAtMs:e})].join(` `)}function buildQrInfoLines(e){const t=e.markdown?`- `:``;return[`${t}Gateway: ${e.payload.url}`,`${t}Auth: ${e.authLabel}`,...buildAccessLines(e.payload,e.markdown),...buildSecurityNoticeLines({kind:`QR code`,expiresAtMs:e.payload.expiresAtMs,markdown:e.markdown}),``,...buildQrFollowUpLines(e.autoNotifyArmed),``,"If your camera still won’t lock on, run `/pair` for a pasteable setup code."]}function resolveQrReplyTarget(e){if(e.channel===`discord`){const t=normalizeOptionalString(e.senderId)??``;if(t)return t.startsWith(`user:`)||t.startsWith(`channel:`)?t:`user:${t}`}return normalizeOptionalString(e.senderId)||normalizeOptionalString(e.from)||normalizeOptionalString(e.to)||``}function buildAccessLines(e,t=false){const n=t?`- `:``;return[`${n}Access: ${e.access}`,...e.accessDowngraded?[`${n}Plaintext ws:// was limited for safety. Use wss:// or Tailscale Serve, then generate a new code for full access.`]:[]]}async function issueSetupPayload(e){const t=e.assertCurrent;const{issueDeviceBootstrapToken:n,PAIRING_SETUP_BOOTSTRAP_PROFILE:r}=await loadDevicePairApiModule();const i=!isFullAccessMobilePairingUrl(e.url);const a=e.allowFullAccess&&!i;const o=e.allowFullAccess&&i;const s=await n({...t?{assertCurrent:t}:{},profile:a?{roles:[...r.roles],scopes:[`operator.admin`,...r.scopes],purpose:`mobile-full`}:r});return{url:e.url,bootstrapToken:s.token,expiresAtMs:s.expiresAtMs,access:a?`full`:`limited`,...o?{accessDowngraded:true}:{}}}var device_pair_default=definePluginEntry({id:`device-pair`,name:`Device Pair`,description:`QR/bootstrap pairing helpers for OpenClaw devices`,register(e){e.registerService({id:`device-pair-notifier`,apiVersion:2,start:async({scheduler:t})=>{const{startPairingNotifier:n}=await loadNotifyModule();n(e,t)}});e.registerCommand({name:`pair`,description:`Generate setup codes and approve device pairing requests.`,acceptsArgs:true,clientPresentation:{when:`no-arguments`,action:{kind:`device-pairing`}},requiredScopes:[`operator.pairing`],handler:async t=>{const n=t.assertOwnerCurrent;const r=(normalizeOptionalString(t.args)??``).split(/\s+/).filter(Boolean);const i=normalizeLowercaseStringOrEmpty(r[0]);const a=Array.isArray(t.gatewayClientScopes)?t.gatewayClientScopes:void 0;const{resolveAuthLabel:o,resolvePairingCommandAuthState:s}=await loadPairCommandAuthModule();const c=s({channel:t.channel,gatewayClientScopes:a,senderIsOwner:t.senderIsOwner});const l=c.isInternalGatewayCaller?void 0:n;e.logger.info?.(`device-pair: /pair invoked channel=${t.channel} sender=${t.senderId??`unknown`} action=${i||`new`}`);if(c.isMissingPairingPrivilege)return{text:`⚠️ This command requires operator.pairing.`};l?.();if(i===`status`||i===`pending`){const[{listDevicePairing:e},{formatPendingRequests:t}]=await Promise.all([loadDevicePairApiModule(),loadNotifyModule()]);const n=await e();l?.();return{text:t(n.pending)}}if(i===`notify`){const n=normalizeLowercaseStringOrEmpty(r[1])||`status`;const{handleNotifyCommand:i}=await loadNotifyModule();return await i({api:e,ctx:{...t,assertOwnerCurrent:l},action:n})}if(i===`approve`){const[{listDevicePairing:e},{approvePendingPairingRequest:t,selectPendingApprovalRequest:n}]=await Promise.all([loadDevicePairApiModule(),loadPairCommandApproveModule()]);const i=n({pending:(await e()).pending,requested:normalizeOptionalString(r[1])});if(i.reply)return i.reply;const a=i.pending;if(!a)return{text:`Pairing request not found.`};return await t({requestId:a.requestId,callerScopes:c.approvalCallerScopes,assertCurrent:l})}if(i===`cleanup`||i===`clear`||i===`revoke`){const{clearDeviceBootstrapTokens:e}=await loadDevicePairApiModule();const t=await e({assertCurrent:l});return{text:t.removed>0?`Invalidated ${t.removed} unused setup code${t.removed===1?``:`s`}.`:`No unused setup codes were active.`}}if(c.isMissingSetupHandoffPrivilege)return{text:`⚠️ Setup code handoff includes Talk secrets and requires operator.talk.secrets.`};const u=o(e.config);if(u.error)return{text:`Error: ${u.error}`};const d=await resolveMobilePairingGatewayUrl(e);if(!d.url)return{text:`Error: ${d.error??`Gateway URL unavailable.`}`};const f=u.label??`auth`;const p={url:d.url,allowFullAccess:c.canIssueFullAccessSetup,assertCurrent:l};if(i===`qr`){const n=t.channel;const r=resolveQrReplyTarget(t);let i=false;if(n===`telegram`&&r)try{const{armPairNotifyOnce:n}=await loadNotifyModule();i=await n({api:e,ctx:{...t,assertOwnerCurrent:l}})}catch(t){e.logger.warn?.(`device-pair: failed to arm one-shot pairing notify (${t?.message??t})`)}let a=await issueSetupPayload(p);let o=encodeSetupCode(a);const s=buildQrInfoLines({payload:a,authLabel:f,autoNotifyArmed:i});if(r&&QR_SUPPORTED_CHANNELS.has(n)){let i;try{const{resolvePreferredOpenClawTmpDir:n,writeQrPngTempFile:c}=await loadDevicePairApiModule();i=(await c(o,{tmpRoot:n(),dirPrefix:`device-pair-qr-`,fileName:`pair-qr.png`})).filePath;const l=[path.dirname(i)];const u=normalizeOptionalString(t.accountId)||void 0;const d=(await e.runtime.channel.outbound.loadAdapter(t.channel))?.sendMedia;if(d){await d({cfg:e.config,to:r,text:[`Scan this QR code with the OpenClaw iOS app:`,``,...s].join(` `),...t.channel===`whatsapp`?{verbose:false}:{},mediaUrl:i,mediaLocalRoots:l,...t.messageThreadId!=null&&(t.channel===`telegram`||t.channel===`slack`)?{threadId:t.channel===`slack`?String(t.messageThreadId):t.messageThreadId}:{},...u?{accountId:u}:{}});return{text:`QR code sent above.\nExpires: ${formatDurationMinutes(a.expiresAtMs)}\nIMPORTANT: Run /pair cleanup after pairing finishes.`}}}catch(t){const{revokeDeviceBootstrapToken:r}=await loadDevicePairApiModule();e.logger.warn?.(`device-pair: QR image send failed channel=${n}, falling back (${t?.message??t})`);await r({token:a.bootstrapToken}).catch(()=>{});a=await issueSetupPayload(p);o=encodeSetupCode(a)}finally{if(i)await rm(path.dirname(i),{recursive:true,force:true}).catch(()=>{})}}e.logger.info?.(`device-pair: QR fallback channel=${n} target=${r}`);if(n===`webchat`)return{text:[`Scan this QR code with the OpenClaw iOS app:`,``,buildQrInfoLines({payload:a,authLabel:f,autoNotifyArmed:i,markdown:true}).join(` `)].join(` `),channelData:{openclawPairingQr:{setupCode:o,expiresAtMs:a.expiresAtMs}},sensitiveMedia:true};return{text:`QR image delivery is not available on this channel, so I generated a pasteable setup code instead. `+formatSetupReply(a,f)}}const m=t.channel;const h=normalizeOptionalString(t.senderId)||normalizeOptionalString(t.from)||normalizeOptionalString(t.to)||``;const g=await issueSetupPayload(p);if(m===`telegram`&&h)try{const n=Object.keys(e.runtime);const r=Object.keys(e.runtime.channel);e.logger.debug?.(`device-pair: runtime keys=${n.join(`,`)||`none`} channel keys=${r.join(`,`)||`none`}`);const i=(await e.runtime.channel.outbound.loadAdapter(`telegram`))?.sendText;if(!i)throw new Error(`telegram runtime unavailable (runtime keys: ${n.join(`,`)}; channel keys: ${r.join(`,`)})`);await i({cfg:e.config,to:h,text:formatSetupInstructions(g.expiresAtMs),...t.messageThreadId!=null?{threadId:t.messageThreadId}:{},...t.accountId?{accountId:t.accountId}:{}});e.logger.info?.(`device-pair: telegram split send ok target=${h} account=${t.accountId??`none`} thread=${t.messageThreadId??`none`}`);return{text:encodeSetupCode(g)}}catch(t){e.logger.warn?.(`device-pair: telegram split send failed, falling back to single message (${t?.message??t})`)}return{text:formatSetupReply(g,f)}}})}});export{device_pair_default as default};