@zapo-js/fake-server 1.1.0 → 1.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (66) hide show
  1. package/README.md +89 -30
  2. package/dist/api/FakeMobilePrimary.d.ts +55 -0
  3. package/dist/api/FakeMobilePrimary.js +106 -0
  4. package/dist/api/FakePairingDriver.js +1 -3
  5. package/dist/api/FakeServerSession.d.ts +35 -2
  6. package/dist/api/FakeServerSession.js +65 -3
  7. package/dist/api/FakeWaServer.d.ts +73 -1
  8. package/dist/api/FakeWaServer.js +230 -4
  9. package/dist/api/ServerRegistries.d.ts +7 -0
  10. package/dist/api/ServerRegistries.js +20 -5
  11. package/dist/api/iq-handlers.d.ts +19 -1
  12. package/dist/api/iq-handlers.js +96 -1
  13. package/dist/esm/api/FakeMobilePrimary.js +102 -0
  14. package/dist/esm/api/FakePairingDriver.js +2 -4
  15. package/dist/esm/api/FakeServerSession.js +66 -4
  16. package/dist/esm/api/FakeWaServer.js +230 -4
  17. package/dist/esm/api/ServerRegistries.js +20 -5
  18. package/dist/esm/api/iq-handlers.js +96 -1
  19. package/dist/esm/index.js +8 -0
  20. package/dist/esm/infra/WaFakeConnection.js +8 -22
  21. package/dist/esm/infra/WaFakeConnectionPipeline.js +17 -5
  22. package/dist/esm/infra/WaFakeTcpServer.js +69 -0
  23. package/dist/esm/infra/WaFakeWsServer.js +2 -1
  24. package/dist/esm/infra/socket-adapters.js +79 -0
  25. package/dist/esm/protocol/auth/client-payload-validate.js +77 -1
  26. package/dist/esm/protocol/auth/pair-device.js +16 -1
  27. package/dist/esm/protocol/iq/companion-host.js +104 -0
  28. package/dist/esm/protocol/iq/link-code.js +90 -0
  29. package/dist/esm/protocol/iq/router.js +3 -3
  30. package/dist/esm/protocol/push/mobile-notification.js +97 -0
  31. package/dist/esm/state/fake-companion-host.js +158 -0
  32. package/dist/esm/transport/auth.js +7 -0
  33. package/dist/esm/transport/crypto.js +1 -1
  34. package/dist/esm/transport/util.js +1 -0
  35. package/dist/index.d.ts +17 -2
  36. package/dist/index.js +28 -1
  37. package/dist/infra/WaFakeConnection.d.ts +21 -3
  38. package/dist/infra/WaFakeConnection.js +8 -22
  39. package/dist/infra/WaFakeConnectionPipeline.d.ts +1 -0
  40. package/dist/infra/WaFakeConnectionPipeline.js +17 -5
  41. package/dist/infra/WaFakeTcpServer.d.ts +29 -0
  42. package/dist/infra/WaFakeTcpServer.js +73 -0
  43. package/dist/infra/WaFakeWsServer.js +2 -1
  44. package/dist/infra/socket-adapters.d.ts +18 -0
  45. package/dist/infra/socket-adapters.js +83 -0
  46. package/dist/protocol/auth/client-payload-validate.d.ts +24 -0
  47. package/dist/protocol/auth/client-payload-validate.js +77 -1
  48. package/dist/protocol/auth/pair-device.d.ts +15 -1
  49. package/dist/protocol/auth/pair-device.js +16 -0
  50. package/dist/protocol/iq/companion-host.d.ts +52 -0
  51. package/dist/protocol/iq/companion-host.js +109 -0
  52. package/dist/protocol/iq/link-code.d.ts +46 -0
  53. package/dist/protocol/iq/link-code.js +95 -0
  54. package/dist/protocol/iq/router.d.ts +15 -2
  55. package/dist/protocol/iq/router.js +3 -3
  56. package/dist/protocol/push/mobile-notification.d.ts +58 -0
  57. package/dist/protocol/push/mobile-notification.js +102 -0
  58. package/dist/state/fake-companion-host.d.ts +73 -0
  59. package/dist/state/fake-companion-host.js +163 -0
  60. package/dist/transport/auth.d.ts +8 -0
  61. package/dist/transport/auth.js +8 -0
  62. package/dist/transport/crypto.d.ts +1 -1
  63. package/dist/transport/crypto.js +2 -1
  64. package/dist/transport/util.d.ts +1 -0
  65. package/dist/transport/util.js +2 -1
  66. package/package.json +1 -1
