agent-messenger 2.23.3 → 2.23.5
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/.claude-plugin/plugin.json +1 -1
- package/README.md +2 -2
- package/dist/package.json +1 -1
- package/dist/src/platforms/webex/cli.d.ts.map +1 -1
- package/dist/src/platforms/webex/cli.js +2 -1
- package/dist/src/platforms/webex/cli.js.map +1 -1
- package/dist/src/platforms/webex/client.d.ts +4 -0
- package/dist/src/platforms/webex/client.d.ts.map +1 -1
- package/dist/src/platforms/webex/client.js +161 -0
- package/dist/src/platforms/webex/client.js.map +1 -1
- package/dist/src/platforms/webex/commands/file.d.ts +12 -0
- package/dist/src/platforms/webex/commands/file.d.ts.map +1 -0
- package/dist/src/platforms/webex/commands/file.js +64 -0
- package/dist/src/platforms/webex/commands/file.js.map +1 -0
- package/dist/src/platforms/webex/commands/index.d.ts +1 -0
- package/dist/src/platforms/webex/commands/index.d.ts.map +1 -1
- package/dist/src/platforms/webex/commands/index.js +1 -0
- package/dist/src/platforms/webex/commands/index.js.map +1 -1
- package/dist/src/platforms/webex/encryption.d.ts +14 -0
- package/dist/src/platforms/webex/encryption.d.ts.map +1 -1
- package/dist/src/platforms/webex/encryption.js +36 -0
- package/dist/src/platforms/webex/encryption.js.map +1 -1
- package/dist/src/platforms/webex/id-normalizer.d.ts +6 -6
- package/dist/src/platforms/webex/id-normalizer.d.ts.map +1 -1
- package/dist/src/platforms/webex/id-normalizer.js.map +1 -1
- package/dist/src/platforms/webex/index.d.ts +1 -1
- package/dist/src/platforms/webex/index.d.ts.map +1 -1
- package/dist/src/platforms/webex/index.js.map +1 -1
- package/dist/src/platforms/webex/listener.d.ts +10 -9
- package/dist/src/platforms/webex/listener.d.ts.map +1 -1
- package/dist/src/platforms/webex/listener.js.map +1 -1
- package/dist/src/platforms/webex/types.d.ts +31 -0
- package/dist/src/platforms/webex/types.d.ts.map +1 -1
- package/dist/src/platforms/webex/types.js.map +1 -1
- package/dist/src/platforms/webexbot/index.d.ts +1 -1
- package/dist/src/platforms/webexbot/index.d.ts.map +1 -1
- package/dist/src/platforms/webexbot/index.js.map +1 -1
- package/docs/content/docs/cli/webex.mdx +13 -0
- package/docs/content/docs/sdk/webex.mdx +12 -0
- package/package.json +1 -1
- package/skills/agent-channeltalk/SKILL.md +1 -1
- package/skills/agent-channeltalkbot/SKILL.md +1 -1
- package/skills/agent-discord/SKILL.md +1 -1
- package/skills/agent-discordbot/SKILL.md +1 -1
- package/skills/agent-instagram/SKILL.md +1 -1
- package/skills/agent-kakaotalk/SKILL.md +1 -1
- package/skills/agent-line/SKILL.md +1 -1
- package/skills/agent-slack/SKILL.md +1 -1
- package/skills/agent-slackbot/SKILL.md +1 -1
- package/skills/agent-teams/SKILL.md +1 -1
- package/skills/agent-telegram/SKILL.md +1 -1
- package/skills/agent-telegrambot/SKILL.md +1 -1
- package/skills/agent-webex/SKILL.md +14 -2
- package/skills/agent-webexbot/SKILL.md +1 -1
- package/skills/agent-wechatbot/SKILL.md +1 -1
- package/skills/agent-whatsapp/SKILL.md +1 -1
- package/skills/agent-whatsappbot/SKILL.md +1 -1
- package/src/platforms/webex/cli.ts +10 -1
- package/src/platforms/webex/client.test.ts +131 -0
- package/src/platforms/webex/client.ts +195 -0
- package/src/platforms/webex/commands/file.test.ts +96 -0
- package/src/platforms/webex/commands/file.ts +87 -0
- package/src/platforms/webex/commands/index.ts +1 -0
- package/src/platforms/webex/encryption.test.ts +38 -0
- package/src/platforms/webex/encryption.ts +59 -0
- package/src/platforms/webex/id-normalizer.ts +15 -6
- package/src/platforms/webex/index.ts +13 -1
- package/src/platforms/webex/listener.ts +16 -8
- package/src/platforms/webex/types.ts +48 -0
- package/src/platforms/webexbot/index.ts +12 -1
|
@@ -1018,6 +1018,137 @@ describe('WebexClient', () => {
|
|
|
1018
1018
|
})
|
|
1019
1019
|
})
|
|
1020
1020
|
|
|
1021
|
+
describe('uploadFile', () => {
|
|
1022
|
+
const mockUploadFlow = () => {
|
|
1023
|
+
// given: the full internal share flow — conv lookup, space, session, PUT, finish, content
|
|
1024
|
+
mockResponse({ id: TEST_CONV_UUID })
|
|
1025
|
+
mockResponse({ spaceUrl: 'https://files.wbx2.com/spaces/sp1' })
|
|
1026
|
+
mockResponse({
|
|
1027
|
+
uploadUrl: 'https://up.wbx2.com/upload/sess1',
|
|
1028
|
+
finishUploadUrl: 'https://up.wbx2.com/upload/sess1/finish',
|
|
1029
|
+
})
|
|
1030
|
+
mockResponse({}, 200)
|
|
1031
|
+
mockResponse({ downloadUrl: 'https://files.wbx2.com/files/f1' })
|
|
1032
|
+
mockResponse({ ...mockActivity(''), verb: 'share' })
|
|
1033
|
+
}
|
|
1034
|
+
|
|
1035
|
+
const file = () => ({ content: new Blob(['hello world']), filename: 'note.txt' })
|
|
1036
|
+
|
|
1037
|
+
it('routes to the internal conversation API instead of the public messages endpoint', async () => {
|
|
1038
|
+
mockUploadFlow()
|
|
1039
|
+
|
|
1040
|
+
const client = await createExtractedClient()
|
|
1041
|
+
await client.uploadFile(TEST_ROOM_ID, file())
|
|
1042
|
+
|
|
1043
|
+
expect(fetchCalls.every((c) => !c.url.includes('webexapis.com/v1/messages'))).toBe(true)
|
|
1044
|
+
expect(fetchCalls.at(-1)?.url).toBe(`${CONV_BASE}/conversations/${TEST_CONV_UUID}/content`)
|
|
1045
|
+
expect(fetchCalls.at(-1)?.options?.method).toBe('POST')
|
|
1046
|
+
})
|
|
1047
|
+
|
|
1048
|
+
it('requests a space, opens an upload session, PUTs the bytes, then finalizes', async () => {
|
|
1049
|
+
mockUploadFlow()
|
|
1050
|
+
|
|
1051
|
+
const client = await createExtractedClient()
|
|
1052
|
+
await client.uploadFile(TEST_ROOM_ID, file())
|
|
1053
|
+
|
|
1054
|
+
expect(fetchCalls[1].url).toBe(`${CONV_BASE}/conversations/${TEST_CONV_UUID}/space`)
|
|
1055
|
+
expect(fetchCalls[1].options?.method).toBe('PUT')
|
|
1056
|
+
expect(fetchCalls[2].url).toBe('https://files.wbx2.com/spaces/sp1/upload_sessions')
|
|
1057
|
+
expect(fetchCalls[3].url).toBe('https://up.wbx2.com/upload/sess1')
|
|
1058
|
+
expect(fetchCalls[3].options?.method).toBe('PUT')
|
|
1059
|
+
expect(fetchCalls[4].url).toBe('https://up.wbx2.com/upload/sess1/finish')
|
|
1060
|
+
})
|
|
1061
|
+
|
|
1062
|
+
it('finalize body carries fileSize and a sha256 fileHash of the uploaded bytes', async () => {
|
|
1063
|
+
mockUploadFlow()
|
|
1064
|
+
|
|
1065
|
+
const client = await createExtractedClient()
|
|
1066
|
+
await client.uploadFile(TEST_ROOM_ID, file())
|
|
1067
|
+
|
|
1068
|
+
const body = JSON.parse(fetchCalls[4].options?.body as string)
|
|
1069
|
+
expect(body.fileSize).toBe(11)
|
|
1070
|
+
expect(body.fileHash).toMatch(/^[0-9a-f]{64}$/)
|
|
1071
|
+
})
|
|
1072
|
+
|
|
1073
|
+
it('share activity references the uploaded file with download url and metadata', async () => {
|
|
1074
|
+
mockUploadFlow()
|
|
1075
|
+
|
|
1076
|
+
const client = await createExtractedClient()
|
|
1077
|
+
await client.uploadFile(TEST_ROOM_ID, file())
|
|
1078
|
+
|
|
1079
|
+
const body = JSON.parse(fetchCalls.at(-1)?.options?.body as string)
|
|
1080
|
+
expect(body.verb).toBe('share')
|
|
1081
|
+
expect(body.object.objectType).toBe('content')
|
|
1082
|
+
expect(body.object.contentCategory).toBe('documents')
|
|
1083
|
+
const item = body.object.files.items[0]
|
|
1084
|
+
expect(item.objectType).toBe('file')
|
|
1085
|
+
expect(item.url).toBe('https://files.wbx2.com/files/f1')
|
|
1086
|
+
expect(item.fileSize).toBe(11)
|
|
1087
|
+
expect(item.mimeType).toBe('text/plain')
|
|
1088
|
+
expect(item.displayName).toBe('note.txt')
|
|
1089
|
+
})
|
|
1090
|
+
|
|
1091
|
+
it('attaches an optional text comment to the share activity', async () => {
|
|
1092
|
+
mockUploadFlow()
|
|
1093
|
+
|
|
1094
|
+
const client = await createExtractedClient()
|
|
1095
|
+
await client.uploadFile(TEST_ROOM_ID, file(), { text: 'see attached' })
|
|
1096
|
+
|
|
1097
|
+
const body = JSON.parse(fetchCalls.at(-1)?.options?.body as string)
|
|
1098
|
+
expect(body.object.displayName).toBe('see attached')
|
|
1099
|
+
})
|
|
1100
|
+
|
|
1101
|
+
it('categorizes images by mime type', async () => {
|
|
1102
|
+
mockUploadFlow()
|
|
1103
|
+
|
|
1104
|
+
const client = await createExtractedClient()
|
|
1105
|
+
await client.uploadFile(TEST_ROOM_ID, { content: new Blob(['x']), filename: 'photo.png' })
|
|
1106
|
+
|
|
1107
|
+
const body = JSON.parse(fetchCalls.at(-1)?.options?.body as string)
|
|
1108
|
+
expect(body.object.contentCategory).toBe('images')
|
|
1109
|
+
expect(body.object.files.items[0].mimeType).toBe('image/png')
|
|
1110
|
+
})
|
|
1111
|
+
|
|
1112
|
+
it('refuses to upload when the server returns an untrusted space url', async () => {
|
|
1113
|
+
mockResponse({ id: TEST_CONV_UUID })
|
|
1114
|
+
mockResponse({ spaceUrl: 'https://evil.example.com/spaces/sp1' })
|
|
1115
|
+
|
|
1116
|
+
const client = await createExtractedClient()
|
|
1117
|
+
|
|
1118
|
+
await expect(client.uploadFile(TEST_ROOM_ID, file())).rejects.toThrow('untrusted host')
|
|
1119
|
+
expect(fetchCalls.every((c) => !c.url.includes('evil.example.com'))).toBe(true)
|
|
1120
|
+
})
|
|
1121
|
+
|
|
1122
|
+
it('refuses to upload when the server returns a non-https upload url', async () => {
|
|
1123
|
+
mockResponse({ id: TEST_CONV_UUID })
|
|
1124
|
+
mockResponse({ spaceUrl: 'https://files.wbx2.com/spaces/sp1' })
|
|
1125
|
+
mockResponse({
|
|
1126
|
+
uploadUrl: 'http://up.wbx2.com/upload/sess1',
|
|
1127
|
+
finishUploadUrl: 'https://up.wbx2.com/upload/sess1/finish',
|
|
1128
|
+
})
|
|
1129
|
+
|
|
1130
|
+
const client = await createExtractedClient()
|
|
1131
|
+
|
|
1132
|
+
await expect(client.uploadFile(TEST_ROOM_ID, file())).rejects.toThrow('untrusted host')
|
|
1133
|
+
})
|
|
1134
|
+
|
|
1135
|
+
it('accepts trusted Webex urls that carry an explicit port', async () => {
|
|
1136
|
+
mockResponse({ id: TEST_CONV_UUID })
|
|
1137
|
+
mockResponse({ spaceUrl: 'https://files.wbx2.com:443/spaces/sp1' })
|
|
1138
|
+
mockResponse({
|
|
1139
|
+
uploadUrl: 'https://up.wbx2.com:443/upload/sess1',
|
|
1140
|
+
finishUploadUrl: 'https://up.wbx2.com:443/upload/sess1/finish',
|
|
1141
|
+
})
|
|
1142
|
+
mockResponse({}, 200)
|
|
1143
|
+
mockResponse({ downloadUrl: 'https://files.wbx2.com/files/f1' })
|
|
1144
|
+
mockResponse({ ...mockActivity(''), verb: 'share' })
|
|
1145
|
+
|
|
1146
|
+
const client = await createExtractedClient()
|
|
1147
|
+
|
|
1148
|
+
await expect(client.uploadFile(TEST_ROOM_ID, file())).resolves.toBeDefined()
|
|
1149
|
+
})
|
|
1150
|
+
})
|
|
1151
|
+
|
|
1021
1152
|
describe('error handling', () => {
|
|
1022
1153
|
it('throws WebexError when internal API returns non-OK response', async () => {
|
|
1023
1154
|
fetchResponses.push(
|
|
@@ -1,5 +1,8 @@
|
|
|
1
|
+
import { createHash } from 'node:crypto'
|
|
2
|
+
|
|
1
3
|
import { WebexCredentialManager } from './credential-manager'
|
|
2
4
|
import { WebexEncryptionService } from './encryption'
|
|
5
|
+
import type { WebexScr } from './encryption'
|
|
3
6
|
import {
|
|
4
7
|
decodeWebexId,
|
|
5
8
|
normalizeSdkMembership,
|
|
@@ -655,6 +658,11 @@ export class WebexClient {
|
|
|
655
658
|
options?: { text?: string; markdown?: boolean; parentId?: string },
|
|
656
659
|
): Promise<WebexMessage> {
|
|
657
660
|
const resolvedRoomId = await this.resolveRoomId(roomId)
|
|
661
|
+
|
|
662
|
+
if (this.useInternalAPI) {
|
|
663
|
+
return this.uploadFileInternal(resolvedRoomId, file, options)
|
|
664
|
+
}
|
|
665
|
+
|
|
658
666
|
const resolvedParentId = options?.parentId ? this.resolveMessageId(options.parentId) : undefined
|
|
659
667
|
const form = new FormData()
|
|
660
668
|
form.set('roomId', resolvedRoomId)
|
|
@@ -677,6 +685,137 @@ export class WebexClient {
|
|
|
677
685
|
return normalizeSdkMessage((await response.json()) as WebexMessage)
|
|
678
686
|
}
|
|
679
687
|
|
|
688
|
+
private async uploadFileInternal(
|
|
689
|
+
roomId: string,
|
|
690
|
+
file: { content: Blob; filename: string },
|
|
691
|
+
options?: { text?: string; markdown?: boolean; parentId?: string },
|
|
692
|
+
): Promise<WebexMessage> {
|
|
693
|
+
const convUuid = this.decodeConvUuid(roomId)
|
|
694
|
+
const conversationUrl = `${this.convBaseUrl}/conversations/${convUuid}`
|
|
695
|
+
const conv = await this.internalRequest<InternalConversation>(
|
|
696
|
+
`/conversations/${convUuid}?activitiesLimit=0&participantsLimit=0`,
|
|
697
|
+
)
|
|
698
|
+
const keyUri = conv.defaultActivityEncryptionKeyUrl
|
|
699
|
+
|
|
700
|
+
const bytes = new Uint8Array(await file.content.arrayBuffer())
|
|
701
|
+
const fileItem = await this.uploadFileContent(conversationUrl, file.filename, bytes, keyUri)
|
|
702
|
+
|
|
703
|
+
const object: Record<string, unknown> = {
|
|
704
|
+
objectType: 'content',
|
|
705
|
+
contentCategory: contentCategoryFor(fileItem.mimeType),
|
|
706
|
+
files: { items: [fileItem.item] },
|
|
707
|
+
}
|
|
708
|
+
let encryptionKeyUrl: string | undefined
|
|
709
|
+
if (options?.text) {
|
|
710
|
+
const built = await this.buildEncryptedObject(convUuid, options.text, { markdown: options.markdown })
|
|
711
|
+
object.displayName = built.object.displayName
|
|
712
|
+
if (built.object.content) object.content = built.object.content
|
|
713
|
+
encryptionKeyUrl = built.encryptionKeyUrl
|
|
714
|
+
}
|
|
715
|
+
|
|
716
|
+
const activity: Record<string, unknown> = {
|
|
717
|
+
verb: 'share',
|
|
718
|
+
object,
|
|
719
|
+
target: { id: convUuid, objectType: 'conversation' },
|
|
720
|
+
clientTempId: `tmp-${Date.now()}-share`,
|
|
721
|
+
}
|
|
722
|
+
if (options?.parentId) {
|
|
723
|
+
activity.parent = { id: this.toMessageRef(options.parentId), type: 'reply' }
|
|
724
|
+
}
|
|
725
|
+
if (encryptionKeyUrl ?? keyUri) {
|
|
726
|
+
activity.encryptionKeyUrl = encryptionKeyUrl ?? keyUri
|
|
727
|
+
}
|
|
728
|
+
|
|
729
|
+
const result = await this.internalActivityRequest<InternalActivity>(`${conversationUrl}/content`, {
|
|
730
|
+
method: 'POST',
|
|
731
|
+
body: JSON.stringify(activity),
|
|
732
|
+
})
|
|
733
|
+
return this.activityToMessage(result, roomId)
|
|
734
|
+
}
|
|
735
|
+
|
|
736
|
+
private async uploadFileContent(
|
|
737
|
+
conversationUrl: string,
|
|
738
|
+
filename: string,
|
|
739
|
+
bytes: Uint8Array,
|
|
740
|
+
keyUri: string | undefined,
|
|
741
|
+
): Promise<{ item: Record<string, unknown>; mimeType: string }> {
|
|
742
|
+
const space = await this.internalActivityRequest<{ spaceUrl: string }>(`${conversationUrl}/space`, {
|
|
743
|
+
method: 'PUT',
|
|
744
|
+
})
|
|
745
|
+
|
|
746
|
+
let body: Uint8Array
|
|
747
|
+
let scr: WebexScr | undefined
|
|
748
|
+
if (this.encryption && keyUri) {
|
|
749
|
+
const encrypted = this.encryption.encryptBinary(bytes)
|
|
750
|
+
body = encrypted.ciphertext
|
|
751
|
+
scr = encrypted.scr
|
|
752
|
+
} else {
|
|
753
|
+
body = bytes
|
|
754
|
+
}
|
|
755
|
+
|
|
756
|
+
const downloadUrl = await this.uploadToSpace(space.spaceUrl, body)
|
|
757
|
+
|
|
758
|
+
const mimeType = guessMimeType(filename)
|
|
759
|
+
const item: Record<string, unknown> = {
|
|
760
|
+
objectType: 'file',
|
|
761
|
+
displayName: filename,
|
|
762
|
+
fileSize: bytes.byteLength,
|
|
763
|
+
mimeType,
|
|
764
|
+
url: downloadUrl,
|
|
765
|
+
}
|
|
766
|
+
|
|
767
|
+
if (scr && keyUri && this.encryption) {
|
|
768
|
+
scr.loc = downloadUrl
|
|
769
|
+
const encryptedScr = await this.encryption.encryptScr(keyUri, scr)
|
|
770
|
+
if (!encryptedScr) {
|
|
771
|
+
throw new WebexError('Cannot encrypt file for Webex E2E conversation', 'encryption_failed')
|
|
772
|
+
}
|
|
773
|
+
item.scr = encryptedScr
|
|
774
|
+
item.displayName = (await this.encryption.encryptText(keyUri, filename)) ?? filename
|
|
775
|
+
}
|
|
776
|
+
|
|
777
|
+
return { item, mimeType }
|
|
778
|
+
}
|
|
779
|
+
|
|
780
|
+
private async uploadToSpace(spaceUrl: string, body: Uint8Array): Promise<string> {
|
|
781
|
+
const session = await this.internalActivityRequest<{ uploadUrl: string; finishUploadUrl: string }>(
|
|
782
|
+
`${spaceUrl}/upload_sessions`,
|
|
783
|
+
{
|
|
784
|
+
method: 'POST',
|
|
785
|
+
body: JSON.stringify({ uploadProtocol: 'content-length', fileSize: body.byteLength }),
|
|
786
|
+
},
|
|
787
|
+
)
|
|
788
|
+
|
|
789
|
+
const putResponse = await fetch(assertTrustedWebexUrl(session.uploadUrl), {
|
|
790
|
+
method: 'PUT',
|
|
791
|
+
headers: { 'Content-Type': 'application/octet-stream', 'Content-Length': String(body.byteLength) },
|
|
792
|
+
body,
|
|
793
|
+
})
|
|
794
|
+
if (!putResponse.ok) {
|
|
795
|
+
throw new WebexError(`File upload failed: HTTP ${putResponse.status}`, `http_${putResponse.status}`)
|
|
796
|
+
}
|
|
797
|
+
|
|
798
|
+
const fileHash = createHash('sha256').update(body).digest('hex')
|
|
799
|
+
const finished = await this.internalActivityRequest<{ downloadUrl: string }>(session.finishUploadUrl, {
|
|
800
|
+
method: 'POST',
|
|
801
|
+
body: JSON.stringify({ fileSize: body.byteLength, fileHash }),
|
|
802
|
+
})
|
|
803
|
+
return finished.downloadUrl
|
|
804
|
+
}
|
|
805
|
+
|
|
806
|
+
private async internalActivityRequest<T>(url: string, init: RequestInit): Promise<T> {
|
|
807
|
+
const response = await fetch(assertTrustedWebexUrl(url), {
|
|
808
|
+
...init,
|
|
809
|
+
headers: { ...this.internalHeaders, ...(init.headers as Record<string, string>) },
|
|
810
|
+
})
|
|
811
|
+
if (!response.ok) {
|
|
812
|
+
const errorBody = (await response.json().catch(() => null)) as { message?: string } | null
|
|
813
|
+
throw new WebexError(errorBody?.message ?? `HTTP ${response.status}`, `http_${response.status}`)
|
|
814
|
+
}
|
|
815
|
+
if (response.status === 204) return undefined as T
|
|
816
|
+
return response.json() as Promise<T>
|
|
817
|
+
}
|
|
818
|
+
|
|
680
819
|
private async lookupRoomId(uuid: string, fallback: string): Promise<string> {
|
|
681
820
|
try {
|
|
682
821
|
// Page through every room the account belongs to, stopping as soon as the
|
|
@@ -816,6 +955,62 @@ function looksLikeUuid(value: string): boolean {
|
|
|
816
955
|
return /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(value)
|
|
817
956
|
}
|
|
818
957
|
|
|
958
|
+
function isTrustedWebexHost(host: string): boolean {
|
|
959
|
+
return (
|
|
960
|
+
host === 'webex.com' ||
|
|
961
|
+
host.endsWith('.webex.com') ||
|
|
962
|
+
host === 'wbx2.com' ||
|
|
963
|
+
host.endsWith('.wbx2.com') ||
|
|
964
|
+
host === 'ciscospark.com' ||
|
|
965
|
+
host.endsWith('.ciscospark.com')
|
|
966
|
+
)
|
|
967
|
+
}
|
|
968
|
+
|
|
969
|
+
// Pin server-returned upload URLs to HTTPS Webex hosts: they receive the bearer
|
|
970
|
+
// token (activity calls) and file bytes, so a compromised response must not be
|
|
971
|
+
// able to exfiltrate them to an attacker-controlled host (SSRF/token leak).
|
|
972
|
+
function assertTrustedWebexUrl(url: string): string {
|
|
973
|
+
let parsed: URL
|
|
974
|
+
try {
|
|
975
|
+
parsed = new URL(url)
|
|
976
|
+
} catch {
|
|
977
|
+
throw new WebexError(`Invalid Webex URL: ${url}`, 'invalid_url')
|
|
978
|
+
}
|
|
979
|
+
if (parsed.protocol !== 'https:' || !isTrustedWebexHost(parsed.hostname)) {
|
|
980
|
+
throw new WebexError(`Refusing to send request to untrusted host: ${parsed.origin}`, 'untrusted_url')
|
|
981
|
+
}
|
|
982
|
+
return parsed.toString()
|
|
983
|
+
}
|
|
984
|
+
|
|
985
|
+
const MIME_TYPES: Record<string, string> = {
|
|
986
|
+
png: 'image/png',
|
|
987
|
+
jpg: 'image/jpeg',
|
|
988
|
+
jpeg: 'image/jpeg',
|
|
989
|
+
gif: 'image/gif',
|
|
990
|
+
webp: 'image/webp',
|
|
991
|
+
svg: 'image/svg+xml',
|
|
992
|
+
mp4: 'video/mp4',
|
|
993
|
+
mov: 'video/quicktime',
|
|
994
|
+
webm: 'video/webm',
|
|
995
|
+
pdf: 'application/pdf',
|
|
996
|
+
txt: 'text/plain',
|
|
997
|
+
md: 'text/markdown',
|
|
998
|
+
json: 'application/json',
|
|
999
|
+
csv: 'text/csv',
|
|
1000
|
+
zip: 'application/zip',
|
|
1001
|
+
}
|
|
1002
|
+
|
|
1003
|
+
function guessMimeType(filename: string): string {
|
|
1004
|
+
const ext = filename.split('.').pop()?.toLowerCase() ?? ''
|
|
1005
|
+
return MIME_TYPES[ext] ?? 'application/octet-stream'
|
|
1006
|
+
}
|
|
1007
|
+
|
|
1008
|
+
function contentCategoryFor(mimeType: string): string {
|
|
1009
|
+
if (mimeType.startsWith('image/')) return 'images'
|
|
1010
|
+
if (mimeType.startsWith('video/')) return 'videos'
|
|
1011
|
+
return 'documents'
|
|
1012
|
+
}
|
|
1013
|
+
|
|
819
1014
|
function looksLikeEmail(value: string): boolean {
|
|
820
1015
|
return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(value)
|
|
821
1016
|
}
|
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
import { afterEach, beforeEach, expect, it, spyOn } from 'bun:test'
|
|
2
|
+
import { mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
|
|
3
|
+
import { tmpdir } from 'node:os'
|
|
4
|
+
import { join } from 'node:path'
|
|
5
|
+
|
|
6
|
+
import { WebexClient } from '../client'
|
|
7
|
+
import { toRestId } from '../id-normalizer'
|
|
8
|
+
|
|
9
|
+
const roomId = toRestId('space_456', 'ROOM')
|
|
10
|
+
|
|
11
|
+
const mockMessage = {
|
|
12
|
+
id: toRestId('msg_123', 'MESSAGE'),
|
|
13
|
+
ref: 'msg_123',
|
|
14
|
+
roomId,
|
|
15
|
+
roomRef: 'space_456',
|
|
16
|
+
roomType: 'group' as const,
|
|
17
|
+
text: '',
|
|
18
|
+
personId: toRestId('person_789', 'PEOPLE'),
|
|
19
|
+
personRef: 'person_789',
|
|
20
|
+
personEmail: 'user@example.com',
|
|
21
|
+
files: ['https://files.wbx2.com/files/f1'],
|
|
22
|
+
created: '2025-01-29T10:00:00.000Z',
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
import { downloadAction, uploadAction } from './file'
|
|
26
|
+
|
|
27
|
+
let mockUploadFile: ReturnType<typeof spyOn>
|
|
28
|
+
let mockDownloadContent: ReturnType<typeof spyOn>
|
|
29
|
+
let consoleLogSpy: ReturnType<typeof spyOn>
|
|
30
|
+
const protoSpies: ReturnType<typeof spyOn>[] = []
|
|
31
|
+
let workDir: string
|
|
32
|
+
|
|
33
|
+
function protoSpy(method: keyof WebexClient) {
|
|
34
|
+
const s = spyOn(WebexClient.prototype, method as never)
|
|
35
|
+
protoSpies.push(s)
|
|
36
|
+
return s
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
beforeEach(() => {
|
|
40
|
+
protoSpy('login').mockImplementation(async function (this: WebexClient) {
|
|
41
|
+
return this
|
|
42
|
+
})
|
|
43
|
+
protoSpy('dispose').mockResolvedValue(undefined)
|
|
44
|
+
mockUploadFile = protoSpy('uploadFile').mockResolvedValue(mockMessage)
|
|
45
|
+
mockDownloadContent = protoSpy('downloadContent').mockResolvedValue({
|
|
46
|
+
data: new TextEncoder().encode('file-bytes').buffer,
|
|
47
|
+
filename: 'report.pdf',
|
|
48
|
+
contentType: 'application/pdf',
|
|
49
|
+
})
|
|
50
|
+
consoleLogSpy = spyOn(console, 'log').mockImplementation(() => {})
|
|
51
|
+
workDir = mkdtempSync(join(tmpdir(), 'webex-file-test-'))
|
|
52
|
+
})
|
|
53
|
+
|
|
54
|
+
afterEach(() => {
|
|
55
|
+
for (const s of protoSpies) s.mockRestore()
|
|
56
|
+
protoSpies.length = 0
|
|
57
|
+
consoleLogSpy.mockRestore()
|
|
58
|
+
rmSync(workDir, { recursive: true, force: true })
|
|
59
|
+
})
|
|
60
|
+
|
|
61
|
+
it('upload reads the local file and forwards filename plus text to uploadFile', async () => {
|
|
62
|
+
const filePath = join(workDir, 'note.txt')
|
|
63
|
+
writeFileSync(filePath, 'hello world')
|
|
64
|
+
|
|
65
|
+
await uploadAction(roomId, filePath, { text: 'see attached' })
|
|
66
|
+
|
|
67
|
+
expect(mockUploadFile).toHaveBeenCalledTimes(1)
|
|
68
|
+
const [space, file, options] = mockUploadFile.mock.calls[0] as [
|
|
69
|
+
string,
|
|
70
|
+
{ content: Blob; filename: string },
|
|
71
|
+
{ text?: string },
|
|
72
|
+
]
|
|
73
|
+
expect(space).toBe(roomId)
|
|
74
|
+
expect(file.filename).toBe('note.txt')
|
|
75
|
+
expect(options.text).toBe('see attached')
|
|
76
|
+
})
|
|
77
|
+
|
|
78
|
+
it('upload prints the resulting message with file urls', async () => {
|
|
79
|
+
const filePath = join(workDir, 'note.txt')
|
|
80
|
+
writeFileSync(filePath, 'hello world')
|
|
81
|
+
|
|
82
|
+
await uploadAction(roomId, filePath, {})
|
|
83
|
+
|
|
84
|
+
const printed = JSON.parse(consoleLogSpy.mock.calls[0]?.[0] as string)
|
|
85
|
+
expect(printed.id).toBe(mockMessage.id)
|
|
86
|
+
expect(printed.files).toEqual(['https://files.wbx2.com/files/f1'])
|
|
87
|
+
})
|
|
88
|
+
|
|
89
|
+
it('download writes content to the given output path', async () => {
|
|
90
|
+
const outPath = join(workDir, 'out.pdf')
|
|
91
|
+
|
|
92
|
+
await downloadAction('https://webexapis.com/v1/contents/c1', outPath, {})
|
|
93
|
+
|
|
94
|
+
expect(mockDownloadContent).toHaveBeenCalledWith('https://webexapis.com/v1/contents/c1')
|
|
95
|
+
expect(readFileSync(outPath, 'utf8')).toBe('file-bytes')
|
|
96
|
+
})
|
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
import { readFile, writeFile } from 'node:fs/promises'
|
|
2
|
+
import { basename, resolve } from 'node:path'
|
|
3
|
+
|
|
4
|
+
import { Command } from 'commander'
|
|
5
|
+
|
|
6
|
+
import { handleError } from '@/shared/utils/error-handler'
|
|
7
|
+
import { formatOutput } from '@/shared/utils/output'
|
|
8
|
+
|
|
9
|
+
import { WebexClient } from '../client'
|
|
10
|
+
|
|
11
|
+
async function withWebexClient<T>(run: (client: WebexClient) => Promise<T>): Promise<T> {
|
|
12
|
+
const client = new WebexClient()
|
|
13
|
+
try {
|
|
14
|
+
await client.login()
|
|
15
|
+
return await run(client)
|
|
16
|
+
} finally {
|
|
17
|
+
await client.dispose()
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
export async function uploadAction(
|
|
22
|
+
space: string,
|
|
23
|
+
path: string,
|
|
24
|
+
options: { text?: string; markdown?: boolean; parent?: string; pretty?: boolean },
|
|
25
|
+
): Promise<void> {
|
|
26
|
+
try {
|
|
27
|
+
const filePath = resolve(path)
|
|
28
|
+
const content = await readFile(filePath)
|
|
29
|
+
const message = await withWebexClient((client) =>
|
|
30
|
+
client.uploadFile(
|
|
31
|
+
space,
|
|
32
|
+
{ content: new Blob([content]), filename: basename(filePath) },
|
|
33
|
+
{ text: options.text, markdown: options.markdown, parentId: options.parent },
|
|
34
|
+
),
|
|
35
|
+
)
|
|
36
|
+
|
|
37
|
+
const output = {
|
|
38
|
+
id: message.id,
|
|
39
|
+
ref: message.ref,
|
|
40
|
+
roomId: message.roomId,
|
|
41
|
+
roomRef: message.roomRef,
|
|
42
|
+
files: message.files,
|
|
43
|
+
created: message.created,
|
|
44
|
+
}
|
|
45
|
+
console.log(formatOutput(output, options.pretty))
|
|
46
|
+
} catch (error) {
|
|
47
|
+
handleError(error as Error)
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
export async function downloadAction(
|
|
52
|
+
content: string,
|
|
53
|
+
output: string | undefined,
|
|
54
|
+
options: { pretty?: boolean },
|
|
55
|
+
): Promise<void> {
|
|
56
|
+
try {
|
|
57
|
+
const { data, filename, contentType } = await withWebexClient((client) => client.downloadContent(content))
|
|
58
|
+
const outputPath = output ? resolve(output) : resolve(process.cwd(), basename(filename))
|
|
59
|
+
await writeFile(outputPath, Buffer.from(data))
|
|
60
|
+
|
|
61
|
+
console.log(formatOutput({ downloaded: outputPath, filename, contentType, size: data.byteLength }, options.pretty))
|
|
62
|
+
} catch (error) {
|
|
63
|
+
handleError(error as Error)
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
export const fileCommand = new Command('file')
|
|
68
|
+
.description('File commands')
|
|
69
|
+
.addCommand(
|
|
70
|
+
new Command('upload')
|
|
71
|
+
.description('Upload a local file to a space')
|
|
72
|
+
.argument('<space>', 'Space/Room ID')
|
|
73
|
+
.argument('<path>', 'Local file path')
|
|
74
|
+
.option('--text <text>', 'Optional message to send with the file')
|
|
75
|
+
.option('--markdown', 'Treat --text as markdown')
|
|
76
|
+
.option('--parent <id>', 'Reply within a thread (parent message ID)')
|
|
77
|
+
.option('--pretty', 'Pretty print JSON output')
|
|
78
|
+
.action(uploadAction),
|
|
79
|
+
)
|
|
80
|
+
.addCommand(
|
|
81
|
+
new Command('download')
|
|
82
|
+
.description('Download a file attachment by content URL or ID')
|
|
83
|
+
.argument('<content>', 'File content URL (from message.files) or content ID')
|
|
84
|
+
.argument('[output]', 'Output path (defaults to original filename)')
|
|
85
|
+
.option('--pretty', 'Pretty print JSON output')
|
|
86
|
+
.action(downloadAction),
|
|
87
|
+
)
|
|
@@ -106,4 +106,42 @@ describe('WebexEncryptionService', () => {
|
|
|
106
106
|
expect(key).not.toBeNull()
|
|
107
107
|
expect(provider.fetchKey).toHaveBeenCalledTimes(1)
|
|
108
108
|
})
|
|
109
|
+
|
|
110
|
+
it('encryptBinary produces A256GCM scr material and ciphertext that differs from input', async () => {
|
|
111
|
+
const service = new WebexEncryptionService(new Map())
|
|
112
|
+
|
|
113
|
+
const plaintext = new Uint8Array([1, 2, 3, 4, 5])
|
|
114
|
+
const { scr, ciphertext } = service.encryptBinary(plaintext)
|
|
115
|
+
|
|
116
|
+
expect(scr.enc).toBe('A256GCM')
|
|
117
|
+
expect(scr.key).toMatch(/^[A-Za-z0-9_-]+$/)
|
|
118
|
+
expect(scr.iv).toMatch(/^[A-Za-z0-9_-]+$/)
|
|
119
|
+
expect(scr.tag).toMatch(/^[A-Za-z0-9_-]+$/)
|
|
120
|
+
expect(Buffer.from(scr.key, 'base64url')).toHaveLength(32)
|
|
121
|
+
expect(Buffer.from(scr.iv, 'base64url')).toHaveLength(12)
|
|
122
|
+
expect(Buffer.from(ciphertext)).not.toEqual(Buffer.from(plaintext))
|
|
123
|
+
})
|
|
124
|
+
|
|
125
|
+
it('encryptScr requires loc to be set before encrypting', async () => {
|
|
126
|
+
const service = await createKeyring(keyUri)
|
|
127
|
+
const { scr } = service.encryptBinary(new Uint8Array([9, 9, 9]))
|
|
128
|
+
|
|
129
|
+
const result = await service.encryptScr(keyUri, scr)
|
|
130
|
+
|
|
131
|
+
expect(result).toBeNull()
|
|
132
|
+
})
|
|
133
|
+
|
|
134
|
+
it('encryptScr wraps the scr as a JWE with kid once loc is set', async () => {
|
|
135
|
+
const service = await createKeyring(keyUri)
|
|
136
|
+
const { scr } = service.encryptBinary(new Uint8Array([9, 9, 9]))
|
|
137
|
+
scr.loc = 'https://files.wbx2.com/files/f1'
|
|
138
|
+
|
|
139
|
+
const jwe = await service.encryptScr(keyUri, scr)
|
|
140
|
+
|
|
141
|
+
expect(jwe).not.toBeNull()
|
|
142
|
+
const header = decodeJweHeader(jwe as string)
|
|
143
|
+
expect(header.alg).toBe('dir')
|
|
144
|
+
expect(header.enc).toBe('A256GCM')
|
|
145
|
+
expect(header.kid).toBe(keyUri)
|
|
146
|
+
})
|
|
109
147
|
})
|
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
import { createCipheriv, randomBytes } from 'node:crypto'
|
|
2
|
+
|
|
1
3
|
import * as jose from 'node-jose'
|
|
2
4
|
|
|
3
5
|
export interface WebexKeyProvider {
|
|
@@ -5,6 +7,26 @@ export interface WebexKeyProvider {
|
|
|
5
7
|
close?(): Promise<void>
|
|
6
8
|
}
|
|
7
9
|
|
|
10
|
+
// SCR (Secure Content Resource): Webex's per-file AES-256-GCM material. The file bytes
|
|
11
|
+
// are encrypted with this key, then the SCR itself is JWE-wrapped with the conversation key.
|
|
12
|
+
export interface WebexScr {
|
|
13
|
+
enc: 'A256GCM'
|
|
14
|
+
key: string
|
|
15
|
+
iv: string
|
|
16
|
+
aad: string
|
|
17
|
+
loc?: string
|
|
18
|
+
tag: string
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
export interface WebexEncryptedBinary {
|
|
22
|
+
scr: WebexScr
|
|
23
|
+
ciphertext: Uint8Array
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
function toBase64Url(buffer: Buffer): string {
|
|
27
|
+
return buffer.toString('base64url')
|
|
28
|
+
}
|
|
29
|
+
|
|
8
30
|
export class WebexEncryptionService {
|
|
9
31
|
private rawKeys: Map<string, string>
|
|
10
32
|
private keyCache: Map<string, jose.JWK.Key> = new Map()
|
|
@@ -70,4 +92,41 @@ export class WebexEncryptionService {
|
|
|
70
92
|
return null
|
|
71
93
|
}
|
|
72
94
|
}
|
|
95
|
+
|
|
96
|
+
encryptBinary(plaintext: Uint8Array): WebexEncryptedBinary {
|
|
97
|
+
const key = randomBytes(32)
|
|
98
|
+
const iv = randomBytes(12)
|
|
99
|
+
const aad = new Date().toISOString()
|
|
100
|
+
|
|
101
|
+
const cipher = createCipheriv('aes-256-gcm', key, iv)
|
|
102
|
+
cipher.setAAD(Buffer.from(aad, 'utf8'))
|
|
103
|
+
const ciphertext = Buffer.concat([cipher.update(Buffer.from(plaintext)), cipher.final()])
|
|
104
|
+
const tag = cipher.getAuthTag()
|
|
105
|
+
|
|
106
|
+
return {
|
|
107
|
+
scr: {
|
|
108
|
+
enc: 'A256GCM',
|
|
109
|
+
key: toBase64Url(key),
|
|
110
|
+
iv: toBase64Url(iv),
|
|
111
|
+
aad,
|
|
112
|
+
tag: toBase64Url(tag),
|
|
113
|
+
},
|
|
114
|
+
ciphertext,
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
async encryptScr(keyUri: string, scr: WebexScr): Promise<string | null> {
|
|
119
|
+
if (!scr.loc) return null
|
|
120
|
+
const key = await this.getKey(keyUri)
|
|
121
|
+
if (!key) return null
|
|
122
|
+
|
|
123
|
+
try {
|
|
124
|
+
return await jose.JWE.createEncrypt(
|
|
125
|
+
{ format: 'compact', contentAlg: 'A256GCM' },
|
|
126
|
+
{ key, header: { alg: 'dir', kid: keyUri }, reference: null },
|
|
127
|
+
).final(JSON.stringify(scr), 'utf8')
|
|
128
|
+
} catch {
|
|
129
|
+
return null
|
|
130
|
+
}
|
|
131
|
+
}
|
|
73
132
|
}
|