appium-ios-remotexpc 0.0.4 → 0.0.5

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 (26) hide show
  1. package/CHANGELOG.md +6 -0
  2. package/build/src/lib/apple-tv/constants.d.ts +28 -0
  3. package/build/src/lib/apple-tv/constants.d.ts.map +1 -1
  4. package/build/src/lib/apple-tv/constants.js +35 -0
  5. package/build/src/lib/apple-tv/encryption/chacha20-poly1305.d.ts +22 -0
  6. package/build/src/lib/apple-tv/encryption/chacha20-poly1305.d.ts.map +1 -0
  7. package/build/src/lib/apple-tv/encryption/chacha20-poly1305.js +97 -0
  8. package/build/src/lib/apple-tv/encryption/ed25519.d.ts +16 -0
  9. package/build/src/lib/apple-tv/encryption/ed25519.d.ts.map +1 -0
  10. package/build/src/lib/apple-tv/encryption/ed25519.js +93 -0
  11. package/build/src/lib/apple-tv/encryption/hkdf.d.ts +18 -0
  12. package/build/src/lib/apple-tv/encryption/hkdf.d.ts.map +1 -0
  13. package/build/src/lib/apple-tv/encryption/hkdf.js +73 -0
  14. package/build/src/lib/apple-tv/encryption/index.d.ts +5 -0
  15. package/build/src/lib/apple-tv/encryption/index.d.ts.map +1 -0
  16. package/build/src/lib/apple-tv/encryption/index.js +4 -0
  17. package/build/src/lib/apple-tv/encryption/opack2.d.ts +57 -0
  18. package/build/src/lib/apple-tv/encryption/opack2.d.ts.map +1 -0
  19. package/build/src/lib/apple-tv/encryption/opack2.js +203 -0
  20. package/package.json +1 -1
  21. package/src/lib/apple-tv/constants.ts +42 -0
  22. package/src/lib/apple-tv/encryption/chacha20-poly1305.ts +147 -0
  23. package/src/lib/apple-tv/encryption/ed25519.ts +126 -0
  24. package/src/lib/apple-tv/encryption/hkdf.ts +95 -0
  25. package/src/lib/apple-tv/encryption/index.ts +11 -0
  26. package/src/lib/apple-tv/encryption/opack2.ts +257 -0