@@ -5,12 +5,36 @@ export interface RegistrationPayload {
5
5
  readonly raw: Proto.IClientPayload;
6
6
  readonly devicePairingData: NonNullable<Proto.IClientPayload['devicePairingData']>;
7
7
  }
8
+ /**
9
+ * Transport flavor a login `ClientPayload` was built for. `web` covers the
10
+ * companion/WhatsApp Web payload, `mobile` the phone payload sent over the
11
+ * mobile TCP transport.
12
+ */
13
+ export type ClientPayloadFlavor = 'web' | 'mobile';
14
+ /** Phone identity a mobile login advertises in its `UserAgent`. */
15
+ export interface MobileLoginDetails {
16
+ readonly manufacturer: string;
17
+ readonly device: string;
18
+ readonly osVersion: string;
19
+ readonly osBuildNumber: string;
20
+ /** Dotted Android app version rebuilt from the `AppVersion` message. */
21
+ readonly appVersion: string;
22
+ readonly phoneId: string;
23
+ readonly mcc: string;
24
+ readonly mnc: string;
25
+ readonly pushName: string | null;
26
+ readonly yearClass: number | null;
27
+ readonly memClass: number | null;
28
+ }
8
29
  export interface LoginPayload {
9
30
  readonly kind: 'login';
10
31
  readonly raw: Proto.IClientPayload;
11
32
  readonly username: string;
12
33
  readonly device: number;
13
34
  readonly loginCounter: number;
35
+ readonly flavor: ClientPayloadFlavor;
36
+ /** Phone details for a `mobile` login; `null` for a web login. */
37
+ readonly mobile: MobileLoginDetails | null;
14
38
  }
15
39
  export type ParsedClientPayload = RegistrationPayload | LoginPayload;
