@mamans2973/maman 0.0.0-stage → 1.0.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.
Files changed (164) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +1275 -2
  3. package/WAProto/index.d.ts +37016 -0
  4. package/WAProto/index.js +2972 -0
  5. package/WASignalGroup/GroupProtocol.js +1697 -0
  6. package/WASignalGroup/ciphertext_message.js +16 -0
  7. package/WASignalGroup/group_cipher.js +120 -0
  8. package/WASignalGroup/group_session_builder.js +46 -0
  9. package/WASignalGroup/index.js +5 -0
  10. package/WASignalGroup/keyhelper.js +21 -0
  11. package/WASignalGroup/protobufs.js +3 -0
  12. package/WASignalGroup/queue_job.js +69 -0
  13. package/WASignalGroup/sender_chain_key.js +50 -0
  14. package/WASignalGroup/sender_key_distribution_message.js +78 -0
  15. package/WASignalGroup/sender_key_message.js +92 -0
  16. package/WASignalGroup/sender_key_name.js +70 -0
  17. package/WASignalGroup/sender_key_record.js +56 -0
  18. package/WASignalGroup/sender_key_state.js +129 -0
  19. package/WASignalGroup/sender_message_key.js +39 -0
  20. package/engine-requirements.js +1 -0
  21. package/lib/Defaults/baileys-version.json +3 -0
  22. package/lib/Defaults/index.d.ts +51 -0
  23. package/lib/Defaults/index.js +10 -0
  24. package/lib/Signal/libsignal.d.ts +3 -0
  25. package/lib/Signal/libsignal.js +9 -0
  26. package/lib/Socket/Client/index.d.ts +2 -0
  27. package/lib/Socket/Client/index.js +2 -0
  28. package/lib/Socket/Client/types.d.ts +15 -0
  29. package/lib/Socket/Client/types.js +1 -0
  30. package/lib/Socket/Client/websocket.d.ts +12 -0
  31. package/lib/Socket/Client/websocket.js +4 -0
  32. package/lib/Socket/business.d.ts +146 -0
  33. package/lib/Socket/business.js +8 -0
  34. package/lib/Socket/chats.d.ts +85 -0
  35. package/lib/Socket/chats.js +29 -0
  36. package/lib/Socket/groups.d.ts +124 -0
  37. package/lib/Socket/groups.js +14 -0
  38. package/lib/Socket/index.d.ts +146 -0
  39. package/lib/Socket/index.js +1 -0
  40. package/lib/Socket/messages-recv.d.ts +135 -0
  41. package/lib/Socket/messages-recv.js +39 -0
  42. package/lib/Socket/messages-send.d.ts +130 -0
  43. package/lib/Socket/messages-send.js +26 -0
  44. package/lib/Socket/socket.d.ts +42 -0
  45. package/lib/Socket/socket.js +25 -0
  46. package/lib/Socket/usync.d.ts +36 -0
  47. package/lib/Socket/usync.js +3 -0
  48. package/lib/Types/Auth.d.ts +103 -0
  49. package/lib/Types/Auth.js +1 -0
  50. package/lib/Types/Call.d.ts +13 -0
  51. package/lib/Types/Call.js +1 -0
  52. package/lib/Types/Chat.d.ts +112 -0
  53. package/lib/Types/Chat.js +1 -0
  54. package/lib/Types/Contact.d.ts +19 -0
  55. package/lib/Types/Contact.js +1 -0
  56. package/lib/Types/Events.d.ts +172 -0
  57. package/lib/Types/Events.js +1 -0
  58. package/lib/Types/GroupMetadata.d.ts +58 -0
  59. package/lib/Types/GroupMetadata.js +1 -0
  60. package/lib/Types/Label.d.ts +46 -0
  61. package/lib/Types/Label.js +3 -0
  62. package/lib/Types/LabelAssociation.d.ts +29 -0
  63. package/lib/Types/LabelAssociation.js +1 -0
  64. package/lib/Types/Message.d.ts +267 -0
  65. package/lib/Types/Message.js +1 -0
  66. package/lib/Types/Product.d.ts +78 -0
  67. package/lib/Types/Product.js +1 -0
  68. package/lib/Types/Signal.d.ts +57 -0
  69. package/lib/Types/Signal.js +1 -0
  70. package/lib/Types/Socket.d.ts +121 -0
  71. package/lib/Types/Socket.js +1 -0
  72. package/lib/Types/State.d.ts +27 -0
  73. package/lib/Types/State.js +1 -0
  74. package/lib/Types/USync.d.ts +25 -0
  75. package/lib/Types/USync.js +1 -0
  76. package/lib/Types/index.d.ts +63 -0
  77. package/lib/Types/index.js +4 -0
  78. package/lib/Utils/auth-utils.d.ts +18 -0
  79. package/lib/Utils/auth-utils.js +8 -0
  80. package/lib/Utils/baileys-event-stream.d.ts +16 -0
  81. package/lib/Utils/baileys-event-stream.js +3 -0
  82. package/lib/Utils/business.d.ts +22 -0
  83. package/lib/Utils/business.js +14 -0
  84. package/lib/Utils/chat-utils.d.ts +70 -0
  85. package/lib/Utils/chat-utils.js +36 -0
  86. package/lib/Utils/crypto.d.ts +40 -0
  87. package/lib/Utils/crypto.js +11 -0
  88. package/lib/Utils/decode-wa-message.d.ts +36 -0
  89. package/lib/Utils/decode-wa-message.js +9 -0
  90. package/lib/Utils/event-buffer.d.ts +35 -0
  91. package/lib/Utils/event-buffer.js +19 -0
  92. package/lib/Utils/generics.d.ts +90 -0
  93. package/lib/Utils/generics.js +22 -0
  94. package/lib/Utils/history.d.ts +19 -0
  95. package/lib/Utils/history.js +7 -0
  96. package/lib/Utils/index.d.ts +17 -0
  97. package/lib/Utils/index.js +3 -0
  98. package/lib/Utils/link-preview.d.ts +21 -0
  99. package/lib/Utils/link-preview.js +5 -0
  100. package/lib/Utils/logger.d.ts +11 -0
  101. package/lib/Utils/logger.js +1 -0
  102. package/lib/Utils/lt-hash.d.ts +12 -0
  103. package/lib/Utils/lt-hash.js +3 -0
  104. package/lib/Utils/make-mutex.d.ts +7 -0
  105. package/lib/Utils/make-mutex.js +1 -0
  106. package/lib/Utils/messages-media.d.ts +103 -0
  107. package/lib/Utils/messages-media.js +35 -0
  108. package/lib/Utils/messages.d.ts +75 -0
  109. package/lib/Utils/messages.js +43 -0
  110. package/lib/Utils/noise-handler.d.ts +19 -0
  111. package/lib/Utils/noise-handler.js +6 -0
  112. package/lib/Utils/process-message.d.ts +41 -0
  113. package/lib/Utils/process-message.js +19 -0
  114. package/lib/Utils/signal.d.ts +33 -0
  115. package/lib/Utils/signal.js +10 -0
  116. package/lib/Utils/use-multi-file-auth-state.d.ts +12 -0
  117. package/lib/Utils/use-multi-file-auth-state.js +5 -0
  118. package/lib/Utils/validate-connection.d.ts +10 -0
  119. package/lib/Utils/validate-connection.js +10 -0
  120. package/lib/WABinary/constants.d.ts +27 -0
  121. package/lib/WABinary/constants.js +6 -0
  122. package/lib/WABinary/decode.d.ts +6 -0
  123. package/lib/WABinary/decode.js +9 -0
  124. package/lib/WABinary/encode.d.ts +2 -0
  125. package/lib/WABinary/encode.js +9 -0
  126. package/lib/WABinary/generic-utils.d.ts +14 -0
  127. package/lib/WABinary/generic-utils.js +7 -0
  128. package/lib/WABinary/index.d.ts +5 -0
  129. package/lib/WABinary/index.js +2 -0
  130. package/lib/WABinary/jid-utils.d.ts +35 -0
  131. package/lib/WABinary/jid-utils.js +5 -0
  132. package/lib/WABinary/types.d.ts +18 -0
  133. package/lib/WABinary/types.js +1 -0
  134. package/lib/WAM/BinaryInfo.d.ts +8 -0
  135. package/lib/WAM/BinaryInfo.js +1 -0
  136. package/lib/WAM/constants.d.ts +39 -0
  137. package/lib/WAM/constants.js +492 -0
  138. package/lib/WAM/encode.d.ts +2 -0
  139. package/lib/WAM/encode.js +7 -0
  140. package/lib/WAM/index.d.ts +3 -0
  141. package/lib/WAM/index.js +2 -0
  142. package/lib/WAUSync/Protocols/USyncContactProtocol.d.ts +9 -0
  143. package/lib/WAUSync/Protocols/USyncContactProtocol.js +2 -0
  144. package/lib/WAUSync/Protocols/USyncDeviceProtocol.d.ts +22 -0
  145. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +3 -0
  146. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.d.ts +12 -0
  147. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +2 -0
  148. package/lib/WAUSync/Protocols/USyncStatusProtocol.d.ts +12 -0
  149. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +2 -0
  150. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.d.ts +25 -0
  151. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js +4 -0
  152. package/lib/WAUSync/Protocols/UsyncLIDProtocol.d.ts +8 -0
  153. package/lib/WAUSync/Protocols/UsyncLIDProtocol.js +1 -0
  154. package/lib/WAUSync/Protocols/index.d.ts +4 -0
  155. package/lib/WAUSync/Protocols/index.js +2 -0
  156. package/lib/WAUSync/USyncQuery.d.ts +28 -0
  157. package/lib/WAUSync/USyncQuery.js +4 -0
  158. package/lib/WAUSync/USyncUser.d.ts +12 -0
  159. package/lib/WAUSync/USyncUser.js +1 -0
  160. package/lib/WAUSync/index.d.ts +3 -0
  161. package/lib/WAUSync/index.js +2 -0
  162. package/lib/index.d.ts +11 -0
  163. package/lib/index.js +3 -0
  164. package/package.json +94 -4
