kersiosocket 0.5.0-dev → 0.6.0-dev

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/BUILD-INFO.md CHANGED
@@ -1,14 +1,15 @@
1
- # Build information — KersioSocket v0.5.0-dev
1
+ # Build information — KersioSocket v0.6.0-dev
2
2
 
3
- - Package version: `0.5.0-dev`
3
+ - Package version: `0.6.0-dev`
4
4
  - Verification runtime: Node.js `v22.16.0`
5
- - Test suite: `60/60` passing with `npm test`
6
- - Serial test suite: `60/60` passing with `npm run test:serial`
7
- - Syntax checks: core WABinary, NodeProtocol, DeviceProps, and pairing adapter passed
8
- - Examples checked: `examples/wabinary.js`, `examples/device-props.js`, `examples/client-payload.js`
5
+ - Full automated suite: `78/78` passing with `npm test`
6
+ - Serial suite: `78/78` passing with `npm run test:serial`
7
+ - Backend/facade bridge suite: `9/9` passing with `npm run test:backends`
8
+ - JavaScript syntax: `node --check` passed for every project `.js` file outside `node_modules`
9
+ - Packaging: `npm pack --dry-run` completed; 70 package files listed
9
10
  - Token data inside this archive: intentionally empty placeholder
10
11
  - Refresh token data after extraction: `npm run refresh:tokens`
11
12
 
12
13
  ## Evidence boundary
13
14
 
14
- The tests establish local behavior only. They do not establish successful live WhatsApp authentication, current server compatibility, Noise server-certificate verification, signed pairing-success validation, Pairing Code flow, Signal Protocol interoperability, or `sendMessage` functionality. See `docs/RESEARCH-BASELINE.md` and `docs/PROTOCOL-ROADMAP.md`.
15
+ The tests establish local behavior and adapter contracts only. They do not establish successful live WhatsApp authentication, server trust/pinning, cryptographic verification of a real WhatsApp pairing-success response, Pairing Code end-to-end, Signal Protocol interoperability, actual live media/group/app-state support, or performance relative to Baileys, Zapo-JS, or whatsmeow. The native engine still fails closed when no server-certificate verifier is configured and does not yet implement a complete native Signal/message engine. Baileys and Zapo-JS features are delegated through adapters; whatsmeow is an external JSONL sidecar contract and its Go binary is not included. See `README.md`, `docs/ENGINE-MATRIX.md`, `docs/RESEARCH-BASELINE.md`, and `docs/PROTOCOL-ROADMAP.md`.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,16 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.6.0-dev — unified engine facade and hardening
4
+
5
+ - Adds `KersioClient` / `createKersioClient()` with normalized connection, pairing, message, credential, and history events plus explicit capability errors.
6
+ - Adds adapters for an existing `zapo-js` `WaClient`, an `@whiskeysockets/baileys` socket/factory, and a bounded JSONL-RPC Go `whatsmeow` process bridge.
7
+ - Adds normalized high-level message builders for text, media, location, contacts, polls, reactions, edit and delete. The selected engine remains the implementation of transport/protocol semantics; backend coverage varies.
8
+ - Adds `KersioSessionManager` so distinct accounts may select distinct engines in one process.
9
+ - Adds `MessageArchive` (bounded per-chat history + `getMessage()`), `KeyedMutex`, local-filesystem `FileLockManager`, and `LockedStore`.
10
+ - Makes native `Connection` fail closed by default if no Noise server-certificate verifier is configured; adds optional synchronous verifier hook and verified-pairing commit guard.
11
+ - Documents that the Go sidecar is a separate executable and the bridge test is transport-only; does not ship or claim an untested Go protocol implementation.
12
+ - Adds mocked adapter/bridge, archive/lock, secure-pairing and strict-Noise tests. No live WhatsApp account test is claimed.
13
+
3
14
  ## 0.5.0-dev — major protocol foundations upgrade
4
15
 
5
16
  - WABinary defaults to the `0x00` uncompressed prefix; adds explicit golden-byte test, optional zlib `0x02` prefix, packed digit/hex strings, AD-JID and decode fixtures for FB/INTEROP JIDs, plus bounded parser checks.