16
40
  export declare class ClientPayloadValidationError extends Error {
@@ -32,14 +32,90 @@ function parseClientPayload(bytes) {
32
32
  if (raw.username === undefined || raw.username === null) {
33
33
  throw new ClientPayloadValidationError('missing_username', 'login ClientPayload is missing the username field');
34
34
  }
35
+ const flavor = resolveLoginFlavor(raw);
35
36
  return {
36
37
  kind: 'login',
37
38
  raw,
38
39
  username: String(raw.username),
39
40
  device: typeof raw.device === 'number' ? raw.device : 0,
40
- loginCounter: typeof raw.lc === 'number' ? raw.lc : 0
41
+ loginCounter: typeof raw.lc === 'number' ? raw.lc : 0,
42
+ flavor,
43
+ mobile: flavor === 'mobile' ? parseMobileDetails(raw) : null
41
44
  };
42
45
  }
46
+ /**
47
+ * Resolves the transport flavor of a login payload. `webInfo` and the `WEB`
48
+ * platform mark a companion; a phone is identified by the device fields only
49
+ * the mobile payload carries. Sniffing those fields (rather than the platform
50
+ * enum alone) is deliberate: `ANDROID` is the zero value of the enum, so a
51
+ * payload that omits `platform` entirely would otherwise read as mobile.
52
+ */
53
+ function resolveLoginFlavor(raw) {
54
+ if (raw.webInfo) {
55
+ return 'web';
56
+ }
57
+ const userAgent = raw.userAgent;
58
+ if (!userAgent || userAgent.platform === protos_1.proto.ClientPayload.UserAgent.Platform.WEB) {
59
+ return 'web';
60
+ }
61
+ return userAgent.manufacturer && userAgent.device ? 'mobile' : 'web';
62
+ }
63
+ function parseMobileDetails(raw) {
64
+ const userAgent = raw.userAgent;
65
+ if (!userAgent) {
66
+ throw new ClientPayloadValidationError('missing_field', 'mobile login ClientPayload is missing the userAgent');
67
+ }
68
+ const required = [
69
+ ['manufacturer', 'device manufacturer'],
70
+ ['device', 'device model'],
71
+ ['osVersion', 'os version'],
72
+ ['osBuildNumber', 'os build number'],
73
+ ['phoneId', 'phone id']
74
+ ];
75
+ for (const [field, label] of required) {
76
+ const value = userAgent[field];
77
+ if (value === undefined || value === null || value === '') {
78
+ throw new ClientPayloadValidationError('missing_field', `mobile login ClientPayload missing ${label} (userAgent.${String(field)})`);
79
+ }
80
+ }
81
+ const appVersion = userAgent.appVersion;
82
+ if (!appVersion || appVersion.primary === undefined || appVersion.primary === null) {
83
+ throw new ClientPayloadValidationError('missing_field', 'mobile login ClientPayload missing the app version (userAgent.appVersion)');
84
+ }
85
+ return {
86
+ manufacturer: String(userAgent.manufacturer),
87
+ device: String(userAgent.device),
88
+ osVersion: String(userAgent.osVersion),
89
+ osBuildNumber: String(userAgent.osBuildNumber),
90
+ appVersion: formatAppVersion(appVersion),
91
+ phoneId: String(userAgent.phoneId),
92
+ mcc: userAgent.mcc ? String(userAgent.mcc) : '000',
93
+ mnc: userAgent.mnc ? String(userAgent.mnc) : '000',
94
+ pushName: typeof raw.pushName === 'string' ? raw.pushName : null,
95
+ yearClass: toOptionalNumber(raw.yearClass),
96
+ memClass: toOptionalNumber(raw.memClass)
97
+ };
98
+ }
99
+ function formatAppVersion(version) {
100
+ const parts = [
101
+ version.primary,
102
+ version.secondary,
103
+ version.tertiary,
104
+ version.quaternary,
105
+ version.quinary
106
+ ];
107
+ const present = [];
108
+ for (const part of parts) {
109
+ if (part === undefined || part === null) {
110
+ break;
111
+ }
112
+ present.push(Number(part));
113
+ }
114
+ return present.join('.');
115
+ }
116
+ function toOptionalNumber(value) {
117
+ return typeof value === 'number' && Number.isFinite(value) ? value : null;
118
+ }
43
119
  function validateRegistrationFields(devicePairingData) {
44
120
  const required = [
45
121
  ['eIdent', 'identity public key'],
@@ -1,8 +1,22 @@
1
1
  /** Pairing IQ builders/parsers (source: `WAWebHandlePairDevice*`, `/wa-web`). */
2
2
  import type { BinaryNode } from '../../transport/codec';
3
+ /**
4
+ * Mints the rotating refs a `pair-device` push carries.
5
+ *
6
+ * They are printable on purpose. A client reads `<ref>` as text and pastes it
7
+ * into a comma-separated QR payload, so raw random bytes can decode into a
8
+ * comma or a newline and quietly corrupt whatever reads that payload back -
9
+ * including the primary that has to echo the ref in its upload.
10
+ */
11
+ export declare function mintPairingRefs(count?: number): Promise<string[]>;
3
12
  export interface BuildPairDeviceIqInput {
4
13
  readonly id?: string;
5
- readonly refs: readonly Uint8Array[];
14
+ /**
15
+ * The six rotating refs the companion turns into a QR. The client reads
16
+ * them as text, so a primary-driven link (where the ref has to survive the
17
+ * round trip back in the primary's upload) issues printable strings.
18
+ */
19
+ readonly refs: readonly (Uint8Array | string)[];
6
20
  }
7
21
  export declare function buildPairDeviceIq(input: BuildPairDeviceIqInput): BinaryNode;
8
22
  export interface BuildPairSuccessIqInput {
@@ -1,10 +1,26 @@
1
1
  "use strict";
2
2
  /** Pairing IQ builders/parsers (source: `WAWebHandlePairDevice*`, `/wa-web`). */
3
3
  Object.defineProperty(exports, "__esModule", { value: true });
4
+ exports.mintPairingRefs = mintPairingRefs;
4
5
  exports.buildPairDeviceIq = buildPairDeviceIq;
5
6
  exports.buildPairSuccessIq = buildPairSuccessIq;
6
7
  exports.parsePairingQrString = parsePairingQrString;
8
+ const crypto_1 = require("../../transport/crypto");
7
9
  const util_1 = require("../../transport/util");
10
+ const PAIR_DEVICE_REF_COUNT = 6;
11
+ const PAIR_DEVICE_REF_BYTES = 16;
12
+ /**
13
+ * Mints the rotating refs a `pair-device` push carries.
14
+ *
15
+ * They are printable on purpose. A client reads `<ref>` as text and pastes it
16
+ * into a comma-separated QR payload, so raw random bytes can decode into a
17
+ * comma or a newline and quietly corrupt whatever reads that payload back -
18
+ * including the primary that has to echo the ref in its upload.
19
+ */
20
+ async function mintPairingRefs(count = PAIR_DEVICE_REF_COUNT) {
21
+ const raw = await Promise.all(Array.from({ length: count }, () => (0, crypto_1.randomBytesAsync)(PAIR_DEVICE_REF_BYTES)));
22
+ return raw.map((bytes) => (0, util_1.bytesToBase64UrlSafe)(bytes));
23
+ }
8
24
  function buildPairDeviceIq(input) {
9
25
  if (input.refs.length !== 6) {
10
26
  throw new Error(`pair-device requires exactly 6 refs, got ${input.refs.length}`);
@@ -0,0 +1,52 @@
1
+ /**
2
+ * Primary-side `md` IQ parsers: a phone hosting companion devices.
3
+ *
4
+ * These are the inverse of `protocol/auth/pair-device.ts`, which drives the
5
+ * companion side. Here the client is the primary: it signs a companion's device
6
+ * identity and uploads it, republishes its key-index list, and revokes devices.
7
+ */
8
+ import type { BinaryNode } from '../../transport/codec';
9
+ export interface ParsedPairDeviceUpload {
10
+ /** Pairing ref the companion advertised in its QR. */
11
+ readonly ref: string;
12
+ readonly companionNoisePublicKey: Uint8Array;
13
+ /** `ADVSignedDeviceIdentityHMAC` bytes the primary signed. */
14
+ readonly deviceIdentityBytes: Uint8Array;
15
+ /** `ADVSignedKeyIndexList` bytes for the account's device set. */
16
+ readonly keyIndexListBytes: Uint8Array;
17
+ readonly keyIndexListTimestampSeconds: number;
18
+ /** Encoded `ClientPairingProps`, when the primary declared them. */
19
+ readonly clientPropsBytes: Uint8Array | null;
20
+ /** AES-GCM key from the optional `<pem>` element. */
21
+ readonly pemKeyBytes: Uint8Array | null;
22
+ }
23
+ /**
24
+ * Parses the primary's `<iq type="set" xmlns="md"><pair-device>` upload.
25
+ * Returns `null` when the stanza is not a well-formed pair-device upload, which
26
+ * lets the router fall through to another handler.
27
+ */
28
+ export declare function parsePairDeviceUpload(iq: BinaryNode): ParsedPairDeviceUpload | null;
29
+ export interface ParsedKeyIndexListPublish {
30
+ readonly keyIndexListBytes: Uint8Array;
31
+ readonly timestampSeconds: number;
32
+ }
33
+ /**
34
+ * Parses the standalone key-index-list republish the primary sends whenever its
35
+ * companion set changes. Returns `null` when the stanza carries no list.
36
+ */
37
+ export declare function parseKeyIndexListPublish(iq: BinaryNode): ParsedKeyIndexListPublish | null;
38
+ export interface ParsedRemoveCompanionDevice {
39
+ /** Device to unlink; `null` when the stanza revokes every companion. */
40
+ readonly deviceJid: string | null;
41
+ /** `all="true"` – the phone's "log out all companion devices". */
42
+ readonly all: boolean;
43
+ readonly reason: string;
44
+ readonly excludeHostedCompanion: boolean;
45
+ }
46
+ /**
47
+ * Parses `<remove-companion-device>`. The same stanza serves a companion
48
+ * logging itself out (`jid` = its own device) and a primary unlinking one of
49
+ * its companions, so the caller decides by comparing against the connection's
50
+ * own jid.
51
+ */
52
+ export declare function parseRemoveCompanionDevice(iq: BinaryNode): ParsedRemoveCompanionDevice | null;
@@ -0,0 +1,109 @@
1
+ "use strict";
2
+ /**
3
+ * Primary-side `md` IQ parsers: a phone hosting companion devices.
4
+ *
5
+ * These are the inverse of `protocol/auth/pair-device.ts`, which drives the
6
+ * companion side. Here the client is the primary: it signs a companion's device
7
+ * identity and uploads it, republishes its key-index list, and revokes devices.
8
+ */
9
+ Object.defineProperty(exports, "__esModule", { value: true });
10
+ exports.parsePairDeviceUpload = parsePairDeviceUpload;
11
+ exports.parseKeyIndexListPublish = parseKeyIndexListPublish;
12
+ exports.parseRemoveCompanionDevice = parseRemoveCompanionDevice;
13
+ const util_1 = require("../../transport/util");
14
+ /**
15
+ * Parses the primary's `<iq type="set" xmlns="md"><pair-device>` upload.
16
+ * Returns `null` when the stanza is not a well-formed pair-device upload, which
17
+ * lets the router fall through to another handler.
18
+ */
19
+ function parsePairDeviceUpload(iq) {
20
+ const pairDevice = findChild(iq, 'pair-device');
21
+ if (!pairDevice) {
22
+ return null;
23
+ }
24
+ const ref = readText(findChild(pairDevice, 'ref'));
25
+ const companionNoisePublicKey = readBytes(findChild(pairDevice, 'pub-key'));
26
+ const deviceIdentityBytes = readBytes(findChild(pairDevice, 'device-identity'));
27
+ const keyIndexList = findChild(pairDevice, 'key-index-list');
28
+ const keyIndexListBytes = readBytes(keyIndexList);
29
+ if (!ref || !companionNoisePublicKey || !deviceIdentityBytes || !keyIndexListBytes) {
30
+ return null;
31
+ }
32
+ return {
33
+ ref,
34
+ companionNoisePublicKey,
35
+ deviceIdentityBytes,
36
+ keyIndexListBytes,
37
+ keyIndexListTimestampSeconds: readTimestampSeconds(keyIndexList),
38
+ clientPropsBytes: readBytes(findChild(pairDevice, 'client-props')),
39
+ pemKeyBytes: readPemKey(pairDevice)
40
+ };
41
+ }
42
+ /**
43
+ * Parses the standalone key-index-list republish the primary sends whenever its
44
+ * companion set changes. Returns `null` when the stanza carries no list.
45
+ */
46
+ function parseKeyIndexListPublish(iq) {
47
+ const keyIndexList = findChild(iq, 'key-index-list');
48
+ const keyIndexListBytes = readBytes(keyIndexList);
49
+ if (!keyIndexListBytes) {
50
+ return null;
51
+ }
52
+ return {
53
+ keyIndexListBytes,
54
+ timestampSeconds: readTimestampSeconds(keyIndexList)
55
+ };
56
+ }
57
+ /**
58
+ * Parses `<remove-companion-device>`. The same stanza serves a companion
59
+ * logging itself out (`jid` = its own device) and a primary unlinking one of
60
+ * its companions, so the caller decides by comparing against the connection's
61
+ * own jid.
62
+ */
63
+ function parseRemoveCompanionDevice(iq) {
64
+ const remove = findChild(iq, 'remove-companion-device');
65
+ if (!remove) {
66
+ return null;
67
+ }
68
+ const jid = remove.attrs.jid;
69
+ return {
70
+ deviceJid: typeof jid === 'string' && jid.length > 0 ? jid : null,
71
+ all: remove.attrs.all === 'true',
72
+ reason: typeof remove.attrs.reason === 'string' ? remove.attrs.reason : '',
73
+ excludeHostedCompanion: remove.attrs.exclude_hosted_companion === 'true'
74
+ };
75
+ }
76
+ function findChild(parent, tag) {
77
+ if (!Array.isArray(parent.content)) {
78
+ return null;
79
+ }
80
+ return parent.content.find((child) => child.tag === tag) ?? null;
81
+ }
82
+ function readBytes(node) {
83
+ if (!node) {
84
+ return null;
85
+ }
86
+ return node.content instanceof Uint8Array ? node.content : null;
87
+ }
88
+ function readText(node) {
89
+ if (!node) {
90
+ return null;
91
+ }
92
+ if (typeof node.content === 'string') {
93
+ return node.content;
94
+ }
95
+ return node.content instanceof Uint8Array ? util_1.TEXT_DECODER.decode(node.content) : null;
96
+ }
97
+ function readTimestampSeconds(node) {
98
+ const raw = node?.attrs.ts;
99
+ const parsed = typeof raw === 'string' ? Number.parseInt(raw, 10) : Number.NaN;
100
+ return Number.isFinite(parsed) ? parsed : 0;
101
+ }
102
+ /** The `<pem>` wrapper nests the key bytes in a second `<pem>` element. */
103
+ function readPemKey(pairDevice) {
104
+ const pem = findChild(pairDevice, 'pem');
105
+ if (!pem) {
106
+ return null;
107
+ }
108
+ return readBytes(findChild(pem, 'pem'));
109
+ }
@@ -0,0 +1,46 @@
1
+ /**
2
+ * Link-code (pairing-code) relay stanzas.
3
+ *
4
+ * The handshake runs between two clients with the server in the middle: the
5
+ * companion asks for a code (`companion_hello`), the primary answers with its
6
+ * wrapped ephemeral (`primary_hello`), and the companion closes with the key
7
+ * bundle (`companion_finish`). Each stage arrives as an IQ from one client and
8
+ * leaves as a notification to the other; the server only routes and mints the
9
+ * ref that ties the three together.
10
+ */
11
+ import type { BinaryNode } from '../../transport/codec';
12
+ export type LinkCodeStage = 'companion_hello' | 'primary_hello' | 'companion_finish';
13
+ export interface ParsedLinkCodeStanza {
14
+ readonly stage: LinkCodeStage;
15
+ /** Account the companion wants to link to, on the stages that carry it. */
16
+ readonly phoneJid: string | null;
17
+ /** Ref the stage refers to; absent on `companion_hello`, which mints it. */
18
+ readonly ref: string | null;
19
+ /** The stage's payload elements, relayed verbatim to the other client. */
20
+ readonly children: readonly BinaryNode[];
21
+ }
22
+ /**
23
+ * Parses a `<link_code_companion_reg>` IQ. Returns `null` for a stage this
24
+ * server does not relay (for example `get_country_code`), letting the router
25
+ * fall through to another handler.
26
+ */
27
+ export declare function parseLinkCodeStanza(iq: BinaryNode): ParsedLinkCodeStanza | null;
28
+ /**
29
+ * Builds the `companion_hello` IQ result carrying the ref the server minted.
30
+ * The companion keys its whole pairing session off it.
31
+ */
32
+ export declare function buildCompanionHelloResultContent(ref: string): BinaryNode[];
33
+ export interface BuildLinkCodeNotificationInput {
34
+ readonly stage: LinkCodeStage;
35
+ readonly ref: string;
36
+ /** Payload elements copied from the originating stanza. */
37
+ readonly children: readonly BinaryNode[];
38
+ readonly id?: string;
39
+ readonly to?: string;
40
+ }
41
+ /**
42
+ * Wraps a relayed stage as the notification the receiving client handles. The
43
+ * ref is (re)stamped so the receiver can match it against its pairing session,
44
+ * replacing any copy carried by the source stanza.
45
+ */
46
+ export declare function buildLinkCodeNotification(input: BuildLinkCodeNotificationInput): BinaryNode;
@@ -0,0 +1,95 @@
1
+ "use strict";
2
+ /**
3
+ * Link-code (pairing-code) relay stanzas.
4
+ *
5
+ * The handshake runs between two clients with the server in the middle: the
6
+ * companion asks for a code (`companion_hello`), the primary answers with its
7
+ * wrapped ephemeral (`primary_hello`), and the companion closes with the key
8
+ * bundle (`companion_finish`). Each stage arrives as an IQ from one client and
9
+ * leaves as a notification to the other; the server only routes and mints the
10
+ * ref that ties the three together.
11
+ */
12
+ Object.defineProperty(exports, "__esModule", { value: true });
13
+ exports.parseLinkCodeStanza = parseLinkCodeStanza;
14
+ exports.buildCompanionHelloResultContent = buildCompanionHelloResultContent;
15
+ exports.buildLinkCodeNotification = buildLinkCodeNotification;
16
+ const util_1 = require("../../transport/util");
17
+ const RELAYED_STAGES = new Set([
18
+ 'companion_hello',
19
+ 'primary_hello',
20
+ 'companion_finish'
21
+ ]);
22
+ /**
23
+ * Parses a `<link_code_companion_reg>` IQ. Returns `null` for a stage this
24
+ * server does not relay (for example `get_country_code`), letting the router
25
+ * fall through to another handler.
26
+ */
27
+ function parseLinkCodeStanza(iq) {
28
+ const node = findChild(iq, 'link_code_companion_reg');
29
+ const stage = node?.attrs.stage;
30
+ if (!node || typeof stage !== 'string' || !RELAYED_STAGES.has(stage)) {
31
+ return null;
32
+ }
33
+ const jid = node.attrs.jid;
34
+ return {
35
+ stage: stage,
36
+ phoneJid: typeof jid === 'string' && jid.length > 0 ? jid : null,
37
+ ref: readText(findChild(node, 'link_code_pairing_ref')),
38
+ children: Array.isArray(node.content) ? node.content : []
39
+ };
40
+ }
41
+ /**
42
+ * Builds the `companion_hello` IQ result carrying the ref the server minted.
43
+ * The companion keys its whole pairing session off it.
44
+ */
45
+ function buildCompanionHelloResultContent(ref) {
46
+ return [
47
+ {
48
+ tag: 'link_code_companion_reg',
49
+ attrs: { stage: 'companion_hello' },
50
+ content: [{ tag: 'link_code_pairing_ref', attrs: {}, content: ref }]
51
+ }
52
+ ];
53
+ }
54
+ /**
55
+ * Wraps a relayed stage as the notification the receiving client handles. The
56
+ * ref is (re)stamped so the receiver can match it against its pairing session,
57
+ * replacing any copy carried by the source stanza.
58
+ */
59
+ function buildLinkCodeNotification(input) {
60
+ const children = input.children.filter((child) => child.tag !== 'link_code_pairing_ref');
61
+ return {
62
+ tag: 'notification',
63
+ attrs: {
64
+ id: input.id ?? `link-code-${Math.random().toString(36).slice(2, 10)}`,
65
+ from: 's.whatsapp.net',
66
+ type: 'link_code_companion_reg',
67
+ ...(input.to !== undefined ? { to: input.to } : {})
68
+ },
69
+ content: [
70
+ {
71
+ tag: 'link_code_companion_reg',
72
+ attrs: { stage: input.stage },
73
+ content: [
74
+ { tag: 'link_code_pairing_ref', attrs: {}, content: input.ref },
75
+ ...children
76
+ ]
77
+ }
78
+ ]
79
+ };
80
+ }
81
+ function findChild(parent, tag) {
82
+ if (!Array.isArray(parent.content)) {
83
+ return null;
84
+ }
85
+ return parent.content.find((child) => child.tag === tag) ?? null;
86
+ }
87
+ function readText(node) {
88
+ if (!node) {
89
+ return null;
90
+ }
91
+ if (typeof node.content === 'string') {
92
+ return node.content;
93
+ }
94
+ return node.content instanceof Uint8Array ? util_1.TEXT_DECODER.decode(node.content) : null;
95
+ }
@@ -1,6 +1,19 @@
1
1
  /** IQ matcher/dispatcher used by the fake server. */
2
2
  import type { BinaryNode } from '../../transport/codec';
3
+ import type { ParsedClientPayload } from '../auth/client-payload-validate';
3
4
  export type WaFakeIqType = 'get' | 'set';
5
+ /**
6
+ * The connection an IQ arrived on. Handlers that relay between two clients
7
+ * (companion pairing, link-code) need to know who is asking; `WaFakeConnection
8
+ * Pipeline` satisfies this structurally.
9
+ */
10
+ export interface WaFakeIqConnection {
11
+ sendStanza(node: BinaryNode): Promise<void>;
12
+ readonly clientPayload: ParsedClientPayload | null;
13
+ }
14
+ export interface WaFakeIqContext {
15
+ readonly connection: WaFakeIqConnection;
16
+ }
4
17
  export interface WaFakeIqMatcher {
5
18
  readonly id?: string;
6
19
  readonly type?: WaFakeIqType;
@@ -13,7 +26,7 @@ export interface WaFakeIqMatcher {
13
26
  * high-priority handler observe an IQ (capture, log, assert) while the
14
27
  * default handler still answers it.
15
28
  */
16
- export type WaFakeIqResponder = (iq: BinaryNode) => BinaryNode | null | Promise<BinaryNode | null>;
29
+ export type WaFakeIqResponder = (iq: BinaryNode, context?: WaFakeIqContext) => BinaryNode | null | Promise<BinaryNode | null>;
17
30
  export interface WaFakeIqHandler {
18
31
  readonly matcher: WaFakeIqMatcher;
19
32
  readonly respond: WaFakeIqResponder;
@@ -31,7 +44,7 @@ export declare class WaFakeIqRouter {
31
44
  readonly priority?: 'high' | 'default';
32
45
  }): () => void;
33
46
  setEvents(events: WaFakeIqRouterEvents): void;
34
- route(iq: BinaryNode): Promise<BinaryNode | null>;
47
+ route(iq: BinaryNode, context?: WaFakeIqContext): Promise<BinaryNode | null>;
35
48
  }
36
49
  export declare function buildIqResult(inbound: BinaryNode, options?: {
37
50
  readonly from?: string;
@@ -24,13 +24,13 @@ class WaFakeIqRouter {
24
24
  setEvents(events) {
25
25
  this.events = events;
26
26
  }
27
- async route(iq) {
27
+ async route(iq, context) {
28
28
  if (iq.tag !== 'iq') {
29
29
  return null;
30
30
  }
31
31
  for (const handler of this.highPriorityHandlers) {
32
32
  if (matches(iq, handler.matcher)) {
33
- const response = await handler.respond(iq);
33
+ const response = await handler.respond(iq, context);
34
34
  if (response !== null) {
35
35
  return response;
36
36
  }
@@ -38,7 +38,7 @@ class WaFakeIqRouter {
38
38
  }
39
39
  for (const handler of this.handlers) {
40
40
  if (matches(iq, handler.matcher)) {
41
- const response = await handler.respond(iq);
41
+ const response = await handler.respond(iq, context);
42
42
  if (response !== null) {
43
43
  return response;
44
44
  }
@@ -0,0 +1,58 @@
1
+ /**
2
+ * Push notifications only a phone receives.
3
+ *
4
+ * `account_sync` carries the account's live device set: the primary keys its
5
+ * companion bookkeeping off it, allocating a fresh key index for the next link
6
+ * and dropping companions the server no longer lists. The registration
7
+ * notifications carry the login code and the takeover warning that fire while
8
+ * a number is being moved to another phone.
9
+ */
10
+ import type { BinaryNode } from '../../transport/codec';
11
+ export interface FakeAccountDevice {
12
+ readonly deviceJid: string;
13
+ /** ADV key index of the device; the primary keeps every listed one valid. */
14
+ readonly keyIndex?: number;
15
+ readonly deviceLid?: string;
16
+ }
17
+ export interface BuildAccountSyncDevicesInput {
18
+ readonly devices: readonly FakeAccountDevice[];
19
+ readonly id?: string;
20
+ readonly from?: string;
21
+ readonly timestampSeconds?: number;
22
+ }
23
+ /**
24
+ * Builds `<notification type="account_sync">` with the account's `<devices>`
25
+ * list. Every device the account still owns must be present: the primary reads
26
+ * this as authoritative and prunes anything missing from it.
27
+ */
28
+ export declare function buildAccountSyncDevicesNotification(input: BuildAccountSyncDevicesInput): BinaryNode;
29
+ export interface BuildRegistrationCodeNotificationInput {
30
+ /** The login code shown on the new device. */
31
+ readonly code: string;
32
+ /** Device that requested it, as reported by the server. */
33
+ readonly fromDeviceId: string;
34
+ readonly expirySeconds?: number;
35
+ readonly id?: string;
36
+ readonly from?: string;
37
+ }
38
+ /**
39
+ * Builds the `<notification type="registration">` carrying a login code, which
40
+ * the client surfaces as `mobile_registration_code`.
41
+ */
42
+ export declare function buildRegistrationCodeNotification(input: BuildRegistrationCodeNotificationInput): BinaryNode;
43
+ export interface BuildAccountTakeoverNoticeInput {
44
+ /** Server token that identifies the takeover attempt. */
45
+ readonly serverToken: string;
46
+ readonly attemptTimestampSeconds?: number;
47
+ readonly newDeviceName?: string;
48
+ readonly newDevicePlatform?: string;
49
+ readonly newDeviceAppVersion?: string;
50
+ readonly id?: string;
51
+ readonly from?: string;
52
+ }
53
+ /**
54
+ * Builds the `<notification type="registration">` warning that the number is
55
+ * being registered on another phone, surfaced as
56
+ * `mobile_account_takeover_notice`.
57
+ */
58
+ export declare function buildAccountTakeoverNotice(input: BuildAccountTakeoverNoticeInput): BinaryNode;