@wats/graph 0.3.25 → 0.3.27
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 +1 -1
- package/dist/endpoints/businessManagement.d.ts +372 -1
- package/dist/endpoints/businessManagement.js +775 -5
- package/dist/endpoints/calling.d.ts +41 -1
- package/dist/endpoints/calling.js +100 -2
- package/dist/endpoints/flows/dataChannel.d.ts +139 -0
- package/dist/endpoints/flows/dataChannel.js +252 -0
- package/dist/endpoints/flows/flowDsl.d.ts +306 -0
- package/dist/endpoints/flows/flowDsl.js +610 -0
- package/dist/endpoints/flows/flowMediaUpload.d.ts +102 -0
- package/dist/endpoints/flows/flowMediaUpload.js +188 -0
- package/dist/endpoints/flows/index.d.ts +9 -1
- package/dist/endpoints/flows/index.js +70 -0
- package/dist/endpoints/flows/metricsMigration.d.ts +36 -0
- package/dist/endpoints/flows/metricsMigration.js +207 -0
- package/dist/endpoints/flows/types.d.ts +145 -0
- package/dist/endpoints/flows/types.js +14 -0
- package/dist/endpoints/flows.d.ts +2 -2
- package/dist/endpoints/flows.js +49 -1
- package/dist/endpoints/media.js +15 -1
- package/dist/endpoints/messages/builders-interactive.d.ts +9 -1
- package/dist/endpoints/messages/builders-interactive.js +49 -0
- package/dist/endpoints/messages/builders-template.d.ts +2 -1
- package/dist/endpoints/messages/builders-template.js +53 -2
- package/dist/endpoints/messages/deepLinks.d.ts +12 -0
- package/dist/endpoints/messages/deepLinks.js +38 -0
- package/dist/endpoints/messages/index.d.ts +4 -3
- package/dist/endpoints/messages/index.js +13 -2
- package/dist/endpoints/messages/types.d.ts +26 -3
- package/dist/endpoints/messages/validation.d.ts +7 -0
- package/dist/endpoints/messages/validation.js +12 -0
- package/dist/endpoints/oauth.d.ts +57 -0
- package/dist/endpoints/oauth.js +116 -0
- package/dist/endpoints/templates/advanced.d.ts +280 -0
- package/dist/endpoints/templates/advanced.js +519 -0
- package/dist/endpoints/templates/builders.js +21 -1
- package/dist/endpoints/templates/index.d.ts +2 -0
- package/dist/endpoints/templates/index.js +15 -0
- package/dist/endpoints/templates/shared.js +7 -1
- package/dist/endpoints/templates/types.d.ts +17 -2
- package/dist/endpoints/templates.d.ts +2 -1
- package/dist/endpoints/templates.js +14 -1
- package/dist/endpoints/wabaEndpoints.d.ts +4 -4
- package/dist/endpoints/wabaEndpoints.js +56 -0
- package/dist/index.d.ts +2 -1
- package/dist/index.js +1 -0
- package/dist/nodeMedia.d.ts +57 -0
- package/dist/nodeMedia.js +178 -0
- package/dist/subclients/phoneNumberClient.d.ts +92 -2
- package/dist/subclients/phoneNumberClient.js +133 -1
- package/dist/subclients/wabaClient.d.ts +82 -2
- package/dist/subclients/wabaClient.js +102 -2
- package/package.json +9 -11
|
@@ -21,7 +21,8 @@ export interface CallSessionDescriptionPayload {
|
|
|
21
21
|
readonly [key: string]: unknown;
|
|
22
22
|
}
|
|
23
23
|
export interface InitiateCallRequest {
|
|
24
|
-
readonly to
|
|
24
|
+
readonly to?: string;
|
|
25
|
+
readonly recipient?: string;
|
|
25
26
|
readonly session: CallSessionDescription | Record<string, unknown>;
|
|
26
27
|
readonly bizOpaqueCallbackData?: string;
|
|
27
28
|
}
|
|
@@ -65,4 +66,43 @@ export declare const rejectCall: ((client: GraphClient, params: CallsParams, bod
|
|
|
65
66
|
export declare const terminateCall: ((client: GraphClient, params: CallsParams, body: TerminateCallRequest, opts?: EndpointInvokeOptions) => Promise<CallLifecycleResponse>) & {
|
|
66
67
|
definition: import("../endpoint.js").EndpointDefinition<CallsParams, WireBody, CallLifecycleResponse>;
|
|
67
68
|
};
|
|
69
|
+
export type CallPermissionStatus = "no_permission" | "temporary" | "permanent";
|
|
70
|
+
export interface CallPermissionActionLimit {
|
|
71
|
+
readonly timePeriod?: string;
|
|
72
|
+
readonly maxAllowed?: number;
|
|
73
|
+
readonly currentUsage?: number;
|
|
74
|
+
readonly limitExpirationTime?: number;
|
|
75
|
+
readonly [key: string]: unknown;
|
|
76
|
+
}
|
|
77
|
+
export interface CallPermissionAction {
|
|
78
|
+
readonly actionName?: string;
|
|
79
|
+
readonly canPerformAction?: boolean;
|
|
80
|
+
readonly limits?: ReadonlyArray<CallPermissionActionLimit>;
|
|
81
|
+
readonly [key: string]: unknown;
|
|
82
|
+
}
|
|
83
|
+
export interface CallPermission {
|
|
84
|
+
readonly status?: CallPermissionStatus | string;
|
|
85
|
+
readonly expirationTime?: number;
|
|
86
|
+
readonly [key: string]: unknown;
|
|
87
|
+
}
|
|
88
|
+
export interface CallPermissionsResponse {
|
|
89
|
+
readonly messagingProduct?: string;
|
|
90
|
+
readonly permission?: CallPermission;
|
|
91
|
+
readonly actions?: ReadonlyArray<CallPermissionAction>;
|
|
92
|
+
readonly [key: string]: unknown;
|
|
93
|
+
}
|
|
94
|
+
export interface GetCallPermissionsInput {
|
|
95
|
+
readonly phoneNumberId: string;
|
|
96
|
+
readonly userWaId?: string;
|
|
97
|
+
readonly recipient?: string;
|
|
98
|
+
}
|
|
99
|
+
type CallPermissionsParams = {
|
|
100
|
+
readonly phoneNumberId: string;
|
|
101
|
+
readonly user_wa_id?: string;
|
|
102
|
+
readonly recipient?: string;
|
|
103
|
+
};
|
|
104
|
+
type WireResponse = Record<string, unknown>;
|
|
105
|
+
export declare const getCallPermissions: ((client: GraphClient, input: GetCallPermissionsInput, _body?: undefined, opts?: EndpointInvokeOptions) => Promise<CallPermissionsResponse>) & {
|
|
106
|
+
definition: import("../endpoint.js").EndpointDefinition<CallPermissionsParams, never, WireResponse>;
|
|
107
|
+
};
|
|
68
108
|
export {};
|
|
@@ -211,13 +211,22 @@ function assertBodyRecord(value, helperName) {
|
|
|
211
211
|
function buildInitiate(body) {
|
|
212
212
|
const record = assertBodyRecord(body, "initiateCall");
|
|
213
213
|
const tracker = optionalTracker(record.bizOpaqueCallbackData);
|
|
214
|
-
|
|
214
|
+
const hasTo = record.to !== undefined;
|
|
215
|
+
const hasRecipient = record.recipient !== undefined;
|
|
216
|
+
if (!hasTo && !hasRecipient) {
|
|
217
|
+
throw validationError("Invalid Calling API input: at least one of to or recipient is required.");
|
|
218
|
+
}
|
|
219
|
+
const out = {
|
|
215
220
|
messaging_product: "whatsapp",
|
|
216
|
-
to: assertPublicString(record.to, "to"),
|
|
217
221
|
action: "connect",
|
|
218
222
|
session: sanitizeCallSession(record.session),
|
|
219
223
|
...tracker !== undefined ? { biz_opaque_callback_data: tracker } : {}
|
|
220
224
|
};
|
|
225
|
+
if (hasTo)
|
|
226
|
+
out.to = assertPublicString(record.to, "to");
|
|
227
|
+
if (hasRecipient)
|
|
228
|
+
out.recipient = assertPublicString(record.recipient, "recipient");
|
|
229
|
+
return out;
|
|
221
230
|
}
|
|
222
231
|
function buildPreAccept(body) {
|
|
223
232
|
const record = assertBodyRecord(body, "preAcceptCall");
|
|
@@ -282,3 +291,92 @@ export const preAcceptCall = Object.assign(async (client, params, body, opts) =>
|
|
|
282
291
|
export const acceptCall = Object.assign(async (client, params, body, opts) => callsEndpoint(client, safeParams(params), buildAccept(body), opts), { definition: callsEndpoint.definition });
|
|
283
292
|
export const rejectCall = Object.assign(async (client, params, body, opts) => callsEndpoint(client, safeParams(params), buildReject(body), opts), { definition: callsEndpoint.definition });
|
|
284
293
|
export const terminateCall = Object.assign(async (client, params, body, opts) => callsEndpoint(client, safeParams(params), buildTerminate(body), opts), { definition: callsEndpoint.definition });
|
|
294
|
+
const callPermissionsEndpoint = defineEndpoint({
|
|
295
|
+
method: "GET",
|
|
296
|
+
pathTemplate: "/{phoneNumberId}/call_permissions",
|
|
297
|
+
params: {
|
|
298
|
+
phoneNumberId: { in: "path", required: true },
|
|
299
|
+
user_wa_id: { in: "query" },
|
|
300
|
+
recipient: { in: "query" }
|
|
301
|
+
}
|
|
302
|
+
});
|
|
303
|
+
function asWireRecord(value) {
|
|
304
|
+
if (typeof value !== "object" || value === null || Array.isArray(value)) {
|
|
305
|
+
return;
|
|
306
|
+
}
|
|
307
|
+
return value;
|
|
308
|
+
}
|
|
309
|
+
function asWireArray(value) {
|
|
310
|
+
return Array.isArray(value) ? value : undefined;
|
|
311
|
+
}
|
|
312
|
+
function normalizeWith(source, rename, transform = {}) {
|
|
313
|
+
const out = {};
|
|
314
|
+
for (const [key, value] of Object.entries(source)) {
|
|
315
|
+
if (isUnsafePrototypeKey(key))
|
|
316
|
+
continue;
|
|
317
|
+
const targetKey = rename[key] ?? key;
|
|
318
|
+
const fn = transform[key];
|
|
319
|
+
out[targetKey] = fn !== undefined ? fn(value) : value;
|
|
320
|
+
}
|
|
321
|
+
return out;
|
|
322
|
+
}
|
|
323
|
+
function normalizeLimit(value) {
|
|
324
|
+
const record = asWireRecord(value);
|
|
325
|
+
if (record === undefined)
|
|
326
|
+
return {};
|
|
327
|
+
return normalizeWith(record, {
|
|
328
|
+
time_period: "timePeriod",
|
|
329
|
+
max_allowed: "maxAllowed",
|
|
330
|
+
current_usage: "currentUsage",
|
|
331
|
+
limit_expiration_time: "limitExpirationTime"
|
|
332
|
+
});
|
|
333
|
+
}
|
|
334
|
+
function normalizeAction(value) {
|
|
335
|
+
const record = asWireRecord(value);
|
|
336
|
+
if (record === undefined)
|
|
337
|
+
return {};
|
|
338
|
+
return normalizeWith(record, { action_name: "actionName", can_perform_action: "canPerformAction" }, {
|
|
339
|
+
limits: (limits) => {
|
|
340
|
+
const arr = asWireArray(limits);
|
|
341
|
+
return arr !== undefined ? arr.map(normalizeLimit) : limits;
|
|
342
|
+
}
|
|
343
|
+
});
|
|
344
|
+
}
|
|
345
|
+
function normalizePermission(value) {
|
|
346
|
+
const record = asWireRecord(value);
|
|
347
|
+
if (record === undefined)
|
|
348
|
+
return value;
|
|
349
|
+
return normalizeWith(record, { expiration_time: "expirationTime" });
|
|
350
|
+
}
|
|
351
|
+
function normalizeCallPermissionsResponse(wire) {
|
|
352
|
+
const record = asWireRecord(wire);
|
|
353
|
+
if (record === undefined)
|
|
354
|
+
return {};
|
|
355
|
+
return normalizeWith(record, { messaging_product: "messagingProduct" }, {
|
|
356
|
+
permission: normalizePermission,
|
|
357
|
+
actions: (actions) => {
|
|
358
|
+
const arr = asWireArray(actions);
|
|
359
|
+
return arr !== undefined ? arr.map(normalizeAction) : actions;
|
|
360
|
+
}
|
|
361
|
+
});
|
|
362
|
+
}
|
|
363
|
+
function buildCallPermissionsParams(input) {
|
|
364
|
+
if (typeof input !== "object" || input === null || Array.isArray(input)) {
|
|
365
|
+
throw validationError("Invalid Calling API input: getCallPermissions input must be an object.");
|
|
366
|
+
}
|
|
367
|
+
const phoneNumberId = safeParams({ phoneNumberId: input.phoneNumberId }).phoneNumberId;
|
|
368
|
+
const hasUserWaId = input.userWaId !== undefined;
|
|
369
|
+
const hasRecipient = input.recipient !== undefined;
|
|
370
|
+
if (hasUserWaId === hasRecipient) {
|
|
371
|
+
throw validationError("Invalid Calling API input: exactly one of userWaId or recipient is required.");
|
|
372
|
+
}
|
|
373
|
+
if (hasUserWaId) {
|
|
374
|
+
return { phoneNumberId, user_wa_id: assertPublicString(input.userWaId, "userWaId") };
|
|
375
|
+
}
|
|
376
|
+
return { phoneNumberId, recipient: assertPublicString(input.recipient, "recipient") };
|
|
377
|
+
}
|
|
378
|
+
export const getCallPermissions = Object.assign(async (client, input, _body, opts) => {
|
|
379
|
+
const params = buildCallPermissionsParams(input);
|
|
380
|
+
const wire = await callPermissionsEndpoint(client, params, undefined, opts);
|
|
381
|
+
return normalizeCallPermissionsResponse(wire);
|
|
382
|
+
}, { definition: callPermissionsEndpoint.definition });
|
|
@@ -0,0 +1,139 @@
|
|
|
1
|
+
import type { CryptoProvider } from "@wats/crypto";
|
|
2
|
+
import type { EncryptedFlowRequestInput, FlowRequest, FlowResponsePayload } from "./types.js";
|
|
3
|
+
/**
|
|
4
|
+
* Maximum number of decoded bytes accepted for any single base64 field of the
|
|
5
|
+
* encrypted request, and for the decrypted plaintext before it is parsed as
|
|
6
|
+
* JSON. Finite by construction so a hostile body cannot drive unbounded
|
|
7
|
+
* allocation or JSON parsing. Meta's Flow payloads are far smaller than this.
|
|
8
|
+
*/
|
|
9
|
+
export declare const FLOW_DATA_CHANNEL_MAX_BYTES = 131072;
|
|
10
|
+
/**
|
|
11
|
+
* Endpoint error → HTTP status mapping for the Flow data-channel endpoint.
|
|
12
|
+
* 421 — decryption failed (plain body, NOT encrypted)
|
|
13
|
+
* 427 — FlowTokenNoLongerValid (plain `{ error_msg }` body)
|
|
14
|
+
* 432 — request signature authentication failed (plain body)
|
|
15
|
+
* 500 — construction / unhandled handler failure (plain body)
|
|
16
|
+
*/
|
|
17
|
+
export declare const FLOW_ENDPOINT_STATUS: {
|
|
18
|
+
readonly decryptionFailure: 421;
|
|
19
|
+
readonly flowTokenInvalid: 427;
|
|
20
|
+
readonly signatureFailure: 432;
|
|
21
|
+
readonly serverError: 500;
|
|
22
|
+
};
|
|
23
|
+
/**
|
|
24
|
+
* Thrown by `decryptRequest` for ANY failure on the decrypt path — missing or
|
|
25
|
+
* malformed fields, invalid base64, RSA/GCM failure, JSON parse failure, or a
|
|
26
|
+
* structurally invalid decrypted payload. Carries no key/IV/plaintext material;
|
|
27
|
+
* the `cause` is preserved for server-side diagnostics but the public message
|
|
28
|
+
* is a fixed string so nothing sensitive is leaked. Maps to HTTP 421.
|
|
29
|
+
*/
|
|
30
|
+
export declare class FlowRequestDecryptionError extends Error {
|
|
31
|
+
readonly cause?: unknown;
|
|
32
|
+
constructor(cause?: unknown);
|
|
33
|
+
}
|
|
34
|
+
/**
|
|
35
|
+
* Thrown by a Flow handler when the supplied `flow_token` is no longer valid.
|
|
36
|
+
* Maps to HTTP 427 with a plain `{ "error_msg": <message> }` body. The message
|
|
37
|
+
* is caller-supplied and SHOULD NOT contain secrets.
|
|
38
|
+
*/
|
|
39
|
+
export declare class FlowTokenNoLongerValidError extends Error {
|
|
40
|
+
readonly errorMsg: string;
|
|
41
|
+
constructor(message?: string);
|
|
42
|
+
}
|
|
43
|
+
/**
|
|
44
|
+
* Thrown when the inbound request signature fails authentication. Maps to
|
|
45
|
+
* HTTP 432. Signature validation itself lives upstream of this module; this
|
|
46
|
+
* type exists so the dispatch glue can surface the 432 mapping uniformly.
|
|
47
|
+
*/
|
|
48
|
+
export declare class FlowSignatureError extends Error {
|
|
49
|
+
constructor(message?: string);
|
|
50
|
+
}
|
|
51
|
+
/**
|
|
52
|
+
* Thrown when the injected CryptoProvider lacks a capability the data-channel
|
|
53
|
+
* runtime requires. This is a server-side misconfiguration (maps to HTTP 500),
|
|
54
|
+
* distinct from a malformed inbound payload (421).
|
|
55
|
+
*/
|
|
56
|
+
export declare class FlowCryptoUnavailableError extends Error {
|
|
57
|
+
constructor(capability: string);
|
|
58
|
+
}
|
|
59
|
+
export interface DecryptedFlowRequest {
|
|
60
|
+
readonly request: FlowRequest;
|
|
61
|
+
readonly aesKey: Uint8Array;
|
|
62
|
+
readonly iv: Uint8Array;
|
|
63
|
+
}
|
|
64
|
+
/**
|
|
65
|
+
* Decrypt and parse an inbound encrypted Flow request (REFERENCE-76 §B.2).
|
|
66
|
+
*
|
|
67
|
+
* Steps:
|
|
68
|
+
* 1. base64-decode `encrypted_flow_data`, `encrypted_aes_key`, `initial_vector`.
|
|
69
|
+
* 2. `aesKey = crypto.rsaOaepDecrypt(privateKey, encryptedAesKey)`.
|
|
70
|
+
* 3. `plaintext = crypto.aesGcmDecrypt(aesKey, iv, encryptedFlowData)` — the
|
|
71
|
+
* 16-byte GCM tag is the LAST 16 bytes of `encryptedFlowData` and is split
|
|
72
|
+
* off internally by the provider, so the FULL ciphertext+tag is passed.
|
|
73
|
+
* 4. JSON.parse the UTF-8 plaintext and map to a camelCase FlowRequest.
|
|
74
|
+
*
|
|
75
|
+
* Returns the parsed request plus the AES key and IV (needed to encrypt the
|
|
76
|
+
* matching response). On ANY failure throws {@link FlowRequestDecryptionError}
|
|
77
|
+
* (→ HTTP 421); a missing provider capability throws
|
|
78
|
+
* {@link FlowCryptoUnavailableError} (→ HTTP 500). Never throws a host error.
|
|
79
|
+
*/
|
|
80
|
+
export declare function decryptRequest(crypto: CryptoProvider, body: EncryptedFlowRequestInput | unknown, privateKey: JsonWebKey | Uint8Array, password?: string): Promise<DecryptedFlowRequest>;
|
|
81
|
+
/**
|
|
82
|
+
* Encrypt a Flow response object for the HTTP body (REFERENCE-76 §B.3).
|
|
83
|
+
*
|
|
84
|
+
* Steps:
|
|
85
|
+
* 1. `flippedIv = iv` with every byte XOR 0xFF (bitwise NOT).
|
|
86
|
+
* 2. `{ ciphertext, authTag } = crypto.aesGcmEncrypt(aesKey, flippedIv, utf8(JSON.stringify(response)))`.
|
|
87
|
+
* 3. Return `base64( ciphertext ++ authTag )` — ciphertext FOLLOWED BY the
|
|
88
|
+
* 16-byte tag, then base64. This raw string is the `text/plain` HTTP body.
|
|
89
|
+
*/
|
|
90
|
+
export declare function encryptResponse(crypto: CryptoProvider, response: FlowResponsePayload, aesKey: Uint8Array, iv: Uint8Array): Promise<string>;
|
|
91
|
+
/**
|
|
92
|
+
* True if the decrypted request's `data` signals a client-reported error, i.e.
|
|
93
|
+
* it carries any of `error`, `error_message`, or `error_key` (REFERENCE-76 §B.4).
|
|
94
|
+
*/
|
|
95
|
+
export declare function flowRequestHasError(request: FlowRequest): boolean;
|
|
96
|
+
/** The fixed ping acknowledgement payload (REFERENCE-76 §B.5). */
|
|
97
|
+
export declare function buildFlowPingResponse(): FlowResponsePayload;
|
|
98
|
+
/** The error-acknowledgement payload (REFERENCE-76 §B.6). */
|
|
99
|
+
export declare function buildFlowErrorAckResponse(request: FlowRequest): FlowResponsePayload;
|
|
100
|
+
export type FlowRequestHandler = (request: FlowRequest) => FlowResponsePayload | Promise<FlowResponsePayload>;
|
|
101
|
+
export interface HandleFlowRequestOptions {
|
|
102
|
+
/** The parsed JSON request body (snake_case wire or camelCase). */
|
|
103
|
+
readonly rawBody: EncryptedFlowRequestInput | unknown;
|
|
104
|
+
/** RSA private key (PEM string bytes or JWK) used to unwrap the AES key. */
|
|
105
|
+
readonly privateKey: JsonWebKey | Uint8Array;
|
|
106
|
+
/** The injected crypto provider (slice C). */
|
|
107
|
+
readonly crypto: CryptoProvider;
|
|
108
|
+
/** User callback invoked for normal (non-ping, non-error-ack) requests. */
|
|
109
|
+
readonly handler: FlowRequestHandler;
|
|
110
|
+
/** When true, has_error requests are auto-acknowledged (§B.6). Default false. */
|
|
111
|
+
readonly acknowledgeErrors?: boolean;
|
|
112
|
+
/** Reserved: passphrase for an encrypted private key. */
|
|
113
|
+
readonly password?: string;
|
|
114
|
+
}
|
|
115
|
+
export interface FlowEndpointResult {
|
|
116
|
+
readonly statusCode: number;
|
|
117
|
+
/**
|
|
118
|
+
* The HTTP response body. When `encrypted` is true this is the base64
|
|
119
|
+
* ciphertext+tag string; otherwise it is a plain status/error string.
|
|
120
|
+
*/
|
|
121
|
+
readonly body: string;
|
|
122
|
+
/** Whether `body` is an encrypted Flow response (true) or a plain text body. */
|
|
123
|
+
readonly encrypted: boolean;
|
|
124
|
+
}
|
|
125
|
+
/**
|
|
126
|
+
* Framework-agnostic Flow endpoint dispatch (REFERENCE-76 §B.5/§B.6/§B.8).
|
|
127
|
+
*
|
|
128
|
+
* Decrypts the request, routes it (ping → active, has_error+ack → acknowledged,
|
|
129
|
+
* else → user handler), encrypts the response, and returns `{ statusCode, body,
|
|
130
|
+
* encrypted }`. NEVER throws: every failure is mapped to a status code —
|
|
131
|
+
* - decrypt failure → 421 "Decryption failed" (plain)
|
|
132
|
+
* - FlowTokenNoLongerValid → 427 `{ "error_msg": ... }` (plain)
|
|
133
|
+
* - signature failure → 432 (plain)
|
|
134
|
+
* - unhandled error → 500 (plain)
|
|
135
|
+
*
|
|
136
|
+
* The actual @wats/http wiring is a thin shell that calls this and writes the
|
|
137
|
+
* returned status/body.
|
|
138
|
+
*/
|
|
139
|
+
export declare function handleFlowRequest(options: HandleFlowRequestOptions): Promise<FlowEndpointResult>;
|
|
@@ -0,0 +1,252 @@
|
|
|
1
|
+
import { flowIsPlainObject, flowIsUnsafeObjectKey } from "./shared.js";
|
|
2
|
+
export const FLOW_DATA_CHANNEL_MAX_BYTES = 131072;
|
|
3
|
+
const FLOW_REQUEST_ACTIONS = new Set([
|
|
4
|
+
"INIT",
|
|
5
|
+
"BACK",
|
|
6
|
+
"data_exchange",
|
|
7
|
+
"navigate",
|
|
8
|
+
"ping"
|
|
9
|
+
]);
|
|
10
|
+
export const FLOW_ENDPOINT_STATUS = {
|
|
11
|
+
decryptionFailure: 421,
|
|
12
|
+
flowTokenInvalid: 427,
|
|
13
|
+
signatureFailure: 432,
|
|
14
|
+
serverError: 500
|
|
15
|
+
};
|
|
16
|
+
|
|
17
|
+
export class FlowRequestDecryptionError extends Error {
|
|
18
|
+
cause;
|
|
19
|
+
constructor(cause) {
|
|
20
|
+
super("Flow request could not be decrypted");
|
|
21
|
+
this.name = "FlowRequestDecryptionError";
|
|
22
|
+
if (cause !== undefined)
|
|
23
|
+
this.cause = cause;
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
export class FlowTokenNoLongerValidError extends Error {
|
|
28
|
+
errorMsg;
|
|
29
|
+
constructor(message = "Flow token is no longer valid") {
|
|
30
|
+
super(message);
|
|
31
|
+
this.name = "FlowTokenNoLongerValidError";
|
|
32
|
+
this.errorMsg = message;
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
export class FlowSignatureError extends Error {
|
|
37
|
+
constructor(message = "Flow request signature authentication failed") {
|
|
38
|
+
super(message);
|
|
39
|
+
this.name = "FlowSignatureError";
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
export class FlowCryptoUnavailableError extends Error {
|
|
44
|
+
constructor(capability) {
|
|
45
|
+
super(`CryptoProvider does not implement required capability: ${capability}`);
|
|
46
|
+
this.name = "FlowCryptoUnavailableError";
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
function decodeBase64Field(value, _fieldName) {
|
|
50
|
+
if (typeof value !== "string" || value.length === 0 || value.trim().length === 0) {
|
|
51
|
+
throw new FlowRequestDecryptionError;
|
|
52
|
+
}
|
|
53
|
+
if (value.length > FLOW_DATA_CHANNEL_MAX_BYTES * 2) {
|
|
54
|
+
throw new FlowRequestDecryptionError;
|
|
55
|
+
}
|
|
56
|
+
let binary;
|
|
57
|
+
try {
|
|
58
|
+
binary = atob(value);
|
|
59
|
+
} catch (cause) {
|
|
60
|
+
throw new FlowRequestDecryptionError(cause);
|
|
61
|
+
}
|
|
62
|
+
if (binary.length === 0 || binary.length > FLOW_DATA_CHANNEL_MAX_BYTES) {
|
|
63
|
+
throw new FlowRequestDecryptionError;
|
|
64
|
+
}
|
|
65
|
+
const out = new Uint8Array(binary.length);
|
|
66
|
+
for (let i = 0;i < binary.length; i += 1)
|
|
67
|
+
out[i] = binary.charCodeAt(i);
|
|
68
|
+
return out;
|
|
69
|
+
}
|
|
70
|
+
function encodeBase64(bytes) {
|
|
71
|
+
let binary = "";
|
|
72
|
+
for (let i = 0;i < bytes.length; i += 1) {
|
|
73
|
+
binary += String.fromCharCode(bytes[i]);
|
|
74
|
+
}
|
|
75
|
+
return btoa(binary);
|
|
76
|
+
}
|
|
77
|
+
function concatBytes(a, b) {
|
|
78
|
+
const out = new Uint8Array(a.length + b.length);
|
|
79
|
+
out.set(a, 0);
|
|
80
|
+
out.set(b, a.length);
|
|
81
|
+
return out;
|
|
82
|
+
}
|
|
83
|
+
function readEnvelope(body) {
|
|
84
|
+
if (!flowIsPlainObject(body)) {
|
|
85
|
+
throw new FlowRequestDecryptionError;
|
|
86
|
+
}
|
|
87
|
+
const record = body;
|
|
88
|
+
const encryptedFlowData = record.encrypted_flow_data ?? record.encryptedFlowData;
|
|
89
|
+
const encryptedAesKey = record.encrypted_aes_key ?? record.encryptedAesKey;
|
|
90
|
+
const initialVector = record.initial_vector ?? record.initialVector;
|
|
91
|
+
if (typeof encryptedFlowData !== "string" || typeof encryptedAesKey !== "string" || typeof initialVector !== "string") {
|
|
92
|
+
throw new FlowRequestDecryptionError;
|
|
93
|
+
}
|
|
94
|
+
return { encryptedFlowData, encryptedAesKey, initialVector };
|
|
95
|
+
}
|
|
96
|
+
function parseDecryptedRequest(plaintext) {
|
|
97
|
+
let text;
|
|
98
|
+
try {
|
|
99
|
+
text = new TextDecoder("utf-8", { fatal: true }).decode(plaintext);
|
|
100
|
+
} catch (cause) {
|
|
101
|
+
throw new FlowRequestDecryptionError(cause);
|
|
102
|
+
}
|
|
103
|
+
if (text.length === 0) {
|
|
104
|
+
throw new FlowRequestDecryptionError;
|
|
105
|
+
}
|
|
106
|
+
let parsed;
|
|
107
|
+
try {
|
|
108
|
+
parsed = JSON.parse(text, (key, value) => {
|
|
109
|
+
if (flowIsUnsafeObjectKey(key)) {
|
|
110
|
+
throw new Error("unsafe object key in decrypted payload");
|
|
111
|
+
}
|
|
112
|
+
return value;
|
|
113
|
+
});
|
|
114
|
+
} catch (cause) {
|
|
115
|
+
throw new FlowRequestDecryptionError(cause);
|
|
116
|
+
}
|
|
117
|
+
if (!flowIsPlainObject(parsed)) {
|
|
118
|
+
throw new FlowRequestDecryptionError;
|
|
119
|
+
}
|
|
120
|
+
const record = parsed;
|
|
121
|
+
const version = record.version;
|
|
122
|
+
if (typeof version !== "string" || version.length === 0) {
|
|
123
|
+
throw new FlowRequestDecryptionError;
|
|
124
|
+
}
|
|
125
|
+
const action = record.action;
|
|
126
|
+
if (typeof action !== "string" || !FLOW_REQUEST_ACTIONS.has(action)) {
|
|
127
|
+
throw new FlowRequestDecryptionError;
|
|
128
|
+
}
|
|
129
|
+
const request = { version, action };
|
|
130
|
+
const flowToken = record.flow_token ?? record.flowToken;
|
|
131
|
+
if (flowToken !== undefined) {
|
|
132
|
+
if (typeof flowToken !== "string") {
|
|
133
|
+
throw new FlowRequestDecryptionError;
|
|
134
|
+
}
|
|
135
|
+
request.flowToken = flowToken;
|
|
136
|
+
}
|
|
137
|
+
const screen = record.screen;
|
|
138
|
+
if (screen !== undefined && screen !== "") {
|
|
139
|
+
if (typeof screen !== "string") {
|
|
140
|
+
throw new FlowRequestDecryptionError;
|
|
141
|
+
}
|
|
142
|
+
request.screen = screen;
|
|
143
|
+
}
|
|
144
|
+
const data = record.data;
|
|
145
|
+
if (data !== undefined) {
|
|
146
|
+
if (!flowIsPlainObject(data)) {
|
|
147
|
+
throw new FlowRequestDecryptionError;
|
|
148
|
+
}
|
|
149
|
+
if (Object.keys(data).length > 0) {
|
|
150
|
+
request.data = data;
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
return request;
|
|
154
|
+
}
|
|
155
|
+
export async function decryptRequest(crypto, body, privateKey, password) {
|
|
156
|
+
if (typeof crypto.rsaOaepDecrypt !== "function") {
|
|
157
|
+
throw new FlowCryptoUnavailableError("rsaOaepDecrypt");
|
|
158
|
+
}
|
|
159
|
+
if (typeof crypto.aesGcmDecrypt !== "function") {
|
|
160
|
+
throw new FlowCryptoUnavailableError("aesGcmDecrypt");
|
|
161
|
+
}
|
|
162
|
+
const envelope = readEnvelope(body);
|
|
163
|
+
const encryptedFlowData = decodeBase64Field(envelope.encryptedFlowData, "encrypted_flow_data");
|
|
164
|
+
const encryptedAesKey = decodeBase64Field(envelope.encryptedAesKey, "encrypted_aes_key");
|
|
165
|
+
const iv = decodeBase64Field(envelope.initialVector, "initial_vector");
|
|
166
|
+
let aesKey;
|
|
167
|
+
try {
|
|
168
|
+
aesKey = await crypto.rsaOaepDecrypt(privateKey, encryptedAesKey);
|
|
169
|
+
} catch (cause) {
|
|
170
|
+
throw new FlowRequestDecryptionError(cause);
|
|
171
|
+
}
|
|
172
|
+
let plaintext;
|
|
173
|
+
try {
|
|
174
|
+
plaintext = await crypto.aesGcmDecrypt(aesKey, iv, encryptedFlowData);
|
|
175
|
+
} catch (cause) {
|
|
176
|
+
throw new FlowRequestDecryptionError(cause);
|
|
177
|
+
}
|
|
178
|
+
const request = parseDecryptedRequest(plaintext);
|
|
179
|
+
return { request, aesKey, iv };
|
|
180
|
+
}
|
|
181
|
+
export async function encryptResponse(crypto, response, aesKey, iv) {
|
|
182
|
+
if (typeof crypto.aesGcmEncrypt !== "function") {
|
|
183
|
+
throw new FlowCryptoUnavailableError("aesGcmEncrypt");
|
|
184
|
+
}
|
|
185
|
+
const flippedIv = new Uint8Array(iv.length);
|
|
186
|
+
for (let i = 0;i < iv.length; i += 1) {
|
|
187
|
+
flippedIv[i] = iv[i] ^ 255;
|
|
188
|
+
}
|
|
189
|
+
const plaintext = new TextEncoder().encode(JSON.stringify(response));
|
|
190
|
+
const { ciphertext, authTag } = await crypto.aesGcmEncrypt(aesKey, flippedIv, plaintext);
|
|
191
|
+
return encodeBase64(concatBytes(ciphertext, authTag));
|
|
192
|
+
}
|
|
193
|
+
export function flowRequestHasError(request) {
|
|
194
|
+
const data = request.data;
|
|
195
|
+
if (data === undefined)
|
|
196
|
+
return false;
|
|
197
|
+
return Object.prototype.hasOwnProperty.call(data, "error") || Object.prototype.hasOwnProperty.call(data, "error_message") || Object.prototype.hasOwnProperty.call(data, "error_key");
|
|
198
|
+
}
|
|
199
|
+
export function buildFlowPingResponse() {
|
|
200
|
+
return { data: { status: "active" } };
|
|
201
|
+
}
|
|
202
|
+
export function buildFlowErrorAckResponse(request) {
|
|
203
|
+
const out = { data: { acknowledged: true } };
|
|
204
|
+
if (request.version !== undefined) {
|
|
205
|
+
out.version = request.version;
|
|
206
|
+
}
|
|
207
|
+
return out;
|
|
208
|
+
}
|
|
209
|
+
export async function handleFlowRequest(options) {
|
|
210
|
+
const { rawBody, privateKey, crypto, handler, acknowledgeErrors, password } = options;
|
|
211
|
+
let decrypted;
|
|
212
|
+
try {
|
|
213
|
+
decrypted = await decryptRequest(crypto, rawBody, privateKey, password);
|
|
214
|
+
} catch (err) {
|
|
215
|
+
if (err instanceof FlowRequestDecryptionError) {
|
|
216
|
+
return { statusCode: FLOW_ENDPOINT_STATUS.decryptionFailure, body: "Decryption failed", encrypted: false };
|
|
217
|
+
}
|
|
218
|
+
if (err instanceof FlowSignatureError) {
|
|
219
|
+
return { statusCode: FLOW_ENDPOINT_STATUS.signatureFailure, body: "Signature authentication failed", encrypted: false };
|
|
220
|
+
}
|
|
221
|
+
return { statusCode: FLOW_ENDPOINT_STATUS.serverError, body: "Internal Server Error", encrypted: false };
|
|
222
|
+
}
|
|
223
|
+
const { request, aesKey, iv } = decrypted;
|
|
224
|
+
let payload;
|
|
225
|
+
try {
|
|
226
|
+
if (request.action === "ping") {
|
|
227
|
+
payload = buildFlowPingResponse();
|
|
228
|
+
} else if (acknowledgeErrors === true && flowRequestHasError(request)) {
|
|
229
|
+
payload = buildFlowErrorAckResponse(request);
|
|
230
|
+
} else {
|
|
231
|
+
payload = await handler(request);
|
|
232
|
+
}
|
|
233
|
+
} catch (err) {
|
|
234
|
+
if (err instanceof FlowTokenNoLongerValidError) {
|
|
235
|
+
return {
|
|
236
|
+
statusCode: FLOW_ENDPOINT_STATUS.flowTokenInvalid,
|
|
237
|
+
body: JSON.stringify({ error_msg: err.errorMsg }),
|
|
238
|
+
encrypted: false
|
|
239
|
+
};
|
|
240
|
+
}
|
|
241
|
+
if (err instanceof FlowSignatureError) {
|
|
242
|
+
return { statusCode: FLOW_ENDPOINT_STATUS.signatureFailure, body: "Signature authentication failed", encrypted: false };
|
|
243
|
+
}
|
|
244
|
+
return { statusCode: FLOW_ENDPOINT_STATUS.serverError, body: "Internal Server Error", encrypted: false };
|
|
245
|
+
}
|
|
246
|
+
try {
|
|
247
|
+
const body = await encryptResponse(crypto, payload, aesKey, iv);
|
|
248
|
+
return { statusCode: 200, body, encrypted: true };
|
|
249
|
+
} catch {
|
|
250
|
+
return { statusCode: FLOW_ENDPOINT_STATUS.serverError, body: "Internal Server Error", encrypted: false };
|
|
251
|
+
}
|
|
252
|
+
}
|