package/README.md CHANGED
@@ -1,146 +1,192 @@
1
- # KersioSocket
2
-
3
- Library protokol WhatsApp Web eksperimental yang ditulis sebagai proyek mandiri. Target desainnya adalah API event yang mudah dipakai, session store yang bisa diganti, isolasi multi-session, dan jalur data berbasis `Buffer` dengan batas input eksplisit.
4
-
5
- > **Status v0.5.0-dev: belum siap dipakai login WhatsApp secara live.** Tes lokal menguji format dan state internal. Kode ini belum memverifikasi rantai sertifikat Noise server, belum memiliki implementasi Signal Protocol, dan belum memverifikasi signature/HMAC `pair-success`. Karena itu, handshake Noise atau event QR bukan bukti akun berhasil tertaut.
6
-
7
- ## Upgrade v0.5.0-dev
8
-
9
- - WABinary: prefix standar `0x00`, prefix zlib `0x02`, single/double token dictionary, raw UTF-8, binary values, packed nibble/hex, JID pair dan AD-JID, validasi panjang/kedalaman, serta fixture byte eksplisit.
10
- - Protobuf: encoder manual untuk subset `ClientPayload` berdasarkan schema snapshot yang tercatat, termasuk field opsional yang sebelumnya belum ada.
11
- - `DeviceProps`: encoder schema eksplisit, builder `createDevicePairingData()` dari kunci dan signed prekey **yang disediakan pemanggil**, ID big-endian, dan build hash MD5 dari versi aplikasi bertitik.
12
- - `NodeProtocol`: decoding node dari frame Noise, event `node`, `node:<tag>`, `iq`, `query()` dengan timeout/abort, penanganan error remote dan pembatas IQ pending.
13
- - QR adapter: menanggapi node `iq/pair-device` yang sudah di-decode, ack sesuai referensi, dan memancarkan kandidat payload QR dari `ref` yang diterima server. Adapter ini **tidak** mengesahkan `pair-success` atau menyimpan akun sebagai paired.
14
- - `EncryptedStore`: AES-256-GCM dengan IV acak, AAD terikat ke storage key, serta fail-closed jika kunci salah atau envelope dimodifikasi.
15
- - Koneksi: listener error terisolasi, kegagalan frame protokol fail-closed, dan metrik secara eksplisit melaporkan `serverCertificateVerified: false` sampai verifier sertifikat diterapkan.
16
- - Benchmark lokal WABinary dan dokumentasi baseline riset/versi.
17
-
18
- ## Fitur dan batasannya
19
-
20
- | Bagian | Status di v0.5.0-dev |
21
- |---|---|
22
- | WebSocket, frame length prefix, reconnect backoff | Ada; koneksi target live belum diverifikasi menyeluruh |
23
- | Noise XX, X25519, AES-GCM | Lulus tes loopback; **verifikasi sertifikat server belum ada** |
24
- | WABinary encode/decode dan token version pin | Ada; fixture/golden test lokal. Token table tidak dibundel penuh dan perlu diimpor |
25
- | Node layer / IQ query | Ada; diuji dengan transport tiruan, belum seluruh alur server live |
26
- | `ClientPayload` / `DeviceProps` protobuf | Encoder schema snapshot dan fixture; bukan jaminan server menerima payload |
27
- | QR adapter dari `pair-device` | Ada sebagai adapter awal; butuh kredensial asli yang dibuat secara benar |
28
- | Verifikasi cryptographic `pair-success` dan simpan auth final | **Belum ada** |
29
- | Pairing code / PBKDF2 + AES-CTR end-to-end | **Belum ada** |
30
- | Signal Protocol, prekey upload, message encryption | **Belum ada** |
31
- | `messages.upsert`, `sendMessage`, media, group/app-state sync | **Belum ada** |
32
- | Store memory/file/SQLite/Redis/Mongo, LRU, multi-session | Ada; Redis/Mongo diuji dengan fake client, perlu integrasi server sungguhan |
33
- | Store AES-GCM untuk kredensial | Ada; kunci master harus dipasok dari secret manager/environment |
34
-
35
- ## Setup di CMD Windows
36
-
37
- Ekstrak ZIP ke folder proyek, lalu di CMD:
38
-
39
- ```bat
40
- cd /d C:\kersiosocket
1
+ # KersioSocket v0.6.0-dev
2
+
3
+ KersioSocket v0.6 adds a **common API facade** for three independently maintained WhatsApp Web client engines: `zapo-js`, `@whiskeysockets/baileys`, and a Go `whatsmeow` process bridge. It keeps the original KersioSocket native transport/protocol research code and adds message helpers, event normalization, selectable multi-session engines, message archive, and file-based locking.
4
+
5
+ > **Honest status:** this is a development build. The Zapo and Baileys adapters are tested with mocked clients, and the Go bridge transport is tested with a mock JSONL process; there is no live-account integration test in this ZIP. The Go `whatsmeow` executable is **not bundled**. The native KersioSocket engine remains experimental: by default it fails closed when Noise server-certificate verification is not configured, and this package does not include a verified WhatsApp certificate-root chain, a full native Signal Protocol implementation, or an internal cryptographic verifier for pairing-success. Choose a maintained backend for live messaging rather than disabling security checks.
6
+
7
+ ## Apa arti “digabung” di v0.6?
8
+
9
+ KersioSocket menyatukan API dan lifecycle backend di satu package, bukan mencampur tiga set auth key/Signal session menjadi satu sesi protokol. Untuk setiap akun WhatsApp, pilih **satu** engine pemilik transport, autentikasi, dan state. Beberapa akun boleh menggunakan engine berbeda di satu proses melalui `KersioSessionManager`. Menjalankan Baileys, Zapo, dan whatsmeow bersamaan dengan kredensial akun yang sama tidak disarankan karena ketiganya mengelola sesi dan counter protokol sendiri.
10
+
11
+ Engine:
12
+
13
+ - **Zapo-JS** — adapter ke API `WaClient` dan `.message.send()`; sesi, Signal, prekey, media, dan app-state dikelola Zapo. Konfigurasi store diberikan oleh pemanggil agar KersioSocket tidak menebak backend/credential provider.
14
+ - **Baileys** — adapter ke socket Baileys; meneruskan event, QR/pairing code, credential updates, pesan, media download bila modul helper tersedia, dan method socket yang diizinkan.
15
+ - **Go whatsmeow process** — JSON Lines RPC bridge terbatasi ke executable Go yang dibuat terpisah. Lihat `bridges/whatsmeow/README.md` untuk protokolnya. Hasil mock test bukan bukti bahwa binary Go atau koneksi WhatsApp live sudah diuji.
16
+ - **Native KersioSocket** — tetap menyediakan codec WABinary, Noise framing, IQ/node protocol, dan adapter pairing awal; fitur autentikasi dan enkripsi pesan native belum lengkap untuk sesi live.
17
+
18
+ ## Install dan tests
19
+
20
+ Butuh Node.js **22.5 atau lebih baru**. Engine eksternal bersifat opsional supaya pemasangan core tidak memaksa dua client tambahan.
21
+
22
+ ```bash
41
23
  npm install
