@wats/graph 0.3.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +3 -0
- package/dist/client.d.ts +41 -0
- package/dist/client.js +392 -0
- package/dist/createFetchTransport.d.ts +6 -0
- package/dist/createFetchTransport.js +46 -0
- package/dist/createMockTransport.d.ts +20 -0
- package/dist/createMockTransport.js +120 -0
- package/dist/endpoint.d.ts +26 -0
- package/dist/endpoint.js +223 -0
- package/dist/endpoints/businessManagement.d.ts +157 -0
- package/dist/endpoints/businessManagement.js +277 -0
- package/dist/endpoints/calling.d.ts +65 -0
- package/dist/endpoints/calling.js +284 -0
- package/dist/endpoints/flows/callables.d.ts +90 -0
- package/dist/endpoints/flows/callables.js +97 -0
- package/dist/endpoints/flows/dataExchange.d.ts +4 -0
- package/dist/endpoints/flows/dataExchange.js +40 -0
- package/dist/endpoints/flows/flowJson.d.ts +18 -0
- package/dist/endpoints/flows/flowJson.js +214 -0
- package/dist/endpoints/flows/index.d.ts +6 -0
- package/dist/endpoints/flows/index.js +26 -0
- package/dist/endpoints/flows/shared.d.ts +17 -0
- package/dist/endpoints/flows/shared.js +113 -0
- package/dist/endpoints/flows/types.d.ts +105 -0
- package/dist/endpoints/flows/types.js +0 -0
- package/dist/endpoints/flows.d.ts +2 -0
- package/dist/endpoints/flows.js +23 -0
- package/dist/endpoints/media.d.ts +123 -0
- package/dist/endpoints/media.js +976 -0
- package/dist/endpoints/messages.d.ts +375 -0
- package/dist/endpoints/messages.js +675 -0
- package/dist/endpoints/templates/builders.d.ts +9 -0
- package/dist/endpoints/templates/builders.js +101 -0
- package/dist/endpoints/templates/callables.d.ts +54 -0
- package/dist/endpoints/templates/callables.js +98 -0
- package/dist/endpoints/templates/index.d.ts +5 -0
- package/dist/endpoints/templates/index.js +16 -0
- package/dist/endpoints/templates/shared.d.ts +21 -0
- package/dist/endpoints/templates/shared.js +203 -0
- package/dist/endpoints/templates/types.d.ts +135 -0
- package/dist/endpoints/templates/types.js +0 -0
- package/dist/endpoints/templates/validation.d.ts +2 -0
- package/dist/endpoints/templates/validation.js +113 -0
- package/dist/endpoints/templates.d.ts +2 -0
- package/dist/endpoints/templates.js +14 -0
- package/dist/endpoints/waba/index.d.ts +4 -0
- package/dist/endpoints/waba/index.js +1 -0
- package/dist/endpoints/waba/phoneNumbers.d.ts +25 -0
- package/dist/endpoints/waba/phoneNumbers.js +23 -0
- package/dist/endpoints/waba/types.d.ts +8 -0
- package/dist/endpoints/waba/types.js +0 -0
- package/dist/endpoints/wabaEndpoints.d.ts +6 -0
- package/dist/endpoints/wabaEndpoints.js +38 -0
- package/dist/errorRegistry.d.ts +45 -0
- package/dist/errorRegistry.js +68 -0
- package/dist/errorSubclasses.d.ts +277 -0
- package/dist/errorSubclasses.js +613 -0
- package/dist/errors.d.ts +92 -0
- package/dist/errors.js +250 -0
- package/dist/index.d.ts +20 -0
- package/dist/index.js +48 -0
- package/dist/internal/validation/arrays.d.ts +19 -0
- package/dist/internal/validation/arrays.js +102 -0
- package/dist/internal/validation/errors.d.ts +3 -0
- package/dist/internal/validation/errors.js +13 -0
- package/dist/internal/validation/headers.d.ts +15 -0
- package/dist/internal/validation/headers.js +77 -0
- package/dist/internal/validation/index.d.ts +8 -0
- package/dist/internal/validation/index.js +8 -0
- package/dist/internal/validation/json.d.ts +10 -0
- package/dist/internal/validation/json.js +79 -0
- package/dist/internal/validation/options.d.ts +5 -0
- package/dist/internal/validation/options.js +36 -0
- package/dist/internal/validation/paths.d.ts +8 -0
- package/dist/internal/validation/paths.js +37 -0
- package/dist/internal/validation/records.d.ts +20 -0
- package/dist/internal/validation/records.js +69 -0
- package/dist/internal/validation/strings.d.ts +12 -0
- package/dist/internal/validation/strings.js +46 -0
- package/dist/pagination.d.ts +35 -0
- package/dist/pagination.js +160 -0
- package/dist/subclients/phoneNumberClient.d.ts +60 -0
- package/dist/subclients/phoneNumberClient.js +194 -0
- package/dist/subclients/wabaClient.d.ts +66 -0
- package/dist/subclients/wabaClient.js +180 -0
- package/dist/transport.d.ts +32 -0
- package/dist/transport.js +5 -0
- package/package.json +70 -0
|
@@ -0,0 +1,976 @@
|
|
|
1
|
+
import { createGraphApiError } from "../errors";
|
|
2
|
+
|
|
3
|
+
export class MediaNotImplementedError extends Error {
|
|
4
|
+
code;
|
|
5
|
+
operation;
|
|
6
|
+
linearIssue;
|
|
7
|
+
constructor(operation, linearIssue) {
|
|
8
|
+
super(`Media ${operation} is not implemented. Track implementation via Linear issue ${linearIssue}.`);
|
|
9
|
+
this.name = "MediaNotImplementedError";
|
|
10
|
+
this.code = "not_implemented";
|
|
11
|
+
this.operation = operation;
|
|
12
|
+
this.linearIssue = linearIssue;
|
|
13
|
+
}
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
export class MediaValidationError extends Error {
|
|
17
|
+
code;
|
|
18
|
+
constructor(code, message, cause) {
|
|
19
|
+
super(message);
|
|
20
|
+
this.name = "MediaValidationError";
|
|
21
|
+
this.code = code;
|
|
22
|
+
if (cause !== undefined) {
|
|
23
|
+
Object.defineProperty(this, "cause", {
|
|
24
|
+
value: cause,
|
|
25
|
+
enumerable: false,
|
|
26
|
+
configurable: true,
|
|
27
|
+
writable: true
|
|
28
|
+
});
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
export class MediaCryptoError extends Error {
|
|
34
|
+
code;
|
|
35
|
+
constructor(code, message, cause) {
|
|
36
|
+
super(message);
|
|
37
|
+
this.name = "MediaCryptoError";
|
|
38
|
+
this.code = code;
|
|
39
|
+
if (cause !== undefined) {
|
|
40
|
+
Object.defineProperty(this, "cause", {
|
|
41
|
+
value: cause,
|
|
42
|
+
enumerable: false,
|
|
43
|
+
configurable: true,
|
|
44
|
+
writable: true
|
|
45
|
+
});
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
export class MediaIntegrityError extends Error {
|
|
51
|
+
code;
|
|
52
|
+
constructor(code, message) {
|
|
53
|
+
super(message);
|
|
54
|
+
this.name = "MediaIntegrityError";
|
|
55
|
+
this.code = code;
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
export const DEFAULT_MAX_MEDIA_UPLOAD_BYTES = 16777216;
|
|
59
|
+
export const MAX_MEDIA_UPLOAD_BYTES = DEFAULT_MAX_MEDIA_UPLOAD_BYTES;
|
|
60
|
+
export const DEFAULT_MAX_MEDIA_DOWNLOAD_BYTES = 16777216;
|
|
61
|
+
export const MAX_MEDIA_DOWNLOAD_BYTES = DEFAULT_MAX_MEDIA_DOWNLOAD_BYTES;
|
|
62
|
+
export const DEFAULT_MAX_UPLOAD_SESSION_BYTES = 67108864;
|
|
63
|
+
export const MAX_UPLOAD_SESSION_BYTES = DEFAULT_MAX_UPLOAD_SESSION_BYTES;
|
|
64
|
+
const TYPED_ARRAY_PROTOTYPE = Object.getPrototypeOf(Uint8Array.prototype);
|
|
65
|
+
const TYPED_ARRAY_BUFFER_GETTER = Object.getOwnPropertyDescriptor(TYPED_ARRAY_PROTOTYPE, "buffer")?.get;
|
|
66
|
+
const TYPED_ARRAY_BYTE_LENGTH_GETTER = Object.getOwnPropertyDescriptor(TYPED_ARRAY_PROTOTYPE, "byteLength")?.get;
|
|
67
|
+
const TYPED_ARRAY_BYTE_OFFSET_GETTER = Object.getOwnPropertyDescriptor(TYPED_ARRAY_PROTOTYPE, "byteOffset")?.get;
|
|
68
|
+
export const MEDIA_LINEAR_ISSUE_UPLOAD = "WATS-37";
|
|
69
|
+
export const MEDIA_LINEAR_ISSUE_DOWNLOAD = "WATS-37";
|
|
70
|
+
export const MEDIA_LINEAR_ISSUE_DELETE = "WATS-37";
|
|
71
|
+
export const MEDIA_LINEAR_ISSUE_DECRYPT = "WATS-37";
|
|
72
|
+
const MAX_PATH_DECODE_ROUNDS = 5;
|
|
73
|
+
const SAFE_ID_REGEXP = /^[A-Za-z0-9_-]+$/;
|
|
74
|
+
const PHONE_NUMBER_ID_REGEXP = /^\d+$/;
|
|
75
|
+
const BOUNDARY_REGEXP = /^[A-Za-z0-9_.-]+$/;
|
|
76
|
+
const SUPPORTED_MEDIA_TYPES = new Set([
|
|
77
|
+
"audio/aac",
|
|
78
|
+
"audio/amr",
|
|
79
|
+
"audio/mp4",
|
|
80
|
+
"audio/mpeg",
|
|
81
|
+
"audio/ogg",
|
|
82
|
+
"application/msword",
|
|
83
|
+
"application/pdf",
|
|
84
|
+
"application/vnd.ms-excel",
|
|
85
|
+
"application/vnd.ms-powerpoint",
|
|
86
|
+
"application/vnd.openxmlformats-officedocument.presentationml.presentation",
|
|
87
|
+
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
|
|
88
|
+
"application/vnd.openxmlformats-officedocument.wordprocessingml.document",
|
|
89
|
+
"image/jpeg",
|
|
90
|
+
"image/png",
|
|
91
|
+
"image/webp",
|
|
92
|
+
"text/plain",
|
|
93
|
+
"video/3gpp",
|
|
94
|
+
"video/mp4"
|
|
95
|
+
]);
|
|
96
|
+
function isRecord(value) {
|
|
97
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
98
|
+
}
|
|
99
|
+
function findCauseByName(error, name) {
|
|
100
|
+
let current = error;
|
|
101
|
+
const seen = new Set;
|
|
102
|
+
while (isRecord(current) && !seen.has(current)) {
|
|
103
|
+
if (current.name === name)
|
|
104
|
+
return current;
|
|
105
|
+
seen.add(current);
|
|
106
|
+
current = current.cause;
|
|
107
|
+
}
|
|
108
|
+
return;
|
|
109
|
+
}
|
|
110
|
+
function hasControlChar(value) {
|
|
111
|
+
for (let i = 0;i < value.length; i += 1) {
|
|
112
|
+
const code = value.charCodeAt(i);
|
|
113
|
+
if (code < 32 || code === 127)
|
|
114
|
+
return true;
|
|
115
|
+
}
|
|
116
|
+
return false;
|
|
117
|
+
}
|
|
118
|
+
function decodePathLike(value, code, label) {
|
|
119
|
+
let current = value;
|
|
120
|
+
assertSafeDecodedPathValue(current, code, label);
|
|
121
|
+
for (let round = 0;round < MAX_PATH_DECODE_ROUNDS; round += 1) {
|
|
122
|
+
let decoded;
|
|
123
|
+
try {
|
|
124
|
+
decoded = decodeURIComponent(current);
|
|
125
|
+
} catch (cause) {
|
|
126
|
+
throw new MediaValidationError(code, `Invalid media ${label}: malformed percent-encoding is not allowed.`, cause);
|
|
127
|
+
}
|
|
128
|
+
assertSafeDecodedPathValue(decoded, code, label);
|
|
129
|
+
if (decoded === current)
|
|
130
|
+
return decoded;
|
|
131
|
+
current = decoded;
|
|
132
|
+
}
|
|
133
|
+
throw new MediaValidationError(code, `Invalid media ${label}: excessive nested percent-encoding is not allowed.`);
|
|
134
|
+
}
|
|
135
|
+
function assertSafeDecodedPathValue(value, code, label) {
|
|
136
|
+
if (value.length === 0 || value.trim().length === 0) {
|
|
137
|
+
throw new MediaValidationError(code, `Invalid media ${label}: value must be a non-empty string.`);
|
|
138
|
+
}
|
|
139
|
+
if (hasControlChar(value)) {
|
|
140
|
+
throw new MediaValidationError(code, `Invalid media ${label}: control characters are not allowed.`);
|
|
141
|
+
}
|
|
142
|
+
if (value === "." || value === ".." || value.includes("..")) {
|
|
143
|
+
throw new MediaValidationError(code, `Invalid media ${label}: dot-segments are not allowed.`);
|
|
144
|
+
}
|
|
145
|
+
if (value.includes("/") || value.includes("\\")) {
|
|
146
|
+
throw new MediaValidationError(code, `Invalid media ${label}: path separators are not allowed.`);
|
|
147
|
+
}
|
|
148
|
+
if (value.includes("?") || value.includes("#") || value.includes("://") || value.includes(":")) {
|
|
149
|
+
throw new MediaValidationError(code, `Invalid media ${label}: URL markers are not allowed.`);
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
function validatePhoneNumberId(value) {
|
|
153
|
+
if (typeof value !== "string") {
|
|
154
|
+
throw new MediaValidationError("invalid_phone_number_id", "Invalid media phoneNumberId: value must be a string.");
|
|
155
|
+
}
|
|
156
|
+
const decoded = decodePathLike(value, "invalid_phone_number_id", "phoneNumberId");
|
|
157
|
+
if (!PHONE_NUMBER_ID_REGEXP.test(decoded)) {
|
|
158
|
+
throw new MediaValidationError("invalid_phone_number_id", "Invalid media phoneNumberId: value must contain digits only.");
|
|
159
|
+
}
|
|
160
|
+
return decoded;
|
|
161
|
+
}
|
|
162
|
+
function validateMediaId(value) {
|
|
163
|
+
if (typeof value !== "string") {
|
|
164
|
+
throw new MediaValidationError("invalid_media_id", "Invalid mediaId: value must be a string.");
|
|
165
|
+
}
|
|
166
|
+
const decoded = decodePathLike(value, "invalid_media_id", "mediaId");
|
|
167
|
+
if (!SAFE_ID_REGEXP.test(decoded)) {
|
|
168
|
+
throw new MediaValidationError("invalid_media_id", "Invalid mediaId: value must contain only letters, digits, '_' or '-'.");
|
|
169
|
+
}
|
|
170
|
+
return decoded;
|
|
171
|
+
}
|
|
172
|
+
function assertClient(client) {
|
|
173
|
+
if (!isRecord(client) || typeof client.request !== "function" || typeof client.requestRaw !== "function") {
|
|
174
|
+
throw new MediaValidationError("invalid_client", "Invalid media client: expected a GraphClient-like object with request() and requestRaw().");
|
|
175
|
+
}
|
|
176
|
+
}
|
|
177
|
+
function validateSignal(value) {
|
|
178
|
+
if (value === undefined)
|
|
179
|
+
return;
|
|
180
|
+
if (!isRecord(value) || typeof value.aborted !== "boolean" || typeof value.addEventListener !== "function" || typeof value.removeEventListener !== "function") {
|
|
181
|
+
throw new MediaValidationError("invalid_options", "Invalid media options: signal must be an AbortSignal-like object.");
|
|
182
|
+
}
|
|
183
|
+
return value;
|
|
184
|
+
}
|
|
185
|
+
function validatePositiveSafeInteger(value, code, label, max) {
|
|
186
|
+
if (typeof value !== "number" || !Number.isInteger(value) || !Number.isSafeInteger(value) || value <= 0 || !Number.isFinite(value) || max !== undefined && value > max) {
|
|
187
|
+
throw new MediaValidationError(code, `Invalid ${label}: expected a positive safe integer${max !== undefined ? ` <= ${max}` : ""}.`);
|
|
188
|
+
}
|
|
189
|
+
return value;
|
|
190
|
+
}
|
|
191
|
+
function validateNonNegativeSafeInteger(value, code, label, max) {
|
|
192
|
+
if (typeof value !== "number" || !Number.isInteger(value) || !Number.isSafeInteger(value) || value < 0 || !Number.isFinite(value) || max !== undefined && value > max) {
|
|
193
|
+
throw new MediaValidationError(code, `Invalid ${label}: expected a non-negative safe integer${max !== undefined ? ` <= ${max}` : ""}.`);
|
|
194
|
+
}
|
|
195
|
+
return value;
|
|
196
|
+
}
|
|
197
|
+
function validateMaxBytes(options) {
|
|
198
|
+
if (options === undefined)
|
|
199
|
+
return DEFAULT_MAX_MEDIA_UPLOAD_BYTES;
|
|
200
|
+
if (!isRecord(options)) {
|
|
201
|
+
throw new MediaValidationError("invalid_options", "Invalid media upload options: expected an object.");
|
|
202
|
+
}
|
|
203
|
+
validateSignal(options.signal);
|
|
204
|
+
const maxBytes = options.maxBytes;
|
|
205
|
+
if (maxBytes === undefined)
|
|
206
|
+
return DEFAULT_MAX_MEDIA_UPLOAD_BYTES;
|
|
207
|
+
return validatePositiveSafeInteger(maxBytes, "invalid_options", "media upload options maxBytes", MAX_MEDIA_UPLOAD_BYTES);
|
|
208
|
+
}
|
|
209
|
+
function validateDownloadMaxBytes(options) {
|
|
210
|
+
if (options === undefined)
|
|
211
|
+
return DEFAULT_MAX_MEDIA_DOWNLOAD_BYTES;
|
|
212
|
+
if (!isRecord(options)) {
|
|
213
|
+
throw new MediaValidationError("invalid_options", "Invalid media download options: expected an object.");
|
|
214
|
+
}
|
|
215
|
+
validateSignal(options.signal);
|
|
216
|
+
const maxBytes = options.maxBytes;
|
|
217
|
+
if (maxBytes === undefined)
|
|
218
|
+
return DEFAULT_MAX_MEDIA_DOWNLOAD_BYTES;
|
|
219
|
+
return validatePositiveSafeInteger(maxBytes, "invalid_options", "media download options maxBytes", MAX_MEDIA_DOWNLOAD_BYTES);
|
|
220
|
+
}
|
|
221
|
+
function validateSessionMaxBytes(options) {
|
|
222
|
+
if (options === undefined)
|
|
223
|
+
return DEFAULT_MAX_UPLOAD_SESSION_BYTES;
|
|
224
|
+
if (!isRecord(options)) {
|
|
225
|
+
throw new MediaValidationError("invalid_options", "Invalid media upload session options: expected an object.");
|
|
226
|
+
}
|
|
227
|
+
validateSignal(options.signal);
|
|
228
|
+
const maxBytes = options.maxBytes;
|
|
229
|
+
if (maxBytes === undefined)
|
|
230
|
+
return DEFAULT_MAX_UPLOAD_SESSION_BYTES;
|
|
231
|
+
return validatePositiveSafeInteger(maxBytes, "invalid_options", "media upload session options maxBytes", MAX_UPLOAD_SESSION_BYTES);
|
|
232
|
+
}
|
|
233
|
+
function validateUploadOptions(options) {
|
|
234
|
+
if (options !== undefined && !isRecord(options)) {
|
|
235
|
+
throw new MediaValidationError("invalid_options", "Invalid media upload options: expected an object.");
|
|
236
|
+
}
|
|
237
|
+
const maxBytes = validateMaxBytes(options);
|
|
238
|
+
const signal = isRecord(options) ? validateSignal(options.signal) : undefined;
|
|
239
|
+
return signal === undefined ? { maxBytes } : { maxBytes, signal };
|
|
240
|
+
}
|
|
241
|
+
function validateUploadBody(body) {
|
|
242
|
+
if (!isRecord(body)) {
|
|
243
|
+
throw new MediaValidationError("invalid_upload_body", "Invalid media upload body: expected an object.");
|
|
244
|
+
}
|
|
245
|
+
const type = validateMediaType(body.type);
|
|
246
|
+
if (body.messagingProduct !== "whatsapp") {
|
|
247
|
+
throw new MediaValidationError("invalid_messaging_product", 'Invalid media upload body: messagingProduct must be exactly "whatsapp".');
|
|
248
|
+
}
|
|
249
|
+
validateFileShape(body.file);
|
|
250
|
+
return {
|
|
251
|
+
file: body.file,
|
|
252
|
+
type,
|
|
253
|
+
messagingProduct: "whatsapp"
|
|
254
|
+
};
|
|
255
|
+
}
|
|
256
|
+
function validateMediaType(value) {
|
|
257
|
+
if (typeof value !== "string" || value.length === 0 || value.trim().length === 0) {
|
|
258
|
+
throw new MediaValidationError("invalid_media_type", "Invalid media type: value must be a non-empty string.");
|
|
259
|
+
}
|
|
260
|
+
if (hasControlChar(value)) {
|
|
261
|
+
throw new MediaValidationError("invalid_media_type", "Invalid media type: control characters are not allowed.");
|
|
262
|
+
}
|
|
263
|
+
const normalized = value.trim().toLowerCase();
|
|
264
|
+
if (!/^[a-z0-9][a-z0-9!#$&^_.+-]*\/[a-z0-9][a-z0-9!#$&^_.+-]*$/.test(normalized)) {
|
|
265
|
+
throw new MediaValidationError("unsupported_media_type", "Unsupported media type: parameters and malformed MIME types are not accepted.");
|
|
266
|
+
}
|
|
267
|
+
if (!SUPPORTED_MEDIA_TYPES.has(normalized)) {
|
|
268
|
+
throw new MediaValidationError("unsupported_media_type", `Unsupported media type: ${normalized}.`);
|
|
269
|
+
}
|
|
270
|
+
return normalized;
|
|
271
|
+
}
|
|
272
|
+
function getIntrinsicUint8ArrayBuffer(value) {
|
|
273
|
+
const buffer = TYPED_ARRAY_BUFFER_GETTER?.call(value);
|
|
274
|
+
if (buffer === undefined) {
|
|
275
|
+
throw new MediaValidationError("invalid_file", "Invalid media file: could not read intrinsic Uint8Array buffer.");
|
|
276
|
+
}
|
|
277
|
+
return buffer;
|
|
278
|
+
}
|
|
279
|
+
function getIntrinsicUint8ArrayByteLength(value) {
|
|
280
|
+
const byteLength = TYPED_ARRAY_BYTE_LENGTH_GETTER?.call(value);
|
|
281
|
+
if (byteLength === undefined) {
|
|
282
|
+
throw new MediaValidationError("invalid_file", "Invalid media file: could not read intrinsic Uint8Array byteLength.");
|
|
283
|
+
}
|
|
284
|
+
return byteLength;
|
|
285
|
+
}
|
|
286
|
+
function getIntrinsicUint8ArrayByteOffset(value) {
|
|
287
|
+
const byteOffset = TYPED_ARRAY_BYTE_OFFSET_GETTER?.call(value);
|
|
288
|
+
if (byteOffset === undefined) {
|
|
289
|
+
throw new MediaValidationError("invalid_file", "Invalid media file: could not read intrinsic Uint8Array byteOffset.");
|
|
290
|
+
}
|
|
291
|
+
return byteOffset;
|
|
292
|
+
}
|
|
293
|
+
function isSharedArrayBufferBacked(value) {
|
|
294
|
+
return typeof SharedArrayBuffer !== "undefined" && getIntrinsicUint8ArrayBuffer(value) instanceof SharedArrayBuffer;
|
|
295
|
+
}
|
|
296
|
+
function normalizeUint8ArrayChunk(value) {
|
|
297
|
+
if (isSharedArrayBufferBacked(value)) {
|
|
298
|
+
throw new MediaValidationError("invalid_file", "Invalid media file: SharedArrayBuffer-backed Uint8Array is not supported.");
|
|
299
|
+
}
|
|
300
|
+
const byteLength = getIntrinsicUint8ArrayByteLength(value);
|
|
301
|
+
const byteOffset = getIntrinsicUint8ArrayByteOffset(value);
|
|
302
|
+
const buffer = getIntrinsicUint8ArrayBuffer(value);
|
|
303
|
+
return new Uint8Array(buffer, byteOffset, byteLength).slice();
|
|
304
|
+
}
|
|
305
|
+
function validateFileShape(value) {
|
|
306
|
+
if (value instanceof Blob)
|
|
307
|
+
return;
|
|
308
|
+
if (value instanceof ArrayBuffer)
|
|
309
|
+
return;
|
|
310
|
+
if (value instanceof Uint8Array) {
|
|
311
|
+
if (isSharedArrayBufferBacked(value)) {
|
|
312
|
+
throw new MediaValidationError("invalid_file", "Invalid media file: SharedArrayBuffer-backed Uint8Array is not supported.");
|
|
313
|
+
}
|
|
314
|
+
return;
|
|
315
|
+
}
|
|
316
|
+
throw new MediaValidationError("invalid_file", "Invalid media file: supported file bodies are Blob, ArrayBuffer, and Uint8Array only.");
|
|
317
|
+
}
|
|
318
|
+
function assertSizeAtMost(size, maxBytes) {
|
|
319
|
+
if (!Number.isInteger(size) || size < 0) {
|
|
320
|
+
throw new MediaValidationError("invalid_file", "Invalid media file: byte length must be a non-negative integer.");
|
|
321
|
+
}
|
|
322
|
+
if (size > maxBytes) {
|
|
323
|
+
throw new MediaValidationError("upload_too_large", `Media upload body exceeds maxBytes (${size} > ${maxBytes}).`);
|
|
324
|
+
}
|
|
325
|
+
}
|
|
326
|
+
async function normalizeFileBytes(file, maxBytes) {
|
|
327
|
+
try {
|
|
328
|
+
if (file instanceof Blob) {
|
|
329
|
+
assertSizeAtMost(file.size, maxBytes);
|
|
330
|
+
const bytes = new Uint8Array(await file.arrayBuffer());
|
|
331
|
+
assertSizeAtMost(bytes.byteLength, maxBytes);
|
|
332
|
+
return bytes;
|
|
333
|
+
}
|
|
334
|
+
if (file instanceof ArrayBuffer) {
|
|
335
|
+
assertSizeAtMost(file.byteLength, maxBytes);
|
|
336
|
+
return new Uint8Array(file).slice();
|
|
337
|
+
}
|
|
338
|
+
if (file instanceof Uint8Array) {
|
|
339
|
+
const bytes = normalizeUint8ArrayChunk(file);
|
|
340
|
+
assertSizeAtMost(bytes.byteLength, maxBytes);
|
|
341
|
+
return bytes;
|
|
342
|
+
}
|
|
343
|
+
} catch (cause) {
|
|
344
|
+
if (cause instanceof MediaValidationError)
|
|
345
|
+
throw cause;
|
|
346
|
+
throw new MediaValidationError("invalid_file", "Invalid media file: could not read bytes.", cause);
|
|
347
|
+
}
|
|
348
|
+
throw new MediaValidationError("invalid_file", "Invalid media file: supported file bodies are Blob, ArrayBuffer, and Uint8Array only.");
|
|
349
|
+
}
|
|
350
|
+
function encodeAscii(value) {
|
|
351
|
+
return new TextEncoder().encode(value);
|
|
352
|
+
}
|
|
353
|
+
function concatUint8Arrays(parts) {
|
|
354
|
+
const total = parts.reduce((sum, part) => sum + part.byteLength, 0);
|
|
355
|
+
const out = new Uint8Array(total);
|
|
356
|
+
let offset = 0;
|
|
357
|
+
for (const part of parts) {
|
|
358
|
+
out.set(part, offset);
|
|
359
|
+
offset += part.byteLength;
|
|
360
|
+
}
|
|
361
|
+
return out;
|
|
362
|
+
}
|
|
363
|
+
function randomHex(byteLength) {
|
|
364
|
+
const bytes = new Uint8Array(byteLength);
|
|
365
|
+
const cryptoLike = globalThis.crypto;
|
|
366
|
+
if (cryptoLike === undefined || typeof cryptoLike.getRandomValues !== "function") {
|
|
367
|
+
throw new MediaValidationError("invalid_upload_body", "Cannot generate multipart boundary: crypto.getRandomValues is unavailable.");
|
|
368
|
+
}
|
|
369
|
+
cryptoLike.getRandomValues(bytes);
|
|
370
|
+
return Array.from(bytes, (byte) => byte.toString(16).padStart(2, "0")).join("");
|
|
371
|
+
}
|
|
372
|
+
function createMultipartBoundary() {
|
|
373
|
+
const boundary = `wats_media_${randomHex(16)}`;
|
|
374
|
+
if (!BOUNDARY_REGEXP.test(boundary)) {
|
|
375
|
+
throw new MediaValidationError("invalid_upload_body", "Generated multipart boundary contained unsafe characters.");
|
|
376
|
+
}
|
|
377
|
+
return boundary;
|
|
378
|
+
}
|
|
379
|
+
async function buildMultipartBody(body, maxBytes) {
|
|
380
|
+
const fileBytes = await normalizeFileBytes(body.file, maxBytes);
|
|
381
|
+
const boundary = createMultipartBoundary();
|
|
382
|
+
const parts = [
|
|
383
|
+
encodeAscii(`--${boundary}\r
|
|
384
|
+
Content-Disposition: form-data; name="messaging_product"\r
|
|
385
|
+
\r
|
|
386
|
+
whatsapp\r
|
|
387
|
+
--${boundary}\r
|
|
388
|
+
Content-Disposition: form-data; name="type"\r
|
|
389
|
+
\r
|
|
390
|
+
${body.type}\r
|
|
391
|
+
--${boundary}\r
|
|
392
|
+
Content-Disposition: form-data; name="file"; filename="media"\r
|
|
393
|
+
Content-Type: ${body.type}\r
|
|
394
|
+
\r
|
|
395
|
+
`),
|
|
396
|
+
fileBytes,
|
|
397
|
+
encodeAscii(`\r
|
|
398
|
+
--${boundary}--\r
|
|
399
|
+
`)
|
|
400
|
+
];
|
|
401
|
+
return { bytes: concatUint8Arrays(parts), boundary };
|
|
402
|
+
}
|
|
403
|
+
function validateUploadResponse(value) {
|
|
404
|
+
if (!isRecord(value) || typeof value.id !== "string" || value.id.length === 0) {
|
|
405
|
+
throw new MediaValidationError("invalid_response", "Invalid media upload response: expected { id: string }.");
|
|
406
|
+
}
|
|
407
|
+
return { id: value.id };
|
|
408
|
+
}
|
|
409
|
+
function asNonEmptyString(value, code, label) {
|
|
410
|
+
if (typeof value !== "string" || value.length === 0 || value.trim().length === 0) {
|
|
411
|
+
throw new MediaValidationError(code, `Invalid media response: ${label} must be a non-empty string.`);
|
|
412
|
+
}
|
|
413
|
+
return value;
|
|
414
|
+
}
|
|
415
|
+
function parseFileSize(value) {
|
|
416
|
+
const parsed = typeof value === "number" ? value : typeof value === "string" ? Number(value) : NaN;
|
|
417
|
+
if (!Number.isInteger(parsed) || parsed < 0 || !Number.isFinite(parsed)) {
|
|
418
|
+
throw new MediaValidationError("invalid_response", "Invalid media response: file_size must parse to a non-negative integer.");
|
|
419
|
+
}
|
|
420
|
+
return parsed;
|
|
421
|
+
}
|
|
422
|
+
function validateDownloadResponse(value) {
|
|
423
|
+
if (!isRecord(value)) {
|
|
424
|
+
throw new MediaValidationError("invalid_response", "Invalid media metadata response: expected an object.");
|
|
425
|
+
}
|
|
426
|
+
const messagingProduct = value.messaging_product ?? value.messagingProduct;
|
|
427
|
+
if (messagingProduct !== "whatsapp") {
|
|
428
|
+
throw new MediaValidationError("invalid_response", 'Invalid media metadata response: messaging_product must be "whatsapp".');
|
|
429
|
+
}
|
|
430
|
+
return {
|
|
431
|
+
messagingProduct: "whatsapp",
|
|
432
|
+
url: asNonEmptyString(value.url, "invalid_response", "url"),
|
|
433
|
+
mimeType: asNonEmptyString(value.mime_type ?? value.mimeType, "invalid_response", "mime_type"),
|
|
434
|
+
sha256: asNonEmptyString(value.sha256, "invalid_response", "sha256"),
|
|
435
|
+
fileSize: parseFileSize(value.file_size ?? value.fileSize)
|
|
436
|
+
};
|
|
437
|
+
}
|
|
438
|
+
function validateDeleteResponse(value) {
|
|
439
|
+
if (!isRecord(value) || typeof value.success !== "boolean") {
|
|
440
|
+
throw new MediaValidationError("invalid_response", "Invalid media delete response: expected { success: boolean }.");
|
|
441
|
+
}
|
|
442
|
+
return { success: value.success };
|
|
443
|
+
}
|
|
444
|
+
function validateUploadParams(params) {
|
|
445
|
+
if (!isRecord(params)) {
|
|
446
|
+
throw new MediaValidationError("invalid_params", "Invalid media upload params: expected an object.");
|
|
447
|
+
}
|
|
448
|
+
return { phoneNumberId: validatePhoneNumberId(params.phoneNumberId) };
|
|
449
|
+
}
|
|
450
|
+
function validateDownloadOptions(options) {
|
|
451
|
+
if (!isRecord(options)) {
|
|
452
|
+
throw new MediaValidationError("invalid_options", "Invalid media download options: expected an object.");
|
|
453
|
+
}
|
|
454
|
+
const signal = validateSignal(options.signal);
|
|
455
|
+
const mediaId = validateMediaId(options.mediaId);
|
|
456
|
+
return signal === undefined ? { mediaId } : { mediaId, signal };
|
|
457
|
+
}
|
|
458
|
+
function validateDeleteOptions(options) {
|
|
459
|
+
if (!isRecord(options)) {
|
|
460
|
+
throw new MediaValidationError("invalid_params", "Invalid media delete params: expected an object.");
|
|
461
|
+
}
|
|
462
|
+
const signal = validateSignal(options.signal);
|
|
463
|
+
const mediaId = validateMediaId(options.mediaId);
|
|
464
|
+
return signal === undefined ? { mediaId } : { mediaId, signal };
|
|
465
|
+
}
|
|
466
|
+
function validateHttpUrl(value) {
|
|
467
|
+
if (typeof value !== "string" || value.length === 0 || value.trim().length === 0) {
|
|
468
|
+
throw new MediaValidationError("invalid_url", "Invalid media URL: value must be a non-empty string.");
|
|
469
|
+
}
|
|
470
|
+
if (hasControlChar(value)) {
|
|
471
|
+
throw new MediaValidationError("invalid_url", "Invalid media URL: control characters are not allowed.");
|
|
472
|
+
}
|
|
473
|
+
let url;
|
|
474
|
+
try {
|
|
475
|
+
url = new URL(value);
|
|
476
|
+
} catch (cause) {
|
|
477
|
+
throw new MediaValidationError("invalid_url", "Invalid media URL: malformed URL.", cause);
|
|
478
|
+
}
|
|
479
|
+
if (url.protocol !== "http:" && url.protocol !== "https:") {
|
|
480
|
+
throw new MediaValidationError("invalid_url", "Invalid media URL: protocol must be http: or https:.");
|
|
481
|
+
}
|
|
482
|
+
return url.toString();
|
|
483
|
+
}
|
|
484
|
+
function validateBase64Digest(value, label, code = "invalid_base64", expectedLength) {
|
|
485
|
+
if (typeof value !== "string" || value.length === 0 || value.trim().length === 0) {
|
|
486
|
+
if (code === "invalid_options") {
|
|
487
|
+
throw new MediaValidationError("invalid_options", `Invalid ${label}: expected a non-empty base64 string.`);
|
|
488
|
+
}
|
|
489
|
+
throw new MediaCryptoError(code, `Invalid ${label}: expected a non-empty base64 string.`);
|
|
490
|
+
}
|
|
491
|
+
try {
|
|
492
|
+
const binary = atob(value);
|
|
493
|
+
const out = new Uint8Array(binary.length);
|
|
494
|
+
for (let i = 0;i < binary.length; i += 1)
|
|
495
|
+
out[i] = binary.charCodeAt(i);
|
|
496
|
+
if (out.byteLength === 0)
|
|
497
|
+
throw new Error("empty");
|
|
498
|
+
if (expectedLength !== undefined && out.byteLength !== expectedLength) {
|
|
499
|
+
if (code === "invalid_options") {
|
|
500
|
+
throw new MediaValidationError("invalid_options", `Invalid ${label}: expected ${expectedLength} decoded bytes.`);
|
|
501
|
+
}
|
|
502
|
+
throw new MediaCryptoError("invalid_key_length", `Invalid ${label}: expected ${expectedLength} decoded bytes.`);
|
|
503
|
+
}
|
|
504
|
+
return out;
|
|
505
|
+
} catch (cause) {
|
|
506
|
+
if (code === "invalid_options") {
|
|
507
|
+
throw new MediaValidationError("invalid_options", `Invalid ${label}: malformed base64.`, cause);
|
|
508
|
+
}
|
|
509
|
+
throw new MediaCryptoError(code, `Invalid ${label}: malformed base64.`, cause);
|
|
510
|
+
}
|
|
511
|
+
}
|
|
512
|
+
function validateDownloadBytesOptions(options) {
|
|
513
|
+
if (!isRecord(options)) {
|
|
514
|
+
throw new MediaValidationError("invalid_options", "Invalid media download bytes options: expected an object.");
|
|
515
|
+
}
|
|
516
|
+
const url = validateHttpUrl(options.url);
|
|
517
|
+
const maxBytes = validateDownloadMaxBytes(options);
|
|
518
|
+
const signal = validateSignal(options.signal);
|
|
519
|
+
const expectedSha256 = options.expectedSha256 === undefined ? undefined : validateBase64Digest(options.expectedSha256, "expectedSha256", "invalid_options", 32);
|
|
520
|
+
return {
|
|
521
|
+
url,
|
|
522
|
+
maxBytes,
|
|
523
|
+
...signal !== undefined ? { signal } : {},
|
|
524
|
+
...expectedSha256 !== undefined ? { expectedSha256 } : {}
|
|
525
|
+
};
|
|
526
|
+
}
|
|
527
|
+
function validateFileName(value) {
|
|
528
|
+
if (typeof value !== "string" || value.length === 0 || value.trim().length === 0) {
|
|
529
|
+
throw new MediaValidationError("invalid_file_name", "Invalid fileName: expected a non-empty string.");
|
|
530
|
+
}
|
|
531
|
+
if (hasControlChar(value) || value.includes("/") || value.includes("\\") || value.includes("..")) {
|
|
532
|
+
throw new MediaValidationError("invalid_file_name", "Invalid fileName: path/control characters are not allowed.");
|
|
533
|
+
}
|
|
534
|
+
const decoded = decodePathLike(value, "invalid_file_name", "fileName");
|
|
535
|
+
return decoded;
|
|
536
|
+
}
|
|
537
|
+
function validateCreateUploadSessionParams(params, options) {
|
|
538
|
+
if (!isRecord(params)) {
|
|
539
|
+
throw new MediaValidationError("invalid_params", "Invalid upload session params: expected an object.");
|
|
540
|
+
}
|
|
541
|
+
const maxBytes = validateSessionMaxBytes(options ?? params);
|
|
542
|
+
const signal = validateSignal((options ?? params).signal);
|
|
543
|
+
const appId = validatePhoneNumberId(params.appId);
|
|
544
|
+
const fileName = validateFileName(params.fileName);
|
|
545
|
+
const fileLength = validatePositiveSafeInteger(params.fileLength, "invalid_file_length", "fileLength", maxBytes);
|
|
546
|
+
const fileType = validateMediaType(params.fileType);
|
|
547
|
+
const out = { appId, fileName, fileLength, fileType };
|
|
548
|
+
return signal === undefined ? { params: out } : { params: out, signal };
|
|
549
|
+
}
|
|
550
|
+
function validateUploadSessionId(value) {
|
|
551
|
+
if (typeof value !== "string") {
|
|
552
|
+
throw new MediaValidationError("invalid_upload_session_id", "Invalid uploadSessionId: value must be a string.");
|
|
553
|
+
}
|
|
554
|
+
const decoded = decodeUploadSessionPathLike(value);
|
|
555
|
+
if (!/^[A-Za-z0-9_:-]+$/.test(decoded)) {
|
|
556
|
+
throw new MediaValidationError("invalid_upload_session_id", "Invalid uploadSessionId: value must contain only letters, digits, '_', '-' or ':'.");
|
|
557
|
+
}
|
|
558
|
+
return decoded;
|
|
559
|
+
}
|
|
560
|
+
function decodeUploadSessionPathLike(value) {
|
|
561
|
+
let current = value;
|
|
562
|
+
assertSafeUploadSessionPathValue(current);
|
|
563
|
+
for (let round = 0;round < MAX_PATH_DECODE_ROUNDS; round += 1) {
|
|
564
|
+
let decoded;
|
|
565
|
+
try {
|
|
566
|
+
decoded = decodeURIComponent(current);
|
|
567
|
+
} catch (cause) {
|
|
568
|
+
throw new MediaValidationError("invalid_upload_session_id", "Invalid uploadSessionId: malformed percent-encoding is not allowed.", cause);
|
|
569
|
+
}
|
|
570
|
+
assertSafeUploadSessionPathValue(decoded);
|
|
571
|
+
if (decoded === current)
|
|
572
|
+
return decoded;
|
|
573
|
+
current = decoded;
|
|
574
|
+
}
|
|
575
|
+
throw new MediaValidationError("invalid_upload_session_id", "Invalid uploadSessionId: excessive nested percent-encoding is not allowed.");
|
|
576
|
+
}
|
|
577
|
+
function assertSafeUploadSessionPathValue(value) {
|
|
578
|
+
if (value.length === 0 || value.trim().length === 0) {
|
|
579
|
+
throw new MediaValidationError("invalid_upload_session_id", "Invalid uploadSessionId: value must be a non-empty string.");
|
|
580
|
+
}
|
|
581
|
+
if (hasControlChar(value)) {
|
|
582
|
+
throw new MediaValidationError("invalid_upload_session_id", "Invalid uploadSessionId: control characters are not allowed.");
|
|
583
|
+
}
|
|
584
|
+
if (value === "." || value === ".." || value.includes("..")) {
|
|
585
|
+
throw new MediaValidationError("invalid_upload_session_id", "Invalid uploadSessionId: dot-segments are not allowed.");
|
|
586
|
+
}
|
|
587
|
+
if (value.includes("/") || value.includes("\\")) {
|
|
588
|
+
throw new MediaValidationError("invalid_upload_session_id", "Invalid uploadSessionId: path separators are not allowed.");
|
|
589
|
+
}
|
|
590
|
+
if (value.includes("?") || value.includes("#") || value.includes("://")) {
|
|
591
|
+
throw new MediaValidationError("invalid_upload_session_id", "Invalid uploadSessionId: URL markers are not allowed.");
|
|
592
|
+
}
|
|
593
|
+
}
|
|
594
|
+
function validateGetUploadSessionParams(params) {
|
|
595
|
+
if (!isRecord(params)) {
|
|
596
|
+
throw new MediaValidationError("invalid_params", "Invalid getUploadSession params: expected an object.");
|
|
597
|
+
}
|
|
598
|
+
const uploadSessionId = validateUploadSessionId(params.uploadSessionId);
|
|
599
|
+
const signal = validateSignal(params.signal);
|
|
600
|
+
return signal === undefined ? { uploadSessionId } : { uploadSessionId, signal };
|
|
601
|
+
}
|
|
602
|
+
function validateReadableStreamLike(value) {
|
|
603
|
+
return isRecord(value) && typeof value.getReader === "function";
|
|
604
|
+
}
|
|
605
|
+
function validateUploadFileToSessionParams(params, options) {
|
|
606
|
+
if (!isRecord(params)) {
|
|
607
|
+
throw new MediaValidationError("invalid_params", "Invalid uploadFileToSession params: expected an object.");
|
|
608
|
+
}
|
|
609
|
+
const uploadSessionId = validateUploadSessionId(params.uploadSessionId);
|
|
610
|
+
const maxBytes = validateSessionMaxBytes(options ?? params);
|
|
611
|
+
const signal = validateSignal((options ?? params).signal);
|
|
612
|
+
const fileOffset = params.fileOffset === undefined ? 0 : validateNonNegativeSafeInteger(params.fileOffset, "invalid_file_offset", "fileOffset", maxBytes);
|
|
613
|
+
const contentLength = params.contentLength === undefined ? undefined : validatePositiveSafeInteger(params.contentLength, "invalid_content_length", "contentLength", maxBytes);
|
|
614
|
+
const file = params.file;
|
|
615
|
+
let fileIsStream = false;
|
|
616
|
+
if (file instanceof Blob || file instanceof ArrayBuffer || file instanceof Uint8Array) {
|
|
617
|
+
validateFileShape(file);
|
|
618
|
+
} else if (validateReadableStreamLike(file)) {
|
|
619
|
+
fileIsStream = true;
|
|
620
|
+
if (contentLength === undefined) {
|
|
621
|
+
throw new MediaValidationError("invalid_content_length", "contentLength is required for ReadableStream uploads.");
|
|
622
|
+
}
|
|
623
|
+
} else {
|
|
624
|
+
throw new MediaValidationError("invalid_file", "Invalid upload session file body.");
|
|
625
|
+
}
|
|
626
|
+
if (file instanceof Blob && file.size > maxBytes || file instanceof ArrayBuffer && file.byteLength > maxBytes || file instanceof Uint8Array && getIntrinsicUint8ArrayByteLength(file) > maxBytes) {
|
|
627
|
+
throw new MediaValidationError("upload_too_large", "Upload session file exceeds maxBytes.");
|
|
628
|
+
}
|
|
629
|
+
return {
|
|
630
|
+
uploadSessionId,
|
|
631
|
+
file,
|
|
632
|
+
fileOffset,
|
|
633
|
+
maxBytes,
|
|
634
|
+
fileIsStream,
|
|
635
|
+
...contentLength !== undefined ? { contentLength } : {},
|
|
636
|
+
...signal !== undefined ? { signal } : {}
|
|
637
|
+
};
|
|
638
|
+
}
|
|
639
|
+
export async function uploadMedia(client, params, body, options) {
|
|
640
|
+
assertClient(client);
|
|
641
|
+
const validatedParams = validateUploadParams(params);
|
|
642
|
+
const uploadOptions = validateUploadOptions(options);
|
|
643
|
+
const validatedBody = validateUploadBody(body);
|
|
644
|
+
const multipart = await buildMultipartBody(validatedBody, uploadOptions.maxBytes);
|
|
645
|
+
const response = await client.request({
|
|
646
|
+
method: "POST",
|
|
647
|
+
path: `/${validatedParams.phoneNumberId}/media`,
|
|
648
|
+
body: multipart.bytes,
|
|
649
|
+
headers: {
|
|
650
|
+
"content-type": `multipart/form-data; boundary=${multipart.boundary}`
|
|
651
|
+
},
|
|
652
|
+
...uploadOptions.signal !== undefined ? { signal: uploadOptions.signal } : {}
|
|
653
|
+
});
|
|
654
|
+
return validateUploadResponse(response);
|
|
655
|
+
}
|
|
656
|
+
export async function downloadMedia(client, opts) {
|
|
657
|
+
assertClient(client);
|
|
658
|
+
const validated = validateDownloadOptions(opts);
|
|
659
|
+
const response = await client.request({
|
|
660
|
+
method: "GET",
|
|
661
|
+
path: `/${validated.mediaId}`,
|
|
662
|
+
...validated.signal !== undefined ? { signal: validated.signal } : {}
|
|
663
|
+
});
|
|
664
|
+
return validateDownloadResponse(response);
|
|
665
|
+
}
|
|
666
|
+
export async function deleteMedia(client, params) {
|
|
667
|
+
assertClient(client);
|
|
668
|
+
const validated = validateDeleteOptions(params);
|
|
669
|
+
const response = await client.request({
|
|
670
|
+
method: "DELETE",
|
|
671
|
+
path: `/${validated.mediaId}`,
|
|
672
|
+
...validated.signal !== undefined ? { signal: validated.signal } : {}
|
|
673
|
+
});
|
|
674
|
+
return validateDeleteResponse(response);
|
|
675
|
+
}
|
|
676
|
+
async function sha256(bytes) {
|
|
677
|
+
const digest = await globalThis.crypto?.subtle?.digest("SHA-256", bytes.slice());
|
|
678
|
+
if (digest === undefined) {
|
|
679
|
+
throw new MediaCryptoError("unsupported_crypto", "SubtleCrypto SHA-256 is unavailable.");
|
|
680
|
+
}
|
|
681
|
+
return new Uint8Array(digest);
|
|
682
|
+
}
|
|
683
|
+
function timingSafeEqualBytes(a, b) {
|
|
684
|
+
if (a.byteLength !== b.byteLength)
|
|
685
|
+
return false;
|
|
686
|
+
let diff = 0;
|
|
687
|
+
for (let i = 0;i < a.byteLength; i += 1)
|
|
688
|
+
diff |= a[i] ^ b[i];
|
|
689
|
+
return diff === 0;
|
|
690
|
+
}
|
|
691
|
+
function assertLength(bytes, expected, label) {
|
|
692
|
+
if (bytes.byteLength !== expected) {
|
|
693
|
+
throw new MediaCryptoError("invalid_key_length", `Invalid ${label}: expected ${expected} bytes.`);
|
|
694
|
+
}
|
|
695
|
+
}
|
|
696
|
+
function validateEncryptedBundle(bundle) {
|
|
697
|
+
if (!isRecord(bundle))
|
|
698
|
+
throw new MediaCryptoError("invalid_bundle", "Encrypted media bundle must be an object.");
|
|
699
|
+
const encryptionKey = validateBase64Digest(bundle.encryptionKey, "encryptionKey");
|
|
700
|
+
const hmacKey = validateBase64Digest(bundle.hmacKey, "hmacKey");
|
|
701
|
+
const iv = validateBase64Digest(bundle.iv, "iv");
|
|
702
|
+
const plainHash = validateBase64Digest(bundle.sha256, "sha256");
|
|
703
|
+
const encHash = validateBase64Digest(bundle.sha256Enc, "sha256Enc");
|
|
704
|
+
assertLength(encryptionKey, 32, "encryptionKey");
|
|
705
|
+
assertLength(hmacKey, 32, "hmacKey");
|
|
706
|
+
assertLength(iv, 16, "iv");
|
|
707
|
+
assertLength(plainHash, 32, "sha256");
|
|
708
|
+
assertLength(encHash, 32, "sha256Enc");
|
|
709
|
+
return { encryptionKey, hmacKey, iv, sha256: plainHash, sha256Enc: encHash };
|
|
710
|
+
}
|
|
711
|
+
function validateEncryptedBytes(encrypted) {
|
|
712
|
+
if (!(encrypted instanceof Uint8Array) || encrypted.byteLength <= 10) {
|
|
713
|
+
throw new MediaCryptoError("invalid_ciphertext", "Encrypted media bytes must be Uint8Array ciphertext plus 10-byte tag.");
|
|
714
|
+
}
|
|
715
|
+
const cipherLength = encrypted.byteLength - 10;
|
|
716
|
+
if (cipherLength <= 0 || cipherLength % 16 !== 0) {
|
|
717
|
+
throw new MediaCryptoError("invalid_ciphertext", "Encrypted media ciphertext must be non-empty and AES-block aligned.");
|
|
718
|
+
}
|
|
719
|
+
return encrypted.slice();
|
|
720
|
+
}
|
|
721
|
+
export async function decryptEncryptedMedia(bundle, encrypted) {
|
|
722
|
+
const b = validateEncryptedBundle(bundle);
|
|
723
|
+
const file = validateEncryptedBytes(encrypted);
|
|
724
|
+
const ciphertext = file.slice(0, file.byteLength - 10);
|
|
725
|
+
const tag = file.slice(file.byteLength - 10);
|
|
726
|
+
const actualEncryptedHash = await sha256(file);
|
|
727
|
+
if (!timingSafeEqualBytes(actualEncryptedHash, b.sha256Enc)) {
|
|
728
|
+
throw new MediaIntegrityError("encrypted_hash_mismatch", "Encrypted media SHA-256 verification failed.");
|
|
729
|
+
}
|
|
730
|
+
const subtle = globalThis.crypto?.subtle;
|
|
731
|
+
if (subtle === undefined) {
|
|
732
|
+
throw new MediaCryptoError("unsupported_crypto", "SubtleCrypto is unavailable.");
|
|
733
|
+
}
|
|
734
|
+
const hmacKey = await subtle.importKey("raw", b.hmacKey.slice(), { name: "HMAC", hash: "SHA-256" }, false, ["sign"]);
|
|
735
|
+
const mac = new Uint8Array(await subtle.sign("HMAC", hmacKey, concatUint8Arrays([b.iv, ciphertext]).slice()));
|
|
736
|
+
if (!timingSafeEqualBytes(mac.slice(0, 10), tag)) {
|
|
737
|
+
throw new MediaIntegrityError("hmac_mismatch", "Encrypted media HMAC verification failed.");
|
|
738
|
+
}
|
|
739
|
+
let decryptedBytes;
|
|
740
|
+
try {
|
|
741
|
+
const key = await subtle.importKey("raw", b.encryptionKey.slice(), { name: "AES-CBC" }, false, ["decrypt"]);
|
|
742
|
+
const decrypted = await subtle.decrypt({ name: "AES-CBC", iv: b.iv.slice() }, key, ciphertext.slice());
|
|
743
|
+
decryptedBytes = new Uint8Array(decrypted);
|
|
744
|
+
} catch (cause) {
|
|
745
|
+
throw new MediaCryptoError("invalid_padding", "AES-CBC decrypt or PKCS#7 padding validation failed.", cause);
|
|
746
|
+
}
|
|
747
|
+
const plaintext = decryptedBytes;
|
|
748
|
+
const actualPlainHash = await sha256(plaintext);
|
|
749
|
+
if (!timingSafeEqualBytes(actualPlainHash, b.sha256)) {
|
|
750
|
+
throw new MediaIntegrityError("plaintext_hash_mismatch", "Decrypted media SHA-256 verification failed.");
|
|
751
|
+
}
|
|
752
|
+
return plaintext;
|
|
753
|
+
}
|
|
754
|
+
function wrapUploadSessionStream(stream, maxBytes) {
|
|
755
|
+
const reader = stream.getReader();
|
|
756
|
+
let total = 0;
|
|
757
|
+
let done = false;
|
|
758
|
+
return new ReadableStream({
|
|
759
|
+
async pull(controller) {
|
|
760
|
+
if (done)
|
|
761
|
+
return;
|
|
762
|
+
let result;
|
|
763
|
+
try {
|
|
764
|
+
result = await reader.read();
|
|
765
|
+
} catch (cause) {
|
|
766
|
+
done = true;
|
|
767
|
+
try {
|
|
768
|
+
reader.releaseLock();
|
|
769
|
+
} catch {}
|
|
770
|
+
throw new MediaValidationError("invalid_file", "ReadableStream upload failed while reading.", cause);
|
|
771
|
+
}
|
|
772
|
+
if (result.done) {
|
|
773
|
+
done = true;
|
|
774
|
+
try {
|
|
775
|
+
reader.releaseLock();
|
|
776
|
+
} catch {}
|
|
777
|
+
controller.close();
|
|
778
|
+
return;
|
|
779
|
+
}
|
|
780
|
+
if (!(result.value instanceof Uint8Array)) {
|
|
781
|
+
done = true;
|
|
782
|
+
try {
|
|
783
|
+
await reader.cancel();
|
|
784
|
+
} catch {}
|
|
785
|
+
try {
|
|
786
|
+
reader.releaseLock();
|
|
787
|
+
} catch {}
|
|
788
|
+
throw new MediaValidationError("invalid_file", "ReadableStream upload yielded non-Uint8Array chunk.");
|
|
789
|
+
}
|
|
790
|
+
let chunk;
|
|
791
|
+
try {
|
|
792
|
+
chunk = normalizeUint8ArrayChunk(result.value);
|
|
793
|
+
} catch (cause) {
|
|
794
|
+
done = true;
|
|
795
|
+
try {
|
|
796
|
+
await reader.cancel();
|
|
797
|
+
} catch {}
|
|
798
|
+
try {
|
|
799
|
+
reader.releaseLock();
|
|
800
|
+
} catch {}
|
|
801
|
+
if (cause instanceof MediaValidationError)
|
|
802
|
+
throw cause;
|
|
803
|
+
throw new MediaValidationError("invalid_file", "ReadableStream upload yielded invalid Uint8Array chunk.", cause);
|
|
804
|
+
}
|
|
805
|
+
total += chunk.byteLength;
|
|
806
|
+
if (total > maxBytes) {
|
|
807
|
+
done = true;
|
|
808
|
+
try {
|
|
809
|
+
await reader.cancel();
|
|
810
|
+
} catch {}
|
|
811
|
+
try {
|
|
812
|
+
reader.releaseLock();
|
|
813
|
+
} catch {}
|
|
814
|
+
throw new MediaValidationError("upload_too_large", "Upload session stream exceeds maxBytes.");
|
|
815
|
+
}
|
|
816
|
+
controller.enqueue(chunk);
|
|
817
|
+
},
|
|
818
|
+
async cancel(reason) {
|
|
819
|
+
done = true;
|
|
820
|
+
try {
|
|
821
|
+
await reader.cancel(reason);
|
|
822
|
+
} finally {
|
|
823
|
+
try {
|
|
824
|
+
reader.releaseLock();
|
|
825
|
+
} catch {}
|
|
826
|
+
}
|
|
827
|
+
}
|
|
828
|
+
});
|
|
829
|
+
}
|
|
830
|
+
async function readTransportBytes(response, maxBytes) {
|
|
831
|
+
const contentLength = response.headers.get("content-length");
|
|
832
|
+
if (contentLength !== null) {
|
|
833
|
+
const parsed = Number(contentLength);
|
|
834
|
+
if (!Number.isSafeInteger(parsed) || parsed < 0) {
|
|
835
|
+
throw new MediaValidationError("invalid_response", "Invalid media response content-length.");
|
|
836
|
+
}
|
|
837
|
+
if (parsed > maxBytes)
|
|
838
|
+
throw new MediaValidationError("download_too_large", "Media download exceeds maxBytes.");
|
|
839
|
+
}
|
|
840
|
+
const stream = response.body;
|
|
841
|
+
if (stream !== null && typeof stream.getReader === "function") {
|
|
842
|
+
const reader = stream.getReader();
|
|
843
|
+
const chunks = [];
|
|
844
|
+
let total = 0;
|
|
845
|
+
try {
|
|
846
|
+
while (true) {
|
|
847
|
+
let result;
|
|
848
|
+
try {
|
|
849
|
+
result = await reader.read();
|
|
850
|
+
} catch (cause) {
|
|
851
|
+
throw new MediaValidationError("invalid_response", "Media response stream failed while reading.", cause);
|
|
852
|
+
}
|
|
853
|
+
if (result.done)
|
|
854
|
+
break;
|
|
855
|
+
if (!(result.value instanceof Uint8Array)) {
|
|
856
|
+
throw new MediaValidationError("invalid_response", "Media response stream yielded non-Uint8Array chunk.");
|
|
857
|
+
}
|
|
858
|
+
let chunk;
|
|
859
|
+
try {
|
|
860
|
+
chunk = normalizeUint8ArrayChunk(result.value);
|
|
861
|
+
} catch (cause) {
|
|
862
|
+
if (cause instanceof MediaValidationError) {
|
|
863
|
+
throw new MediaValidationError(cause.code, cause.message, cause);
|
|
864
|
+
}
|
|
865
|
+
throw new MediaValidationError("invalid_response", "Media response stream yielded invalid Uint8Array chunk.", cause);
|
|
866
|
+
}
|
|
867
|
+
total += chunk.byteLength;
|
|
868
|
+
if (total > maxBytes) {
|
|
869
|
+
try {
|
|
870
|
+
await reader.cancel();
|
|
871
|
+
} catch {}
|
|
872
|
+
throw new MediaValidationError("download_too_large", "Media download exceeds maxBytes.");
|
|
873
|
+
}
|
|
874
|
+
chunks.push(chunk);
|
|
875
|
+
}
|
|
876
|
+
} finally {
|
|
877
|
+
try {
|
|
878
|
+
reader.releaseLock();
|
|
879
|
+
} catch {}
|
|
880
|
+
}
|
|
881
|
+
return concatUint8Arrays(chunks);
|
|
882
|
+
}
|
|
883
|
+
const bytes = new Uint8Array(await response.arrayBuffer());
|
|
884
|
+
if (bytes.byteLength > maxBytes)
|
|
885
|
+
throw new MediaValidationError("download_too_large", "Media download exceeds maxBytes.");
|
|
886
|
+
return bytes;
|
|
887
|
+
}
|
|
888
|
+
export async function downloadMediaBytes(client, opts) {
|
|
889
|
+
assertClient(client);
|
|
890
|
+
const options = validateDownloadBytesOptions(opts);
|
|
891
|
+
const res = await client.requestRaw({
|
|
892
|
+
method: "GET",
|
|
893
|
+
url: options.url,
|
|
894
|
+
body: null,
|
|
895
|
+
...options.signal !== undefined ? { signal: options.signal } : {}
|
|
896
|
+
});
|
|
897
|
+
if (res.status < 200 || res.status >= 300) {
|
|
898
|
+
let payload;
|
|
899
|
+
try {
|
|
900
|
+
payload = await res.json();
|
|
901
|
+
} catch {
|
|
902
|
+
payload = undefined;
|
|
903
|
+
}
|
|
904
|
+
const maybe = isRecord(payload) && isRecord(payload.error) ? payload.error : undefined;
|
|
905
|
+
throw createGraphApiError({ status: res.status, payload: maybe, fallbackMessage: `Graph API request failed with status ${res.status}` });
|
|
906
|
+
}
|
|
907
|
+
const bytes = await readTransportBytes(res, options.maxBytes);
|
|
908
|
+
const actualHash = await sha256(bytes);
|
|
909
|
+
if (options.expectedSha256 !== undefined && !timingSafeEqualBytes(actualHash, options.expectedSha256)) {
|
|
910
|
+
throw new MediaIntegrityError("sha256_mismatch", "Downloaded media SHA-256 mismatch.");
|
|
911
|
+
}
|
|
912
|
+
return {
|
|
913
|
+
bytes,
|
|
914
|
+
sha256: bytesToBase64Local(actualHash),
|
|
915
|
+
...res.headers.get("content-type") !== null ? { contentType: res.headers.get("content-type") } : {}
|
|
916
|
+
};
|
|
917
|
+
}
|
|
918
|
+
function bytesToBase64Local(bytes) {
|
|
919
|
+
let binary = "";
|
|
920
|
+
for (const byte of bytes)
|
|
921
|
+
binary += String.fromCharCode(byte);
|
|
922
|
+
return btoa(binary);
|
|
923
|
+
}
|
|
924
|
+
export async function createUploadSession(client, params, opts) {
|
|
925
|
+
assertClient(client);
|
|
926
|
+
const validated = validateCreateUploadSessionParams(params, opts);
|
|
927
|
+
const p = validated.params;
|
|
928
|
+
const response = await client.request({
|
|
929
|
+
method: "POST",
|
|
930
|
+
path: `/${p.appId}/uploads`,
|
|
931
|
+
query: { file_name: p.fileName, file_length: p.fileLength, file_type: p.fileType },
|
|
932
|
+
...validated.signal !== undefined ? { signal: validated.signal } : {}
|
|
933
|
+
});
|
|
934
|
+
return validateUploadResponse(response);
|
|
935
|
+
}
|
|
936
|
+
export async function uploadFileToSession(client, params, opts) {
|
|
937
|
+
assertClient(client);
|
|
938
|
+
const p = validateUploadFileToSessionParams(params, opts);
|
|
939
|
+
const body = p.fileIsStream ? wrapUploadSessionStream(p.file, p.maxBytes) : p.file instanceof Uint8Array ? normalizeUint8ArrayChunk(p.file) : p.file;
|
|
940
|
+
let response;
|
|
941
|
+
try {
|
|
942
|
+
response = await client.request({
|
|
943
|
+
method: "POST",
|
|
944
|
+
path: `/${p.uploadSessionId}`,
|
|
945
|
+
body,
|
|
946
|
+
headers: {
|
|
947
|
+
file_offset: String(p.fileOffset),
|
|
948
|
+
...p.contentLength !== undefined ? { "content-length": String(p.contentLength) } : {}
|
|
949
|
+
},
|
|
950
|
+
...p.signal !== undefined ? { signal: p.signal } : {}
|
|
951
|
+
});
|
|
952
|
+
} catch (cause) {
|
|
953
|
+
const streamError = p.fileIsStream ? findCauseByName(cause, "MediaValidationError") : undefined;
|
|
954
|
+
if (streamError instanceof MediaValidationError) {
|
|
955
|
+
throw streamError;
|
|
956
|
+
}
|
|
957
|
+
throw cause;
|
|
958
|
+
}
|
|
959
|
+
if (!isRecord(response) || typeof response.h !== "string" || response.h.length === 0) {
|
|
960
|
+
throw new MediaValidationError("invalid_response", "Invalid upload session response: expected { h: string }.");
|
|
961
|
+
}
|
|
962
|
+
return { h: response.h };
|
|
963
|
+
}
|
|
964
|
+
export async function getUploadSession(client, params) {
|
|
965
|
+
assertClient(client);
|
|
966
|
+
const p = validateGetUploadSessionParams(params);
|
|
967
|
+
const response = await client.request({
|
|
968
|
+
method: "GET",
|
|
969
|
+
path: `/${p.uploadSessionId}`,
|
|
970
|
+
...p.signal !== undefined ? { signal: p.signal } : {}
|
|
971
|
+
});
|
|
972
|
+
if (!isRecord(response) || typeof response.id !== "string" || response.id.length === 0) {
|
|
973
|
+
throw new MediaValidationError("invalid_response", "Invalid upload session status response.");
|
|
974
|
+
}
|
|
975
|
+
return { id: response.id, fileOffset: parseFileSize(response.file_offset ?? response.fileOffset) };
|
|
976
|
+
}
|