@openclaw/crabline 0.1.16 → 0.1.18

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.
Files changed (39) hide show
  1. package/README.md +8 -0
  2. package/dist/src/openclaw/bridges/whatsapp.js +21 -1
  3. package/dist/src/openclaw/bridges/whatsapp.js.map +1 -1
  4. package/dist/src/openclaw/private-file.js +87 -30
  5. package/dist/src/openclaw/private-file.js.map +1 -1
  6. package/dist/src/openclaw/shared.d.ts +9 -0
  7. package/dist/src/openclaw/shared.js +2 -1
  8. package/dist/src/openclaw/shared.js.map +1 -1
  9. package/dist/src/platform/process-owned-lock.d.ts +5 -2
  10. package/dist/src/platform/process-owned-lock.js +20 -10
  11. package/dist/src/platform/process-owned-lock.js.map +1 -1
  12. package/dist/src/servers/discord.js +25 -35
  13. package/dist/src/servers/discord.js.map +1 -1
  14. package/dist/src/servers/http.d.ts +3 -0
  15. package/dist/src/servers/http.js +15 -0
  16. package/dist/src/servers/http.js.map +1 -1
  17. package/dist/src/servers/matrix.js +8 -8
  18. package/dist/src/servers/matrix.js.map +1 -1
  19. package/dist/src/servers/mattermost.js +7 -10
  20. package/dist/src/servers/mattermost.js.map +1 -1
  21. package/dist/src/servers/recorder.d.ts +16 -6
  22. package/dist/src/servers/recorder.js +52 -12
  23. package/dist/src/servers/recorder.js.map +1 -1
  24. package/dist/src/servers/signal.js +8 -8
  25. package/dist/src/servers/signal.js.map +1 -1
  26. package/dist/src/servers/slack.js +8 -8
  27. package/dist/src/servers/slack.js.map +1 -1
  28. package/dist/src/servers/telegram.d.ts +2 -2
  29. package/dist/src/servers/telegram.js +8 -8
  30. package/dist/src/servers/telegram.js.map +1 -1
  31. package/dist/src/servers/whatsapp-baileys-websocket.d.ts +15 -0
  32. package/dist/src/servers/whatsapp-baileys-websocket.js +32 -2
  33. package/dist/src/servers/whatsapp-baileys-websocket.js.map +1 -1
  34. package/dist/src/servers/whatsapp.js +189 -29
  35. package/dist/src/servers/whatsapp.js.map +1 -1
  36. package/dist/src/servers/zalo.js +8 -7
  37. package/dist/src/servers/zalo.js.map +1 -1
  38. package/docs/channel-setup.md +65 -1
  39. package/package.json +12 -12
package/README.md CHANGED
@@ -187,6 +187,14 @@ provider server, or `startOpenClawCrablineAdapter`. Crabline awaits the callback
187
187
  after appending each API/admin event to `recorderPath`, so callers can react in
188
188
  process while retaining the JSONL artifact as durable evidence.
189
189
 
190
+ Provider servers initialize recorder ownership before reporting readiness,
191
+ without creating recorder files or emitting synthetic events. Closing a server
192
+ stops new recorder admissions and waits for admitted persistence to finish.
193
+ Shutdown does not wait for event observers, which may themselves call `close()`.
194
+ Concurrent and repeated close calls share the same shutdown. All transports are
195
+ closed even if one fails, and the persistence drain includes asynchronous cleanup
196
+ after a failed recorder lock acquisition.
197
+
190
198
  Recorder files should normally have one filesystem name. If multiple processes
191
199
  cannot share the same OS account home, the home is read-only, or they write
192
200
  through hardlinks to the same recorder inode, set
@@ -25,7 +25,26 @@ function requireWhatsAppConversationKind(kind, targetId) {
25
25
  throw new Error("WhatsApp inbound conversation kind does not match the native JID.");
26
26
  }
27
27
  }