42
24
  npm test
25
+ npm run test:serial
26
+ npm run test:backends
27
+ npm run bench:wabinary
43
28
  ```
44
29
 
45
- `ws` dipakai oleh adapter WebSocket dan merupakan peer dependency opsional:
30
+ Instal engine yang memang ingin dipakai:
46
31
 
47
- ```bat
48
- npm install ws
32
+ ```bash
33
+ npm install zapo-js
34
+ # atau
35
+ npm install @whiskeysockets/baileys
49
36
  ```
50
37
 
51
- ### Impor token table
38
+ Untuk Zapo dengan SQLite gunakan paket add-on yang didokumentasikan Zapo, misalnya `@zapo-js/store-sqlite` bersama driver `better-sqlite3`. Ikuti persyaratan OS/runtime driver dan dokumentasi upstream. Library ini tidak memasang/mengonfigurasi database server secara otomatis.
52
39
 
53
- ZIP sengaja menyertakan `src/wabinary/tokens.json` kosong. Untuk penggunaan NodeProtocol yang membaca traffic tokenized, jalankan importer yang mengambil data dari commit publik terpin dan memvalidasi source blob SHA-1 serta lisensi:
40
+ ## API umum
54
41
 
55
- ```bat
56
- npm run refresh:tokens
57
- ```
42
+ ```js
43
+ const { createKersioClient } = require('kersiosocket')
44
+
45
+ // zapoClient adalah instance WaClient zapo-js yang sudah kamu konfigurasi dan kelola
46
+ const zapoClient = createYourConfiguredZapoClient()
47
+ const client = await createKersioClient({ engine: 'zapo', client: zapoClient, sessionId: 'akun-1' })
48
+ client.on('pairing.qr', ({ qr }) => console.log('QR:', qr))
49
+ client.on('pairing.code', ({ code }) => console.log('Pairing code:', code))
50
+ client.on('messages.upsert', async ({ messages }) => {
51
+ for (const message of messages) console.log(message.key?.remoteJid, message.message)
52
+ })
53
+ client.on('connection.update', (update) => console.log('connection:', update.connection))
54
+ client.on('backend.error', ({ error }) => console.error(error))
58
55
 
59
- Importer memerlukan internet dari mesinmu. Hasilnya adalah dataset reverse-engineering publik, bukan tabel resmi WhatsApp dan bukan jaminan kompatibilitas versi server aktif. Simpan `licenses/whatsmeow-MPL-2.0.txt` dan `licenses/THIRD-PARTY-NOTICES.md` saat mendistribusikan hasil impor.
56
+ await client.connect()
57
+ // Kirim hanya sesudah backend memberi status connection.update open.
58
+ await client.sendText('6281234567890@s.whatsapp.net', 'Halo dari KersioSocket')
59
+ await client.close()
60
+ ```
60
61
 
61
- ## API singkat
62
+ Ganti `createYourConfiguredZapoClient()` dengan inisialisasi `WaClient` milikmu, seperti contoh lengkap pada bagian Zapo-JS di bawah.
62
63
 
63
- ### Codec WABinary lokal
64
+ ### Zapo-JS
64
65
 
65
66
  ```js
66
- const { encodeBinaryNode, decodeBinaryNode, loadTokenTable } = require('./src')
67
- const tokens = loadTokenTable()
68
- const node = { tag: 'iq', attrs: { id: 'fixture-1', type: 'get' }, content: [{ tag: 'ping', attrs: {} }] }
69
- const bytes = encodeBinaryNode(node, { tokens }) // sudah menyertakan prefix 0x00
70
- const decoded = decodeBinaryNode(bytes, { tokens, requirePrefix: true })
71
- console.log(bytes.toString('hex'), decoded)
67
+ const { createKersioClient } = require('./src')
68
+ const { createStore, WaClient, ConsoleLogger } = require('zapo-js')
69
+ const { createSqliteStore } = require('@zapo-js/store-sqlite')
70
+
71
+ const store = createStore({
72
+ backends: { sqlite: createSqliteStore({ path: '.auth/state.sqlite' }) },
73
+ providers: {
74
+ auth: 'sqlite', signal: 'sqlite', preKey: 'sqlite', session: 'sqlite',
75
+ identity: 'sqlite', senderKey: 'sqlite', appState: 'sqlite', privacyToken: 'sqlite',
76
+ messages: 'sqlite', threads: 'sqlite', contacts: 'sqlite'
77
+ }
78
+ })
79
+ const zapoClient = new WaClient({ store, sessionId: 'akun-1' }, new ConsoleLogger('info'))
80
+ const client = await createKersioClient({ engine: 'zapo', client: zapoClient, sessionId: 'akun-1' })
81
+ client.on('pairing.qr', ({ qr }) => console.log(qr))
82
+ client.on('messages.upsert', ({ messages }) => console.log(messages.length, 'pesan'))
83
+ await client.connect()
72
84
  ```
73
85
 
74
- ### Socket + NodeProtocol
86
+ KersioSocket tidak otomatis menyimpan credentials Zapo sendiri. Store milik Zapo harus menyimpan provider `auth`, `signal`, `preKey`, `session`, `identity`, `senderKey`, dan `appState` sebagaimana dibutuhkan engine. Pertahankan dokumentasi dan versi Zapo yang dipakai.
75
87
 