@@ -0,0 +1,57 @@
1
+ import { proto } from '../../WAProto';
2
+ type DecryptGroupSignalOpts = {
3
+ group: string;
4
+ authorJid: string;
5
+ msg: Uint8Array;
6
+ };
7
+ type ProcessSenderKeyDistributionMessageOpts = {
8
+ item: proto.Message.ISenderKeyDistributionMessage;
9
+ authorJid: string;
10
+ };
11
+ type DecryptSignalProtoOpts = {
12
+ jid: string;
13
+ type: 'pkmsg' | 'msg';
14
+ ciphertext: Uint8Array;
15
+ };
16
+ type EncryptMessageOpts = {
17
+ jid: string;
18
+ data: Uint8Array;
19
+ };
20
+ type EncryptGroupMessageOpts = {
21
+ group: string;
22
+ data: Uint8Array;
23
+ meId: string;
24
+ };
25
+ type PreKey = {
26
+ keyId: number;
27
+ publicKey: Uint8Array;
28
+ };
29
+ type SignedPreKey = PreKey & {
30
+ signature: Uint8Array;
31
+ };
32
+ type E2ESession = {
33
+ registrationId: number;
34
+ identityKey: Uint8Array;
35
+ signedPreKey: SignedPreKey;
36
+ preKey: PreKey;
37
+ };
38
+ type E2ESessionOpts = {
39
+ jid: string;
40
+ session: E2ESession;
41
+ };
42
+ export type SignalRepository = {
43
+ decryptGroupMessage(opts: DecryptGroupSignalOpts): Promise<Uint8Array>;
44
+ processSenderKeyDistributionMessage(opts: ProcessSenderKeyDistributionMessageOpts): Promise<void>;
45
+ decryptMessage(opts: DecryptSignalProtoOpts): Promise<Uint8Array>;
46
+ encryptMessage(opts: EncryptMessageOpts): Promise<{
47
+ type: 'pkmsg' | 'msg';
48
+ ciphertext: Uint8Array;
49
+ }>;
50
+ encryptGroupMessage(opts: EncryptGroupMessageOpts): Promise<{
51
+ senderKeyDistributionMessage: Uint8Array;
52
+ ciphertext: Uint8Array;
53
+ }>;
54
+ injectE2ESession(opts: E2ESessionOpts): Promise<void>;
55
+ jidToSignalProtocolAddress(jid: string): string;
56
+ };
57
+ export {};
@@ -0,0 +1 @@
1
+ Object.defineProperty(exports,"__esModule",{value:!0});
@@ -0,0 +1,121 @@
1
+ import { AxiosRequestConfig } from 'axios';
2
+ import type { Agent } from 'https';
3
+ import type { URL } from 'url';
4
+ import { proto } from '../../WAProto';
5
+ import { ILogger } from '../Utils/logger';
6
+ import { AuthenticationState, SignalAuthState, TransactionCapabilityOptions } from './Auth';
7
+ import { GroupMetadata } from './GroupMetadata';
8
+ import { MediaConnInfo } from './Message';
9
+ import { SignalRepository } from './Signal';
10
+ export type WAVersion = [number, number, number];
11
+ export type WABrowserDescription = [string, string, string];
12
+ export type CacheStore = {
13
+ /** get a cached key and change the stats */
14
+ get<T>(key: string): T | undefined;
15
+ /** set a key in the cache */
16
+ set<T>(key: string, value: T): void;
17
+ /** delete a key from the cache */
18
+ del(key: string): void;
19
+ /** flush all data */
20
+ flushAll(): void;
21
+ };
22
+ export type PatchedMessageWithRecipientJID = proto.IMessage & {
23
+ recipientJid?: string;
24
+ };
25
+ export type SocketConfig = {
26
+ /** the WS url to connect to WA */
27
+ waWebSocketUrl: string | URL;
28
+ /** Fails the connection if the socket times out in this interval */
29
+ connectTimeoutMs: number;
30
+ /** Default timeout for queries, undefined for no timeout */
31
+ defaultQueryTimeoutMs: number | undefined;
32
+ /** ping-pong interval for WS connection */
33
+ keepAliveIntervalMs: number;
34
+ /** should baileys use the mobile api instead of the multi device api
35
+ * @deprecated This feature has been removed
36
+ */
37
+ mobile?: boolean;
38
+ /** proxy agent */
39
+ agent?: Agent;
40
+ /** logger */
41
+ logger: ILogger;
42
+ /** version to connect with */
43
+ version: WAVersion;
44
+ /** override browser config */
45
+ browser: WABrowserDescription;
46
+ /** agent used for fetch requests -- uploading/downloading media */
47
+ fetchAgent?: Agent;
48
+ /** should the QR be printed in the terminal
49
+ * @deprecated This feature has been removed
50
+ */
51
+ printQRInTerminal?: boolean;
52
+ /** should events be emitted for actions done by this socket connection */
53
+ emitOwnEvents: boolean;
54
+ /** custom upload hosts to upload media to */
55
+ customUploadHosts: MediaConnInfo['hosts'];
56
+ /** time to wait between sending new retry requests */
57
+ retryRequestDelayMs: number;
58
+ /** max retry count */
59
+ maxMsgRetryCount: number;
60
+ /** time to wait for the generation of the next QR in ms */
61
+ qrTimeout?: number;
62
+ /** provide an auth state object to maintain the auth state */
63
+ auth: AuthenticationState;
64
+ /** manage history processing with this control; by default will sync up everything */
65
+ shouldSyncHistoryMessage: (msg: proto.Message.IHistorySyncNotification) => boolean;
66
+ /** transaction capability options for SignalKeyStore */
67
+ transactionOpts: TransactionCapabilityOptions;
68
+ /** marks the client as online whenever the socket successfully connects */
69
+ markOnlineOnConnect: boolean;
70
+ /** alphanumeric country code (USA -> US) for the number used */
71
+ countryCode: string;
72
+ /** provide a cache to store media, so does not have to be re-uploaded */
73
+ mediaCache?: CacheStore;
74
+ /**
75
+ * map to store the retry counts for failed messages;
76
+ * used to determine whether to retry a message or not */
77
+ msgRetryCounterCache?: CacheStore;
78
+ /** provide a cache to store a user's device list */
79
+ userDevicesCache?: CacheStore;
80
+ /** cache to store call offers */
81
+ callOfferCache?: CacheStore;
82
+ /** cache to track placeholder resends */
83
+ placeholderResendCache?: CacheStore;
84
+ /** width for link preview images */
85
+ linkPreviewImageThumbnailWidth: number;
86
+ /** Should Baileys ask the phone for full history, will be received async */
87
+ syncFullHistory: boolean;
88
+ /** Should baileys fire init queries automatically, default true */
89
+ fireInitQueries: boolean;
90
+ /**
91
+ * generate a high quality link preview,
92
+ * entails uploading the jpegThumbnail to WA
93
+ * */
94
+ generateHighQualityLinkPreview: boolean;
95
+ /**
96
+ * Returns if a jid should be ignored,
97
+ * no event for that jid will be triggered.
98
+ * Messages from that jid will also not be decrypted
99
+ * */
100
+ shouldIgnoreJid: (jid: string) => boolean | undefined;
101
+ /**
102
+ * Optionally patch the message before sending out
103
+ * */
104
+ patchMessageBeforeSending: (msg: proto.IMessage, recipientJids?: string[]) => Promise<PatchedMessageWithRecipientJID[] | PatchedMessageWithRecipientJID> | PatchedMessageWithRecipientJID[] | PatchedMessageWithRecipientJID;
105
+ /** verify app state MACs */
106
+ appStateMacVerification: {
107
+ patch: boolean;
108
+ snapshot: boolean;
109
+ };
110
+ /** options for axios */
111
+ options: AxiosRequestConfig<{}>;
112
+ /**
113
+ * fetch a message from your store
114
+ * implement this so that messages failed to send
115
+ * (solves the "this message can take a while" issue) can be retried
116
+ * */
117
+ getMessage: (key: proto.IMessageKey) => Promise<proto.IMessage | undefined>;
118
+ /** cached group metadata, use to prevent redundant requests to WA & speed up msg sending */
119
+ cachedGroupMetadata: (jid: string) => Promise<GroupMetadata | undefined>;
120
+ makeSignalRepository: (auth: SignalAuthState) => SignalRepository;
121
+ };
@@ -0,0 +1 @@
1
+ Object.defineProperty(exports,"__esModule",{value:!0});
@@ -0,0 +1,27 @@
1
+ import { Contact } from './Contact';
2
+ export type WAConnectionState = 'open' | 'connecting' | 'close';
3
+ export type ConnectionState = {
4
+ /** connection is now open, connecting or closed */
5
+ connection: WAConnectionState;
6
+ /** the error that caused the connection to close */
7
+ lastDisconnect?: {
8
+ error: Error | undefined;
9
+ date: Date;
10
+ };
11
+ /** is this a new login */
12
+ isNewLogin?: boolean;
13
+ /** the current QR code */
14
+ qr?: string;
15
+ /** has the device received all pending notifications while it was offline */
16
+ receivedPendingNotifications?: boolean;
17
+ /** legacy connection options */
18
+ legacy?: {
19
+ phoneConnected: boolean;
20
+ user?: Contact;
21
+ };
22
+ /**
23
+ * if the client is shown as an active, online client.
24
+ * If this is false, the primary phone and other devices will receive notifs
25
+ * */
26
+ isOnline?: boolean;
27
+ };
@@ -0,0 +1 @@
1
+ Object.defineProperty(exports,"__esModule",{value:!0});
@@ -0,0 +1,25 @@
1
+ import { BinaryNode } from '../WABinary';
2
+ import { USyncUser } from '../WAUSync';
3
+ /**
4
+ * Defines the interface for a USyncQuery protocol
5
+ */
6
+ export interface USyncQueryProtocol {
7
+ /**
8
+ * The name of the protocol
9
+ */
10
+ name: string;
11
+ /**
12
+ * Defines what goes inside the query part of a USyncQuery
13
+ */
14
+ getQueryElement: () => BinaryNode;
15
+ /**
16
+ * Defines what goes inside the user part of a USyncQuery
17
+ */
18
+ getUserElement: (user: USyncUser) => BinaryNode | null;
19
+ /**
20
+ * Parse the result of the query
21
+ * @param data Data from the result
22
+ * @returns Whatever the protocol is supposed to return
23
+ */
24
+ parser: (data: BinaryNode) => unknown;
25
+ }
@@ -0,0 +1 @@
1
+ Object.defineProperty(exports,"__esModule",{value:!0});
@@ -0,0 +1,63 @@
1
+ export * from './Auth';
2
+ export * from './GroupMetadata';
3
+ export * from './Chat';
4
+ export * from './Contact';
5
+ export * from './State';
6
+ export * from './Message';
7
+ export * from './Socket';
8
+ export * from './Events';
9
+ export * from './Product';
10
+ export * from './Call';
11
+ export * from './Signal';
12
+ import { AuthenticationState } from './Auth';
13
+ import { SocketConfig } from './Socket';
14
+ export type UserFacingSocketConfig = Partial<SocketConfig> & {
15
+ auth: AuthenticationState;
16
+ };
17
+ export type BrowsersMap = {
18
+ ubuntu(browser: string): [string, string, string];
19
+ macOS(browser: string): [string, string, string];
20
+ baileys(browser: string): [string, string, string];
21
+ windows(browser: string): [string, string, string];
22
+ appropriate(browser: string): [string, string, string];
23
+ };
24
+ export declare enum DisconnectReason {
25
+ connectionClosed = 428,
26
+ connectionLost = 408,
27
+ connectionReplaced = 440,
28
+ timedOut = 408,
29
+ loggedOut = 401,
30
+ badSession = 500,
31
+ restartRequired = 515,
32
+ multideviceMismatch = 411,
33
+ forbidden = 403,
34
+ unavailableService = 503
35
+ }
36
+ export type WAInitResponse = {
37
+ ref: string;
38
+ ttl: number;
39
+ status: 200;
40
+ };
41
+ export type WABusinessHoursConfig = {
42
+ day_of_week: string;
43
+ mode: string;
44
+ open_time?: number;
45
+ close_time?: number;
46
+ };
47
+ export type WABusinessProfile = {
48
+ description: string;
49
+ email: string | undefined;
50
+ business_hours: {
51
+ timezone?: string;
52
+ config?: WABusinessHoursConfig[];
53
+ business_config?: WABusinessHoursConfig[];
54
+ };
55
+ website: string[];
56
+ category?: string;
57
+ wid?: string;
58
+ address?: string;
59
+ };
60
+ export type CurveKeyPair = {
61
+ private: Uint8Array;
62
+ public: Uint8Array;
63
+ };
@@ -0,0 +1,4 @@
1
+ var __createBinding=this&&this.__createBinding||(Object.create?function(a,c,b,d){void 0===d&&(d=b);var e=Object.getOwnPropertyDescriptor(c,b);if(!e||("get"in e?!c.__esModule:e.writable||e.configurable))e={enumerable:!0,get:function(){return c[b]}};Object.defineProperty(a,d,e)}:function(a,c,b,d){void 0===d&&(d=b);a[d]=c[b]}),__exportStar=this&&this.__exportStar||function(a,c){for(var b in a)"default"===b||Object.prototype.hasOwnProperty.call(c,b)||__createBinding(c,a,b)};
2
+ Object.defineProperty(exports,"__esModule",{value:!0});exports.DisconnectReason=void 0;__exportStar(require("./Auth"),exports);__exportStar(require("./GroupMetadata"),exports);__exportStar(require("./Chat"),exports);__exportStar(require("./Contact"),exports);__exportStar(require("./State"),exports);__exportStar(require("./Message"),exports);__exportStar(require("./Socket"),exports);__exportStar(require("./Events"),exports);__exportStar(require("./Product"),exports);
3
+ __exportStar(require("./Call"),exports);__exportStar(require("./Signal"),exports);var DisconnectReason;
4
+ (function(a){a[a.connectionClosed=428]="connectionClosed";a[a.connectionLost=408]="connectionLost";a[a.connectionReplaced=440]="connectionReplaced";a[a.timedOut=408]="timedOut";a[a.loggedOut=401]="loggedOut";a[a.badSession=500]="badSession";a[a.restartRequired=515]="restartRequired";a[a.multideviceMismatch=411]="multideviceMismatch";a[a.forbidden=403]="forbidden";a[a.unavailableService=503]="unavailableService"})(DisconnectReason||(exports.DisconnectReason=DisconnectReason={}));
@@ -0,0 +1,18 @@
1
+ import type { AuthenticationCreds, CacheStore, SignalKeyStore, SignalKeyStoreWithTransaction, TransactionCapabilityOptions } from '../Types';
2
+ import { ILogger } from './logger';
3
+ /**
4
+ * Adds caching capability to a SignalKeyStore
5
+ * @param store the store to add caching to
6
+ * @param logger to log trace events
7
+ * @param _cache cache store to use
8
+ */
9
+ export declare function makeCacheableSignalKeyStore(store: SignalKeyStore, logger?: ILogger, _cache?: CacheStore): SignalKeyStore;
10
+ /**
11
+ * Adds DB like transaction capability (https://en.wikipedia.org/wiki/Database_transaction) to the SignalKeyStore,
12
+ * this allows batch read & write operations & improves the performance of the lib
13
+ * @param state the key store to apply this capability to
14
+ * @param logger logger to log events
15
+ * @returns SignalKeyStore with transaction capability
16
+ */
17
+ export declare const addTransactionCapability: (state: SignalKeyStore, logger: ILogger, { maxCommitRetries, delayBetweenTriesMs }: TransactionCapabilityOptions) => SignalKeyStoreWithTransaction;
18
+ export declare const initAuthCreds: () => AuthenticationCreds;
@@ -0,0 +1,8 @@
1
+ var __importDefault=this&&this.__importDefault||function(d){return d&&d.__esModule?d:{"default":d}};Object.defineProperty(exports,"__esModule",{value:!0});exports.initAuthCreds=exports.addTransactionCapability=void 0;exports.makeCacheableSignalKeyStore=makeCacheableSignalKeyStore;const node_cache_1=__importDefault(require("@cacheable/node-cache")),crypto_1=require("crypto"),Defaults_1=require("../Defaults"),crypto_2=require("./crypto"),generics_1=require("./generics");
2
+ function makeCacheableSignalKeyStore(d,h,n){const k=n||new node_cache_1.default({stdTTL:Defaults_1.DEFAULT_CACHE_TTLS.SIGNAL_STORE,useClones:!1,deleteOnExpire:!0});return{async get(f,e){const g={};var b=[];for(var a of e)e=k.get(`${f}.${a}`),"undefined"!==typeof e?g[a]=e:b.push(a);if(b.length){null===h||void 0===h||h.trace({items:b.length},"loading from store");a=await d.get(f,b);for(const c of b)if(b=a[c])g[c]=b,k.set(`${f}.${c}`,b)}return g},async set(f){let e=0;for(const g in f)for(const b in f[g])k.set(`${g}.${b}`,
3
+ f[g][b]),e+=1;null===h||void 0===h||h.trace({keys:e},"updated cache");await d.set(f)},async clear(){var f;k.flushAll();await (null===(f=d.clear)||void 0===f?void 0:f.call(d))}}}
4
+ const addTransactionCapability=(d,h,{maxCommitRetries:n,delayBetweenTriesMs:k})=>{let f=0,e={},g={},b=0;return{get:async(a,c)=>{if(0<b){const q=e[a];var l=q?c.filter(m=>"undefined"===typeof q[m]):c;l.length&&(f+=1,l=await d.get(a,l),e[a]||(e[a]={}),Object.assign(e[a],l));return c.reduce((m,r)=>{var p;const t=null===(p=e[a])||void 0===p?void 0:p[r];t&&(m[r]=t);return m},{})}return d.get(a,c)},set:a=>{if(0<b){h.trace({types:Object.keys(a)},"caching in transaction");for(const c in a)e[c]=e[c]||{},Object.assign(e[c],
5
+ a[c]),g[c]=g[c]||{},Object.assign(g[c],a[c])}else return d.set(a)},isInTransaction:function(){return 0<b},async transaction(a){let c;b+=1;1===b&&h.trace("entering transaction");try{if(c=await a(),1===b)if(Object.keys(g).length)for(h.trace("committing transaction"),a=n;a;){--a;try{await d.set(g);h.trace({dbQueriesInTransaction:f},"committed transaction");break}catch(l){h.warn(`failed to commit ${Object.keys(g).length} mutations, tries left=${a}`),await (0,generics_1.delay)(k)}}else h.trace("no mutations in transaction")}finally{--b,
6
+ 0===b&&(e={},g={},f=0)}return c}}};exports.addTransactionCapability=addTransactionCapability;
7
+ const initAuthCreds=()=>{const d=crypto_2.Curve.generateKeyPair();return{noiseKey:crypto_2.Curve.generateKeyPair(),pairingEphemeralKeyPair:crypto_2.Curve.generateKeyPair(),signedIdentityKey:d,signedPreKey:(0,crypto_2.signedKeyPair)(d,1),registrationId:(0,generics_1.generateRegistrationId)(),advSecretKey:(0,crypto_1.randomBytes)(32).toString("base64"),processedHistoryMessages:[],nextPreKeyId:1,firstUnuploadedPreKeyId:1,accountSyncCounter:0,accountSettings:{unarchiveChats:!1},registered:!1,pairingCode:void 0,
8
+ lastPropHash:void 0,routingInfo:void 0}};exports.initAuthCreds=initAuthCreds;
@@ -0,0 +1,16 @@
1
+ import type { BaileysEventEmitter } from '../Types';
2
+ /**
3
+ * Captures events from a baileys event emitter & stores them in a file
4
+ * @param ev The event emitter to read events from
5
+ * @param filename File to save to
6
+ */
7
+ export declare const captureEventStream: (ev: BaileysEventEmitter, filename: string) => void;
8
+ /**
9
+ * Read event file and emit events from there
10
+ * @param filename filename containing event data
11
+ * @param delayIntervalMs delay between each event emit
12
+ */
13
+ export declare const readAndEmitEventStream: (filename: string, delayIntervalMs?: number) => {
14
+ ev: BaileysEventEmitter;
15
+ task: Promise<void>;
16
+ };
@@ -0,0 +1,3 @@
1
+ var __importDefault=this&&this.__importDefault||function(a){return a&&a.__esModule?a:{"default":a}};Object.defineProperty(exports,"__esModule",{value:!0});exports.readAndEmitEventStream=exports.captureEventStream=void 0;
2
+ const events_1=__importDefault(require("events")),fs_1=require("fs"),promises_1=require("fs/promises"),readline_1=require("readline"),generics_1=require("./generics"),make_mutex_1=require("./make-mutex"),captureEventStream=(a,c)=>{const d=a.emit,e=(0,make_mutex_1.makeMutex)();a.emit=function(...b){const f=JSON.stringify({timestamp:Date.now(),event:b[0],data:b[1]})+"\n";b=d.apply(a,b);e.mutex(async()=>{await (0,promises_1.writeFile)(c,f,{flag:"a"})});return b}};exports.captureEventStream=captureEventStream;
3
+ const readAndEmitEventStream=(a,c=0)=>{const d=new events_1.default;return{ev:d,task:(async()=>{const e=(0,fs_1.createReadStream)(a),b=(0,readline_1.createInterface)({input:e,crlfDelay:Infinity});for await(const f of b)if(f){const {event:g,data:h}=JSON.parse(f);d.emit(g,h);c&&await (0,generics_1.delay)(c)}e.close()})()}};exports.readAndEmitEventStream=readAndEmitEventStream;
@@ -0,0 +1,22 @@
1
+ import { CatalogCollection, OrderDetails, Product, ProductCreate, ProductUpdate, WAMediaUpload, WAMediaUploadFunction } from '../Types';
2
+ import { BinaryNode } from '../WABinary';
3
+ export declare const parseCatalogNode: (node: BinaryNode) => {
4
+ products: Product[];
5
+ nextPageCursor: string | undefined;
6
+ };
7
+ export declare const parseCollectionsNode: (node: BinaryNode) => {
8
+ collections: CatalogCollection[];
9
+ };
10
+ export declare const parseOrderDetailsNode: (node: BinaryNode) => OrderDetails;
11
+ export declare const toProductNode: (productId: string | undefined, product: ProductCreate | ProductUpdate) => BinaryNode;
12
+ export declare const parseProductNode: (productNode: BinaryNode) => Product;
13
+ /**
14
+ * Uploads images not already uploaded to WA's servers
15
+ */
16
+ export declare function uploadingNecessaryImagesOfProduct<T extends ProductUpdate | ProductCreate>(product: T, waUploadToServer: WAMediaUploadFunction, timeoutMs?: number): Promise<T>;
17
+ /**
18
+ * Uploads images not already uploaded to WA's servers
19
+ */
20
+ export declare const uploadingNecessaryImages: (images: WAMediaUpload[], waUploadToServer: WAMediaUploadFunction, timeoutMs?: number) => Promise<{
21
+ url: string;
22
+ }[]>;
@@ -0,0 +1,14 @@
1
+ Object.defineProperty(exports,"__esModule",{value:!0});exports.uploadingNecessaryImages=exports.parseProductNode=exports.toProductNode=exports.parseOrderDetailsNode=exports.parseCollectionsNode=exports.parseCatalogNode=void 0;exports.uploadingNecessaryImagesOfProduct=uploadingNecessaryImagesOfProduct;
2
+ const boom_1=require("@hapi/boom"),crypto_1=require("crypto"),fs_1=require("fs"),os_1=require("os"),path_1=require("path"),WABinary_1=require("../WABinary"),generics_1=require("./generics"),messages_media_1=require("./messages-media"),parseCatalogNode=a=>{var b=(0,WABinary_1.getBinaryNodeChild)(a,"product_catalog");a=(0,WABinary_1.getBinaryNodeChildren)(b,"product").map(exports.parseProductNode);b=(0,WABinary_1.getBinaryNodeChild)(b,"paging");return{products:a,nextPageCursor:b?(0,WABinary_1.getBinaryNodeChildString)(b,
3
+ "after"):void 0}};exports.parseCatalogNode=parseCatalogNode;const parseCollectionsNode=a=>{a=(0,WABinary_1.getBinaryNodeChild)(a,"collections");return{collections:(0,WABinary_1.getBinaryNodeChildren)(a,"collection").map(b=>{const d=(0,WABinary_1.getBinaryNodeChildString)(b,"id"),c=(0,WABinary_1.getBinaryNodeChildString)(b,"name"),e=(0,WABinary_1.getBinaryNodeChildren)(b,"product").map(exports.parseProductNode);return{id:d,name:c,products:e,status:parseStatusInfo(b)}})}};
4
+ exports.parseCollectionsNode=parseCollectionsNode;
5
+ const parseOrderDetailsNode=a=>{var b=(0,WABinary_1.getBinaryNodeChild)(a,"order");a=(0,WABinary_1.getBinaryNodeChildren)(b,"product").map(d=>{const c=(0,WABinary_1.getBinaryNodeChild)(d,"image");return{id:(0,WABinary_1.getBinaryNodeChildString)(d,"id"),name:(0,WABinary_1.getBinaryNodeChildString)(d,"name"),imageUrl:(0,WABinary_1.getBinaryNodeChildString)(c,"url"),price:+(0,WABinary_1.getBinaryNodeChildString)(d,"price"),currency:(0,WABinary_1.getBinaryNodeChildString)(d,"currency"),quantity:+(0,WABinary_1.getBinaryNodeChildString)(d,
6
+ "quantity")}});b=(0,WABinary_1.getBinaryNodeChild)(b,"price");return{price:{total:+(0,WABinary_1.getBinaryNodeChildString)(b,"total"),currency:(0,WABinary_1.getBinaryNodeChildString)(b,"currency")},products:a}};exports.parseOrderDetailsNode=parseOrderDetailsNode;
7
+ const toProductNode=(a,b)=>{const d={},c=[];"undefined"!==typeof a&&c.push({tag:"id",attrs:{},content:Buffer.from(a)});"undefined"!==typeof b.name&&c.push({tag:"name",attrs:{},content:Buffer.from(b.name)});"undefined"!==typeof b.description&&c.push({tag:"description",attrs:{},content:Buffer.from(b.description)});"undefined"!==typeof b.retailerId&&c.push({tag:"retailer_id",attrs:{},content:Buffer.from(b.retailerId)});b.images.length&&c.push({tag:"media",attrs:{},content:b.images.map(e=>{if(!("url"in
8
+ e))throw new boom_1.Boom("Expected img for product to already be uploaded",{statusCode:400});return{tag:"image",attrs:{},content:[{tag:"url",attrs:{},content:Buffer.from(e.url.toString())}]}})});"undefined"!==typeof b.price&&c.push({tag:"price",attrs:{},content:Buffer.from(b.price.toString())});"undefined"!==typeof b.currency&&c.push({tag:"currency",attrs:{},content:Buffer.from(b.currency)});"originCountryCode"in b&&("undefined"===typeof b.originCountryCode?d.compliance_category="COUNTRY_ORIGIN_EXEMPT":
9
+ c.push({tag:"compliance_info",attrs:{},content:[{tag:"country_code_origin",attrs:{},content:Buffer.from(b.originCountryCode)}]}));"undefined"!==typeof b.isHidden&&(d.is_hidden=b.isHidden.toString());return{tag:"product",attrs:d,content:c}};exports.toProductNode=toProductNode;
10
+ const parseProductNode=a=>{const b="true"===a.attrs.is_hidden,d=(0,WABinary_1.getBinaryNodeChildString)(a,"id"),c=(0,WABinary_1.getBinaryNodeChild)(a,"media"),e=(0,WABinary_1.getBinaryNodeChild)(a,"status_info");return{id:d,imageUrls:parseImageUrls(c),reviewStatus:{whatsapp:(0,WABinary_1.getBinaryNodeChildString)(e,"status")},availability:"in stock",name:(0,WABinary_1.getBinaryNodeChildString)(a,"name"),retailerId:(0,WABinary_1.getBinaryNodeChildString)(a,"retailer_id"),url:(0,WABinary_1.getBinaryNodeChildString)(a,
11
+ "url"),description:(0,WABinary_1.getBinaryNodeChildString)(a,"description"),price:+(0,WABinary_1.getBinaryNodeChildString)(a,"price"),currency:(0,WABinary_1.getBinaryNodeChildString)(a,"currency"),isHidden:b}};exports.parseProductNode=parseProductNode;async function uploadingNecessaryImagesOfProduct(a,b,d=3E4){return a={...a,images:a.images?await (0,exports.uploadingNecessaryImages)(a.images,b,d):a.images}}
12
+ const uploadingNecessaryImages=async(a,b,d=3E4)=>await Promise.all(a.map(async c=>{if("url"in c){var e=c.url.toString();if(e.includes(".whatsapp.net"))return{url:e}}({stream:e}=await (0,messages_media_1.getStream)(c));const g=(0,crypto_1.createHash)("sha256");c=(0,path_1.join)((0,os_1.tmpdir)(),"img"+(0,generics_1.generateMessageIDV2)());const h=(0,fs_1.createWriteStream)(c);for await(var f of e)g.update(f),h.write(f);f=g.digest("base64");({directPath:f}=await b(c,{mediaType:"product-catalog-image",
13
+ fileEncSha256B64:f,timeoutMs:d}));await fs_1.promises.unlink(c).catch(k=>console.log("Error deleting temp file ",k));return{url:(0,messages_media_1.getUrlFromDirectPath)(f)}}));exports.uploadingNecessaryImages=uploadingNecessaryImages;
14
+ const parseImageUrls=a=>{a=(0,WABinary_1.getBinaryNodeChild)(a,"image");return{requested:(0,WABinary_1.getBinaryNodeChildString)(a,"request_image_url"),original:(0,WABinary_1.getBinaryNodeChildString)(a,"original_image_url")}},parseStatusInfo=a=>{a=(0,WABinary_1.getBinaryNodeChild)(a,"status_info");return{status:(0,WABinary_1.getBinaryNodeChildString)(a,"status"),canAppeal:"true"===(0,WABinary_1.getBinaryNodeChildString)(a,"can_appeal")}};
@@ -0,0 +1,70 @@
1
+ import { AxiosRequestConfig } from 'axios';
2
+ import { proto } from '../../WAProto';
3
+ import { BaileysEventEmitter, ChatModification, ChatMutation, Contact, InitialAppStateSyncOptions, LTHashState, WAPatchCreate, WAPatchName } from '../Types';
4
+ import { BinaryNode } from '../WABinary';
5
+ import { ILogger } from './logger';
6
+ type FetchAppStateSyncKey = (keyId: string) => Promise<proto.Message.IAppStateSyncKeyData | null | undefined>;
7
+ export type ChatMutationMap = {
8
+ [index: string]: ChatMutation;
9
+ };
10
+ export declare const newLTHashState: () => LTHashState;
11
+ export declare const encodeSyncdPatch: ({ type, index, syncAction, apiVersion, operation }: WAPatchCreate, myAppStateKeyId: string, state: LTHashState, getAppStateSyncKey: FetchAppStateSyncKey) => Promise<{
12
+ patch: proto.ISyncdPatch;
13
+ state: LTHashState;
14
+ }>;
15
+ export declare const decodeSyncdMutations: (msgMutations: (proto.ISyncdMutation | proto.ISyncdRecord)[], initialState: LTHashState, getAppStateSyncKey: FetchAppStateSyncKey, onMutation: (mutation: ChatMutation) => void, validateMacs: boolean) => Promise<{
16
+ hash: Buffer<any>;
17
+ indexValueMap: {
18
+ [indexMacBase64: string]: {
19
+ valueMac: Uint8Array | Buffer;
20
+ };
21
+ };
22
+ }>;
23
+ export declare const decodeSyncdPatch: (msg: proto.ISyncdPatch, name: WAPatchName, initialState: LTHashState, getAppStateSyncKey: FetchAppStateSyncKey, onMutation: (mutation: ChatMutation) => void, validateMacs: boolean) => Promise<{
24
+ hash: Buffer<any>;
25
+ indexValueMap: {
26
+ [indexMacBase64: string]: {
27
+ valueMac: Uint8Array | Buffer;
28
+ };
29
+ };
30
+ }>;
31
+ export declare const extractSyncdPatches: (result: BinaryNode, options: AxiosRequestConfig<{}>) => Promise<{
32
+ critical_block: {
33
+ patches: proto.ISyncdPatch[];
34
+ hasMorePatches: boolean;
35
+ snapshot?: proto.ISyncdSnapshot;
36
+ };
37
+ critical_unblock_low: {
38
+ patches: proto.ISyncdPatch[];
39
+ hasMorePatches: boolean;
40
+ snapshot?: proto.ISyncdSnapshot;
41
+ };
42
+ regular_high: {
43
+ patches: proto.ISyncdPatch[];
44
+ hasMorePatches: boolean;
45
+ snapshot?: proto.ISyncdSnapshot;
46
+ };
47
+ regular_low: {
48
+ patches: proto.ISyncdPatch[];
49
+ hasMorePatches: boolean;
50
+ snapshot?: proto.ISyncdSnapshot;
51
+ };
52
+ regular: {
53
+ patches: proto.ISyncdPatch[];
54
+ hasMorePatches: boolean;
55
+ snapshot?: proto.ISyncdSnapshot;
56
+ };
57
+ }>;
58
+ export declare const downloadExternalBlob: (blob: proto.IExternalBlobReference, options: AxiosRequestConfig<{}>) => Promise<Buffer<ArrayBuffer>>;
59
+ export declare const downloadExternalPatch: (blob: proto.IExternalBlobReference, options: AxiosRequestConfig<{}>) => Promise<proto.SyncdMutations>;
60
+ export declare const decodeSyncdSnapshot: (name: WAPatchName, snapshot: proto.ISyncdSnapshot, getAppStateSyncKey: FetchAppStateSyncKey, minimumVersionNumber: number | undefined, validateMacs?: boolean) => Promise<{
61
+ state: LTHashState;
62
+ mutationMap: ChatMutationMap;
63
+ }>;
64
+ export declare const decodePatches: (name: WAPatchName, syncds: proto.ISyncdPatch[], initial: LTHashState, getAppStateSyncKey: FetchAppStateSyncKey, options: AxiosRequestConfig<{}>, minimumVersionNumber?: number, logger?: ILogger, validateMacs?: boolean) => Promise<{
65
+ state: LTHashState;
66
+ mutationMap: ChatMutationMap;
67
+ }>;
68
+ export declare const chatModificationToAppPatch: (mod: ChatModification, jid: string) => WAPatchCreate;
69
+ export declare const processSyncAction: (syncAction: ChatMutation, ev: BaileysEventEmitter, me: Contact, initialSyncOpts?: InitialAppStateSyncOptions, logger?: ILogger) => void;
70
+ export {};
@@ -0,0 +1,36 @@
1
+ Object.defineProperty(exports,"__esModule",{value:!0});exports.processSyncAction=exports.chatModificationToAppPatch=exports.decodePatches=exports.decodeSyncdSnapshot=exports.downloadExternalPatch=exports.downloadExternalBlob=exports.extractSyncdPatches=exports.decodeSyncdPatch=exports.decodeSyncdMutations=exports.encodeSyncdPatch=exports.newLTHashState=void 0;
2
+ const boom_1=require("@hapi/boom"),WAProto_1=require("../../WAProto"),LabelAssociation_1=require("../Types/LabelAssociation"),WABinary_1=require("../WABinary"),crypto_1=require("./crypto"),generics_1=require("./generics"),lt_hash_1=require("./lt-hash"),messages_media_1=require("./messages-media"),mutationKeys=async a=>{a=await (0,crypto_1.hkdf)(a,160,{info:"WhatsApp Mutation Keys"});return{indexKey:a.slice(0,32),valueEncryptionKey:a.slice(32,64),valueMacKey:a.slice(64,96),snapshotMacKey:a.slice(96,
3
+ 128),patchMacKey:a.slice(128,160)}},generateMac=(a,b,c,g)=>{let f;switch(a){case WAProto_1.proto.SyncdMutation.SyncdOperation.SET:f=1;break;case WAProto_1.proto.SyncdMutation.SyncdOperation.REMOVE:f=2}a=Buffer.from([f]);c=Buffer.concat([a,Buffer.from(c,"base64")]);a=Buffer.alloc(8);a.set([c.length],a.length-1);b=Buffer.concat([c,b,a]);return(0,crypto_1.hmacSign)(b,g,"sha512").slice(0,32)},to64BitNetworkOrder=a=>{const b=Buffer.alloc(8);b.writeUint32BE(a,4);return b},makeLtHashGenerator=({indexValueMap:a,
4
+ hash:b})=>{a={...a};const c=[],g=[];return{mix:({indexMac:f,valueMac:h,operation:d})=>{const k=Buffer.from(f).toString("base64"),l=a[k];if(d===WAProto_1.proto.SyncdMutation.SyncdOperation.REMOVE){if(!l)throw new boom_1.Boom("tried remove, but no previous op",{data:{indexMac:f,valueMac:h}});delete a[k]}else c.push((new Uint8Array(h)).buffer),a[k]={valueMac:h};l&&g.push((new Uint8Array(l.valueMac)).buffer)},finish:async()=>{var f=(new Uint8Array(b)).buffer;f=await lt_hash_1.LT_HASH_ANTI_TAMPERING.subtractThenAdd(f,
5
+ c,g);return{hash:Buffer.from(f),indexValueMap:a}}}},generateSnapshotMac=(a,b,c,g)=>{a=Buffer.concat([a,to64BitNetworkOrder(b),Buffer.from(c,"utf-8")]);return(0,crypto_1.hmacSign)(a,g,"sha256")},generatePatchMac=(a,b,c,g,f)=>{a=Buffer.concat([a,...b,to64BitNetworkOrder(c),Buffer.from(g,"utf-8")]);return(0,crypto_1.hmacSign)(a,f)},newLTHashState=()=>({version:0,hash:Buffer.alloc(128),indexValueMap:{}});exports.newLTHashState=newLTHashState;
6
+ const encodeSyncdPatch=async({type:a,index:b,syncAction:c,apiVersion:g,operation:f},h,d,k)=>{k=h?await k(h):void 0;if(!k)throw new boom_1.Boom(`myAppStateKey ("${h}") not present`,{statusCode:404});h=Buffer.from(h,"base64");d={...d,indexValueMap:{...d.indexValueMap}};b=Buffer.from(JSON.stringify(b));c=WAProto_1.proto.SyncActionData.fromObject({index:b,value:c,padding:new Uint8Array(0),version:g});g=WAProto_1.proto.SyncActionData.encode(c).finish();c=await mutationKeys(k.keyData);g=(0,crypto_1.aesEncrypt)(g,
7
+ c.valueEncryptionKey);k=generateMac(f,g,h,c.valueMacKey);b=(0,crypto_1.hmacSign)(b,c.indexKey);var l=makeLtHashGenerator(d);l.mix({indexMac:b,valueMac:k,operation:f});Object.assign(d,await l.finish());d.version+=1;l=generateSnapshotMac(d.hash,d.version,a,c.snapshotMacKey);a={patchMac:generatePatchMac(l,[k],d.version,a,c.patchMacKey),snapshotMac:l,keyId:{id:h},mutations:[{operation:f,record:{index:{blob:b},value:{blob:Buffer.concat([g,k])},keyId:{id:h}}}]};f=b.toString("base64");d.indexValueMap[f]=
8
+ {valueMac:k};return{patch:a,state:d}};exports.encodeSyncdPatch=encodeSyncdPatch;
9
+ const decodeSyncdMutations=async(a,b,c,g,f)=>{async function h(n){n=Buffer.from(n).toString("base64");const p=await c(n);if(!p)throw new boom_1.Boom(`failed to find key "${n}" to decode mutation`,{statusCode:404,data:{msgMutations:a}});return mutationKeys(p.keyData)}b=makeLtHashGenerator(b);for(const n of a){const p="operation"in n?n.operation:WAProto_1.proto.SyncdMutation.SyncdOperation.SET,m="record"in n&&n.record?n.record:n;var d=await h(m.keyId.id),k=Buffer.from(m.value.blob),l=k.slice(0,-32);
10
+ k=k.slice(-32);if(f){const e=generateMac(p,l,m.keyId.id,d.valueMacKey);if(0!==Buffer.compare(e,k))throw new boom_1.Boom("HMAC content verification failed");}l=(0,crypto_1.aesDecrypt)(l,d.valueEncryptionKey);l=WAProto_1.proto.SyncActionData.decode(l);if(f&&(d=(0,crypto_1.hmacSign)(l.index,d.indexKey),0!==Buffer.compare(d,m.index.blob)))throw new boom_1.Boom("HMAC index verification failed");d=Buffer.from(l.index).toString();g({syncAction:l,index:JSON.parse(d)});b.mix({indexMac:m.index.blob,valueMac:k,
11
+ operation:p})}return await b.finish()};exports.decodeSyncdMutations=decodeSyncdMutations;
12
+ const decodeSyncdPatch=async(a,b,c,g,f,h)=>{if(h){var d=Buffer.from(a.keyId.id).toString("base64"),k=await g(d);if(!k)throw new boom_1.Boom(`failed to find key "${d}" to decode patch`,{statusCode:404,data:{msg:a}});d=await mutationKeys(k.keyData);k=a.mutations.map(l=>l.record.value.blob.slice(-32));b=generatePatchMac(a.snapshotMac,k,(0,generics_1.toNumber)(a.version.version),b,d.patchMacKey);if(0!==Buffer.compare(b,a.patchMac))throw new boom_1.Boom("Invalid patch mac");}return await (0,exports.decodeSyncdMutations)(a.mutations,
13
+ c,g,f,h)};exports.decodeSyncdPatch=decodeSyncdPatch;
14
+ const extractSyncdPatches=async(a,b)=>{a=(0,WABinary_1.getBinaryNodeChild)(a,"sync");a=(0,WABinary_1.getBinaryNodeChildren)(a,"collection");const c={};await Promise.all(a.map(async g=>{var f=(0,WABinary_1.getBinaryNodeChild)(g,"patches"),h=(0,WABinary_1.getBinaryNodeChildren)(f||g,"patch");const d=(0,WABinary_1.getBinaryNodeChild)(g,"snapshot");f=[];const k=g.attrs.name,l="true"===g.attrs.has_more_patches;var n=void 0;d&&d.content&&(Buffer.isBuffer(d)||(d.content=Buffer.from(Object.values(d.content))),
15
+ n=WAProto_1.proto.ExternalBlobReference.decode(d.content),n=await (0,exports.downloadExternalBlob)(n,b),n=WAProto_1.proto.SyncdSnapshot.decode(n));for(let {content:p}of h)p&&(Buffer.isBuffer(p)||(p=Buffer.from(Object.values(p))),h=WAProto_1.proto.SyncdPatch.decode(p),h.version||(h.version={version:+g.attrs.version+1}),f.push(h));c[k]={patches:f,hasMorePatches:l,snapshot:n}}));return c};exports.extractSyncdPatches=extractSyncdPatches;
16
+ const downloadExternalBlob=async(a,b)=>{a=await (0,messages_media_1.downloadContentFromMessage)(a,"md-app-state",{options:b});b=[];for await(const c of a)b.push(c);return Buffer.concat(b)};exports.downloadExternalBlob=downloadExternalBlob;const downloadExternalPatch=async(a,b)=>{a=await (0,exports.downloadExternalBlob)(a,b);return WAProto_1.proto.SyncdMutations.decode(a)};exports.downloadExternalPatch=downloadExternalPatch;
17
+ const decodeSyncdSnapshot=async(a,b,c,g,f=!0)=>{const h=(0,exports.newLTHashState)();h.version=(0,generics_1.toNumber)(b.version.version);const d={},{hash:k,indexValueMap:l}=await (0,exports.decodeSyncdMutations)(b.records,h,c,"undefined"===typeof g||h.version>g?n=>{var p;const m=null===(p=n.syncAction.index)||void 0===p?void 0:p.toString();d[m]=n}:()=>{},f);h.hash=k;h.indexValueMap=l;if(f){g=Buffer.from(b.keyId.id).toString("base64");c=await c(g);if(!c)throw new boom_1.Boom(`failed to find key "${g}" to decode mutation`);
18
+ c=await mutationKeys(c.keyData);c=generateSnapshotMac(h.hash,h.version,a,c.snapshotMacKey);if(0!==Buffer.compare(b.mac,c))throw new boom_1.Boom(`failed to verify LTHash at ${h.version} of ${a} from snapshot`);}return{state:h,mutationMap:d}};exports.decodeSyncdSnapshot=decodeSyncdSnapshot;
19
+ const decodePatches=async(a,b,c,g,f,h,d,k=!0)=>{var l;c={...c,indexValueMap:{...c.indexValueMap}};const n={};for(const p of b){const {version:m,keyId:e,snapshotMac:r}=p;p.externalMutations&&(null===d||void 0===d||d.trace({name:a,version:m},"downloading external patch"),b=await (0,exports.downloadExternalPatch)(p.externalMutations,f),null===d||void 0===d||d.debug({name:a,version:m,mutations:b.mutations.length},"downloaded external patch"),null===(l=p.mutations)||void 0===l||l.push(...b.mutations));
20
+ b=(0,generics_1.toNumber)(m.version);c.version=b;b=await (0,exports.decodeSyncdPatch)(p,a,c,g,"undefined"===typeof h||b>h?q=>{var v;const w=null===(v=q.syncAction.index)||void 0===v?void 0:v.toString();n[w]=q}:()=>{},!0);c.hash=b.hash;c.indexValueMap=b.indexValueMap;if(k){b=Buffer.from(e.id).toString("base64");const q=await g(b);if(!q)throw new boom_1.Boom(`failed to find key "${b}" to decode mutation`);b=await mutationKeys(q.keyData);b=generateSnapshotMac(c.hash,c.version,a,b.snapshotMacKey);if(0!==
21
+ Buffer.compare(r,b))throw new boom_1.Boom(`failed to verify LTHash at ${c.version} of ${a}`);}p.mutations=[]}return{state:c,mutationMap:n}};exports.decodePatches=decodePatches;
22
+ const chatModificationToAppPatch=(a,b)=>{const c=WAProto_1.proto.SyncdMutation.SyncdOperation;var g=f=>{if(Array.isArray(f)){const h=f[f.length-1];f={lastMessageTimestamp:null===h||void 0===h?void 0:h.messageTimestamp,messages:(null===f||void 0===f?0:f.length)?f.map(d=>{var k,l;if(!((null===(k=d.key)||void 0===k?0:k.id)&&(null===(l=d.key)||void 0===l?0:l.remoteJid)))throw new boom_1.Boom("Incomplete key",{statusCode:400,data:d});if((0,WABinary_1.isJidGroup)(d.key.remoteJid)&&!d.key.fromMe&&!d.key.participant)throw new boom_1.Boom("Expected not from me message to have participant",
23
+ {statusCode:400,data:d});if(!d.messageTimestamp||!(0,generics_1.toNumber)(d.messageTimestamp))throw new boom_1.Boom("Missing timestamp in last message list",{statusCode:400,data:d});d.key.participant&&(d.key.participant=(0,WABinary_1.jidNormalizedUser)(d.key.participant));return d}):void 0}}return f};if("mute"in a)a={syncAction:{muteAction:{muted:!!a.mute,muteEndTimestamp:a.mute||void 0}},index:["mute",b],type:"regular_high",apiVersion:2,operation:c.SET};else if("archive"in a)a={syncAction:{archiveChatAction:{archived:!!a.archive,
24
+ messageRange:g(a.lastMessages)}},index:["archive",b],type:"regular_low",apiVersion:3,operation:c.SET};else if("markRead"in a)a={syncAction:{markChatAsReadAction:{read:a.markRead,messageRange:g(a.lastMessages)}},index:["markChatAsRead",b],type:"regular_low",apiVersion:3,operation:c.SET};else if("deleteForMe"in a){const {timestamp:f,key:h,deleteMedia:d}=a.deleteForMe;a={syncAction:{deleteMessageForMeAction:{deleteMedia:d,messageTimestamp:f}},index:["deleteMessageForMe",b,h.id,h.fromMe?"1":"0","0"],
25
+ type:"regular_high",apiVersion:3,operation:c.SET}}else if("clear"in a)a={syncAction:{clearChatAction:{}},index:["clearChat",b,"1","0"],type:"regular_high",apiVersion:6,operation:c.SET};else if("pin"in a)a={syncAction:{pinAction:{pinned:!!a.pin}},index:["pin_v1",b],type:"regular_low",apiVersion:5,operation:c.SET};else if("star"in a)g=a.star.messages[0],a={syncAction:{starAction:{starred:!!a.star.star}},index:["star",b,g.id,g.fromMe?"1":"0","0"],type:"regular_low",apiVersion:2,operation:c.SET};else if("delete"in
26
+ a)a={syncAction:{deleteChatAction:{messageRange:g(a.lastMessages)}},index:["deleteChat",b,"1"],type:"regular_high",apiVersion:6,operation:c.SET};else if("pushNameSetting"in a)a={syncAction:{pushNameSetting:{name:a.pushNameSetting}},index:["setting_pushName"],type:"critical_block",apiVersion:1,operation:c.SET};else if("addLabel"in a)a={syncAction:{labelEditAction:{name:a.addLabel.name,color:a.addLabel.color,predefinedId:a.addLabel.predefinedId,deleted:a.addLabel.deleted}},index:["label_edit",a.addLabel.id],
27
+ type:"regular",apiVersion:3,operation:c.SET};else if("addChatLabel"in a)a={syncAction:{labelAssociationAction:{labeled:!0}},index:[LabelAssociation_1.LabelAssociationType.Chat,a.addChatLabel.labelId,b],type:"regular",apiVersion:3,operation:c.SET};else if("removeChatLabel"in a)a={syncAction:{labelAssociationAction:{labeled:!1}},index:[LabelAssociation_1.LabelAssociationType.Chat,a.removeChatLabel.labelId,b],type:"regular",apiVersion:3,operation:c.SET};else if("addMessageLabel"in a)a={syncAction:{labelAssociationAction:{labeled:!0}},
28
+ index:[LabelAssociation_1.LabelAssociationType.Message,a.addMessageLabel.labelId,b,a.addMessageLabel.messageId,"0","0"],type:"regular",apiVersion:3,operation:c.SET};else if("removeMessageLabel"in a)a={syncAction:{labelAssociationAction:{labeled:!1}},index:[LabelAssociation_1.LabelAssociationType.Message,a.removeMessageLabel.labelId,b,a.removeMessageLabel.messageId,"0","0"],type:"regular",apiVersion:3,operation:c.SET};else throw new boom_1.Boom("not supported");a.syncAction.timestamp=Date.now();return a};
29
+ exports.chatModificationToAppPatch=chatModificationToAppPatch;
30
+ const processSyncAction=(a,b,c,g,f)=>{function h(x,t){return p?u=>{if(u=u.historySets.chats[x]||u.chatUpserts[x])return t?Number((null===t||void 0===t?void 0:t.lastMessageTimestamp)||(null===t||void 0===t?void 0:t.lastSystemMessageTimestamp)||0)>=Number((null===u||void 0===u?void 0:u.lastMessageRecvTimestamp)||0):!0}:void 0}var d,k,l,n;const p=!!g;var m=null===g||void 0===g?void 0:g.accountSettings;null===f||void 0===f||f.trace({syncAction:a,initialSync:!!g},"processing sync action");const {syncAction:{value:e},
31
+ index:[r,q,v,w]}=a;if(null===e||void 0===e?0:e.muteAction)b.emit("chats.update",[{id:q,muteEndTime:(null===(d=e.muteAction)||void 0===d?0:d.muted)?(0,generics_1.toNumber)(e.muteAction.muteEndTimestamp):null,conditional:h(q,void 0)}]);else if((null===e||void 0===e?0:e.archiveChatAction)||"archive"===r||"unarchive"===r)a=null===e||void 0===e?void 0:e.archiveChatAction,b.emit("chats.update",[{id:q,archived:a?a.archived:"archive"===r,conditional:h(q,(null===m||void 0===m?0:m.unarchiveChats)?null===a||
32
+ void 0===a?void 0:a.messageRange:void 0)}]);else if(null===e||void 0===e?0:e.markChatAsReadAction)m=e.markChatAsReadAction,b.emit("chats.update",[{id:q,unreadCount:p&&m.read?null:(null===m||void 0===m?0:m.read)?0:-1,conditional:h(q,null===m||void 0===m?void 0:m.messageRange)}]);else if((null===e||void 0===e?0:e.deleteMessageForMeAction)||"deleteMessageForMe"===r)b.emit("messages.delete",{keys:[{remoteJid:q,id:v,fromMe:"1"===w}]});else if(null===e||void 0===e?0:e.contactAction)b.emit("contacts.upsert",
33
+ [{id:q,name:e.contactAction.fullName}]);else if(null===e||void 0===e?0:e.pushNameSetting)(m=null===(k=null===e||void 0===e?void 0:e.pushNameSetting)||void 0===k?void 0:k.name)&&(null===c||void 0===c?void 0:c.name)!==m&&b.emit("creds.update",{me:{...c,name:m}});else if(null===e||void 0===e?0:e.pinAction)b.emit("chats.update",[{id:q,pinned:(null===(l=e.pinAction)||void 0===l?0:l.pinned)?(0,generics_1.toNumber)(e.timestamp):null,conditional:h(q,void 0)}]);else if(null===e||void 0===e?0:e.unarchiveChatsSetting)a=
34
+ !!e.unarchiveChatsSetting.unarchiveChats,b.emit("creds.update",{accountSettings:{unarchiveChats:a}}),null===f||void 0===f||f.info(`archive setting updated => '${e.unarchiveChatsSetting.unarchiveChats}'`),m&&(m.unarchiveChats=a);else if((null===e||void 0===e?0:e.starAction)||"star"===r)m=null===(n=null===e||void 0===e?void 0:e.starAction)||void 0===n?void 0:n.starred,"boolean"!==typeof m&&(m="1"===a.index[a.index.length-1]),b.emit("messages.update",[{key:{remoteJid:q,id:v,fromMe:"1"===w},update:{starred:m}}]);
35
+ else if((null===e||void 0===e?0:e.deleteChatAction)||"deleteChat"===r)p||b.emit("chats.delete",[q]);else if(null===e||void 0===e?0:e.labelEditAction){const {name:x,color:t,deleted:u,predefinedId:y}=e.labelEditAction;b.emit("labels.edit",{id:q,name:x,color:t,deleted:u,predefinedId:y?String(y):void 0})}else(null===e||void 0===e?0:e.labelAssociationAction)?b.emit("labels.association",{type:e.labelAssociationAction.labeled?"add":"remove",association:r===LabelAssociation_1.LabelAssociationType.Chat?{type:LabelAssociation_1.LabelAssociationType.Chat,
36
+ chatId:a.index[2],labelId:a.index[1]}:{type:LabelAssociation_1.LabelAssociationType.Message,chatId:a.index[2],messageId:a.index[3],labelId:a.index[1]}}):null===f||void 0===f||f.debug({syncAction:a,id:q},"unprocessable update")};exports.processSyncAction=processSyncAction;
@@ -0,0 +1,40 @@
1
+ import { KeyPair } from '../Types';
2
+ /** prefix version byte to the pub keys, required for some curve crypto functions */
3
+ export declare const generateSignalPubKey: (pubKey: Uint8Array | Buffer) => Uint8Array<ArrayBufferLike> | Buffer<ArrayBufferLike>;
4
+ export declare const Curve: {
5
+ generateKeyPair: () => KeyPair;
6
+ sharedKey: (privateKey: Uint8Array, publicKey: Uint8Array) => Buffer<any>;
7
+ sign: (privateKey: Uint8Array, buf: Uint8Array) => any;
8
+ verify: (pubKey: Uint8Array, message: Uint8Array, signature: Uint8Array) => boolean;
9
+ };
10
+ export declare const signedKeyPair: (identityKeyPair: KeyPair, keyId: number) => {
11
+ keyPair: KeyPair;
12
+ signature: any;
13
+ keyId: number;
14
+ };
15
+ /**
16
+ * encrypt AES 256 GCM;
17
+ * where the tag tag is suffixed to the ciphertext
18
+ * */
19
+ export declare function aesEncryptGCM(plaintext: Uint8Array, key: Uint8Array, iv: Uint8Array, additionalData: Uint8Array): Buffer<ArrayBuffer>;
20
+ /**
21
+ * decrypt AES 256 GCM;
22
+ * where the auth tag is suffixed to the ciphertext
23
+ * */
24
+ export declare function aesDecryptGCM(ciphertext: Uint8Array, key: Uint8Array, iv: Uint8Array, additionalData: Uint8Array): Buffer<ArrayBuffer>;
25
+ export declare function aesEncryptCTR(plaintext: Uint8Array, key: Uint8Array, iv: Uint8Array): Buffer<ArrayBuffer>;
26
+ export declare function aesDecryptCTR(ciphertext: Uint8Array, key: Uint8Array, iv: Uint8Array): Buffer<ArrayBuffer>;
27
+ /** decrypt AES 256 CBC; where the IV is prefixed to the buffer */
28
+ export declare function aesDecrypt(buffer: Buffer, key: Buffer): Buffer<ArrayBuffer>;
29
+ /** decrypt AES 256 CBC */
30
+ export declare function aesDecryptWithIV(buffer: Buffer, key: Buffer, IV: Buffer): Buffer<ArrayBuffer>;
31
+ export declare function aesEncrypt(buffer: Buffer | Uint8Array, key: Buffer): Buffer<ArrayBuffer>;
32
+ export declare function aesEncrypWithIV(buffer: Buffer, key: Buffer, IV: Buffer): Buffer<ArrayBuffer>;
33
+ export declare function hmacSign(buffer: Buffer | Uint8Array, key: Buffer | Uint8Array, variant?: 'sha256' | 'sha512'): Buffer<ArrayBufferLike>;
34
+ export declare function sha256(buffer: Buffer): Buffer<ArrayBufferLike>;
35
+ export declare function md5(buffer: Buffer): Buffer<ArrayBufferLike>;
36
+ export declare function hkdf(buffer: Uint8Array | Buffer, expandedLength: number, info: {
37
+ salt?: Buffer;
38
+ info?: string;
39
+ }): Promise<Buffer>;
40
+ export declare function derivePairingCodeKey(pairingCode: string, salt: Buffer): Promise<Buffer>;
@@ -0,0 +1,11 @@
1
+ var __createBinding=this&&this.__createBinding||(Object.create?function(b,a,c,d){void 0===d&&(d=c);var e=Object.getOwnPropertyDescriptor(a,c);if(!e||("get"in e?!a.__esModule:e.writable||e.configurable))e={enumerable:!0,get:function(){return a[c]}};Object.defineProperty(b,d,e)}:function(b,a,c,d){void 0===d&&(d=c);b[d]=a[c]}),__setModuleDefault=this&&this.__setModuleDefault||(Object.create?function(b,a){Object.defineProperty(b,"default",{enumerable:!0,value:a})}:function(b,a){b["default"]=a}),__importStar=
2
+ this&&this.__importStar||function(){var b=function(a){b=Object.getOwnPropertyNames||function(c){var d=[],e;for(e in c)Object.prototype.hasOwnProperty.call(c,e)&&(d[d.length]=e);return d};return b(a)};return function(a){if(a&&a.__esModule)return a;var c={};if(null!=a)for(var d=b(a),e=0;e<d.length;e++)"default"!==d[e]&&__createBinding(c,a,d[e]);__setModuleDefault(c,a);return c}}();Object.defineProperty(exports,"__esModule",{value:!0});
3
+ exports.signedKeyPair=exports.Curve=exports.generateSignalPubKey=void 0;exports.aesEncryptGCM=aesEncryptGCM;exports.aesDecryptGCM=aesDecryptGCM;exports.aesEncryptCTR=aesEncryptCTR;exports.aesDecryptCTR=aesDecryptCTR;exports.aesDecrypt=aesDecrypt;exports.aesDecryptWithIV=aesDecryptWithIV;exports.aesEncrypt=aesEncrypt;exports.aesEncrypWithIV=aesEncrypWithIV;exports.hmacSign=hmacSign;exports.sha256=sha256;exports.md5=md5;exports.hkdf=hkdf;exports.derivePairingCodeKey=derivePairingCodeKey;
4
+ const crypto_1=require("crypto"),libsignal=__importStar(require("libsignal")),Defaults_1=require("../Defaults"),{subtle}=globalThis.crypto,generateSignalPubKey=b=>33===b.length?b:Buffer.concat([Defaults_1.KEY_BUNDLE_TYPE,b]);exports.generateSignalPubKey=generateSignalPubKey;
5
+ exports.Curve={generateKeyPair:()=>{const {pubKey:b,privKey:a}=libsignal.curve.generateKeyPair();return{private:Buffer.from(a),public:Buffer.from(b.slice(1))}},sharedKey:(b,a)=>{b=libsignal.curve.calculateAgreement((0,exports.generateSignalPubKey)(a),b);return Buffer.from(b)},sign:(b,a)=>libsignal.curve.calculateSignature(b,a),verify:(b,a,c)=>{try{return libsignal.curve.verifySignature((0,exports.generateSignalPubKey)(b),a,c),!0}catch(d){return!1}}};
6
+ const signedKeyPair=(b,a)=>{const c=exports.Curve.generateKeyPair(),d=(0,exports.generateSignalPubKey)(c.public);b=exports.Curve.sign(b.private,d);return{keyPair:c,signature:b,keyId:a}};exports.signedKeyPair=signedKeyPair;const GCM_TAG_LENGTH=16;function aesEncryptGCM(b,a,c,d){a=(0,crypto_1.createCipheriv)("aes-256-gcm",a,c);a.setAAD(d);return Buffer.concat([a.update(b),a.final(),a.getAuthTag()])}
7
+ function aesDecryptGCM(b,a,c,d){a=(0,crypto_1.createDecipheriv)("aes-256-gcm",a,c);c=b.slice(0,b.length-GCM_TAG_LENGTH);b=b.slice(b.length-GCM_TAG_LENGTH);a.setAAD(d);a.setAuthTag(b);return Buffer.concat([a.update(c),a.final()])}function aesEncryptCTR(b,a,c){a=(0,crypto_1.createCipheriv)("aes-256-ctr",a,c);return Buffer.concat([a.update(b),a.final()])}function aesDecryptCTR(b,a,c){a=(0,crypto_1.createDecipheriv)("aes-256-ctr",a,c);return Buffer.concat([a.update(b),a.final()])}
8
+ function aesDecrypt(b,a){return aesDecryptWithIV(b.slice(16,b.length),a,b.slice(0,16))}function aesDecryptWithIV(b,a,c){a=(0,crypto_1.createDecipheriv)("aes-256-cbc",a,c);return Buffer.concat([a.update(b),a.final()])}function aesEncrypt(b,a){const c=(0,crypto_1.randomBytes)(16);a=(0,crypto_1.createCipheriv)("aes-256-cbc",a,c);return Buffer.concat([c,a.update(b),a.final()])}
9
+ function aesEncrypWithIV(b,a,c){a=(0,crypto_1.createCipheriv)("aes-256-cbc",a,c);return Buffer.concat([a.update(b),a.final()])}function hmacSign(b,a,c="sha256"){return(0,crypto_1.createHmac)(c,a).update(b).digest()}function sha256(b){return(0,crypto_1.createHash)("sha256").update(b).digest()}function md5(b){return(0,crypto_1.createHash)("md5").update(b).digest()}
10
+ async function hkdf(b,a,c){var d=b instanceof Uint8Array?b:new Uint8Array(b);b=c.salt?new Uint8Array(c.salt):new Uint8Array(0);c=c.info?(new TextEncoder).encode(c.info):new Uint8Array(0);d=await subtle.importKey("raw",d,{name:"HKDF"},!1,["deriveBits"]);a=await subtle.deriveBits({name:"HKDF",hash:"SHA-256",salt:b,info:c},d,8*a);return Buffer.from(a)}
11
+ async function derivePairingCodeKey(b,a){b=(new TextEncoder).encode(b);a=a instanceof Uint8Array?a:new Uint8Array(a);b=await subtle.importKey("raw",b,{name:"PBKDF2"},!1,["deriveBits"]);a=await subtle.deriveBits({name:"PBKDF2",salt:a,iterations:131072,hash:"SHA-256"},b,256);return Buffer.from(a)};