28
+ function whatsappInboundAudio(input) {
29
+ if (!input.attachments?.length) {
30
+ return undefined;
31
+ }
32
+ if (input.attachments.length !== 1 || input.attachments[0]?.kind !== "audio") {
33
+ throw new Error("WhatsApp Crabline inbound supports exactly one inline audio attachment.");
34
+ }
35
+ const attachment = input.attachments[0];
36
+ if (!attachment.contentBase64) {
37
+ throw new Error("WhatsApp Crabline inbound audio requires inline contentBase64.");
38
+ }
39
+ return {
40
+ contentBase64: attachment.contentBase64,
41
+ ...(attachment.fileName ? { fileName: attachment.fileName } : {}),
42
+ mimeType: attachment.mimeType,
43
+ ptt: true,
44
+ };
45
+ }
28
46
  export const WHATSAPP_OPENCLAW_CRABLINE_PROVIDER_BRIDGE = createOpenClawCrablineProviderBridge({
47
+ allowAttachmentOnlyInbound: true,
29
48
  provider: "whatsapp",
30
49
  createAdapter(whatsapp) {
31
50
  const messagesPath = new URL(whatsapp.endpoints.messagesUrl).pathname;
@@ -113,6 +132,7 @@ export const WHATSAPP_OPENCLAW_CRABLINE_PROVIDER_BRIDGE = createOpenClawCrabline
113
132
  requireWhatsAppConversationKind(input.conversation.kind, nativeChatJid);
114
133
  const nativeSenderJid = requireWhatsAppJid(input.senderId, "WhatsApp sender", true);
115
134
  const providerTargetKey = canonicalizeWhatsAppChatCorrelationJid(nativeChatJid);
135
+ const audio = whatsappInboundAudio(input);
116
136
  if (input.conversation.kind === "direct" &&
117
137
  canonicalizeWhatsAppUserCorrelationJid(nativeChatJid) !==
118
138
  canonicalizeWhatsAppUserCorrelationJid(nativeSenderJid)) {
@@ -124,7 +144,7 @@ export const WHATSAPP_OPENCLAW_CRABLINE_PROVIDER_BRIDGE = createOpenClawCrabline
124
144
  chatJid: nativeChatJid,
125
145
  senderJid: nativeSenderJid,
126
146
  ...(input.senderName ? { pushName: input.senderName } : {}),
127
- text: input.text,
147
+ ...(audio ? { audio } : { text: input.text }),
128
148
  },
129
149
  providerTargetKey,
130
150
  qaTarget: qaTargetForInbound({
@@ -1 +1 @@
1
- {"version":3,"file":"whatsapp.js","sourceRoot":"","sources":["../../../../src/openclaw/bridges/whatsapp.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,yBAAyB,EACzB,oCAAoC,EACpC,kBAAkB,EAClB,QAAQ,EACR,kBAAkB,EAClB,kBAAkB,EAClB,UAAU,GACX,MAAM,cAAc,CAAC;AACtB,OAAO,EACL,sCAAsC,EACtC,2BAA2B,EAC3B,sCAAsC,EACtC,2BAA2B,GAC5B,MAAM,+BAA+B,CAAC;AACvC,OAAO,EAAE,mBAAmB,EAAE,MAAM,qBAAqB,CAAC;AAE1D,SAAS,kBAAkB,CAAC,KAAa,EAAE,KAAa,EAAE,QAAQ,GAAG,KAAK;IACxE,MAAM,SAAS,GAAG,QAAQ;QACxB,CAAC,CAAC,2BAA2B,CAAC,KAAK,CAAC;QACpC,CAAC,CAAC,2BAA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c,EAAE,CAAC;oBACpB,OAAO,IAAI,CAAC;gBACd,CAAC;gBACD,OAAO;oBACL,SAAS,EAAE,kBAAkB;oBAC7B,QAAQ,EAAE,UAAU;oBACpB,UAAU,EAAE,aAAa;oBACzB,IAAI;oBACJ,kBAAkB,EAAE,CAAC,cAAc,CAAC;oBACpC,cAAc,EAAE,cAAc;iBAC/B,CAAC;YACJ,CAAC;SACF,CAAC;IACJ,CAAC;CACF,CAAC,CAAC","sourcesContent":["import {\n createAdminInboundRequest,\n createOpenClawCrablineProviderBridge,\n DEFAULT_ACCOUNT_ID,\n isRecord,\n qaTargetForInbound,\n readNonBlankString,\n readString,\n} from \"../shared.js\";\nimport {\n canonicalizeWhatsAppChatCorrelationJid,\n canonicalizeWhatsAppChatJid,\n canonicalizeWhatsAppUserCorrelationJid,\n canonicalizeWhatsAppUserJid,\n} from \"../../servers/whatsapp-jid.js\";\nimport { throwProbeHttpError } from \"./probe-response.js\";\n\nfunction requireWhatsAppJid(value: string, label: string, userOnly = false): string {\n const canonical = userOnly\n ? canonicalizeWhatsAppUserJid(value)\n : canonicalizeWhatsAppChatJid(value);\n if (!canonical) {\n throw new Error(`${label} must be a native WhatsApp JID.`);\n }\n return canonical;\n}\n\nfunction requireWhatsAppTargetKind(\n parsed: { kind: \"direct\" | \"group\"; native: boolean },\n targetId: string,\n): void {\n if (parsed.native && parsed.kind === \"direct\") {\n return;\n }\n const nativeKind = targetId.endsWith(\"@g.us\") ? \"group\" : \"direct\";\n if (parsed.kind !== nativeKind) {\n throw new Error(\"WhatsApp target kind does not match the native JID.\");\n }\n}\n\nfunction requireWhatsAppConversationKind(kind: \"direct\" | \"group\", targetId: string): void {\n const nativeKind = targetId.endsWith(\"@g.us\") ? \"group\" : \"direct\";\n if (kind !== nativeKind) {\n throw new Error(\"WhatsApp inbound conversation kind does not match the native JID.\");\n }\n}\n\nexport const WHATSAPP_OPENCLAW_CRABLINE_PROVIDER_BRIDGE = createOpenClawCrablineProviderBridge({\n provider: \"whatsapp\",\n createAdapter(whatsapp) {\n const messagesPath = new URL(whatsapp.endpoints.messagesUrl).pathname;\n return {\n async probe(signal) {\n const response = await fetch(whatsapp.endpoints.phoneNumberUrl, {\n headers: {\n authorization: `Bearer ${whatsapp.accessToken}`,\n },\n ...(signal ? { signal } : {}),\n });\n if (!response.ok) {\n await throwProbeHttpError(\n response,\n `Crabline WhatsApp probe failed with HTTP ${response.status}.`,\n );\n }\n const payload: unknown = await response.json();\n if (!isRecord(payload) || readString(payload.id) !== whatsapp.phoneNumberId) {\n throw new Error(\"Crabline WhatsApp probe returned an unexpected phone number.\");\n }\n return payload;\n },\n createBinding() {\n return {\n accountId: DEFAULT_ACCOUNT_ID,\n channel: \"whatsapp\",\n createProviderReadinessEnv: (env) => ({\n ...env,\n CRABLINE_WHATSAPP_ADMIN_TOKEN: whatsapp.adminToken,\n CRABLINE_WHATSAPP_RECORDER_PATH: whatsapp.recorderPath,\n CRABLINE_WHATSAPP_SELF_JID: whatsapp.selfJid,\n OPENCLAW_WHATSAPP_WEB_SOCKET_URL: whatsapp.endpoints.baileysWebSocketUrl,\n }),\n createGatewayConfig: (openclawConfig = {}) => {\n const channels = isRecord(openclawConfig.channels) ? openclawConfig.channels : {};\n const whatsappConfig = isRecord(channels.whatsapp) ? channels.whatsapp : {};\n const groups = isRecord(whatsappConfig.groups) ? whatsappConfig.groups : {};\n const defaultGroup = isRecord(groups[\"*\"]) ? groups[\"*\"] : {};\n\n return {\n ...openclawConfig,\n channels: {\n ...channels,\n whatsapp: {\n ...whatsappConfig,\n enabled: true,\n dmPolicy: \"open\",\n groupPolicy: \"open\",\n allowFrom: [\"*\"],\n groupAllowFrom: [\"*\"],\n groups: {\n ...groups,\n \"*\": {\n ...defaultGroup,\n requireMention: false,\n },\n },\n },\n },\n };\n },\n requiredPluginIds: [\"whatsapp\"],\n };\n },\n createAgentDelivery(parsed) {\n if (parsed.threadId !== undefined) {\n throw new Error(\"WhatsApp does not support thread targets.\");\n }\n const nativeTo = requireWhatsAppJid(parsed.id, \"WhatsApp target\");\n requireWhatsAppTargetKind(parsed, nativeTo);\n if (nativeTo.endsWith(\"@g.us\")) {\n throw new Error(\"WhatsApp Crabline WebSocket outbound supports direct targets only.\");\n }\n const to = canonicalizeWhatsAppUserCorrelationJid(nativeTo)!;\n return {\n channel: \"whatsapp\",\n providerTargetKey: to,\n to,\n replyChannel: \"whatsapp\",\n replyTo: to,\n };\n },\n createInbound(input) {\n if (input.threadId !== undefined) {\n throw new Error(\"WhatsApp does not support thread targets.\");\n }\n const nativeChatJid = requireWhatsAppJid(input.conversation.id, \"WhatsApp conversation\");\n requireWhatsAppConversationKind(input.conversation.kind, nativeChatJid);\n const nativeSenderJid = requireWhatsAppJid(input.senderId, \"WhatsApp sender\", true);\n const providerTargetKey = canonicalizeWhatsAppChatCorrelationJid(nativeChatJid)!;\n if (\n input.conversation.kind === \"direct\" &&\n canonicalizeWhatsAppUserCorrelationJid(nativeChatJid) !==\n canonicalizeWhatsAppUserCorrelationJid(nativeSenderJid)\n ) {\n throw new Error(\n \"WhatsApp direct conversation and sender must identify the same recipient.\",\n );\n }\n return {\n ...createAdminInboundRequest(whatsapp),\n providerBody: {\n chatJid: nativeChatJid,\n senderJid: nativeSenderJid,\n ...(input.senderName ? { pushName: input.senderName } : {}),\n text: input.text,\n },\n providerTargetKey,\n qaTarget: qaTargetForInbound({\n ...input,\n conversation: { ...input.conversation, id: providerTargetKey },\n }),\n stateConversation: {\n id: nativeChatJid,\n kind: nativeChatJid.endsWith(\"@g.us\") ? \"group\" : \"direct\",\n },\n };\n },\n createOutboundObservation({ event }) {\n if (\n !isRecord(event) ||\n event.type !== \"api\" ||\n event.accepted !== true ||\n typeof event.path !== \"string\"\n ) {\n return null;\n }\n if (!isRecord(event.body)) {\n return null;\n }\n const baileysKey = isRecord(event.body.key) ? event.body.key : undefined;\n const baileysMessage = isRecord(event.body.message) ? event.body.message : undefined;\n const isBaileysSend = event.method === \"WEBSOCKET\" && event.path === \"/ws/chat\";\n const messagingProduct = readString(event.body.messaging_product);\n const messageType = readString(event.body.type);\n const isCloudTextSend =\n event.method === \"POST\" &&\n event.path === messagesPath &&\n (!(\"messaging_product\" in event.body) || messagingProduct === \"whatsapp\") &&\n (!(\"type\" in event.body) || messageType === \"text\") &&\n !(\"status\" in event.body) &&\n !(\"message_id\" in event.body);\n if (!isBaileysSend && !isCloudTextSend) {\n return null;\n }\n const to = isBaileysSend ? readString(baileysKey?.remoteJid) : readString(event.body.to);\n const textPayload = event.body.text;\n const text = isBaileysSend\n ? readNonBlankString(baileysMessage?.conversation)\n : isRecord(textPayload)\n ? readNonBlankString(textPayload.body)\n : undefined;\n if (!to || !text) {\n return null;\n }\n const providerTarget = isBaileysSend\n ? canonicalizeWhatsAppChatCorrelationJid(to)\n : (canonicalizeWhatsAppChatJid(to) ??\n (/^\\d{7,15}$/u.test(to) ? `${to}@s.whatsapp.net` : to));\n if (!providerTarget) {\n return null;\n }\n return {\n accountId: DEFAULT_ACCOUNT_ID,\n senderId: \"openclaw\",\n senderName: \"OpenClaw QA\",\n text,\n providerTargetKeys: [providerTarget],\n fallbackTarget: providerTarget,\n };\n },\n };\n },\n});\n"]}
1
+ {"version":3,"file":"whatsapp.js","sourceRoot":"","sources":["../../../../src/openclaw/bridges/whatsapp.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,yBAAyB,EACzB,oCAAoC,EACpC,kBAAkB,EAClB,QAAQ,EACR,kBAAkB,EAClB,kBAAkB,EAClB,UAAU,GACX,MAAM,cAAc,CAAC;AACtB,OAAO,EACL,sCAAsC,EACtC,2BAA2B,EAC3B,sCAAsC,EACtC,2BAA2B,GAC5B,MAAM,+BAA+B,CAAC;AACvC,OAAO,EAAE,mBAAmB,EAAE,MAAM,qBAAqB,CAAC;AAE1D,SAAS,kBAAkB,CAAC,KAAa,EAAE,KAAa,EAAE,QAAQ,GAAG,KAAK;IACxE,MAAM,SAAS,GAAG,QAAQ;QACxB,CAAC,CAAC,2BAA2B,CAAC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AC;IACJ,CAAC;CACF,CAAC,CAAC","sourcesContent":["import {\n createAdminInboundRequest,\n createOpenClawCrablineProviderBridge,\n DEFAULT_ACCOUNT_ID,\n isRecord,\n qaTargetForInbound,\n readNonBlankString,\n readString,\n} from \"../shared.js\";\nimport {\n canonicalizeWhatsAppChatCorrelationJid,\n canonicalizeWhatsAppChatJid,\n canonicalizeWhatsAppUserCorrelationJid,\n canonicalizeWhatsAppUserJid,\n} from \"../../servers/whatsapp-jid.js\";\nimport { throwProbeHttpError } from \"./probe-response.js\";\n\nfunction requireWhatsAppJid(value: string, label: string, userOnly = false): string {\n const canonical = userOnly\n ? canonicalizeWhatsAppUserJid(value)\n : canonicalizeWhatsAppChatJid(value);\n if (!canonical) {\n throw new Error(`${label} must be a native WhatsApp JID.`);\n }\n return canonical;\n}\n\nfunction requireWhatsAppTargetKind(\n parsed: { kind: \"direct\" | \"group\"; native: boolean },\n targetId: string,\n): void {\n if (parsed.native && parsed.kind === \"direct\") {\n return;\n }\n const nativeKind = targetId.endsWith(\"@g.us\") ? \"group\" : \"direct\";\n if (parsed.kind !== nativeKind) {\n throw new Error(\"WhatsApp target kind does not match the native JID.\");\n }\n}\n\nfunction requireWhatsAppConversationKind(kind: \"direct\" | \"group\", targetId: string): void {\n const nativeKind = targetId.endsWith(\"@g.us\") ? \"group\" : \"direct\";\n if (kind !== nativeKind) {\n throw new Error(\"WhatsApp inbound conversation kind does not match the native JID.\");\n }\n}\n\nfunction whatsappInboundAudio(input: {\n attachments?:\n | Array<{\n contentBase64?: string | undefined;\n fileName?: string | undefined;\n kind: string;\n mimeType: string;\n }>\n | undefined;\n}) {\n if (!input.attachments?.length) {\n return undefined;\n }\n if (input.attachments.length !== 1 || input.attachments[0]?.kind !== \"audio\") {\n throw new Error(\"WhatsApp Crabline inbound supports exactly one inline audio attachment.\");\n }\n const attachment = input.attachments[0];\n if (!attachment.contentBase64) {\n throw new Error(\"WhatsApp Crabline inbound audio requires inline contentBase64.\");\n }\n return {\n contentBase64: attachment.contentBase64,\n ...(attachment.fileName ? { fileName: attachment.fileName } : {}),\n mimeType: attachment.mimeType,\n ptt: true,\n };\n}\n\nexport const WHATSAPP_OPENCLAW_CRABLINE_PROVIDER_BRIDGE = createOpenClawCrablineProviderBridge({\n allowAttachmentOnlyInbound: true,\n provider: \"whatsapp\",\n createAdapter(whatsapp) {\n const messagesPath = new URL(whatsapp.endpoints.messagesUrl).pathname;\n return {\n async probe(signal) {\n const response = await fetch(whatsapp.endpoints.phoneNumberUrl, {\n headers: {\n authorization: `Bearer ${whatsapp.accessToken}`,\n },\n ...(signal ? { signal } : {}),\n });\n if (!response.ok) {\n await throwProbeHttpError(\n response,\n `Crabline WhatsApp probe failed with HTTP ${response.status}.`,\n );\n }\n const payload: unknown = await response.json();\n if (!isRecord(payload) || readString(payload.id) !== whatsapp.phoneNumberId) {\n throw new Error(\"Crabline WhatsApp probe returned an unexpected phone number.\");\n }\n return payload;\n },\n createBinding() {\n return {\n accountId: DEFAULT_ACCOUNT_ID,\n channel: \"whatsapp\",\n createProviderReadinessEnv: (env) => ({\n ...env,\n CRABLINE_WHATSAPP_ADMIN_TOKEN: whatsapp.adminToken,\n CRABLINE_WHATSAPP_RECORDER_PATH: whatsapp.recorderPath,\n CRABLINE_WHATSAPP_SELF_JID: whatsapp.selfJid,\n OPENCLAW_WHATSAPP_WEB_SOCKET_URL: whatsapp.endpoints.baileysWebSocketUrl,\n }),\n createGatewayConfig: (openclawConfig = {}) => {\n const channels = isRecord(openclawConfig.channels) ? openclawConfig.channels : {};\n const whatsappConfig = isRecord(channels.whatsapp) ? channels.whatsapp : {};\n const groups = isRecord(whatsappConfig.groups) ? whatsappConfig.groups : {};\n const defaultGroup = isRecord(groups[\"*\"]) ? groups[\"*\"] : {};\n\n return {\n ...openclawConfig,\n channels: {\n ...channels,\n whatsapp: {\n ...whatsappConfig,\n enabled: true,\n dmPolicy: \"open\",\n groupPolicy: \"open\",\n allowFrom: [\"*\"],\n groupAllowFrom: [\"*\"],\n groups: {\n ...groups,\n \"*\": {\n ...defaultGroup,\n requireMention: false,\n },\n },\n },\n },\n };\n },\n requiredPluginIds: [\"whatsapp\"],\n };\n },\n createAgentDelivery(parsed) {\n if (parsed.threadId !== undefined) {\n throw new Error(\"WhatsApp does not support thread targets.\");\n }\n const nativeTo = requireWhatsAppJid(parsed.id, \"WhatsApp target\");\n requireWhatsAppTargetKind(parsed, nativeTo);\n if (nativeTo.endsWith(\"@g.us\")) {\n throw new Error(\"WhatsApp Crabline WebSocket outbound supports direct targets only.\");\n }\n const to = canonicalizeWhatsAppUserCorrelationJid(nativeTo)!;\n return {\n channel: \"whatsapp\",\n providerTargetKey: to,\n to,\n replyChannel: \"whatsapp\",\n replyTo: to,\n };\n },\n createInbound(input) {\n if (input.threadId !== undefined) {\n throw new Error(\"WhatsApp does not support thread targets.\");\n }\n const nativeChatJid = requireWhatsAppJid(input.conversation.id, \"WhatsApp conversation\");\n requireWhatsAppConversationKind(input.conversation.kind, nativeChatJid);\n const nativeSenderJid = requireWhatsAppJid(input.senderId, \"WhatsApp sender\", true);\n const providerTargetKey = canonicalizeWhatsAppChatCorrelationJid(nativeChatJid)!;\n const audio = whatsappInboundAudio(input);\n if (\n input.conversation.kind === \"direct\" &&\n canonicalizeWhatsAppUserCorrelationJid(nativeChatJid) !==\n canonicalizeWhatsAppUserCorrelationJid(nativeSenderJid)\n ) {\n throw new Error(\n \"WhatsApp direct conversation and sender must identify the same recipient.\",\n );\n }\n return {\n ...createAdminInboundRequest(whatsapp),\n providerBody: {\n chatJid: nativeChatJid,\n senderJid: nativeSenderJid,\n ...(input.senderName ? { pushName: input.senderName } : {}),\n ...(audio ? { audio } : { text: input.text }),\n },\n providerTargetKey,\n qaTarget: qaTargetForInbound({\n ...input,\n conversation: { ...input.conversation, id: providerTargetKey },\n }),\n stateConversation: {\n id: nativeChatJid,\n kind: nativeChatJid.endsWith(\"@g.us\") ? \"group\" : \"direct\",\n },\n };\n },\n createOutboundObservation({ event }) {\n if (\n !isRecord(event) ||\n event.type !== \"api\" ||\n event.accepted !== true ||\n typeof event.path !== \"string\"\n ) {\n return null;\n }\n if (!isRecord(event.body)) {\n return null;\n }\n const baileysKey = isRecord(event.body.key) ? event.body.key : undefined;\n const baileysMessage = isRecord(event.body.message) ? event.body.message : undefined;\n const isBaileysSend = event.method === \"WEBSOCKET\" && event.path === \"/ws/chat\";\n const messagingProduct = readString(event.body.messaging_product);\n const messageType = readString(event.body.type);\n const isCloudTextSend =\n event.method === \"POST\" &&\n event.path === messagesPath &&\n (!(\"messaging_product\" in event.body) || messagingProduct === \"whatsapp\") &&\n (!(\"type\" in event.body) || messageType === \"text\") &&\n !(\"status\" in event.body) &&\n !(\"message_id\" in event.body);\n if (!isBaileysSend && !isCloudTextSend) {\n return null;\n }\n const to = isBaileysSend ? readString(baileysKey?.remoteJid) : readString(event.body.to);\n const textPayload = event.body.text;\n const text = isBaileysSend\n ? readNonBlankString(baileysMessage?.conversation)\n : isRecord(textPayload)\n ? readNonBlankString(textPayload.body)\n : undefined;\n if (!to || !text) {\n return null;\n }\n const providerTarget = isBaileysSend\n ? canonicalizeWhatsAppChatCorrelationJid(to)\n : (canonicalizeWhatsAppChatJid(to) ??\n (/^\\d{7,15}$/u.test(to) ? `${to}@s.whatsapp.net` : to));\n if (!providerTarget) {\n return null;\n }\n return {\n accountId: DEFAULT_ACCOUNT_ID,\n senderId: \"openclaw\",\n senderName: \"OpenClaw QA\",\n text,\n providerTargetKeys: [providerTarget],\n fallbackTarget: providerTarget,\n };\n },\n };\n },\n});\n"]}
@@ -730,28 +730,80 @@ async function syncPathAncestry(filePath, syncParent, platform, firstCreatedDire
730
730
  currentPath = parentPath;
731
731
  }
732
732
  }
733
- async function darwinDirectoryHasExtendedAcl(directoryPath) {
733
+ // Directory rights from chmod(1); inheritance flags are deliberately not rights.
734
+ const DARWIN_DIRECTORY_ACL_RIGHTS = new Set([
735
+ "list",
736
+ "add_file",
737
+ "search",
738
+ "delete",
739
+ "add_subdirectory",
740
+ "delete_child",
741
+ "readattr",
742
+ "writeattr",
743
+ "readextattr",
744
+ "writeextattr",
745
+ "readsecurity",
746
+ "writesecurity",
747
+ "chown",
748
+ ]);
749
+ async function readDarwinDirectoryAcl(directoryPath) {
734
750
  if (process.platform !== "darwin") {
735
- return false;
751
+ return "none";
736
752
  }
753
+ const directory = await captureDirectoryIdentity(directoryPath);
737
754
  let output;
738
755
  try {
739
- const result = await execFileAsync("/bin/ls", ["-lde", directoryPath], {
756
+ // A literal basename prevents newline-containing paths from impersonating ACEs.
757
+ const result = await execFileAsync("/bin/ls", ["-lde", "."], {
758
+ cwd: directoryPath,
740
759
  encoding: "utf8",
741
760
  env: { ...process.env, LC_ALL: "C" },
742
761
  maxBuffer: 64 * 1024,
743
762
  });
763
+ if (result.stderr.length > 0) {
764
+ throw new Error("macOS ACL inspection reported a diagnostic.");
765
+ }
744
766
  output = result.stdout;
745
767
  }
746
768
  catch (error) {
747
769
  throw new Error("Could not verify the private directory macOS ACL.", { cause: error });
748
770
  }
749
- const mode = output.trimStart().split(/\s+/u, 1)[0] ?? "";
750
- return mode.includes("+");
771
+ await directory.assertIdentityAt();
772
+ for (const character of output) {
773
+ const code = character.charCodeAt(0);
774
+ if ((code < 32 && character !== "\n") || (code >= 127 && code <= 159)) {
775
+ return "unsafe";
776
+ }
777
+ }
778
+ const [header, ...entries] = output.slice(0, -1).split("\n");
779
+ const mode = header?.match(/^d[r-][w-][xsS-][r-][w-][xsS-][r-][w-][xtT-]([+@]?) +[1-9]\d* +\S+ +\S+ +\d+ +[A-Z][a-z]{2} +\d{1,2} +(?:\d{2}:\d{2}|\d{4}) +\.$/u);
780
+ if (!output.endsWith("\n") || !mode) {
781
+ return "unsafe";
782
+ }
783
+ // Extended attributes take precedence over '+' in ls, even when an ACL exists.
784
+ if (entries.length === 0) {
785
+ return mode[1] === "+" ? "unsafe" : "none";
786
+ }
787
+ if (mode[1] === "") {
788
+ return "unsafe";
789
+ }
790
+ for (const [index, entry] of entries.entries()) {
791
+ // 'inherited' records origin; unlike *_inherit flags it does not propagate.
792
+ const ace = entry.match(/^ +(\d+): (?:user|group):\S+ (?:inherited )?deny ([a-z_]+(?:,[a-z_]+)*)$/u);
793
+ if (!ace ||
794
+ ace[1] !== String(index) ||
795
+ !ace[2].split(",").every((right) => DARWIN_DIRECTORY_ACL_RIGHTS.has(right))) {
796
+ return "unsafe";
797
+ }
798
+ }
799
+ return "nonpropagating-deny";
751
800
  }
752
- async function assertDarwinDirectoryHasNoExtendedAcl(directoryPath) {
753
- if (await darwinDirectoryHasExtendedAcl(directoryPath)) {
754
- throw new Error("Private directory must not have a macOS extended ACL.");
801
+ async function assertDarwinDirectoryAcl(directoryPath, scope) {
802
+ const acl = await readDarwinDirectoryAcl(directoryPath);
803
+ if (acl === "unsafe" || (scope === "private" && acl !== "none")) {
804
+ throw new Error(scope === "private"
805
+ ? "Private directory must not have a macOS extended ACL."
806
+ : "Private mutation ancestry has an unsafe or unverifiable macOS ACL.");
755
807
  }
756
808
  }
757
809
  async function removeDarwinExtendedAcl(directoryPath) {
@@ -812,7 +864,7 @@ async function assertDarwinCreatedAncestryHasNoExtendedAcl(firstCreatedDirectory
812
864
  currentPath = parentPath;
813
865
  }
814
866
  for (const createdPath of createdPaths.reverse()) {
815
- await assertDarwinDirectoryHasNoExtendedAcl(createdPath);
867
+ await assertDarwinDirectoryAcl(createdPath, "private");
816
868
  }
817
869
  }
818
870
  async function captureSingleSafePrivateMutationBoundary(directoryPath, platform, stickyTargetOwnedByCurrentUser) {
@@ -824,6 +876,7 @@ async function captureSingleSafePrivateMutationBoundary(directoryPath, platform,
824
876
  if (currentUserId === undefined || !Number.isSafeInteger(currentUserId) || currentUserId < 0) {
825
877
  throw new Error("Could not resolve the current POSIX user for private mutation.");
826
878
  }
879
+ const boundary = await captureDirectoryIdentity(directoryPath);
827
880
  const stats = await fs.lstat(directoryPath, { bigint: true });
828
881
  if (!stats.isDirectory()) {
829
882
  throw new Error("Private mutation boundary is not a directory.");
@@ -837,8 +890,9 @@ async function captureSingleSafePrivateMutationBoundary(directoryPath, platform,
837
890
  if (writableByAnotherPrincipal && !protectedByStickyOwnership) {
838
891
  throw new Error("Private mutation boundary is writable by another POSIX principal.");
839
892
  }
840
- await assertDarwinDirectoryHasNoExtendedAcl(directoryPath);
841
- return await captureDirectoryIdentity(directoryPath);
893
+ await assertDarwinDirectoryAcl(directoryPath, "ancestor");
894
+ await boundary.assertIdentityAt();
895
+ return boundary;
842
896
  }
843
897
  async function captureSafePrivateMutationBoundary(directoryPath, platform, stickyTargetOwnedByCurrentUser) {
844
898
  const resolvedBoundaryPath = path.resolve(directoryPath);
@@ -993,7 +1047,7 @@ export async function securePrivateDirectory(directoryPath, options = {}) {
993
1047
  }
994
1048
  }
995
1049
  if (!existed) {
996
- await assertDarwinDirectoryHasNoExtendedAcl(path.dirname(directoryPath));
1050
+ await assertDarwinDirectoryAcl(path.dirname(directoryPath), "ancestor");
997
1051
  }
998
1052
  try {
999
1053
  await fs.mkdir(directoryPath, { mode: 0o700 });
@@ -1059,7 +1113,7 @@ export async function securePrivateDirectory(directoryPath, options = {}) {
1059
1113
  const currentStats = await handle.stat({ bigint: true });
1060
1114
  const mutationRootMode = options.markMutationRoot === false ? currentStats.mode & 512n : 512n;
1061
1115
  await handle.chmod(Number(448n | mutationRootMode));
1062
- await assertDarwinDirectoryHasNoExtendedAcl(directoryPath);
1116
+ await assertDarwinDirectoryAcl(directoryPath, "private");
1063
1117
  await (options.syncDirectory ?? (() => handle.sync()))();
1064
1118
  }
1065
1119
  await secured.assertIdentityAt();
@@ -1263,19 +1317,25 @@ function parsePrivateMutationClaimOwner(contents) {
1263
1317
  }
1264
1318
  return owner;
1265
1319
  }
1266
- async function assertClaimPathIdentity(claimPath, expected, expectedLinkCount) {
1320
+ async function claimPathHasIdentity(claimPath, expected, expectedLinkCount) {
1267
1321
  try {
1268
1322
  const stats = await fs.lstat(claimPath, { bigint: true });
1269
- if (stats.isFile() &&
1323
+ return (stats.isFile() &&
1270
1324
  (expectedLinkCount === undefined ? stats.nlink >= 1n : stats.nlink === expectedLinkCount) &&
1271
1325
  stats.dev === expected.device &&
1272
- stats.ino === expected.inode) {
1273
- return;
1274
- }
1326
+ stats.ino === expected.inode);
1275
1327
  }
1276
1328
  catch (error) {
1329
+ if (error.code === "ENOENT") {
1330
+ return false;
1331
+ }
1277
1332
  throw new Error("Private path mutation claim identity changed.", { cause: error });
1278
1333
  }
1334
+ }
1335
+ async function assertClaimPathIdentity(claimPath, expected, expectedLinkCount) {
1336
+ if (await claimPathHasIdentity(claimPath, expected, expectedLinkCount)) {
1337
+ return;
1338
+ }
1279
1339
  throw new Error("Private path mutation claim identity changed.");
1280
1340
  }
1281
1341
  function assertOwnerOnlyPosixMutationClaim(stats, kind) {
@@ -1331,7 +1391,11 @@ async function readPrivateMutationClaim(claimPath) {
1331
1391
  }
1332
1392
  const contents = buffer.toString("utf8");
1333
1393
  const owner = parsePrivateMutationClaimOwner(contents);
1334
- await assertClaimPathIdentity(claimPath, identity);
1394
+ // A live owner may release or replace this pathname after our handle opens.
1395
+ // The open handle is safe, but its metadata is no longer the active claim.
1396
+ if (!(await claimPathHasIdentity(claimPath, identity))) {
1397
+ return null;
1398
+ }
1335
1399
  return { contents, identity, owner };
1336
1400
  }
1337
1401
  catch (error) {
@@ -1399,15 +1463,6 @@ async function acquireHardLinkPrivateMutationClaim(parent, options) {
1399
1463
  (runtime.processIdentity.length === 0 || runtime.processIdentity.length > 256))) {
1400
1464
  throw new Error("Private path mutation claim runtime is invalid.");
1401
1465
  }
1402
- if (!Number.isSafeInteger(runtime.pid) ||
1403
- runtime.pid <= 0 ||
1404
- !PRIVATE_MUTATION_CLAIM_OWNER_ID_PATTERN.test(runtime.ownerId) ||
1405
- !Number.isSafeInteger(runtime.processStartedAtMs) ||
1406
- runtime.processStartedAtMs <= 0 ||
1407
- (runtime.processIdentity !== undefined &&
1408
- (runtime.processIdentity.length === 0 || runtime.processIdentity.length > 256))) {
1409
- throw new Error("Private path mutation claim runtime is invalid.");
1410
- }
1411
1466
  const ownerContents = `${JSON.stringify({
1412
1467
  ownerId: runtime.ownerId,
1413
1468
  pid: runtime.pid,
@@ -2128,17 +2183,19 @@ async function captureOwnerOnlyPrivateClaimAncestor(directoryPath, platform) {
2128
2183
  if (currentUserId === undefined || !Number.isSafeInteger(currentUserId) || currentUserId < 0) {
2129
2184
  throw new Error("Could not resolve the current POSIX user for private mutation claims.");
2130
2185
  }
2186
+ const directory = await captureDirectoryIdentity(directoryPath);
2131
2187
  const stats = await fs.lstat(directoryPath, { bigint: true });
2132
2188
  if (!stats.isDirectory()) {
2133
2189
  throw new Error("Private mutation claim ancestry contains a non-directory entry.");
2134
2190
  }
2135
2191
  if (stats.uid !== BigInt(currentUserId) ||
2136
2192
  (stats.mode & 18n) !== 0n ||
2137
- (await darwinDirectoryHasExtendedAcl(directoryPath))) {
2193
+ (await readDarwinDirectoryAcl(directoryPath)) === "unsafe") {
2138
2194
  return null;
2139
2195
  }
2196
+ await directory.assertIdentityAt();
2140
2197
  return {
2141
- directory: await captureDirectoryIdentity(directoryPath),
2198
+ directory,
2142
2199
  mutationRoot: (stats.mode & 512n) !== 0n,
2143
2200
  };
2144
2201
  }