76
- Gunakan setelah token table sudah diimpor. Contoh ini membangun lapisan API, bukan berarti login aktif tersedia:
88
+ ### Baileys
77
89
 
78
90
  ```js
79
- const { makeSocket, loadTokenTable } = require('./src')
80
- const sock = makeSocket({
81
- sessionId: 'fixture-session',
82
- clientPayload: Buffer.alloc(0), // smoke-test transport saja; bukan payload login
83
- nodeProtocol: { tokens: loadTokenTable() }
91
+ const baileys = await import('@whiskeysockets/baileys')
92
+ const { state, saveCreds } = await baileys.useMultiFileAuthState('./auth-baileys')
93
+ const client = await require('./src').createKersioClient({
94
+ engine: 'baileys',
95
+ socketOptions: { auth: state, printQRInTerminal: false },
96
+ baileysModule: baileys
84
97
  })
85
-
86
- sock.ev.on('connection.update', (update) => console.log(update.connection))
87
- sock.ev.on('node', (node) => console.log('node diterima:', node.tag))
88
- sock.ev.on('protocol.error', (error) => console.error(error.message))
89
- // sock.query({ tag: 'iq', attrs: { type: 'get', to: 's.whatsapp.net' }, content: [...] })
98
+ client.on('creds.update', saveCreds)
99
+ client.on('pairing.qr', ({ qr }) => console.log(qr))
100
+ client.on('messages.upsert', ({ messages }) => console.log(messages.length))
101
+ await client.connect()
90
102
  ```
91
103
 
92
- Untuk NodeProtocol, jangan kirim query sesuka hati ke server live; panggil query hanya ketika koneksi dan sesi autentikasi memang sudah siap. `clientPayload: Buffer.alloc(0)` di atas sengaja menandakan smoke-test transport, bukan login.
104
+ Untuk penggunaan serius, ikuti panduan upstream tentang penyimpanan credentials/Signal keys dan dampak perubahan versi API Baileys. `useMultiFileAuthState` ditujukan sebagai contoh/kemudahan; rancang storage persisten yang tepat untuk production.
93
105
 
94
- ### DeviceProps dan registration bundle
106
+ ### Go `whatsmeow`
95
107
 
96
108
  ```js
97
- const { encodeDeviceProps, createDevicePairingData, encodeClientPayload } = require('./src')
98
- const deviceProps = encodeDeviceProps({
99
- os: 'Windows', version: [10, 15, 7], platformType: 'CHROME', requireFullSync: true,
100
- historySyncConfig: { storageQuotaMb: 10240, inlineInitialPayloadInE2EeMsg: true }
109
+ const { createKersioClient } = require('./src')
110
+ const client = await createKersioClient({
111
+ engine: 'whatsmeow',
112
+ sessionId: 'akun-go',
113
+ bridge: { command: './whatsmeow-bridge', args: [] }
101
114
  })
115
+ client.on('messages.upsert', ({ messages }) => console.log(messages))
116
+ await client.connect()
117
+ await client.sendText('6281234567890@s.whatsapp.net', 'Halo dari bridge Go')
118
+ ```
102
119
 
103
- // identityPublicKey, signedPreKey.publicKey dan signedPreKey.signature harus berasal
104
- // dari implementasi kriptografi yang benar; helper ini TIDAK membuat atau memvalidasinya.
105
- const pairingData = createDevicePairingData({
106
- registrationId: existingRegistrationId,
107
- identityPublicKey: existingIdentityPublicKey,
108
- signedPreKey: { keyId: existingSignedPreKeyId, publicKey: existingSignedPreKeyPublic, signature: existingValidSignature },
109
- appVersion: [2, 3000, 1043857760],
110
- deviceProps
111
- })
120
+ `./whatsmeow-bridge` harus executable sidecar yang implementasi JSONL RPC-nya mengikuti `bridges/whatsmeow/README.md`; binary tersebut tidak ada di ZIP ini. KersioSocket tidak mengklaim API Go live sampai sidecar yang dipilih terbangun dan diuji sendiri.
121
+
122
+ ## API pesan terpadu
112
123
 
113
- const bytes = encodeClientPayload({ mode: 'registration', userAgent, webInfo, devicePairingData: pairingData })
124
+ ```js
125
+ await client.sendMessage(jid, { text: 'Halo' })
126
+ await client.sendText(jid, 'Halo')
127
+ await client.sendImage(jid, Buffer.from(imageBytes), { caption: 'Foto' })
128
+ await client.sendVideo(jid, Buffer.from(videoBytes), { caption: 'Video' })
129
+ await client.sendAudio(jid, Buffer.from(audioBytes), { mimetype: 'audio/ogg' })
130
+ await client.sendDocument(jid, Buffer.from(fileBytes), { fileName: 'contoh.pdf', mimetype: 'application/pdf' })
131
+ await client.sendSticker(jid, Buffer.from(webpBytes))
132
+ await client.sendLocation(jid, { latitude: -6.2, longitude: 106.8, name: 'Jakarta' })
133
+ await client.sendContact(jid, { displayName: 'Nama', vcard: 'BEGIN:VCARD\\nVERSION:3.0\\nFN:Nama\\nEND:VCARD' })
134
+ await client.sendPoll(jid, { name: 'Pilih', values: ['A', 'B'], selectableCount: 1 })
135
+ await client.react(jid, messageKey, '👍')
136
+ await client.editMessage(jid, messageKey, 'Teks baru')
137
+ await client.deleteMessage(jid, messageKey)
114
138
  ```
115
139
 