@@ -0,0 +1,203 @@
1
+ import * as constants from '../constants.js';
2
+ import { AppleTVError } from '../errors.js';
3
+ /**
4
+ * OPACK2 binary serialization format encoder
5
+ * Implements Apple's OPACK2 protocol for efficient binary serialization of structured data
6
+ */
7
+ export class Opack2 {
8
+ /**
9
+ * Serializes a JavaScript object to OPACK2 binary format
10
+ * @param obj - The object to serialize (supports primitives, arrays, objects, and Buffers)
11
+ * @returns Buffer containing the serialized data
12
+ * @throws AppleTVError if the object contains unsupported types
13
+ */
14
+ static dumps(obj) {
15
+ return this.encode(obj);
16
+ }
17
+ /**
18
+ * Main encoding dispatcher that routes values to appropriate type-specific encoders
19
+ * @param obj - Value to encode
20
+ * @returns Buffer containing encoded value
21
+ * @throws AppleTVError for unsupported types
22
+ */
23
+ static encode(obj) {
24
+ if (obj === null || obj === undefined) {
25
+ return Buffer.from([constants.OPACK2_NULL]);
26
+ }
27
+ if (typeof obj === 'boolean') {
28
+ return Buffer.from([
29
+ obj ? constants.OPACK2_TRUE : constants.OPACK2_FALSE,
30
+ ]);
31
+ }
32
+ if (typeof obj === 'number') {
33
+ return this.encodeNumber(obj);
34
+ }
35
+ if (typeof obj === 'string') {
36
+ return this.encodeString(obj);
37
+ }
38
+ if (Buffer.isBuffer(obj)) {
39
+ return this.encodeBytes(obj);
40
+ }
41
+ if (Array.isArray(obj)) {
42
+ return this.encodeArray(obj);
43
+ }
44
+ if (typeof obj === 'object' &&
45
+ !Array.isArray(obj) &&
46
+ !Buffer.isBuffer(obj)) {
47
+ return this.encodeDict(obj);
48
+ }
49
+ throw new AppleTVError(`Unsupported type for OPACK2 serialization: ${typeof obj}`);
50
+ }
51
+ /**
52
+ * Encodes numeric values with the appropriate size optimization
53
+ * @param num - Number to encode
54
+ * @returns Buffer containing encoded number
55
+ */
56
+ static encodeNumber(num) {
57
+ if (!Number.isInteger(num) || num < 0) {
58
+ const buffer = Buffer.allocUnsafe(5);
59
+ buffer[0] = constants.OPACK2_FLOAT_MARKER;
60
+ buffer.writeFloatLE(num, 1);
61
+ return buffer;
62
+ }
63
+ if (num <= constants.OPACK2_SMALL_INT_MAX) {
64
+ return Buffer.from([num + constants.OPACK2_SMALL_INT_OFFSET]);
65
+ }
66
+ if (num <= constants.OPACK2_UINT8_MAX) {
67
+ return Buffer.from([constants.OPACK2_INT8_MARKER, num]);
68
+ }
69
+ if (num <= constants.OPACK2_UINT32_MAX) {
70
+ const buffer = Buffer.allocUnsafe(5);
71
+ buffer[0] = constants.OPACK2_INT32_MARKER;
72
+ buffer.writeUInt32LE(num, 1);
73
+ return buffer;
74
+ }
75
+ if (num <= Number.MAX_SAFE_INTEGER) {
76
+ const buffer = Buffer.allocUnsafe(9);
77
+ buffer[0] = constants.OPACK2_INT64_MARKER;
78
+ buffer.writeBigUInt64LE(BigInt(num), 1);
79
+ return buffer;
80
+ }
81
+ throw new AppleTVError(`Number too large for OPACK2 encoding: ${num}`);
82
+ }
83
+ /**
84
+ * Encodes UTF-8 strings with length-optimized headers
85
+ * @param str - String to encode
86
+ * @returns Buffer containing encoded string
87
+ */
88
+ static encodeString(str) {
89
+ const encoded = Buffer.from(str, 'utf8');
90
+ const length = encoded.length;
91
+ if (length <= constants.OPACK2_SMALL_STRING_MAX) {
92
+ return Buffer.concat([
93
+ Buffer.from([constants.OPACK2_SMALL_STRING_BASE + length]),
94
+ encoded,
95
+ ]);
96
+ }
97
+ if (length <= constants.OPACK2_UINT8_MAX) {
98
+ return Buffer.concat([
99
+ Buffer.from([constants.OPACK2_STRING_8BIT_LEN_MARKER, length]),
100
+ encoded,
101
+ ]);
102
+ }
103
+ if (length <= constants.OPACK2_UINT16_MAX) {
104
+ const header = Buffer.allocUnsafe(3);
105
+ header[0] = constants.OPACK2_STRING_16BIT_LEN_MARKER;
106
+ header.writeUInt16BE(length, 1);
107
+ return Buffer.concat([header, encoded]);
108
+ }
109
+ if (length <= constants.OPACK2_UINT32_MAX) {
110
+ const header = Buffer.allocUnsafe(5);
111
+ header[0] = constants.OPACK2_STRING_32BIT_LEN_MARKER;
112
+ header.writeUInt32BE(length, 1);
113
+ return Buffer.concat([header, encoded]);
114
+ }
115
+ throw new AppleTVError(`String too long for OPACK2 encoding: ${length} bytes`);
116
+ }
117
+ /**
118
+ * Encodes binary data with length-optimized headers
119
+ * @param bytes - Buffer to encode
120
+ * @returns Buffer containing encoded binary data
121
+ */
122
+ static encodeBytes(bytes) {
123
+ const length = bytes.length;
124
+ if (length <= constants.OPACK2_SMALL_BYTES_MAX) {
125
+ return Buffer.concat([
126
+ Buffer.from([constants.OPACK2_SMALL_BYTES_BASE + length]),
127
+ bytes,
128
+ ]);
129
+ }
130
+ if (length <= constants.OPACK2_UINT8_MAX) {
131
+ return Buffer.concat([
132
+ Buffer.from([constants.OPACK2_BYTES_8BIT_LEN_MARKER, length]),
133
+ bytes,
134
+ ]);
135
+ }
136
+ if (length <= constants.OPACK2_UINT16_MAX) {
137
+ const header = Buffer.allocUnsafe(3);
138
+ header[0] = constants.OPACK2_BYTES_16BIT_LEN_MARKER;
139
+ header.writeUInt16BE(length, 1);
140
+ return Buffer.concat([header, bytes]);
141
+ }
142
+ if (length <= constants.OPACK2_UINT32_MAX) {
143
+ const header = Buffer.allocUnsafe(5);
144
+ header[0] = constants.OPACK2_BYTES_32BIT_LEN_MARKER;
145
+ header.writeUInt32BE(length, 1);
146
+ return Buffer.concat([header, bytes]);
147
+ }
148
+ throw new AppleTVError(`Byte array too long for OPACK2 encoding: ${length} bytes`);
149
+ }
150
+ /**
151
+ * Encodes arrays with count-optimized headers
152
+ * @param arr - Array to encode
153
+ * @returns Buffer containing encoded array
154
+ */
155
+ static encodeArray(arr) {
156
+ const length = arr.length;
157
+ if (length <= constants.OPACK2_SMALL_ARRAY_MAX) {
158
+ const parts = [
159
+ Buffer.from([constants.OPACK2_SMALL_ARRAY_BASE + length]),
160
+ ];
161
+ for (const item of arr) {
162
+ parts.push(this.encode(item));
163
+ }
164
+ return Buffer.concat(parts);
165
+ }
166
+ const parts = [
167
+ Buffer.from([constants.OPACK2_VARIABLE_ARRAY_MARKER]),
168
+ ];
169
+ for (const item of arr) {
170
+ parts.push(this.encode(item));
171
+ }
172
+ parts.push(Buffer.from([constants.OPACK2_NULL]));
173
+ return Buffer.concat(parts);
174
+ }
175
+ /**
176
+ * Encodes objects/dictionaries with count-optimized headers
177
+ * @param dict - Object to encode
178
+ * @returns Buffer containing encoded dictionary
179
+ */
180
+ static encodeDict(dict) {
181
+ const entries = Object.entries(dict);
182
+ const length = entries.length;
183
+ if (length < constants.OPACK2_SMALL_DICT_MAX) {
184
+ const parts = [
185
+ Buffer.from([constants.OPACK2_SMALL_DICT_BASE + length]),
186
+ ];
187
+ for (const [key, value] of entries) {
188
+ parts.push(this.encode(key));
189
+ parts.push(this.encode(value));
190
+ }
191
+ return Buffer.concat(parts);
192
+ }
193
+ const parts = [
194
+ Buffer.from([constants.OPACK2_VARIABLE_DICT_MARKER]),
195
+ ];
196
+ for (const [key, value] of entries) {
197
+ parts.push(this.encode(key));
198
+ parts.push(this.encode(value));
199
+ }
200
+ parts.push(Buffer.from([constants.OPACK2_NULL, constants.OPACK2_NULL]));
201
+ return Buffer.concat(parts);
202
+ }
203
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "appium-ios-remotexpc",
3
- "version": "0.0.4",
3
+ "version": "0.0.5",
4
4
  "main": "build/src/index.js",
5
5
  "types": "build/src/index.d.ts",
6
6
  "type": "module",
@@ -81,3 +81,45 @@ export const HKDF_HASH_ALGORITHM = 'sha512';
81
81
 
82
82
  // Output length (in bytes) for HKDF key derivation
83
83
  export const HKDF_HASH_LENGTH = 64;
84
+
85
+ // OPACK2 encoding constants
86
+ export const OPACK2_NULL = 0x03;
87
+ export const OPACK2_TRUE = 0x01;
88
+ export const OPACK2_FALSE = 0x02;
89
+ export const OPACK2_SMALL_INT_OFFSET = 8;
90
+ export const OPACK2_SMALL_INT_MAX = 0x27;
91
+ export const OPACK2_SMALL_STRING_MAX = 0x20;
92
+ export const OPACK2_SMALL_BYTES_MAX = 0x20;
93
+ export const OPACK2_SMALL_ARRAY_MAX = 15;
94
+ export const OPACK2_SMALL_DICT_MAX = 15;
95
+
96
+ // OPACK2 number type markers
97
+ export const OPACK2_INT8_MARKER = 0x30;
98
+ export const OPACK2_INT32_MARKER = 0x32;
99
+ export const OPACK2_INT64_MARKER = 0x33;
100
+ export const OPACK2_FLOAT_MARKER = 0x35;
101
+
102
+ // OPACK2 string type markers
103
+ export const OPACK2_SMALL_STRING_BASE = 0x40;
104
+ export const OPACK2_STRING_8BIT_LEN_MARKER = 0x61;
105
+ export const OPACK2_STRING_16BIT_LEN_MARKER = 0x62;
106
+ export const OPACK2_STRING_32BIT_LEN_MARKER = 0x63;
107
+
108
+ // OPACK2 bytes type markers
109
+ export const OPACK2_SMALL_BYTES_BASE = 0x70;
110
+ export const OPACK2_BYTES_8BIT_LEN_MARKER = 0x91;
111
+ export const OPACK2_BYTES_16BIT_LEN_MARKER = 0x92;
112
+ export const OPACK2_BYTES_32BIT_LEN_MARKER = 0x93;
113
+
114
+ // OPACK2 array type markers
115
+ export const OPACK2_SMALL_ARRAY_BASE = 0xd0;
116
+ export const OPACK2_VARIABLE_ARRAY_MARKER = 0xdf;
117
+
118
+ // OPACK2 dictionary type markers
119
+ export const OPACK2_SMALL_DICT_BASE = 0xe0;
120
+ export const OPACK2_VARIABLE_DICT_MARKER = 0xef;
121
+
122
+ // OPACK2 size limits
123
+ export const OPACK2_UINT8_MAX = 0xff;
124
+ export const OPACK2_UINT16_MAX = 0xffff;
125
+ export const OPACK2_UINT32_MAX = 0xffffffff;
@@ -0,0 +1,147 @@
1
+ import { logger } from '@appium/support';
2
+ import { createCipheriv, createDecipheriv } from 'node:crypto';
3
+
4
+ import { CryptographyError } from '../errors.js';
5
+
6
+ const log = logger.getLogger('ChaCha20Poly1305');
7
+
8
+ export interface ChaCha20Poly1305Params {
9
+ plaintext?: Buffer;
10
+ ciphertext?: Buffer;
11
+ key: Buffer;
12
+ nonce: Buffer;
13
+ aad?: Buffer;
14
+ }
15
+
16
+ interface DecryptionAttempt {
17
+ tagLen: number;
18
+ aad?: Buffer;
19
+ }
20
+
21
+ /**
22
+ * Encrypts data using ChaCha20-Poly1305 AEAD cipher
23
+ * @param params - Encryption parameters including plaintext, key, nonce, and optional AAD
24
+ * @returns Buffer containing encrypted data concatenated with authentication tag
25
+ * @throws CryptographyError if encryption fails or required parameters are missing
26
+ */
27
+ export function encryptChaCha20Poly1305(
28
+ params: ChaCha20Poly1305Params,
29
+ ): Buffer {
30
+ const { plaintext, key, nonce, aad } = params;
31
+
32
+ if (!plaintext) {
33
+ throw new CryptographyError('Plaintext is required for encryption');
34
+ }
35
+
36
+ if (!key || key.length !== 32) {
37
+ throw new CryptographyError('Key must be 32 bytes');
38
+ }
39
+
40
+ if (!nonce || nonce.length !== 12) {
41
+ throw new CryptographyError('Nonce must be 12 bytes');
42
+ }
43
+
44
+ try {
45
+ const cipher = createCipheriv('chacha20-poly1305', key, nonce) as any;
46
+
47
+ if (aad) {
48
+ cipher.setAAD(aad, { plaintextLength: plaintext.length });
49
+ }
50
+
51
+ const encrypted = Buffer.concat([cipher.update(plaintext), cipher.final()]);
52
+ const authTag = cipher.getAuthTag();
53
+
54
+ return Buffer.concat([encrypted, authTag]);
55
+ } catch (error) {
56
+ log.error('ChaCha20-Poly1305 encryption failed:', error);
57
+ const message = error instanceof Error ? error.message : String(error);
58
+ throw new CryptographyError(
59
+ `ChaCha20-Poly1305 encryption failed: ${message}`,
60
+ );
61
+ }
62
+ }
63
+
64
+ /**
65
+ * Decrypts data using ChaCha20-Poly1305 AEAD cipher with multiple fallback strategies
66
+ * @param params - Decryption parameters including ciphertext, key, nonce, and optional AAD
67
+ * @returns Buffer containing decrypted plaintext
68
+ * @throws CryptographyError if all decryption attempts fail or required parameters are missing
69
+ */
70
+ export function decryptChaCha20Poly1305(
71
+ params: ChaCha20Poly1305Params,
72
+ ): Buffer {
73
+ const { ciphertext, key, nonce, aad } = params;
74
+
75
+ if (!ciphertext) {
76
+ throw new CryptographyError('Ciphertext is required for decryption');
77
+ }
78
+
79
+ if (!key || key.length !== 32) {
80
+ throw new CryptographyError('Key must be 32 bytes');
81
+ }
82
+
83
+ if (!nonce || nonce.length !== 12) {
84
+ throw new CryptographyError('Nonce must be 12 bytes');
85
+ }
86
+
87
+ if (ciphertext.length < 16) {
88
+ throw new CryptographyError(
89
+ 'Ciphertext too short to contain authentication tag',
90
+ );
91
+ }
92
+
93
+ // ChaCha20-Poly1305 in Node.js only supports 16-byte authentication tags
94
+ const tagLength = 16;
95
+ const decryptionAttempts: DecryptionAttempt[] = [
96
+ { tagLen: tagLength, aad },
97
+ { tagLen: tagLength, aad: Buffer.alloc(0) },
98
+ { tagLen: tagLength, aad: undefined },
99
+ ];
100
+
101
+ let lastError: Error | undefined;
102
+
103
+ for (const attempt of decryptionAttempts) {
104
+ try {
105
+ const encrypted = ciphertext.subarray(
106
+ 0,
107
+ ciphertext.length - attempt.tagLen,
108
+ );
109
+ const authTag = ciphertext.subarray(ciphertext.length - attempt.tagLen);
110
+
111
+ const decipher = createDecipheriv('chacha20-poly1305', key, nonce) as any;
112
+ decipher.setAuthTag(authTag);
113
+
114
+ if (attempt.aad !== undefined) {
115
+ decipher.setAAD(attempt.aad, { plaintextLength: encrypted.length });
116
+ }
117
+
118
+ const decrypted = Buffer.concat([
119
+ decipher.update(encrypted),
120
+ decipher.final(),
121
+ ]);
122
+
123
+ log.debug(
124
+ 'Decryption successful with AAD:',
125
+ attempt.aad ? 'provided' : 'none',
126
+ );
127
+ return decrypted;
128
+ } catch (error) {
129
+ lastError = error instanceof Error ? error : new Error(String(error));
130
+ }
131
+ }
132
+
133
+ const errorMessage = lastError
134
+ ? `ChaCha20-Poly1305 decryption failed: ${lastError.message}`
135
+ : 'ChaCha20-Poly1305 decryption failed: invalid ciphertext or authentication tag';
136
+
137
+ // Log the error with stack trace for debugging real failures
138
+ // Skip logging in test environment to avoid cluttering test output with expected failures
139
+ if (lastError && process.env.NODE_ENV !== 'test') {
140
+ log.error('All ChaCha20-Poly1305 decryption attempts failed:', {
141
+ message: lastError.message,
142
+ stack: lastError.stack,
143
+ });
144
+ }
145
+
146
+ throw new CryptographyError(errorMessage);
147
+ }
@@ -0,0 +1,126 @@
1
+ import { logger } from '@appium/support';
2
+ import {
3
+ type KeyPairKeyObjectResult,
4
+ generateKeyPairSync,
5
+ sign,
6
+ } from 'node:crypto';
7
+
8
+ import { CryptographyError } from '../errors.js';
9
+ import type { PairingKeys } from '../types.js';
10
+
11
+ const log = logger.getLogger('Ed25519');
12
+
13
+ const ED25519_PUBLIC_KEY_LENGTH = 32;
14
+ const ED25519_PRIVATE_KEY_LENGTH = 32;
15
+ const ED25519_PKCS8_PREFIX = Buffer.from(
16
+ '302e020100300506032b657004220420',
17
+ 'hex',
18
+ );
19
+
20
+ /**
21
+ * Generates a new Ed25519 key pair for cryptographic operations
22
+ * @returns PairingKeys object containing 32-byte public and private key buffers
23
+ * @throws CryptographyError if key generation fails
24
+ */
25
+ export function generateEd25519KeyPair(): PairingKeys {
26
+ try {
27
+ const keyPair: KeyPairKeyObjectResult = generateKeyPairSync('ed25519');
28
+
29
+ const publicKeyDer = keyPair.publicKey.export({
30
+ type: 'spki',
31
+ format: 'der',
32
+ }) as Buffer;
33
+
34
+ const privateKeyDer = keyPair.privateKey.export({
35
+ type: 'pkcs8',
36
+ format: 'der',
37
+ }) as Buffer;
38
+
39
+ const publicKeyBuffer = extractEd25519PublicKey(publicKeyDer);
40
+ const privateKeyBuffer = extractEd25519PrivateKey(privateKeyDer);
41
+
42
+ return {
43
+ publicKey: publicKeyBuffer,
44
+ privateKey: privateKeyBuffer,
45
+ };
46
+ } catch (error) {
47
+ log.error('Failed to generate Ed25519 key pair:', error);
48
+ const message = error instanceof Error ? error.message : String(error);
49
+ throw new CryptographyError(
50
+ `Failed to generate Ed25519 key pair: ${message}`,
51
+ );
52
+ }
53
+ }
54
+
55
+ /**
56
+ * Creates an Ed25519 digital signature for the provided data
57
+ * @param data - The data to sign
58
+ * @param privateKey - 32-byte Ed25519 private key
59
+ * @returns Buffer containing the 64-byte signature
60
+ * @throws CryptographyError if signing fails or private key is invalid
61
+ */
62
+ export function createEd25519Signature(
63
+ data: Buffer,
64
+ privateKey: Buffer,
65
+ ): Buffer {
66
+ if (!data || data.length === 0) {
67
+ throw new CryptographyError('Data to sign cannot be empty');
68
+ }
69
+
70
+ if (!privateKey || privateKey.length !== ED25519_PRIVATE_KEY_LENGTH) {
71
+ throw new CryptographyError(
72
+ `Private key must be ${ED25519_PRIVATE_KEY_LENGTH} bytes`,
73
+ );
74
+ }
75
+
76
+ try {
77
+ const privateKeyDer = Buffer.concat([ED25519_PKCS8_PREFIX, privateKey]);
78
+
79
+ return sign(null, data, {
80
+ key: privateKeyDer,
81
+ format: 'der',
82
+ type: 'pkcs8',
83
+ });
84
+ } catch (error) {
85
+ log.error('Failed to create Ed25519 signature:', error);
86
+ const message = error instanceof Error ? error.message : String(error);
87
+ throw new CryptographyError(
88
+ `Failed to create Ed25519 signature: ${message}`,
89
+ );
90
+ }
91
+ }
92
+
93
+ /**
94
+ * Extracts the raw 32-byte public key from DER-encoded SPKI format
95
+ * @param publicKeyDer - DER-encoded public key
96
+ * @returns 32-byte public key buffer
97
+ * @throws CryptographyError if extraction fails
98
+ */
99
+ function extractEd25519PublicKey(publicKeyDer: Buffer): Buffer {
100
+ if (publicKeyDer.length < ED25519_PUBLIC_KEY_LENGTH) {
101
+ throw new CryptographyError('Invalid public key DER format');
102
+ }
103
+
104
+ return publicKeyDer.subarray(publicKeyDer.length - ED25519_PUBLIC_KEY_LENGTH);
105
+ }
106
+
107
+ /**
108
+ * Extracts the raw 32-byte private key from DER-encoded PKCS#8 format
109
+ * @param privateKeyDer - DER-encoded private key
110
+ * @returns 32-byte private key buffer
111
+ * @throws CryptographyError if extraction fails
112
+ */
113
+ function extractEd25519PrivateKey(privateKeyDer: Buffer): Buffer {
114
+ const octetStringPattern = Buffer.from([0x04, 0x20]);
115
+ const index = privateKeyDer.indexOf(octetStringPattern);
116
+
117
+ if (index !== -1 && index + 34 <= privateKeyDer.length) {
118
+ return privateKeyDer.subarray(index + 2, index + 34);
119
+ }
120
+
121
+ if (privateKeyDer.length >= 48) {
122
+ return privateKeyDer.subarray(16, 48);
123
+ }
124
+
125
+ throw new CryptographyError('Unable to extract private key from DER format');
126
+ }
@@ -0,0 +1,95 @@
1
+ import { logger } from '@appium/support';
2
+ import { createHmac } from 'node:crypto';
3
+
4
+ import { HKDF_HASH_ALGORITHM, HKDF_HASH_LENGTH } from '../constants.js';
5
+ import { CryptographyError } from '../errors.js';
6
+
7
+ const log = logger.getLogger('HKDF');
8
+
9
+ export interface HKDFParams {
10
+ ikm: Buffer;
11
+ salt: Buffer | null;
12
+ info: Buffer;
13
+ length: number;
14
+ }
15
+
16
+ const MAX_OUTPUT_LENGTH = 255 * HKDF_HASH_LENGTH;
17
+
18
+ /**
19
+ * HMAC-based Key Derivation Function (HKDF) as defined in RFC 5869
20
+ * Derives cryptographic keys from input key material using a two-step process:
21
+ * 1. Extract: Generate a pseudorandom key from the input key material
22
+ * 2. Expand: Expand the pseudorandom key to the desired output length
23
+ *
24
+ * @param params - HKDF parameters including input key material, salt, info, and desired output length
25
+ * @returns Buffer containing the derived key material of specified length
26
+ * @throws CryptographyError if derivation fails or parameters are invalid
27
+ */
28
+ export function hkdf(params: HKDFParams): Buffer {
29
+ const { ikm, salt, info, length } = params;
30
+
31
+ if (!ikm || ikm.length === 0) {
32
+ throw new CryptographyError('Input key material (IKM) cannot be empty');
33
+ }
34
+
35
+ if (!info) {
36
+ throw new CryptographyError('Info parameter is required');
37
+ }
38
+
39
+ if (length <= 0) {
40
+ throw new CryptographyError('Output length must be positive');
41
+ }
42
+
43
+ if (length > MAX_OUTPUT_LENGTH) {
44
+ throw new CryptographyError(
45
+ `Output length cannot exceed ${MAX_OUTPUT_LENGTH} bytes`,
46
+ );
47
+ }
48
+
49
+ try {
50
+ const extractedKey = hkdfExtract(ikm, salt);
51
+ return hkdfExpand(extractedKey, info, length);
52
+ } catch (error) {
53
+ log.error('HKDF derivation failed:', error);
54
+ const message = error instanceof Error ? error.message : String(error);
55
+ throw new CryptographyError(`HKDF derivation failed: ${message}`);
56
+ }
57
+ }
58
+
59
+ /**
60
+ * HKDF Extract step: generates a pseudorandom key from input key material
61
+ * @param ikm - Input key material
62
+ * @param salt - Optional salt value (uses zero salt if null)
63
+ * @returns Pseudorandom key of hash length
64
+ */
65
+ function hkdfExtract(ikm: Buffer, salt: Buffer | null): Buffer {
66
+ const actualSalt = salt || Buffer.alloc(HKDF_HASH_LENGTH);
67
+ return createHmac(HKDF_HASH_ALGORITHM, actualSalt).update(ikm).digest();
68
+ }
69
+
70
+ /**
71
+ * HKDF Expand a step: expands a pseudorandom key to desired output length
72
+ * @param prk - Pseudorandom key from extract step
73
+ * @param info - Context and application specific information
74
+ * @param length - Desired output key material length
75
+ * @returns Output key material of specified length
76
+ */
77
+ function hkdfExpand(prk: Buffer, info: Buffer, length: number): Buffer {
78
+ const numberOfBlocks = Math.ceil(length / HKDF_HASH_LENGTH);
79
+ const blocks: Buffer[] = [];
80
+ let previousBlock: Buffer = Buffer.alloc(0);
81
+
82
+ for (let blockIndex = 1; blockIndex <= numberOfBlocks; blockIndex++) {
83
+ const hmac = createHmac(HKDF_HASH_ALGORITHM, prk);
84
+ hmac.update(previousBlock);
85
+ hmac.update(info);
86
+ hmac.update(Buffer.from([blockIndex]));
87
+
88
+ const currentBlock = hmac.digest();
89
+ blocks.push(currentBlock);
90
+ previousBlock = currentBlock;
91
+ }
92
+
93
+ const outputKeyMaterial = Buffer.concat(blocks);
94
+ return outputKeyMaterial.subarray(0, length);
95
+ }
@@ -0,0 +1,11 @@
1
+ export { Opack2 } from './opack2.js';
2
+
3
+ export {
4
+ encryptChaCha20Poly1305,
5
+ decryptChaCha20Poly1305,
6
+ type ChaCha20Poly1305Params,
7
+ } from './chacha20-poly1305.js';
8
+
9
+ export { generateEd25519KeyPair, createEd25519Signature } from './ed25519.js';
10
+
11
+ export { hkdf, type HKDFParams } from './hkdf.js';