@12-apps/messaging 1.1.0 → 1.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +37 -1
- package/dist/{channel-Cs_vLGl_.d.ts → channel-HEnMO02x.d.ts} +45 -1
- package/dist/{chunk-R3DKM2IV.js → chunk-LNVSQ5IQ.js} +13 -1
- package/dist/chunk-LNVSQ5IQ.js.map +1 -0
- package/dist/{chunk-Y7MG2UDQ.js → chunk-NKH5TCSO.js} +20 -1
- package/dist/chunk-NKH5TCSO.js.map +1 -0
- package/dist/{chunk-72TDAQUW.js → chunk-S5PJXMXM.js} +2 -2
- package/dist/{engine-DTnp2zUL.d.ts → engine-DAfm8V5S.d.ts} +22 -2
- package/dist/index.d.ts +30 -5
- package/dist/index.js +75 -2
- package/dist/index.js.map +1 -1
- package/dist/manifest/server.d.ts +2 -2
- package/dist/manifest/server.js +2 -2
- package/dist/server/index.d.ts +2 -2
- package/dist/server/index.js +2 -2
- package/dist/whatsapp/index.d.ts +55 -5
- package/dist/whatsapp/index.js +175 -2
- package/dist/whatsapp/index.js.map +1 -1
- package/package.json +1 -1
- package/src/core/channel.ts +58 -0
- package/src/core/engine.ts +9 -0
- package/src/core/errors.ts +31 -0
- package/src/core/media.ts +84 -0
- package/src/core/memory-store.ts +4 -0
- package/src/core/prisma-store.ts +4 -1
- package/src/core/store.ts +6 -0
- package/src/index.ts +7 -0
- package/src/whatsapp/graph.ts +53 -5
- package/src/whatsapp/index.ts +16 -1
- package/src/whatsapp/media.ts +205 -0
- package/dist/chunk-R3DKM2IV.js.map +0 -1
- package/dist/chunk-Y7MG2UDQ.js.map +0 -1
- /package/dist/{chunk-72TDAQUW.js.map → chunk-S5PJXMXM.js.map} +0 -0
package/src/core/errors.ts
CHANGED
|
@@ -46,6 +46,37 @@ export class MessagingConnectError extends Error {
|
|
|
46
46
|
}
|
|
47
47
|
}
|
|
48
48
|
|
|
49
|
+
/** Why a media download was refused or failed. */
|
|
50
|
+
export type MessagingMediaErrorCode =
|
|
51
|
+
/** No such message in this tenant. */
|
|
52
|
+
| "NOT_FOUND"
|
|
53
|
+
/** The message carries no downloadable media (not an inbound audio, or no media id). */
|
|
54
|
+
| "NO_MEDIA"
|
|
55
|
+
/** No adapter for the message's channel is mounted. */
|
|
56
|
+
| "UNKNOWN_CHANNEL"
|
|
57
|
+
/** The channel's adapter has no media download, or the store cannot read a message by id. */
|
|
58
|
+
| "UNSUPPORTED"
|
|
59
|
+
/** The message's connection is not connected (revoked, in error, gone, or holds no credential). */
|
|
60
|
+
| "NOT_CONNECTED"
|
|
61
|
+
/** `maxBytes` or `timeoutMs` is not a positive safe integer. */
|
|
62
|
+
| "BAD_OPTIONS"
|
|
63
|
+
/** The media is larger than the cap, as declared or as read. */
|
|
64
|
+
| "TOO_LARGE"
|
|
65
|
+
/** The download did not finish before its deadline. */
|
|
66
|
+
| "TIMEOUT"
|
|
67
|
+
/** The channel was called and refused or failed. */
|
|
68
|
+
| "CHANNEL_FAILED";
|
|
69
|
+
|
|
70
|
+
/** A media download refused. Its message never carries the credential. */
|
|
71
|
+
export class MessagingMediaError extends Error {
|
|
72
|
+
readonly code: MessagingMediaErrorCode;
|
|
73
|
+
constructor(code: MessagingMediaErrorCode, message: string) {
|
|
74
|
+
super(message);
|
|
75
|
+
this.name = "MessagingMediaError";
|
|
76
|
+
this.code = code;
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
|
|
49
80
|
/** The error text a row keeps: bounded, because a channel's error body can be a page. */
|
|
50
81
|
export function errorText(error: unknown): string {
|
|
51
82
|
const text = error instanceof Error ? error.message : String(error);
|
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
import {
|
|
2
|
+
ChannelMediaFailure,
|
|
3
|
+
ChannelSendFailure,
|
|
4
|
+
DEFAULT_MEDIA_TIMEOUT_MS,
|
|
5
|
+
isPositiveSafeInteger,
|
|
6
|
+
type ChannelMedia,
|
|
7
|
+
} from "./channel";
|
|
8
|
+
import type { EngineContext } from "./context";
|
|
9
|
+
import { errorText, MessagingMediaError } from "./errors";
|
|
10
|
+
import type { MessageView } from "./types";
|
|
11
|
+
|
|
12
|
+
/** The default cap on one download: 16 MiB, WhatsApp's own limit for audio. */
|
|
13
|
+
export const DEFAULT_MEDIA_MAX_BYTES = 16 * 1024 * 1024;
|
|
14
|
+
|
|
15
|
+
export interface DownloadMediaOptions {
|
|
16
|
+
/** The most bytes accepted; larger media is refused (`TOO_LARGE`). Default {@link DEFAULT_MEDIA_MAX_BYTES}. */
|
|
17
|
+
maxBytes?: number;
|
|
18
|
+
/** The deadline for the whole download; past it the download fails `TIMEOUT`. Default {@link DEFAULT_MEDIA_TIMEOUT_MS}. */
|
|
19
|
+
timeoutMs?: number;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
/** The codes an adapter's failure keeps as the engine's own; every other is `CHANNEL_FAILED`. */
|
|
23
|
+
const KEPT_CODES = new Set<string>(["TOO_LARGE", "TIMEOUT", "BAD_OPTIONS"]);
|
|
24
|
+
|
|
25
|
+
/** The media id of a message that has downloadable media: an inbound audio. */
|
|
26
|
+
function mediaIdOf(message: MessageView): string {
|
|
27
|
+
if (message.direction !== "INBOUND" || message.kind !== "AUDIO" || !message.attachmentRef) {
|
|
28
|
+
throw new MessagingMediaError("NO_MEDIA", `message ${message.id} carries no downloadable media`);
|
|
29
|
+
}
|
|
30
|
+
return message.attachmentRef;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/** The adapter's download and the connection's opened credential, or a refusal. */
|
|
34
|
+
async function admitDownload(ctx: EngineContext, tenantId: string, message: MessageView) {
|
|
35
|
+
const adapter = ctx.adapters.get(message.channel);
|
|
36
|
+
if (!adapter) throw new MessagingMediaError("UNKNOWN_CHANNEL", `no adapter for channel "${message.channel}"`);
|
|
37
|
+
if (!adapter.fetchMedia) throw new MessagingMediaError("UNSUPPORTED", `channel "${message.channel}" has no media download`);
|
|
38
|
+
const { store, secrets } = ctx.config;
|
|
39
|
+
const conversation = await store.getConversation(tenantId, message.conversationId);
|
|
40
|
+
const connection = conversation ? await store.getConnection(tenantId, conversation.connectionId) : null;
|
|
41
|
+
if (!connection || connection.status !== "CONNECTED" || connection.credentialSealed === null) {
|
|
42
|
+
throw new MessagingMediaError("NOT_CONNECTED", `message ${message.id}: its connection is not connected`);
|
|
43
|
+
}
|
|
44
|
+
const credential = await secrets.open(connection.credentialSealed);
|
|
45
|
+
return { fetchMedia: adapter.fetchMedia.bind(adapter), credential, accountId: connection.externalAccountId };
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/** An adapter's failure as the engine's, with the credential scrubbed from its text should a channel echo it. */
|
|
49
|
+
function mediaFailureOf(error: unknown, credential: string): MessagingMediaError {
|
|
50
|
+
const coded = error instanceof ChannelMediaFailure || error instanceof ChannelSendFailure;
|
|
51
|
+
const raw = coded ? `${error.code}: ${error.message}` : errorText(error);
|
|
52
|
+
const text = (credential ? raw.split(credential).join("[credential]") : raw).slice(0, 500);
|
|
53
|
+
const kept = error instanceof ChannelMediaFailure && KEPT_CODES.has(error.code);
|
|
54
|
+
return new MessagingMediaError(kept ? (error.code as "TOO_LARGE" | "TIMEOUT" | "BAD_OPTIONS") : "CHANNEL_FAILED", text);
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/**
|
|
58
|
+
* Download an inbound message's media into memory, through its connection's
|
|
59
|
+
* credential (opened exactly as a send opens it). The bytes are returned and
|
|
60
|
+
* never stored: retention is the host's call, and the package keeps none.
|
|
61
|
+
*/
|
|
62
|
+
export async function downloadMedia(
|
|
63
|
+
ctx: EngineContext,
|
|
64
|
+
tenantId: string,
|
|
65
|
+
messageId: string,
|
|
66
|
+
options: DownloadMediaOptions = {},
|
|
67
|
+
): Promise<ChannelMedia> {
|
|
68
|
+
const maxBytes = options.maxBytes ?? DEFAULT_MEDIA_MAX_BYTES;
|
|
69
|
+
const timeoutMs = options.timeoutMs ?? DEFAULT_MEDIA_TIMEOUT_MS;
|
|
70
|
+
if (!isPositiveSafeInteger(maxBytes) || !isPositiveSafeInteger(timeoutMs)) {
|
|
71
|
+
throw new MessagingMediaError("BAD_OPTIONS", "maxBytes and timeoutMs must be positive safe integers");
|
|
72
|
+
}
|
|
73
|
+
const { store } = ctx.config;
|
|
74
|
+
if (!store.getMessage) throw new MessagingMediaError("UNSUPPORTED", "the store cannot read a message by id (getMessage)");
|
|
75
|
+
const message = await store.getMessage(tenantId, messageId);
|
|
76
|
+
if (!message) throw new MessagingMediaError("NOT_FOUND", `no message ${messageId}`);
|
|
77
|
+
const mediaId = mediaIdOf(message);
|
|
78
|
+
const { fetchMedia, credential, accountId } = await admitDownload(ctx, tenantId, message);
|
|
79
|
+
try {
|
|
80
|
+
return await fetchMedia({ credential, accountId, mediaId, maxBytes, timeoutMs });
|
|
81
|
+
} catch (error) {
|
|
82
|
+
throw mediaFailureOf(error, credential);
|
|
83
|
+
}
|
|
84
|
+
}
|
package/src/core/memory-store.ts
CHANGED
|
@@ -210,6 +210,10 @@ function memoryMessages({ messages }: MemoryTables) {
|
|
|
210
210
|
messages.set(id, next);
|
|
211
211
|
return copy(next);
|
|
212
212
|
},
|
|
213
|
+
async getMessage(tenantId, id) {
|
|
214
|
+
const row = messages.get(id);
|
|
215
|
+
return row && row.tenantId === tenantId ? copy(row) : null;
|
|
216
|
+
},
|
|
213
217
|
async listMessages(tenantId, conversationId) {
|
|
214
218
|
return [...messages.values()]
|
|
215
219
|
.filter((row) => row.tenantId === tenantId && row.conversationId === conversationId)
|
package/src/core/prisma-store.ts
CHANGED
|
@@ -247,7 +247,7 @@ function guardWhere(guard: ConversationGuard | undefined): Record<string, unknow
|
|
|
247
247
|
|
|
248
248
|
type MessageOperations = Pick<
|
|
249
249
|
MessagingStore,
|
|
250
|
-
"findMessageByExternalId" | "insertMessage" | "updateMessage" | "listMessages" | "applyReceipt"
|
|
250
|
+
"findMessageByExternalId" | "insertMessage" | "updateMessage" | "getMessage" | "listMessages" | "applyReceipt"
|
|
251
251
|
>;
|
|
252
252
|
|
|
253
253
|
function messageOperations(client: Client): MessageOperations {
|
|
@@ -273,6 +273,9 @@ function messageOperations(client: Client): MessageOperations {
|
|
|
273
273
|
if (result.count === 0) return null;
|
|
274
274
|
return (await delegate.findUnique({ where: { id } })) as MessageView;
|
|
275
275
|
},
|
|
276
|
+
async getMessage(tenantId, id) {
|
|
277
|
+
return ((await (await client()).messagingMessage.findFirst({ where: { id, tenantId } })) as MessageView | null) ?? null;
|
|
278
|
+
},
|
|
276
279
|
async listMessages(tenantId, conversationId) {
|
|
277
280
|
return (await (await client()).messagingMessage.findMany({
|
|
278
281
|
where: { tenantId, conversationId },
|
package/src/core/store.ts
CHANGED
|
@@ -84,6 +84,12 @@ export interface MessagingStore {
|
|
|
84
84
|
/** Insert one; a duplicate `(channel, externalId)` is `created: false` and the existing row. */
|
|
85
85
|
insertMessage(input: NewMessage): Promise<{ created: boolean; message: MessageView }>;
|
|
86
86
|
updateMessage(tenantId: string, id: string, patch: MessagePatch): Promise<MessageView | null>;
|
|
87
|
+
/**
|
|
88
|
+
* The tenant's message by id; null for another tenant's or none. Optional so
|
|
89
|
+
* a host's own store keeps compiling; both shipped stores implement it, and
|
|
90
|
+
* `downloadMedia` is refused (`UNSUPPORTED`) on a store without it.
|
|
91
|
+
*/
|
|
92
|
+
getMessage?(tenantId: string, id: string): Promise<MessageView | null>;
|
|
87
93
|
listMessages(tenantId: string, conversationId: string): Promise<MessageView[]>;
|
|
88
94
|
/**
|
|
89
95
|
* Stamp a receipt on the tenant's outbound message: the receipt's timestamp
|
package/src/index.ts
CHANGED
|
@@ -8,11 +8,15 @@
|
|
|
8
8
|
|
|
9
9
|
export { createMessagingEngine, type MessagingEngine } from "./core/engine";
|
|
10
10
|
export {
|
|
11
|
+
ChannelMediaFailure,
|
|
11
12
|
ChannelSendFailure,
|
|
13
|
+
DEFAULT_MEDIA_TIMEOUT_MS,
|
|
12
14
|
isWindowOpen,
|
|
13
15
|
OPEN_SEND_POLICY,
|
|
14
16
|
serviceWindowPolicy,
|
|
15
17
|
type ChannelAdapter,
|
|
18
|
+
type ChannelMedia,
|
|
19
|
+
type ChannelMediaInput,
|
|
16
20
|
type ChannelSendInput,
|
|
17
21
|
type HandshakeAnswer,
|
|
18
22
|
type SendPolicy,
|
|
@@ -31,13 +35,16 @@ export {
|
|
|
31
35
|
} from "./core/ports";
|
|
32
36
|
export {
|
|
33
37
|
MessagingConnectError,
|
|
38
|
+
MessagingMediaError,
|
|
34
39
|
MessagingSendError,
|
|
35
40
|
type MessagingConnectErrorCode,
|
|
41
|
+
type MessagingMediaErrorCode,
|
|
36
42
|
type MessagingSendErrorCode,
|
|
37
43
|
} from "./core/errors";
|
|
38
44
|
export { PROCESS_DELIVERY_JOB, type DeliveryOutcome } from "./core/inbox";
|
|
39
45
|
export type { EventOutcome } from "./core/inbound";
|
|
40
46
|
export type { SendAuthor, SendInput } from "./core/sender";
|
|
47
|
+
export { DEFAULT_MEDIA_MAX_BYTES, type DownloadMediaOptions } from "./core/media";
|
|
41
48
|
export type { ConnectInput } from "./core/connections";
|
|
42
49
|
export type {
|
|
43
50
|
ConversationPatch,
|
package/src/whatsapp/graph.ts
CHANGED
|
@@ -4,11 +4,45 @@ import type { OutboundContent } from "../core/types";
|
|
|
4
4
|
/**
|
|
5
5
|
* The only way the adapter reaches Meta: an injected fetch. The global
|
|
6
6
|
* `fetch` satisfies it; a test answers it with a recording fake.
|
|
7
|
+
*
|
|
8
|
+
* A JSON call reads `text()` only. A media download also asks for
|
|
9
|
+
* `redirect: "manual"` (a 3xx comes back as itself, never followed) and reads
|
|
10
|
+
* the binary body through `body` (a stream, read up to the size cap) or, when
|
|
11
|
+
* there is none, `arrayBuffer()`. All three are optional so a text-only fake
|
|
12
|
+
* still satisfies the port.
|
|
7
13
|
*/
|
|
8
|
-
export type FetchPort = (
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
14
|
+
export type FetchPort = (url: string, init: FetchInit) => Promise<FetchResponse>;
|
|
15
|
+
|
|
16
|
+
export interface FetchInit {
|
|
17
|
+
method: string;
|
|
18
|
+
headers: Record<string, string>;
|
|
19
|
+
body?: string;
|
|
20
|
+
/** `manual` for a media download: a redirect is answered, never followed. */
|
|
21
|
+
redirect?: "manual" | "follow" | "error";
|
|
22
|
+
/** Aborts the call at a media download's deadline. */
|
|
23
|
+
signal?: AbortSignal;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
export interface FetchResponse {
|
|
27
|
+
status: number;
|
|
28
|
+
text(): Promise<string>;
|
|
29
|
+
arrayBuffer?(): Promise<ArrayBuffer>;
|
|
30
|
+
/** The body as a stream; read chunk by chunk so an oversized one is cut off early. */
|
|
31
|
+
body?: { getReader(): FetchBodyReader; cancel?(reason?: unknown): Promise<void> } | null;
|
|
32
|
+
headers?: { get(name: string): string | null };
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
export interface FetchBodyReader {
|
|
36
|
+
read(): Promise<{ done: boolean; value?: Uint8Array }>;
|
|
37
|
+
cancel(reason?: unknown): Promise<void>;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/**
|
|
41
|
+
* The hosts Meta serves WhatsApp media from: the URL a media lookup returns is
|
|
42
|
+
* `https://lookaside.fbsbx.com/whatsapp_business/attachments/?mid=…`, and the
|
|
43
|
+
* CDN families behind it. `*.` matches any subdomain (not the bare domain).
|
|
44
|
+
*/
|
|
45
|
+
export const DEFAULT_META_MEDIA_HOSTS: readonly string[] = ["lookaside.fbsbx.com", "*.fbcdn.net", "*.whatsapp.net"];
|
|
12
46
|
|
|
13
47
|
/** Where the Graph API is, and through what. Both numbers are config, never constants in the adapter. */
|
|
14
48
|
export interface GraphConfig {
|
|
@@ -17,6 +51,12 @@ export interface GraphConfig {
|
|
|
17
51
|
baseUrl: string;
|
|
18
52
|
/** `v23.0` — the Graph API version every call is pinned to. */
|
|
19
53
|
apiVersion: string;
|
|
54
|
+
/**
|
|
55
|
+
* The hosts a media URL may point at; any other is refused before the token
|
|
56
|
+
* is sent to it. Exact names, or `*.domain` for its subdomains. Default
|
|
57
|
+
* {@link DEFAULT_META_MEDIA_HOSTS}.
|
|
58
|
+
*/
|
|
59
|
+
mediaHosts?: readonly string[];
|
|
20
60
|
}
|
|
21
61
|
|
|
22
62
|
/** A Graph call that did not answer 2xx. Carries Meta's error code; never the token. */
|
|
@@ -37,6 +77,8 @@ interface GraphCall {
|
|
|
37
77
|
token?: string;
|
|
38
78
|
query?: Record<string, string>;
|
|
39
79
|
body?: unknown;
|
|
80
|
+
redirect?: FetchInit["redirect"];
|
|
81
|
+
signal?: AbortSignal;
|
|
40
82
|
}
|
|
41
83
|
|
|
42
84
|
/** Drops trailing "/" characters in one linear pass (a regex here backtracks quadratically on library input). */
|
|
@@ -55,7 +97,13 @@ function requestOf(graph: GraphConfig, call: GraphCall) {
|
|
|
55
97
|
if (call.body !== undefined) headers["content-type"] = "application/json";
|
|
56
98
|
return {
|
|
57
99
|
url: `${base}/${graph.apiVersion}/${call.path}${query}`,
|
|
58
|
-
init: {
|
|
100
|
+
init: {
|
|
101
|
+
method: call.method,
|
|
102
|
+
headers,
|
|
103
|
+
...(call.body !== undefined ? { body: JSON.stringify(call.body) } : {}),
|
|
104
|
+
...(call.redirect ? { redirect: call.redirect } : {}),
|
|
105
|
+
...(call.signal ? { signal: call.signal } : {}),
|
|
106
|
+
} satisfies FetchInit,
|
|
59
107
|
};
|
|
60
108
|
}
|
|
61
109
|
|
package/src/whatsapp/index.ts
CHANGED
|
@@ -15,6 +15,7 @@
|
|
|
15
15
|
import { serviceWindowPolicy, type ChannelAdapter } from "../core/channel";
|
|
16
16
|
import { parseWhatsAppPayload } from "./parse";
|
|
17
17
|
import { sendWhatsAppMessage, type GraphConfig } from "./graph";
|
|
18
|
+
import { downloadWhatsAppMedia } from "./media";
|
|
18
19
|
import { META_SIGNATURE_HEADER, verifyMetaSignature, verifyMetaSubscription } from "./signature";
|
|
19
20
|
|
|
20
21
|
/** The channel key every WhatsApp row carries. */
|
|
@@ -46,6 +47,8 @@ export function createWhatsAppAdapter(config: WhatsAppAdapterConfig): ChannelAda
|
|
|
46
47
|
}),
|
|
47
48
|
send: ({ credential, accountId, to, content }) =>
|
|
48
49
|
sendWhatsAppMessage(config.graph, { token: credential, phoneNumberId: accountId, to, content }),
|
|
50
|
+
fetchMedia: ({ credential, mediaId, maxBytes, timeoutMs }) =>
|
|
51
|
+
downloadWhatsAppMedia(config.graph, { token: credential, mediaId, maxBytes, ...(timeoutMs !== undefined ? { timeoutMs } : {}) }),
|
|
49
52
|
policy: serviceWindowPolicy(WHATSAPP_SERVICE_WINDOW_MS),
|
|
50
53
|
};
|
|
51
54
|
}
|
|
@@ -53,7 +56,19 @@ export function createWhatsAppAdapter(config: WhatsAppAdapterConfig): ChannelAda
|
|
|
53
56
|
export { META_SIGNATURE_HEADER, verifyMetaSignature, verifyMetaSubscription, type MetaHandshake } from "./signature";
|
|
54
57
|
export { parseWhatsAppPayload, parseWhatsAppStatuses } from "./parse";
|
|
55
58
|
export { DEFAULT_OPT_OUT_KEYWORDS, isOptOutText } from "./opt-out";
|
|
56
|
-
export {
|
|
59
|
+
export {
|
|
60
|
+
DEFAULT_META_MEDIA_HOSTS,
|
|
61
|
+
GraphError,
|
|
62
|
+
graphRequest,
|
|
63
|
+
messageBody,
|
|
64
|
+
sendWhatsAppMessage,
|
|
65
|
+
type FetchBodyReader,
|
|
66
|
+
type FetchInit,
|
|
67
|
+
type FetchPort,
|
|
68
|
+
type FetchResponse,
|
|
69
|
+
type GraphConfig,
|
|
70
|
+
} from "./graph";
|
|
71
|
+
export { downloadWhatsAppMedia } from "./media";
|
|
57
72
|
export {
|
|
58
73
|
exchangeSignupCode,
|
|
59
74
|
readSignupAccounts,
|
|
@@ -0,0 +1,205 @@
|
|
|
1
|
+
import { ChannelMediaFailure, DEFAULT_MEDIA_TIMEOUT_MS, isPositiveSafeInteger, type ChannelMedia } from "../core/channel";
|
|
2
|
+
import { DEFAULT_META_MEDIA_HOSTS, graphRequest, type FetchResponse, type GraphConfig } from "./graph";
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* A WhatsApp media download, the Cloud API way: `GET /{version}/{media-id}`
|
|
6
|
+
* with the business token answers `{ url, mime_type, file_size }`, and a
|
|
7
|
+
* `GET` of that URL with the same token answers the bytes.
|
|
8
|
+
*
|
|
9
|
+
* The token travels in the Authorization header only, and only to a Meta
|
|
10
|
+
* media host over https: the URL comes from Meta, but it is still checked
|
|
11
|
+
* against the configured hosts before the token is sent to it, and a redirect
|
|
12
|
+
* is refused rather than followed to wherever it points. The size is capped
|
|
13
|
+
* twice — the declared `file_size` before the download, the bytes actually
|
|
14
|
+
* read during it — the whole download has a deadline, and the media lives
|
|
15
|
+
* only in the returned memory.
|
|
16
|
+
*/
|
|
17
|
+
|
|
18
|
+
const OCTET_STREAM = "application/octet-stream";
|
|
19
|
+
|
|
20
|
+
/** Does `host` match one allowlist entry: an exact name, or `*.domain` for its subdomains. */
|
|
21
|
+
function hostAllowed(host: string, allowed: readonly string[]): boolean {
|
|
22
|
+
return allowed.some((entry) => {
|
|
23
|
+
const pattern = entry.toLowerCase();
|
|
24
|
+
// "*.fbcdn.net" matches "x.fbcdn.net" through its ".fbcdn.net" suffix, never "fbcdn.net" or "evilfbcdn.net".
|
|
25
|
+
return pattern.startsWith("*.") ? host.endsWith(pattern.slice(1)) : host === pattern;
|
|
26
|
+
});
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/** The media URL Meta returned, checked: https, no userinfo, an allowed host. */
|
|
30
|
+
function checkedMediaUrl(raw: unknown, allowed: readonly string[]): string {
|
|
31
|
+
if (typeof raw !== "string" || raw === "") throw new ChannelMediaFailure("NO_MEDIA_URL", "Graph returned no media url");
|
|
32
|
+
let url: URL;
|
|
33
|
+
try {
|
|
34
|
+
url = new URL(raw);
|
|
35
|
+
} catch {
|
|
36
|
+
throw new ChannelMediaFailure("MEDIA_URL_INVALID", "Graph returned a media url that does not parse");
|
|
37
|
+
}
|
|
38
|
+
if (url.protocol !== "https:") throw new ChannelMediaFailure("MEDIA_URL_REFUSED", "the media url is not https");
|
|
39
|
+
if (url.username || url.password) throw new ChannelMediaFailure("MEDIA_URL_REFUSED", "the media url carries credentials");
|
|
40
|
+
if (url.port !== "") throw new ChannelMediaFailure("MEDIA_URL_REFUSED", "the media url names an explicit port");
|
|
41
|
+
if (!hostAllowed(url.hostname.toLowerCase(), allowed)) {
|
|
42
|
+
throw new ChannelMediaFailure("MEDIA_HOST_REFUSED", `the media host ${url.hostname} is not a Meta media host`);
|
|
43
|
+
}
|
|
44
|
+
return url.toString();
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
const tooLarge = (size: number, maxBytes: number) =>
|
|
48
|
+
new ChannelMediaFailure("TOO_LARGE", `the media is ${size} bytes, over the ${maxBytes}-byte cap`);
|
|
49
|
+
|
|
50
|
+
/** A declared size over the cap refuses the download before it starts. */
|
|
51
|
+
function checkDeclaredSize(declared: unknown, maxBytes: number): void {
|
|
52
|
+
const size = typeof declared === "number" ? declared : typeof declared === "string" ? Number(declared) : NaN;
|
|
53
|
+
if (Number.isFinite(size) && size > maxBytes) throw tooLarge(size, maxBytes);
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/** Concatenate the chunks read so far. */
|
|
57
|
+
function joined(chunks: Uint8Array[], total: number): Uint8Array {
|
|
58
|
+
const bytes = new Uint8Array(total);
|
|
59
|
+
let offset = 0;
|
|
60
|
+
for (const chunk of chunks) {
|
|
61
|
+
bytes.set(chunk, offset);
|
|
62
|
+
offset += chunk.length;
|
|
63
|
+
}
|
|
64
|
+
return bytes;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/** The download's deadline: one abort signal for both calls, and a race for every read. */
|
|
68
|
+
interface Deadline {
|
|
69
|
+
signal: AbortSignal;
|
|
70
|
+
/** `promise`, or a `TIMEOUT` failure once the deadline passes — whichever comes first. */
|
|
71
|
+
race<T>(promise: Promise<T>): Promise<T>;
|
|
72
|
+
clear(): void;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
const timedOut = (timeoutMs: number) =>
|
|
76
|
+
new ChannelMediaFailure("TIMEOUT", `the media download did not finish within ${timeoutMs} ms`);
|
|
77
|
+
|
|
78
|
+
function deadlineOf(timeoutMs: number): Deadline {
|
|
79
|
+
const controller = new AbortController();
|
|
80
|
+
let timer: ReturnType<typeof setTimeout> | undefined;
|
|
81
|
+
const expired = new Promise<never>((_resolve, reject) => {
|
|
82
|
+
timer = setTimeout(() => {
|
|
83
|
+
controller.abort();
|
|
84
|
+
reject(timedOut(timeoutMs));
|
|
85
|
+
}, timeoutMs);
|
|
86
|
+
});
|
|
87
|
+
// The race below observes it; this only keeps an unobserved expiry from being reported unhandled.
|
|
88
|
+
expired.catch(() => undefined);
|
|
89
|
+
return {
|
|
90
|
+
signal: controller.signal,
|
|
91
|
+
race: async (promise) => {
|
|
92
|
+
try {
|
|
93
|
+
return await Promise.race([promise, expired]);
|
|
94
|
+
} catch (error) {
|
|
95
|
+
// A port that honours the signal rejects with its own abort error: it is the deadline all the same.
|
|
96
|
+
throw controller.signal.aborted ? timedOut(timeoutMs) : error;
|
|
97
|
+
}
|
|
98
|
+
},
|
|
99
|
+
clear: () => clearTimeout(timer),
|
|
100
|
+
};
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/** Release a body that will not be read; never throws. */
|
|
104
|
+
function discardBody(response: FetchResponse): void {
|
|
105
|
+
try {
|
|
106
|
+
void Promise.resolve(response.body?.cancel?.()).catch(() => undefined);
|
|
107
|
+
} catch {
|
|
108
|
+
// A body that cannot even be cancelled is left to the garbage collector.
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
/** Read a stream, cancelling it the moment it passes the cap or the deadline. */
|
|
113
|
+
async function readStreamCapped(response: FetchResponse, maxBytes: number, deadline: Deadline): Promise<Uint8Array> {
|
|
114
|
+
const reader = response.body!.getReader();
|
|
115
|
+
const chunks: Uint8Array[] = [];
|
|
116
|
+
let total = 0;
|
|
117
|
+
try {
|
|
118
|
+
for (;;) {
|
|
119
|
+
const { done, value } = await deadline.race(reader.read());
|
|
120
|
+
if (done) break;
|
|
121
|
+
if (!value) continue;
|
|
122
|
+
total += value.length;
|
|
123
|
+
if (total > maxBytes) throw tooLarge(total, maxBytes);
|
|
124
|
+
chunks.push(value);
|
|
125
|
+
}
|
|
126
|
+
} catch (error) {
|
|
127
|
+
void reader.cancel().catch(() => undefined);
|
|
128
|
+
throw error;
|
|
129
|
+
}
|
|
130
|
+
return joined(chunks, total);
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
/** The body's bytes, never more than `maxBytes` of them — whatever the headers declared. */
|
|
134
|
+
async function readBodyCapped(response: FetchResponse, maxBytes: number, deadline: Deadline): Promise<Uint8Array> {
|
|
135
|
+
const declared = response.headers?.get("content-length");
|
|
136
|
+
if (declared) {
|
|
137
|
+
try {
|
|
138
|
+
checkDeclaredSize(declared, maxBytes);
|
|
139
|
+
} catch (error) {
|
|
140
|
+
discardBody(response);
|
|
141
|
+
throw error;
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
if (response.body && typeof response.body.getReader === "function") return readStreamCapped(response, maxBytes, deadline);
|
|
145
|
+
if (!response.arrayBuffer) throw new ChannelMediaFailure("NO_BINARY_BODY", "the fetch port cannot read a binary body");
|
|
146
|
+
// Only for a port with no stream: it reads the WHOLE body before the cap can be checked.
|
|
147
|
+
const bytes = new Uint8Array(await deadline.race(response.arrayBuffer()));
|
|
148
|
+
if (bytes.length > maxBytes) throw tooLarge(bytes.length, maxBytes);
|
|
149
|
+
return bytes;
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
/** GET the media URL with the token in a header; a redirect or a non-2xx is refused, its body discarded. */
|
|
153
|
+
async function downloadFrom(graph: GraphConfig, url: string, token: string, deadline: Deadline): Promise<FetchResponse> {
|
|
154
|
+
const response = await deadline.race(
|
|
155
|
+
graph.fetch(url, {
|
|
156
|
+
method: "GET",
|
|
157
|
+
headers: { authorization: `Bearer ${token}`, accept: "*/*" },
|
|
158
|
+
redirect: "manual",
|
|
159
|
+
signal: deadline.signal,
|
|
160
|
+
}),
|
|
161
|
+
);
|
|
162
|
+
if (response.status >= 200 && response.status < 300) return response;
|
|
163
|
+
discardBody(response);
|
|
164
|
+
if (response.status >= 300 && response.status < 400) {
|
|
165
|
+
throw new ChannelMediaFailure("REDIRECT_REFUSED", `the media download answered ${response.status}; redirects are not followed`);
|
|
166
|
+
}
|
|
167
|
+
throw new ChannelMediaFailure(`HTTP_${response.status}`, `the media download answered ${response.status}`);
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
/** A cap or deadline that would not bound anything (NaN, Infinity, 0, negative, fractional) is refused. */
|
|
171
|
+
function checkLimits(maxBytes: number, timeoutMs: number): void {
|
|
172
|
+
if (!isPositiveSafeInteger(maxBytes) || !isPositiveSafeInteger(timeoutMs)) {
|
|
173
|
+
throw new ChannelMediaFailure("BAD_OPTIONS", "maxBytes and timeoutMs must be positive safe integers");
|
|
174
|
+
}
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
/** Download one WhatsApp media object into memory. */
|
|
178
|
+
export async function downloadWhatsAppMedia(
|
|
179
|
+
graph: GraphConfig,
|
|
180
|
+
input: { token: string; mediaId: string; maxBytes: number; timeoutMs?: number },
|
|
181
|
+
): Promise<ChannelMedia> {
|
|
182
|
+
const timeoutMs = input.timeoutMs ?? DEFAULT_MEDIA_TIMEOUT_MS;
|
|
183
|
+
checkLimits(input.maxBytes, timeoutMs);
|
|
184
|
+
const deadline = deadlineOf(timeoutMs);
|
|
185
|
+
try {
|
|
186
|
+
const meta = await deadline.race(
|
|
187
|
+
graphRequest(graph, {
|
|
188
|
+
method: "GET",
|
|
189
|
+
path: encodeURIComponent(input.mediaId),
|
|
190
|
+
token: input.token,
|
|
191
|
+
redirect: "manual",
|
|
192
|
+
signal: deadline.signal,
|
|
193
|
+
}),
|
|
194
|
+
);
|
|
195
|
+
const url = checkedMediaUrl(meta.url, graph.mediaHosts ?? DEFAULT_META_MEDIA_HOSTS);
|
|
196
|
+
checkDeclaredSize(meta.file_size, input.maxBytes);
|
|
197
|
+
const response = await downloadFrom(graph, url, input.token, deadline);
|
|
198
|
+
const bytes = await readBodyCapped(response, input.maxBytes, deadline);
|
|
199
|
+
const declaredType = typeof meta.mime_type === "string" && meta.mime_type ? meta.mime_type : null;
|
|
200
|
+
const mimeType = declaredType ?? response.headers?.get("content-type") ?? OCTET_STREAM;
|
|
201
|
+
return { bytes, mimeType, size: bytes.length };
|
|
202
|
+
} finally {
|
|
203
|
+
deadline.clear();
|
|
204
|
+
}
|
|
205
|
+
}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/core/errors.ts"],"sourcesContent":["/**\n * The engine's refusals, as typed errors with machine codes. The sentence a\n * person reads for each is the host's copy, keyed by `code`.\n */\n\n/** Why a send was refused or failed. */\nexport type MessagingSendErrorCode =\n /** The contact opted out; nothing is sent until they write again. */\n | \"OPTED_OUT\"\n /** The channel's service window is closed (WhatsApp: 24 h after the contact's last message). */\n | \"WINDOW_CLOSED\"\n /** The conversation's connection is not connected (revoked, in error, or gone). */\n | \"NOT_CONNECTED\"\n /** No such conversation in this tenant. */\n | \"NOT_FOUND\"\n /** No adapter for the conversation's channel is mounted. */\n | \"UNKNOWN_CHANNEL\"\n /** The channel was called and refused or failed; the outbound row is FAILED. */\n | \"CHANNEL_FAILED\";\n\nexport class MessagingSendError extends Error {\n readonly code: MessagingSendErrorCode;\n /** The outbound row, when one was recorded before the failure. */\n readonly messageId: string | null;\n constructor(code: MessagingSendErrorCode, message: string, messageId: string | null = null) {\n super(message);\n this.name = \"MessagingSendError\";\n this.code = code;\n this.messageId = messageId;\n }\n}\n\n/** Why a connection could not be saved. */\nexport type MessagingConnectErrorCode =\n /** The account is connected to another tenant. */\n | \"ACCOUNT_TAKEN\"\n /** No adapter for that channel is mounted. */\n | \"UNKNOWN_CHANNEL\";\n\nexport class MessagingConnectError extends Error {\n readonly code: MessagingConnectErrorCode;\n constructor(code: MessagingConnectErrorCode, message: string) {\n super(message);\n this.name = \"MessagingConnectError\";\n this.code = code;\n }\n}\n\n/** The error text a row keeps: bounded, because a channel's error body can be a page. */\nexport function errorText(error: unknown): string {\n const text = error instanceof Error ? error.message : String(error);\n return text.slice(0, 500);\n}\n"],"mappings":";;;;;AAoBO,IAAM,qBAAN,cAAiC,MAAM;AAAA,EApB9C,OAoB8C;AAAA;AAAA;AAAA,EACnC;AAAA;AAAA,EAEA;AAAA,EACT,YAAY,MAA8B,SAAiB,YAA2B,MAAM;AAC1F,UAAM,OAAO;AACb,SAAK,OAAO;AACZ,SAAK,OAAO;AACZ,SAAK,YAAY;AAAA,EACnB;AACF;AASO,IAAM,wBAAN,cAAoC,MAAM;AAAA,EAvCjD,OAuCiD;AAAA;AAAA;AAAA,EACtC;AAAA,EACT,YAAY,MAAiC,SAAiB;AAC5D,UAAM,OAAO;AACb,SAAK,OAAO;AACZ,SAAK,OAAO;AAAA,EACd;AACF;AAGO,SAAS,UAAU,OAAwB;AAChD,QAAM,OAAO,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK;AAClE,SAAO,KAAK,MAAM,GAAG,GAAG;AAC1B;AAHgB;","names":[]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/core/channel.ts"],"sourcesContent":["import type { ChannelKind, NormalizedEvent, OutboundContent } from \"./types\";\n\n/**\n * THE CHANNEL ADAPTER: everything the engine needs to know about one\n * messaging channel, and nothing the engine decides.\n *\n * The engine owns the mechanism — the inbox and its dedupe, the tenant\n * resolution, the conversation and its state, the outbound bookkeeping, the\n * retention. An adapter owns the channel's wire: how a delivery proves where\n * it came from, what its body means, how a message goes out, and when the\n * channel lets a tenant speak first. WhatsApp Cloud is the first adapter\n * (`@12-apps/messaging/whatsapp`); e-mail or a chat workspace join the same\n * way, as one more object of this shape.\n */\nexport interface ChannelAdapter {\n /** The channel's key, stored on every row: `whatsapp`. Lowercase, dash-separated. */\n readonly kind: ChannelKind;\n\n /**\n * Answer the channel's subscription handshake (a `GET` with a challenge),\n * or null for a channel that has none. `ok: false` is a refusal (403).\n */\n handshake(query: Readonly<Record<string, string | undefined>>): HandshakeAnswer | null;\n\n /**\n * Is this delivery really from the channel? Computed over the RAW body\n * bytes, exactly as received. MUST fail closed: a missing secret, a missing\n * header or a malformed one is `false`, never an exception and never `true`.\n */\n verify(delivery: { rawBody: Uint8Array; header(name: string): string | null }): boolean;\n\n /**\n * Turn a raw body into normalized events, in the order the channel listed\n * them. A body the adapter does not recognize yields `[]`; a body that is not\n * even JSON throws (the inbox records the failure).\n */\n parse(rawBody: string): NormalizedEvent[];\n\n /**\n * Send one message from a connected account and report the channel's id\n * for it. Throws {@link ChannelSendFailure} when the channel refuses.\n * `credential` is the OPENED credential: an adapter never logs it, never\n * puts it in an error, never returns it.\n */\n send(input: ChannelSendInput): Promise<{ externalId: string }>;\n\n /** When this channel lets the tenant send free-form messages. */\n readonly policy: SendPolicy;\n}\n\nexport type HandshakeAnswer = { ok: true; challenge: string } | { ok: false };\n\nexport interface ChannelSendInput {\n /** The opened credential of the connection sending it. */\n credential: string;\n /** The connection's account on the channel (WhatsApp's phone_number_id). */\n accountId: string;\n /** The recipient's address. */\n to: string;\n content: OutboundContent;\n}\n\n/** A channel refused or failed a send. `code` is the channel's own, as text. */\nexport class ChannelSendFailure extends Error {\n readonly code: string;\n constructor(code: string, message: string) {\n super(message);\n this.name = \"ChannelSendFailure\";\n this.code = code;\n }\n}\n\n/** What a send policy is asked. */\nexport interface SendPolicyContext {\n /** When the contact last wrote; null if never. */\n lastInboundAt: Date | null;\n now: Date;\n}\n\nexport type SendPolicyVerdict = { allowed: true } | { allowed: false; reason: \"WINDOW_CLOSED\" };\n\n/** A channel's rule for free-form sends. */\nexport interface SendPolicy {\n check(context: SendPolicyContext): SendPolicyVerdict;\n}\n\n/**\n * Is a service window still open? Open while LESS than `windowMs` has passed\n * since the contact's last message: at exactly the window's length it is\n * closed. Never open for a contact who never wrote.\n */\nexport function isWindowOpen(lastInboundAt: Date | null, now: Date, windowMs: number): boolean {\n if (!lastInboundAt) return false;\n return now.getTime() - lastInboundAt.getTime() < windowMs;\n}\n\n/** A policy that allows free-form sends only inside a window after the contact's last message. */\nexport function serviceWindowPolicy(windowMs: number): SendPolicy {\n return {\n check: ({ lastInboundAt, now }) =>\n isWindowOpen(lastInboundAt, now, windowMs) ? { allowed: true } : { allowed: false, reason: \"WINDOW_CLOSED\" },\n };\n}\n\n/** A policy for a channel with no window (e-mail): every send is allowed. */\nexport const OPEN_SEND_POLICY: SendPolicy = { check: () => ({ allowed: true }) };\n"],"mappings":";;;;;AA+DO,IAAM,qBAAN,cAAiC,MAAM;AAAA,EA/D9C,OA+D8C;AAAA;AAAA;AAAA,EACnC;AAAA,EACT,YAAY,MAAc,SAAiB;AACzC,UAAM,OAAO;AACb,SAAK,OAAO;AACZ,SAAK,OAAO;AAAA,EACd;AACF;AAqBO,SAAS,aAAa,eAA4B,KAAW,UAA2B;AAC7F,MAAI,CAAC,cAAe,QAAO;AAC3B,SAAO,IAAI,QAAQ,IAAI,cAAc,QAAQ,IAAI;AACnD;AAHgB;AAMT,SAAS,oBAAoB,UAA8B;AAChE,SAAO;AAAA,IACL,OAAO,wBAAC,EAAE,eAAe,IAAI,MAC3B,aAAa,eAAe,KAAK,QAAQ,IAAI,EAAE,SAAS,KAAK,IAAI,EAAE,SAAS,OAAO,QAAQ,gBAAgB,GADtG;AAAA,EAET;AACF;AALgB;AAQT,IAAM,mBAA+B,EAAE,OAAO,8BAAO,EAAE,SAAS,KAAK,IAAvB,SAA0B;","names":[]}
|
|
File without changes
|