116
- Nama `existing...` di atas adalah placeholder penjelas dan harus diganti oleh caller; contoh tersebut sengaja bukan file yang langsung bisa dijalankan. **Jangan** mengisi signature dengan data acak: ukuran yang benar tidak berarti signature sah. Proyek ini belum membuat signed prekey, belum memverifikasi cert chain Noise, dan belum menyelesaikan verifikasi pairing.
140
+ These are normalized content objects passed to the selected engine. Not every backend/version supports every payload. Feature-specific operations fail explicitly when no implementation is exposed; KersioSocket does not claim that constructing an object proves server support. Group/app-state methods can be accessed through `client.invoke(...)`, using the method/path documented by the chosen backend. Avoid invoking untrusted method names from user input.
117
141
 
118
- ### Multi-session + encrypted store
142
+ ## Multi-session
119
143
 
120
144
  ```js
121
- const { createSessionManager, FileStore, EncryptedStore } = require('./src')
122
- const masterKey = Buffer.from(process.env.KERSIO_STORE_KEY_HEX || '', 'hex')
123
- if (masterKey.length !== 32) throw new Error('KERSIO_STORE_KEY_HEX harus 64 digit hex (32 byte) dari secret manager')
124
- const store = new EncryptedStore(new FileStore('./sessions'), masterKey)
125
- const sessions = createSessionManager({ store, autoConnect: false })
126
- const a = sessions.open('akun-a')
127
- const b = sessions.open('akun-b')
128
- console.log(await sessions.list(), sessions.stats())
129
- // Shutdown: await sessions.closeAll()
145
+ const { createKersioSessionManager } = require('./src')
146
+ const manager = createKersioSessionManager()
147
+ const a = await manager.open('akun-zapo', { engine: 'zapo', client: zapoClient })
148
+ const b = await manager.open('akun-baileys', { engine: 'baileys', socketOptions: { auth: baileysAuth } })
149
+ console.log(manager.stats())
150
+ await manager.close('akun-zapo')
151
+ await manager.closeAll()
130
152
  ```
131
153
 
132
- Jangan taruh master key di source code. `EncryptedStore` mengenkripsi values, tetapi perlindungan backup, akses folder, kunci master, dan koordinasi multi-proses tetap tanggung jawab deployment. Jangan jalankan dua proses terhadap akun/session yang sama tanpa lock terdistribusi.
154
+ This manager prevents duplicate session IDs within one process. It is not a substitute for a distributed scheduler or lock when several processes share one auth database.
133
155
 
134
- ## Tes dan benchmark
156
+ ## Storage dan stabilitas
135
157
 
136
- ```bat
137
- npm test
138
- npm run test:serial
139
- npm run bench:wabinary
158
+ - Existing `MemoryStore`, `FileStore`, `SQLiteStore`, `RedisStore`, `MongoStore`, and `EncryptedStore` are retained.
159
+ - `MessageArchive` stores per-chat message history up to a configurable limit and exposes `getMessage(key)` for retry/reply retrieval.
160
+ - `FileLockManager` provides cooperative local-filesystem lock leases; `LockedStore` wraps operations under those locks. Do not treat this as a distributed lock for network filesystems.
161
+ - Existing Redis/Mongo adapter tests use fake clients. Set up real services and integration-test them before production.
162
+ - Benchmarks cover local WABinary codec paths only. No cross-library speed claim is made.
163
+
164
+ Example encrypted storage:
165
+
166
+ ```js
167
+ const { FileStore, EncryptedStore } = require('./src')
168
+ const key = Buffer.from(process.env.KERSIO_STORE_KEY_HEX || '', 'hex')
169
+ if (key.length !== 32) throw new Error('KERSIO_STORE_KEY_HEX wajib 64 digit hex')
170
+ const store = new EncryptedStore(new FileStore('./sessions'), key)
140
171
  ```
141
172
 
142
- Benchmark menggunakan codec KersioSocket sendiri, warm-up dan sample tetap. Angka ops/s hanya baseline mesin lokal, bukan pembuktian bahwa KersioSocket lebih cepat daripada Go, Baileys, atau zapo-js. Uji di mesin idle, catat versi Node dan status token table jika membandingkan run.
173
+ Use a secret manager or environment injection for the master key; never commit it with the source. Use an encrypted store for auth state when storing it through generic Kersio stores.
174
+
175
+ ## Security gates — native engine
176
+
177
+ - `Connection` now defaults to `strictServerCertificateVerification: true`. Without `verifyServerCertificate` returning exactly `true`, a synthetic/local Noise handshake may be tested only with explicit `strictServerCertificateVerification: false`. Do not turn this off against a live server.
178
+ - A verifier callback is a hook, not a built-in WhatsApp root certificate chain. Pin and independently test the exact root/intermediate certificates before supplying one.
179
+ - `commitVerifiedPairSuccess()` requires a supplied, independently tested verifier returning `deviceIdentity`, `accountSignature`, and `advHmac` checks, credentials, and a reply node. It is a fail-closed persistence guard, not the cryptographic verifier itself.
180
+ - Native `Signal Protocol`, prekey upload, session crypto and message-node transforms are not implemented end-to-end. Native mode intentionally throws for high-level message use.
181
+
182
+ ## Tests & evidence
183
+
184
+ `npm test` covers local unit/mocked tests. This package was **not** connected to a real WhatsApp account during this build. Do not interpret passing unit tests as proof of pairing, media upload, message delivery, app-state sync, or engine interoperability. See `docs/ENGINE-MATRIX.md`, `docs/RESEARCH-BASELINE.md`, and `docs/PROTOCOL-ROADMAP.md`.
185
+
186
+ ## Upstream references / licenses
143
187
 
144
- ## Referensi riset
188
+ - [Baileys](https://github.com/WhiskeySockets/Baileys) — review current v7 migration notes and license before use.
189
+ - [Zapo-JS](https://github.com/vinikjkkj/zapo) — package + optional storage/media/native add-ons; MIT upstream license.
190
+ - [whatsmeow](https://github.com/tulir/whatsmeow) — Go implementation, MPL-2.0 upstream license.
145
191
 
146
- Lihat [`docs/RESEARCH-BASELINE.md`](docs/RESEARCH-BASELINE.md) untuk file referensi, blob hash, versi schema, hasil yang dapat disimpulkan, dan batas bukti. Lihat [`docs/PROTOCOL-ROADMAP.md`](docs/PROTOCOL-ROADMAP.md) untuk gate selanjutnya.
192
+ KersioSocket is not affiliated with WhatsApp. Respect the respective upstream licenses and WhatsApp's applicable terms. Do not use this library for unsolicited bulk messaging or abusive automation.
@@ -0,0 +1,42 @@
1
+ # KersioSocket ↔ Go `whatsmeow` bridge contract
2
+
3
+ KersioSocket includes a tested JSON Lines RPC transport in `src/backends/whatsmeow-process.js`. It does **not** bundle a precompiled Go executable or claim that an uncompiled Go sample is production-ready. Build and audit the Go sidecar against the exact `whatsmeow` version you choose, then pass its executable to `createKersioClient({ engine: 'whatsmeow', bridge: { command, args } })`.
4
+
5
+ This is deliberately a transport contract, not an invented WhatsApp protocol implementation. The Go process must use the public `whatsmeow` client, its supported store and its own event handlers. `whatsmeow` has a separate MPL-2.0 license; retain its notices if you distribute its source or binary. KersioSocket itself does not copy its protocol implementation.
6
+
7
+ ## Standard input / standard output
8
+
9
+ Each request is one UTF-8 JSON object terminated by `\n`:
10
+
11
+ ```json
12
+ {"id":"request-1","method":"connect","params":{"sessionId":"account-a"}}
13
+ ```
14
+
15
+ The sidecar returns one matching response line:
16
+
17
+ ```json
18
+ {"id":"request-1","result":{"connected":true}}
19
+ ```
20
+
21
+ Errors have this shape:
22
+
23
+ ```json
24
+ {"id":"request-2","error":{"code":"ERR_OPERATION","message":"Readable explanation"}}
25
+ ```
26
+
27
+ Asynchronous events use a line without `id`:
28
+
29
+ ```json
30
+ {"event":"messages.upsert","data":{"type":"notify","messages":[]}}
31
+ ```
32
+
33
+ The client currently sends these method names: `connect`, `sendMessage`, `requestPairingCode`, `downloadMedia`, `capabilities`, `invoke`, and `close`. A sidecar may implement additional operations through `invoke`, but the method should be allow-listed by the Go program. Buffers/Uint8Arrays are encoded as `{"$base64":"..."}`; the Go sidecar is responsible for decoding that marker where appropriate. Large media should preferably be streamed or passed by file reference rather than copied through JSONL.
34
+
35
+ ## Security and process model
36
+
37
+ - The bridge is spawned with `shell: false`; command and args must be provided separately.
38
+ - Use a private working directory and a dedicated session database per account.
39
+ - Never log QR payloads, pairing codes, auth credentials, or message content to stderr.
40
+ - Return structured errors; do not write non-JSON diagnostics to stdout.
41
+ - The Node adapter bounds the maximum response line and the number of pending RPCs, and times out requests.
42
+ - This bridge contract has a mock-process test. That test proves JSONL transport semantics only, not a live `whatsmeow` connection.
@@ -0,0 +1,23 @@
1
+ # v0.6.0-dev engine matrix
2
+
3
+ This matrix separates features supplied by an upstream engine from features implemented in KersioSocket's own native transport. A green-looking facade method is never evidence of a successful live server operation.
4
+
5
+ | Capability | Zapo-JS adapter | Baileys adapter | Go `whatsmeow` bridge | Native KersioSocket |
6
+ |---|---|---|---|---|
7
+ | QR / pairing code | Delegated to Zapo; observed auth events normalized | Delegated to Baileys; QR and requestPairingCode mapped | Only if sidecar implements RPC method/events | QR candidate helper only; no verified pair-success implementation |
8
+ | Noise/TLS-like transport trust | Managed by upstream engine | Managed by upstream engine | Managed by whatsmeow in the sidecar | Fail-closed by default; verifier must be injected and independently tested |
9
+ | Signal identity, prekeys, sessions, message crypto | Delegated to Zapo | Delegated to Baileys | Delegated to whatsmeow sidecar | Not implemented end-to-end |
10
+ | Text send and inbound message events | Delegated through `message.send` and event adapter | Delegated through `sendMessage` / `messages.upsert` | Delegated through JSONL RPC | Not supported by native high-level API |
11
+ | Image/video/audio/document/sticker | Delegated; check engine version and media package | Delegated; media upload helpers belong to Baileys | Sidecar must implement media operations | Not implemented |
12
+ | Reactions, polls, edit/delete | Delegated content object; backend support varies | Delegated content object; backend support varies | Sidecar must implement operation | Not implemented |
13
+ | Groups, contacts, app-state/history | Feature detect / backend `invoke()` | Socket methods/events / backend `invoke()` | Sidecar `invoke()` and events | Not implemented end-to-end |
14
+ | Session persistence | Zapo store providers | Baileys auth state/keys | Go store in sidecar | Generic stores and EncryptedStore, but no full native WA auth bundle |
15
+ | Multi-session facade | Supported per distinct session/client | Supported per distinct socket | Supported per distinct bridge process/session | Existing low-level manager retained; live auth not complete |
16
+ | Production live integration evidence in this ZIP | **Not run** | **Not run** | **Not run; sidecar absent** | **Not run; intentionally incomplete** |
17
+
18
+ ## Boundaries
19
+
20
+ - The engine adapters normalize the public API surface; they do not exchange live crypto keys between implementations.
21
+ - For one linked WhatsApp account, use one selected engine as the owner of transport, auth, and Signal state. Don't open the same credentials in all engines concurrently.
22
+ - Zapo and Baileys adapter tests use fake EventEmitters. The Go bridge tests use a fake child process. Tests cover event and RPC semantics only.
23
+ - Native Noise certificate verification callback returns a trusted boolean only if the caller has implemented and tested the complete chain. A callback that merely accepts all certificates defeats the default protection.
@@ -1,4 +1,4 @@
1
- # Protocol roadmap — KersioSocket v0.5.0-dev
1
+ # Protocol roadmap — KersioSocket v0.6.0-dev
2
2
 
3
3
  ## Layer saat ini
4
4
 
@@ -41,3 +41,34 @@ WebSocket transport + reconnect
41
41
  - Receiving `pair-success` is not sufficient to mark paired.
42
42
  - Session encryption depends on user-managed master key storage/rotation; a lost key means stored session values cannot be decrypted.
43
43
  - Public reverse-engineering material is not an official stable specification; record commits/blob hashes and revalidate when targeting another server build.
44
+
45
+ ## v0.6 integrated engine architecture
46
+
47
+ The high-level facade can select a maintained backend, while keeping the native protocol research layer separate:
48
+
49
+ ```text
50
+ KersioClient / KersioSessionManager
51
+ ├─ Zapo-JS WaClient adapter (auth + Signal + messages delegated upstream)
52
+ ├─ Baileys socket adapter (auth + Signal + messages delegated upstream)
53
+ ├─ Go whatsmeow JSONL-RPC process transport (the Go binary is external)
54
+ └─ native KersioSocket research transport (not a complete live WA engine)
55
+ ```
56
+
57
+ This is an API-level integration, not one merged auth/Signal state machine. A linked account must be owned by one engine at a time. The adapters are tested against mocks; real upstream integration remains a separate verification gate.
58
+
59
+ ## v0.6 local improvements
60
+
61
+ - Native Noise handshake defaults to requiring an explicitly supplied certificate verifier; no pinned WhatsApp certificate-chain verifier is included, so strict native connection intentionally fails closed until one is implemented and audited.
62
+ - `commitVerifiedPairSuccess` rejects state transitions unless an external verifier returns successful device identity, account signature and ADV-HMAC checks plus credentials/reply node. The callback contract is a safety gate, not an implementation of the cryptographic verifier.
63
+ - Common client facade, event normalization, message helpers, multi-engine session manager, bounded message archive, and cooperative local file locks.
64
+ - Go adapter implements request/reply correlation, JSONL size bound, request timeout/pending cap, abort handling, structured errors and async events. It does not bundle a Go sidecar or prove live whatsmeow connectivity.
65
+
66
+ ## Remaining native protocol gates
67
+
68
+ 1. Obtain and pin the current trusted Noise certificate/root chain, implement verification against independent vectors, and confirm behavior against a live-compatible fixture. Do not accept all certificates.
69
+ 2. Implement/test verified account pairing: device identity parsing, ADV HMAC, account/device signatures, correct `pair-device-sign` node, and atomic credential update.
70
+ 3. Implement a standards-compatible Signal layer with identity/signed prekeys, signature validation, prekey upload, session creation/rotation, group sender keys, and encrypted inbound/outbound message tests.
71
+ 4. Implement real WABinary message stanza lifecycle, receipts, offline retry/decryption retry and deduplication.
72
+ 5. Add per-backend media upload/download, group APIs, sync/app-state/status/newsletter features, each gated on live or independently captured interoperability tests.
73
+ 6. Build/compile the selected Go sidecar against a pinned whatsmeow release and run Go+Node integration tests; the bundled mock only checks bridge protocol semantics.
74
+ 7. Run real Redis/Mongo, crash-recovery, cross-process lock, long-duration memory and fair side-by-side latency tests before making production or performance claims.
@@ -23,3 +23,14 @@ Snapshot prepared for KersioSocket v0.5.0-dev. These references are useful for u
23
23
  ## Not claimed
24
24
 
25
25
  No successful live WhatsApp login/pair was observed in this build. No live WebSocket interoperability, Noise server certificate verification, Signal session crypto, or `sendMessage` is claimed. Node.js unit tests and local round-trips are only local evidence.
26
+
27
+
28
+ ## v0.6.0-dev adapter research update (2026-10-23)
29
+
30
+ This release adds adapters around public upstream client APIs rather than copying their protocol implementation into KersioSocket:
31
+
32
+ - Baileys public repository/docs: https://github.com/WhiskeySockets/Baileys — adapter targets the current socket factory/event API; upstream notes v7 has breaking changes, so pin versions and run an integration test.
33
+ - Zapo-JS public repository/docs: https://github.com/vinikjkkj/zapo — adapter targets `WaClient`, `connect()`, `message.send()`, and public auth/message events; the chosen store providers are configured by the caller.
34
+ - whatsmeow public repository: https://github.com/tulir/whatsmeow — KersioSocket only provides JSONL-RPC process transport. It does not include a Go implementation or executable; the bridge's transport tests use a fake process.
35
+
36
+ No live account/session was connected during this build. The v0.6 adapter tests demonstrate method forwarding and event normalization, not protocol interoperability or upstream-version compatibility.
package/examples/basic.js CHANGED
@@ -1,18 +1,10 @@
1
1
  'use strict'
2
2
  const { makeSocket } = require('../src')
3
3
 
4
- // Smoke test transport/Noise only. No valid login or registration ClientPayload
5
- // is present here, so a live WhatsApp server may close the socket after Noise.
6
- console.warn('[demo] transport/Noise smoke test only; this example does not log in or pair an account.')
7
-
8
- const sock = makeSocket({
9
- logger: console,
10
- reconnect: { enabled: false }
11
- })
12
-
13
- sock.ev.on('connection.update', (u) => {
14
- console.log('update:', u.connection, u.code ?? '')
15
- if (u.connection === 'noise-ready') console.log('Noise handshake OK. Stats:', sock.stats())
16
- })
17
- sock.ev.on('connection.error', (e) => console.error('error:', e.message))
18
- sock.ev.on('frame', (f) => console.log('frame', f.length, 'byte'))
4
+ // Native transport/protocol research only. It fails closed by default because this
5
+ // project version does not ship a pinned Noise certificate-chain verifier. Do not
6
+ // disable strictServerCertificateVerification for a live server.
7
+ const sock = makeSocket({ autoConnect: false, reconnect: { enabled: false } })
8
+ console.log('[KersioSocket] native research socket created; no network connection was opened.')
9
+ console.log('state:', sock.state, 'stats:', sock.stats())
10
+ sock.end()
@@ -5,3 +5,8 @@ KersioSocket implementation source is distributed under the MIT license stated i
5
5
  When `npm run refresh:tokens` is executed, the importer retrieves token **data** from [`tulir/whatsmeow`](https://github.com/tulir/whatsmeow/blob/b2b1e71d45e2ff171153b025b5a42f475bb30ef8/binary/token/token.go), commit `b2b1e71d45e2ff171153b025b5a42f475bb30ef8`, source blob SHA-1 `361acd19d93c8dea30f516e27ce8c77fdaecc56f`. That token data is identified by the upstream project as MPL-2.0. The importer saves the source license at `licenses/whatsmeow-MPL-2.0.txt` and embeds the source metadata in `src/wabinary/tokens.json`.
6
6
 
7
7
  Keep the generated metadata and license if redistributing an imported token table. The token table is reverse-engineered third-party data, not an official WhatsApp-issued table or a guarantee of current server compatibility. KersioSocket protocol/codec code is implemented separately; refer to `docs/RESEARCH-BASELINE.md` for researched source snapshots.
8
+
9
+
10
+ ## v0.6 adapter notes
11
+
12
+ The Baileys and Zapo-JS adapters invoke their public package APIs at runtime and do not bundle their implementation source. Review the currently installed upstream versions' licenses before redistributing them. The optional Go whatsmeow process bridge is an RPC transport, not a copy or bundle of whatsmeow code; whatsmeow itself is distributed under MPL-2.0. See the upstream license files before distributing a Go sidecar.
package/package.json CHANGED
@@ -1,39 +1,33 @@
1
1
  {
2
2
  "name": "kersiosocket",
3
- "version": "0.5.0-dev",
4
- "description": "Experimental WhatsApp Web protocol library with WABinary, NodeProtocol, encrypted multi-session stores and pairing research.",
3
+ "version": "0.6.0-dev",
4
+ "description": "Unified multi-engine WhatsApp Web client facade with Zapo-JS, Baileys, Go whatsmeow JSONL bridge, hardened native research transport, session archive and lock manager.",
5
5
  "main": "src/index.js",
6
6
  "engines": {
7
7
  "node": ">=22.5"
8
8
  },
9
- "files": [
10
- "src/",
11
- "examples/",
12
- "scripts/import-token-table.js",
13
- "bench/wabinary.js",
14
- "test/",
15
- "docs/",
16
- "licenses/",
17
- "README.md",
18
- "CHANGELOG.md",
19
- "BUILD-INFO.md"
20
- ],
21
9
  "scripts": {
22
10
  "test": "node --test \"test/*.test.js\"",
23
11
  "test:serial": "node --test --test-concurrency=1 \"test/*.test.js\"",
24
12
  "refresh:tokens": "node scripts/import-token-table.js",
25
- "bench:wabinary": "node bench/wabinary.js"
13
+ "bench:wabinary": "node bench/wabinary.js",
14
+ "test:backends": "node --test test/unified-client.test.js test/backend-adapters.test.js test/whatsmeow-process.test.js"
26
15
  },
27
16
  "peerDependencies": {
28
- "ws": ">=8"
17
+ "ws": ">=8",
18
+ "zapo-js": ">=1.0.0",
19
+ "@whiskeysockets/baileys": ">=7.0.0"
29
20
  },
30
21
  "peerDependenciesMeta": {
31
22
  "ws": {
32
23
  "optional": true
24
+ },
25
+ "zapo-js": {
26
+ "optional": true
27
+ },
28
+ "@whiskeysockets/baileys": {
29
+ "optional": true
33
30
  }
34
31
  },
35
- "publishConfig": {
36
- "access": "public"
37
- },
38
32
  "license": "MIT"
39
- }
33
+ }