@proit365/multikey-auth 0.0.0-stage → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 ProIT365
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,130 @@
1
- # Temporary Holding Version
2
-
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
1
+ # JavaScript SDK
2
+
3
+ `@proit365/multikey-auth` is a CommonJS client SDK for MKAP v1. It obtains a
4
+ server-issued challenge and creates an HMAC-SHA256 proof bound to the exact
5
+ HTTP method, request target, and request-body bytes. The SDK uses Node.js built-in
6
+ modules only and has no runtime dependencies.
7
+
8
+ ## Requirements and installation
9
+
10
+ - Node.js 22 or newer, as declared by the package.
11
+ - A server-side Node.js environment. This package is not browser-compatible.
12
+ - A client export generated for the corresponding MKAP client and pool.
13
+
14
+ ```sh
15
+ npm install @proit365/multikey-auth
16
+ ```
17
+
18
+ The package is CommonJS. Use `require()`:
19
+
20
+ ```js
21
+ const { MkapClient } = require('@proit365/multikey-auth');
22
+ ```
23
+
24
+ TypeScript consumers also need Node.js type declarations (for example,
25
+ `@types/node`) because the public API accepts and returns `Buffer` values.
26
+
27
+ ## Configuration and request workflow
28
+
29
+ `baseUri` must be an origin (scheme and host only). HTTPS is required by default.
30
+ `poolVersion`, `identifierLength`, and `identifierAlphabet` must match the
31
+ provided client export. Supply either `exportPath` or `exportJson`; the export
32
+ contains the client's secret key material.
33
+
34
+ ```js
35
+ const { MkapClient } = require('@proit365/multikey-auth');
36
+
37
+ const client = new MkapClient({
38
+ baseUri: 'https://api.example.test',
39
+ clientId: 'CLIENT_001',
40
+ poolVersion: 1,
41
+ identifierLength: 6,
42
+ identifierAlphabet: 'abcdefghijklmnopqrstuvwxyz0123456789',
43
+ exportPath: '/secure/client-export.json'
44
+ });
45
+
46
+ async function main() {
47
+ const response = await client.request(
48
+ 'POST',
49
+ '/api/orders?status=pending',
50
+ Buffer.from('{"status":"pending"}', 'utf8')
51
+ );
52
+ console.log(response.statusCode);
53
+ }
54
+
55
+ main().catch((error) => {
56
+ console.error('Authenticated request failed:', error.message);
57
+ process.exitCode = 1;
58
+ });
59
+ ```
60
+
61
+ For each call, `MkapClient.request()`:
62
+
63
+ 1. Validates the method and origin-form request target and hashes the exact
64
+ request-body bytes. Targets that URL parsing would normalize are rejected;
65
+ percent-encode non-ASCII path or query data.
66
+ 2. Requests a challenge from `POST /v1/auth/challenges`.
67
+ 3. Validates the challenge fields and selected key identifiers against the
68
+ local export.
69
+ 4. Derives the proof key with HKDF-SHA256 and creates an HMAC-SHA256 proof.
70
+ 5. Sends the original request with the MKAP authentication headers.
71
+
72
+ The SDK does not retry a `401` or replay requests. A final API response,
73
+ including non-2xx statuses, is returned to the caller as an `HttpResponse`.
74
+
75
+ ## API
76
+
77
+ - `new MkapClient(config, transport?)`: create a client. Required configuration
78
+ includes `baseUri`, `clientId`, `poolVersion`, `identifierLength`,
79
+ `identifierAlphabet`, and one of `exportPath` or `exportJson`. HTTPS is
80
+ required unless `requireHttps: false` is explicitly supplied for non-production
81
+ use. `maximumChallengeResponseBytes` defaults to 65,536.
82
+ - `MkapClient.request(method, target, body?)`: send a signed request. `body` may
83
+ be a `Buffer`, string, or omitted; strings are encoded as UTF-8.
84
+ - `MkapClient.parseChallenge(body)`: validate and parse a challenge response;
85
+ normally called internally by `request()`.
86
+ - `NodeHttpTransport(options?)`: built-in Node HTTP(S) transport. HTTPS is
87
+ required unless its `requireHttps` option is false. It does not follow
88
+ redirects and returns 3xx responses unchanged.
89
+ - `HttpTransport`: interface for a custom transport. Its `send()` method must
90
+ preserve the supplied method, URL, authentication headers, and body bytes.
91
+ A custom transport may add application headers such as `Content-Type`.
92
+ - Export and protocol helpers are also exported: `loadExportJson`,
93
+ `loadExportFile`, `validateExport`, `encodeBase64Url`, `decodeBase64Url`,
94
+ `uint32`, `uint64`, `lengthField`, `hmacSha256`, `hkdfSha256`, `hkdfContext`,
95
+ `proofMessage`, and `requestUrl`.
96
+
97
+ ## Errors and transport behavior
98
+
99
+ Invalid configuration, methods, targets, exports, or challenge responses throw
100
+ errors. A non-2xx challenge response throws an error with its `statusCode`.
101
+ Transport failures reject the request promise. The final API response status is
102
+ not converted into an exception; handle it according to your API's contract.
103
+
104
+ The default `NodeHttpTransport` enforces HTTPS, does not follow redirects, and
105
+ rejects URLs with credentials. A custom transport must enforce equivalent
106
+ transport security and must send the exact signed target and body bytes.
107
+
108
+ ## Security
109
+
110
+ Treat the client export and its secret keys as credentials: restrict access,
111
+ keep them out of source control and logs, and do not include them in browser
112
+ bundles. Use HTTPS in production; do not set `requireHttps: false` for deployed
113
+ services. Do not send secret exports to untrusted systems.
114
+
115
+ MKAP is a custom protocol. The repository includes cross-language test vectors,
116
+ but the protocol has not been independently security reviewed. Review the
117
+ [MKAP monorepo security guidance](https://github.com/proit365/multikey-auth)
118
+ before production use.
119
+
120
+ ## Browser limitation
121
+
122
+ This package requires Node.js built-ins including `crypto`, `http`, `https`,
123
+ `fs`, and `Buffer`; it does not provide a browser build. Do not bundle this SDK
124
+ or a plaintext key export into browser JavaScript. Browser use requires a
125
+ separate backend-for-frontend or device-bound credential design.
126
+
127
+ ## Project
128
+
129
+ The authoritative source, protocol specification, and other SDKs are in the
130
+ [ProIT365 MultiKey Auth monorepo](https://github.com/proit365/multikey-auth).
package/package.json CHANGED
@@ -1,6 +1,36 @@
1
- {
2
- "name": "@proit365/multikey-auth",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
1
+ {
2
+ "name": "@proit365/multikey-auth",
3
+ "version": "1.0.0",
4
+ "description": "Node.js client SDK for ProIT365 MultiKey Auth (MKAP), creating challenge-response proofs for authenticated API requests.",
5
+ "type": "commonjs",
6
+ "main": "src/index.js",
7
+ "types": "types/index.d.ts",
8
+ "license": "MIT",
9
+ "homepage": "https://github.com/proit365/multikey-auth",
10
+ "repository": {
11
+ "type": "git",
12
+ "url": "https://github.com/proit365/multikey-auth.git",
13
+ "directory": "packages/javascript"
14
+ },
15
+ "engines": {
16
+ "node": ">=22"
17
+ },
18
+ "scripts": {
19
+ "test": "node test/interoperability.test.js"
20
+ },
21
+ "files": [
22
+ "src/",
23
+ "types/",
24
+ "README.md",
25
+ "LICENSE"
26
+ ],
27
+ "keywords": [
28
+ "mkap",
29
+ "nodejs",
30
+ "authentication",
31
+ "api-authentication",
32
+ "challenge-response",
33
+ "hmac",
34
+ "hkdf"
35
+ ]
36
+ }
package/src/client.js ADDED
@@ -0,0 +1,251 @@
1
+ 'use strict';
2
+
3
+ const crypto = require('crypto');
4
+ const { encodeBase64Url, decodeBase64Url } = require('./encoding');
5
+ const { hkdfSha256, hkdfContext, proofMessage, hmacSha256 } = require('./cryptography');
6
+ const { loadExportJson, loadExportFile } = require('./export');
7
+ const { requestUrl, NodeHttpTransport } = require('./transport');
8
+ const { URL } = require('url');
9
+
10
+ function validateUtf8(value, name, maximumBytes) {
11
+ if (typeof value !== 'string') {
12
+ throw new TypeError(name + ' must be a string');
13
+ }
14
+ const bytes = Buffer.byteLength(value, 'utf8');
15
+ if (bytes < 1 || bytes > maximumBytes) {
16
+ throw new Error(name + ' length is outside the supported range');
17
+ }
18
+ if (Buffer.from(value, 'utf8').toString('utf8') !== value) {
19
+ throw new Error(name + ' must be valid UTF-8');
20
+ }
21
+ return bytes;
22
+ }
23
+
24
+ function validateMethod(method) {
25
+ if (!/^[!#$%&'*+.^_`|~0-9A-Z-]{1,32}$/.test(method)) {
26
+ throw new Error('HTTP method must be an uppercase token');
27
+ }
28
+ }
29
+
30
+ function validateTarget(target) {
31
+ validateUtf8(target, 'Request target', 4096);
32
+ if (!target.startsWith('/')
33
+ || target.includes('#')
34
+ || /[\u0000-\u0020\u007f]/.test(target)) {
35
+ throw new Error('Invalid origin-form request target');
36
+ }
37
+ }
38
+
39
+ class MkapClient {
40
+ constructor(config, transport) {
41
+ if (!config || typeof config !== 'object') {
42
+ throw new TypeError('Client config is required');
43
+ }
44
+ if (!config.baseUri || !config.clientId || !config.exportJson && !config.exportPath) {
45
+ throw new Error('Client configuration is incomplete');
46
+ }
47
+ validateUtf8(config.clientId, 'Client identifier', 128);
48
+ let baseUrl;
49
+ try {
50
+ baseUrl = new URL(config.baseUri);
51
+ } catch (error) {
52
+ throw new Error('Base URI is invalid');
53
+ }
54
+ if (!['https:', 'http:'].includes(baseUrl.protocol)
55
+ || baseUrl.username
56
+ || baseUrl.password
57
+ || baseUrl.search
58
+ || baseUrl.hash
59
+ || (baseUrl.pathname !== '/' && baseUrl.pathname !== '')) {
60
+ throw new Error('Base URI must be an origin with no credentials, path, query, or fragment');
61
+ }
62
+ if (config.requireHttps !== false && baseUrl.protocol !== 'https:') {
63
+ throw new Error('HTTPS is required');
64
+ }
65
+ if (!Number.isInteger(config.poolVersion) || config.poolVersion < 1) {
66
+ throw new Error('Pool version must be positive');
67
+ }
68
+ if (!Number.isInteger(config.identifierLength)
69
+ || config.identifierLength < 1 || config.identifierLength > 256) {
70
+ throw new Error('Identifier length is outside the supported range');
71
+ }
72
+ if (typeof config.identifierAlphabet !== 'string'
73
+ || config.identifierAlphabet.length === 0
74
+ || new Set(Array.from(config.identifierAlphabet)).size !== Array.from(config.identifierAlphabet).length) {
75
+ throw new Error('Identifier alphabet is invalid');
76
+ }
77
+
78
+ let pool;
79
+ if (config.exportJson) {
80
+ pool = loadExportJson(config.exportJson);
81
+ } else {
82
+ pool = loadExportFile(config.exportPath);
83
+ }
84
+ if (pool.clientId !== config.clientId
85
+ || pool.poolVersion !== config.poolVersion
86
+ || pool.identifierLength !== config.identifierLength
87
+ || pool.identifierAlphabet !== config.identifierAlphabet) {
88
+ throw new Error('Client configuration does not match the export');
89
+ }
90
+
91
+ this.config = Object.assign({ maximumChallengeResponseBytes: 65536 }, config);
92
+ this.pool = pool;
93
+ this.transport = transport || new NodeHttpTransport({
94
+ requireHttps: config.requireHttps !== false
95
+ });
96
+ }
97
+
98
+ async request(method, target, body) {
99
+ validateMethod(method);
100
+ validateTarget(target);
101
+ const bodyBuffer = Buffer.isBuffer(body)
102
+ ? Buffer.from(body)
103
+ : Buffer.from(body || '', 'utf8');
104
+ if (bodyBuffer.length > 16777216) {
105
+ throw new Error('Request body is too large');
106
+ }
107
+ const bodyHash = crypto.createHash('sha256').update(bodyBuffer).digest();
108
+ const apiUrl = requestUrl(this.config.baseUri, target);
109
+
110
+ const challengeRequest = {
111
+ version: 1,
112
+ client_id: this.config.clientId,
113
+ method,
114
+ target,
115
+ body_sha256: encodeBase64Url(bodyHash)
116
+ };
117
+ const challengeUrl = requestUrl(this.config.baseUri, '/v1/auth/challenges');
118
+ const challengeResponse = await this.transport.send({
119
+ method: 'POST',
120
+ url: challengeUrl.toString(),
121
+ headers: {
122
+ 'Accept': 'application/json',
123
+ 'Content-Type': 'application/json'
124
+ },
125
+ body: Buffer.from(JSON.stringify(challengeRequest))
126
+ });
127
+ if (challengeResponse.statusCode < 200 || challengeResponse.statusCode >= 300) {
128
+ const error = new Error('Challenge endpoint returned HTTP ' + challengeResponse.statusCode);
129
+ error.statusCode = challengeResponse.statusCode;
130
+ throw error;
131
+ }
132
+ if (challengeResponse.body.length > this.config.maximumChallengeResponseBytes) {
133
+ throw new Error('Challenge response exceeds the configured size limit');
134
+ }
135
+
136
+ const challenge = this.parseChallenge(challengeResponse.body);
137
+ const selectedSecrets = [];
138
+ for (const keyId of challenge.keyIds) {
139
+ const secret = this.pool.secrets.get(keyId);
140
+ if (!secret) {
141
+ throw new Error('Challenge selected a key absent from the local export');
142
+ }
143
+ selectedSecrets.push(secret);
144
+ }
145
+
146
+ const ikm = Buffer.concat(selectedSecrets);
147
+ const proofKey = hkdfSha256(
148
+ ikm,
149
+ challenge.nonce,
150
+ hkdfContext(
151
+ challenge.version,
152
+ this.config.clientId,
153
+ challenge.requestId,
154
+ this.config.poolVersion,
155
+ challenge.keyIds
156
+ ),
157
+ 32
158
+ );
159
+ const message = proofMessage(
160
+ challenge.version,
161
+ this.config.clientId,
162
+ challenge.requestId,
163
+ challenge.nonce,
164
+ challenge.expiresAt,
165
+ method,
166
+ target,
167
+ bodyHash,
168
+ this.config.poolVersion,
169
+ challenge.keyIds
170
+ );
171
+ const proof = hmacSha256(proofKey, message);
172
+
173
+ return this.transport.send({
174
+ method,
175
+ url: apiUrl.toString(),
176
+ headers: {
177
+ 'X-MKAP-Version': '1',
178
+ 'X-MKAP-Client': this.config.clientId,
179
+ 'X-MKAP-Request': encodeBase64Url(challenge.requestId),
180
+ 'X-MKAP-Proof': encodeBase64Url(proof)
181
+ },
182
+ body: bodyBuffer
183
+ });
184
+ }
185
+
186
+ parseChallenge(body) {
187
+ let data;
188
+ try {
189
+ data = JSON.parse(body.toString('utf8'));
190
+ } catch (error) {
191
+ throw new Error('Challenge response is not valid JSON');
192
+ }
193
+ if (!data || typeof data !== 'object' || Array.isArray(data)) {
194
+ throw new Error('Challenge response must be a JSON object');
195
+ }
196
+ const fields = ['version', 'request_id', 'nonce', 'key_ids', 'key_count', 'id_length', 'expires_in', 'expires_at'];
197
+ for (const field of fields) {
198
+ if (!Object.prototype.hasOwnProperty.call(data, field)) {
199
+ throw new Error('Challenge response is missing field: ' + field);
200
+ }
201
+ }
202
+ if (data.version !== 1
203
+ || typeof data.request_id !== 'string'
204
+ || typeof data.nonce !== 'string'
205
+ || typeof data.key_ids !== 'string'
206
+ || !Number.isInteger(data.key_count)
207
+ || !Number.isInteger(data.id_length)
208
+ || !Number.isInteger(data.expires_in)
209
+ || !Number.isInteger(data.expires_at)
210
+ || data.key_count < 1
211
+ || data.key_count > this.pool.secrets.size
212
+ || data.id_length !== this.pool.identifierLength
213
+ || data.expires_in < 1
214
+ || data.expires_at < 1
215
+ || data.key_ids.length !== data.key_count * data.id_length) {
216
+ throw new Error('Challenge response fields are invalid');
217
+ }
218
+
219
+ const requestId = decodeBase64Url(data.request_id, 16);
220
+ const nonce = decodeBase64Url(data.nonce, 32);
221
+ if (encodeBase64Url(requestId) !== data.request_id
222
+ || encodeBase64Url(nonce) !== data.nonce) {
223
+ throw new Error('Challenge binary fields must use canonical base64url');
224
+ }
225
+ const keyIds = [];
226
+ for (let offset = 0; offset < data.key_ids.length; offset += data.id_length) {
227
+ keyIds.push(data.key_ids.slice(offset, offset + data.id_length));
228
+ }
229
+ if (new Set(keyIds).size !== keyIds.length) {
230
+ throw new Error('Challenge key identifiers are duplicated');
231
+ }
232
+ for (const keyId of keyIds) {
233
+ for (const character of keyId) {
234
+ if (!this.pool.identifierAlphabet.includes(character)) {
235
+ throw new Error('Challenge key identifier contains an invalid character');
236
+ }
237
+ }
238
+ }
239
+ return {
240
+ version: data.version,
241
+ requestId,
242
+ nonce,
243
+ keyIds,
244
+ expiresAt: data.expires_at
245
+ };
246
+ }
247
+ }
248
+
249
+ module.exports = {
250
+ MkapClient
251
+ };
@@ -0,0 +1,106 @@
1
+ 'use strict';
2
+
3
+ const crypto = require('crypto');
4
+ const { lengthField, uint32, uint64 } = require('./encoding');
5
+
6
+ function hmacSha256(key, message) {
7
+ if (!Buffer.isBuffer(key) || !Buffer.isBuffer(message)) {
8
+ throw new TypeError('HMAC key and message must be Buffers');
9
+ }
10
+ return crypto.createHmac('sha256', key).update(message).digest();
11
+ }
12
+
13
+ function hkdfSha256(ikm, salt, info, length) {
14
+ if (!Buffer.isBuffer(ikm) || !Buffer.isBuffer(salt) || !Buffer.isBuffer(info)) {
15
+ throw new TypeError('HKDF inputs must be Buffers');
16
+ }
17
+ if (salt.length !== 32) {
18
+ throw new Error('HKDF salt must be exactly 32 bytes');
19
+ }
20
+ if (!Number.isInteger(length) || length < 1 || length > 8160) {
21
+ throw new RangeError('HKDF length is outside the supported range');
22
+ }
23
+
24
+ const prk = hmacSha256(salt, ikm);
25
+ const blocks = Math.ceil(length / 32);
26
+ const output = [];
27
+ let previous = Buffer.alloc(0);
28
+ for (let counter = 1; counter <= blocks; counter++) {
29
+ previous = hmacSha256(prk, Buffer.concat([previous, info, Buffer.from([counter])]));
30
+ output.push(previous);
31
+ }
32
+ return Buffer.concat(output).subarray(0, length);
33
+ }
34
+
35
+ function hkdfContext(protocolVersion, clientId, requestId, poolVersion, keyIds) {
36
+ validateKeyIds(keyIds);
37
+ const parts = [
38
+ lengthField('MKAP'),
39
+ uint32(protocolVersion),
40
+ lengthField(clientId),
41
+ lengthField(requestId),
42
+ uint32(poolVersion),
43
+ uint32(keyIds.length)
44
+ ];
45
+ keyIds.forEach((keyId) => parts.push(lengthField(keyId)));
46
+ return Buffer.concat(parts);
47
+ }
48
+
49
+ function proofMessage(
50
+ protocolVersion,
51
+ clientId,
52
+ requestId,
53
+ nonce,
54
+ expiresAt,
55
+ method,
56
+ target,
57
+ bodySha256,
58
+ poolVersion,
59
+ keyIds
60
+ ) {
61
+ if (!Buffer.isBuffer(nonce) || nonce.length !== 32) {
62
+ throw new Error('Nonce must be exactly 32 bytes');
63
+ }
64
+ if (!Buffer.isBuffer(bodySha256) || bodySha256.length !== 32) {
65
+ throw new Error('Body SHA-256 must be exactly 32 bytes');
66
+ }
67
+ validateKeyIds(keyIds);
68
+
69
+ const parts = [
70
+ uint32(protocolVersion),
71
+ lengthField(clientId),
72
+ lengthField(requestId),
73
+ lengthField(nonce),
74
+ uint64(expiresAt),
75
+ lengthField(method),
76
+ lengthField(target),
77
+ lengthField(bodySha256),
78
+ uint32(poolVersion),
79
+ uint32(keyIds.length)
80
+ ];
81
+ keyIds.forEach((keyId) => parts.push(lengthField(keyId)));
82
+ return Buffer.concat(parts);
83
+ }
84
+
85
+ function validateKeyIds(keyIds) {
86
+ if (!Array.isArray(keyIds) || keyIds.length === 0 || keyIds.length > 0xffffffff) {
87
+ throw new Error('Invalid key identifier count');
88
+ }
89
+ const seen = new Set();
90
+ keyIds.forEach((keyId) => {
91
+ if (typeof keyId !== 'string' || keyId.length === 0 || Buffer.byteLength(keyId, 'utf8') > 256) {
92
+ throw new Error('Invalid key identifier');
93
+ }
94
+ if (seen.has(keyId)) {
95
+ throw new Error('Duplicate key identifier');
96
+ }
97
+ seen.add(keyId);
98
+ });
99
+ }
100
+
101
+ module.exports = {
102
+ hmacSha256,
103
+ hkdfSha256,
104
+ hkdfContext,
105
+ proofMessage
106
+ };
@@ -0,0 +1,82 @@
1
+ 'use strict';
2
+
3
+ function assertBuffer(value, name) {
4
+ if (!Buffer.isBuffer(value)) {
5
+ throw new TypeError(name + ' must be a Buffer');
6
+ }
7
+ }
8
+
9
+ function encodeBase64Url(buffer) {
10
+ assertBuffer(buffer, 'Base64URL value');
11
+ return buffer.toString('base64').replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/g, '');
12
+ }
13
+
14
+ function decodeBase64Url(value, exactLength) {
15
+ if (typeof value !== 'string' || value.length === 0 && exactLength !== 0) {
16
+ throw new Error('Invalid base64url value');
17
+ }
18
+ if (value.length > 8388608 || !/^[A-Za-z0-9_-]*$/.test(value)) {
19
+ throw new Error('Invalid base64url value');
20
+ }
21
+ if (value.includes('=')) {
22
+ throw new Error('Invalid base64url padding');
23
+ }
24
+ const padding = (4 - (value.length % 4)) % 4;
25
+ let buffer;
26
+ try {
27
+ buffer = Buffer.from(value.replace(/-/g, '+').replace(/_/g, '/') + '='.repeat(padding), 'base64');
28
+ } catch (error) {
29
+ throw new Error('Invalid base64url value');
30
+ }
31
+ if (encodeBase64Url(buffer) !== value) {
32
+ throw new Error('Invalid canonical base64url value');
33
+ }
34
+ if (typeof exactLength === 'number' && buffer.length !== exactLength) {
35
+ throw new Error('Decoded value has an unexpected length');
36
+ }
37
+ return buffer;
38
+ }
39
+
40
+ function uint32(value) {
41
+ if (!Number.isInteger(value) || value < 0 || value > 0xffffffff) {
42
+ throw new RangeError('uint32 value is outside the supported range');
43
+ }
44
+ const buffer = Buffer.alloc(4);
45
+ buffer.writeUInt32BE(value, 0);
46
+ return buffer;
47
+ }
48
+
49
+ function uint64(value) {
50
+ if (!Number.isSafeInteger(value) || value < 0 || value > 0xffffffff * 0x100000000) {
51
+ throw new RangeError('uint64 value is outside the supported range');
52
+ }
53
+ const buffer = Buffer.alloc(8);
54
+ const high = Math.floor(value / 0x100000000);
55
+ const low = value >>> 0;
56
+ buffer.writeUInt32BE(high, 0);
57
+ buffer.writeUInt32BE(low, 4);
58
+ return buffer;
59
+ }
60
+
61
+ function lengthField(value) {
62
+ let bytes;
63
+ if (typeof value === 'string') {
64
+ bytes = Buffer.from(value, 'utf8');
65
+ } else if (Buffer.isBuffer(value)) {
66
+ bytes = value;
67
+ } else {
68
+ throw new TypeError('Length-delimited value must be a string or Buffer');
69
+ }
70
+ if (bytes.length > 0xffffffff) {
71
+ throw new RangeError('Length-delimited text is too long');
72
+ }
73
+ return Buffer.concat([uint32(bytes.length), bytes]);
74
+ }
75
+
76
+ module.exports = {
77
+ encodeBase64Url,
78
+ decodeBase64Url,
79
+ uint32,
80
+ uint64,
81
+ lengthField
82
+ };
package/src/export.js ADDED
@@ -0,0 +1,97 @@
1
+ 'use strict';
2
+
3
+ const fs = require('fs');
4
+ const { decodeBase64Url } = require('./encoding');
5
+
6
+ function validateExport(manifest) {
7
+ if (!manifest || typeof manifest !== 'object' || Array.isArray(manifest)) {
8
+ throw new Error('Export manifest must be an object');
9
+ }
10
+ const required = [
11
+ 'format_version', 'protocol_version', 'client_id', 'pool_id',
12
+ 'pool_version', 'export_version', 'created_at', 'identifier_length',
13
+ 'identifier_alphabet', 'secret_length_bytes', 'key_count', 'keys'
14
+ ];
15
+ for (const field of required) {
16
+ if (!Object.prototype.hasOwnProperty.call(manifest, field)) {
17
+ throw new Error('Export manifest is missing field: ' + field);
18
+ }
19
+ }
20
+ if (manifest.format_version !== 1 || manifest.protocol_version !== 1) {
21
+ throw new Error('Unsupported export or protocol version');
22
+ }
23
+ if (!Number.isInteger(manifest.identifier_length)
24
+ || manifest.identifier_length < 1 || manifest.identifier_length > 256) {
25
+ throw new Error('Invalid identifier length');
26
+ }
27
+ if (typeof manifest.identifier_alphabet !== 'string'
28
+ || manifest.identifier_alphabet.length === 0
29
+ || new Set(Array.from(manifest.identifier_alphabet)).size !== Array.from(manifest.identifier_alphabet).length) {
30
+ throw new Error('Invalid identifier alphabet');
31
+ }
32
+ if (manifest.secret_length_bytes !== 32) {
33
+ throw new Error('Export secret length must be 32 bytes');
34
+ }
35
+ if (!Number.isInteger(manifest.key_count) || manifest.key_count < 1
36
+ || !Array.isArray(manifest.keys) || manifest.keys.length !== manifest.key_count) {
37
+ throw new Error('Export key count is inconsistent');
38
+ }
39
+
40
+ const secrets = new Map();
41
+ for (const key of manifest.keys) {
42
+ if (!key || typeof key !== 'object'
43
+ || typeof key.id !== 'string'
44
+ || typeof key.secret !== 'string'
45
+ || key.id.length !== manifest.identifier_length) {
46
+ throw new Error('Malformed export key record');
47
+ }
48
+ if (secrets.has(key.id)) {
49
+ throw new Error('Duplicate export key identifier');
50
+ }
51
+ for (const character of key.id) {
52
+ if (!manifest.identifier_alphabet.includes(character)) {
53
+ throw new Error('Export key identifier contains an invalid character');
54
+ }
55
+ }
56
+ const secret = decodeBase64Url(key.secret, 32);
57
+ secrets.set(key.id, secret);
58
+ }
59
+
60
+ return {
61
+ clientId: manifest.client_id,
62
+ poolId: manifest.pool_id,
63
+ poolVersion: manifest.pool_version,
64
+ identifierLength: manifest.identifier_length,
65
+ identifierAlphabet: manifest.identifier_alphabet,
66
+ secrets
67
+ };
68
+ }
69
+
70
+ function loadExportJson(json) {
71
+ if (typeof json !== 'string') {
72
+ throw new TypeError('Export JSON must be a string');
73
+ }
74
+ if (Buffer.byteLength(json, 'utf8') > 67108864) {
75
+ throw new Error('Export exceeds the configured size limit');
76
+ }
77
+ let manifest;
78
+ try {
79
+ manifest = JSON.parse(json);
80
+ } catch (error) {
81
+ throw new Error('Export is not valid JSON');
82
+ }
83
+ return validateExport(manifest);
84
+ }
85
+
86
+ function loadExportFile(path) {
87
+ if (typeof path !== 'string' || path.length === 0) {
88
+ throw new TypeError('Export path must be a non-empty string');
89
+ }
90
+ return loadExportJson(fs.readFileSync(path, 'utf8'));
91
+ }
92
+
93
+ module.exports = {
94
+ validateExport,
95
+ loadExportJson,
96
+ loadExportFile
97
+ };
package/src/index.js ADDED
@@ -0,0 +1,10 @@
1
+ 'use strict';
2
+
3
+ module.exports = Object.assign(
4
+ {},
5
+ require('./client'),
6
+ require('./export'),
7
+ require('./encoding'),
8
+ require('./cryptography'),
9
+ require('./transport')
10
+ );
@@ -0,0 +1,86 @@
1
+ 'use strict';
2
+
3
+ const http = require('http');
4
+ const https = require('https');
5
+ const { URL } = require('url');
6
+
7
+ function requestUrl(baseUri, target) {
8
+ if (typeof baseUri !== 'string' || typeof target !== 'string') {
9
+ throw new TypeError('Base URI and target must be strings');
10
+ }
11
+ const baseUrl = new URL(baseUri);
12
+ const url = new URL(target, baseUrl);
13
+ if (!/^https?:$/.test(url.protocol)) {
14
+ throw new Error('Unsupported transport protocol');
15
+ }
16
+ if (url.origin !== baseUrl.origin) {
17
+ throw new Error('Request target must remain on the base origin');
18
+ }
19
+ if (url.username || url.password || baseUrl.username || baseUrl.password) {
20
+ throw new Error('Transport URLs must not contain credentials');
21
+ }
22
+ if (url.pathname + url.search !== target) {
23
+ throw new Error('Request target is not canonical for the transport');
24
+ }
25
+ return url;
26
+ }
27
+
28
+ class NodeHttpTransport {
29
+ constructor(options) {
30
+ this.options = options && typeof options === 'object' ? options : {};
31
+ }
32
+
33
+ send(request) {
34
+ return new Promise((resolve, reject) => {
35
+ let url;
36
+ try {
37
+ url = new URL(request.url);
38
+ } catch (error) {
39
+ reject(error);
40
+ return;
41
+ }
42
+ if (url.protocol !== 'https:' && url.protocol !== 'http:') {
43
+ reject(new Error('Unsupported transport protocol'));
44
+ return;
45
+ }
46
+ if (url.username || url.password) {
47
+ reject(new Error('Transport URLs must not contain credentials'));
48
+ return;
49
+ }
50
+ if (this.options.requireHttps !== false && url.protocol !== 'https:') {
51
+ reject(new Error('HTTPS is required'));
52
+ return;
53
+ }
54
+
55
+ const body = Buffer.isBuffer(request.body)
56
+ ? request.body
57
+ : Buffer.from(request.body || '', 'utf8');
58
+ const transport = url.protocol === 'https:' ? https : http;
59
+ const outgoing = transport.request({
60
+ protocol: url.protocol,
61
+ hostname: url.hostname,
62
+ port: url.port || undefined,
63
+ method: request.method,
64
+ path: url.pathname + url.search,
65
+ headers: Object.assign({
66
+ 'Content-Length': body.length
67
+ }, request.headers || {})
68
+ }, (incoming) => {
69
+ const chunks = [];
70
+ incoming.on('data', (chunk) => chunks.push(Buffer.from(chunk)));
71
+ incoming.on('end', () => resolve({
72
+ statusCode: incoming.statusCode,
73
+ headers: incoming.headers,
74
+ body: Buffer.concat(chunks)
75
+ }));
76
+ });
77
+ outgoing.on('error', reject);
78
+ outgoing.end(body);
79
+ });
80
+ }
81
+ }
82
+
83
+ module.exports = {
84
+ requestUrl,
85
+ NodeHttpTransport
86
+ };
@@ -0,0 +1,96 @@
1
+ import { URL } from 'url';
2
+
3
+ export interface HttpResponse {
4
+ statusCode: number;
5
+ headers: { [name: string]: string | string[] | undefined };
6
+ body: Buffer;
7
+ }
8
+
9
+ export interface HttpRequest {
10
+ method: string;
11
+ url: string;
12
+ headers: { [name: string]: string };
13
+ body: Buffer;
14
+ }
15
+
16
+ export interface HttpTransport {
17
+ send(request: HttpRequest): Promise<HttpResponse>;
18
+ }
19
+
20
+ export interface NodeHttpTransportOptions {
21
+ requireHttps?: boolean;
22
+ }
23
+
24
+ export interface MkapClientConfig {
25
+ baseUri: string;
26
+ clientId: string;
27
+ poolVersion: number;
28
+ identifierLength: number;
29
+ identifierAlphabet: string;
30
+ exportJson?: string;
31
+ exportPath?: string;
32
+ maximumChallengeResponseBytes?: number;
33
+ requireHttps?: boolean;
34
+ }
35
+
36
+ export class MkapClient {
37
+ constructor(config: MkapClientConfig, transport?: HttpTransport);
38
+ request(method: string, target: string, body?: Buffer | string): Promise<HttpResponse>;
39
+ parseChallenge(body: Buffer): {
40
+ version: number;
41
+ requestId: Buffer;
42
+ nonce: Buffer;
43
+ keyIds: string[];
44
+ expiresAt: number;
45
+ };
46
+ }
47
+
48
+ export class NodeHttpTransport implements HttpTransport {
49
+ constructor(options?: NodeHttpTransportOptions);
50
+ send(request: HttpRequest): Promise<HttpResponse>;
51
+ }
52
+
53
+ export function requestUrl(baseUri: string, target: string): URL;
54
+ export interface ExportPool {
55
+ clientId: string;
56
+ poolId: string;
57
+ poolVersion: number;
58
+ identifierLength: number;
59
+ identifierAlphabet: string;
60
+ secrets: Map<string, Buffer>;
61
+ }
62
+
63
+ export function loadExportJson(json: string): ExportPool;
64
+ export function loadExportFile(path: string): ExportPool;
65
+ export function validateExport(manifest: unknown): ExportPool;
66
+ export function encodeBase64Url(buffer: Buffer): string;
67
+ export function decodeBase64Url(value: string, exactLength?: number): Buffer;
68
+ export function uint32(value: number): Buffer;
69
+ export function uint64(value: number): Buffer;
70
+ export function lengthField(value: string | Buffer): Buffer;
71
+ export function hkdfSha256(
72
+ ikm: Buffer,
73
+ salt: Buffer,
74
+ info: Buffer,
75
+ length: number
76
+ ): Buffer;
77
+ export function hkdfContext(
78
+ protocolVersion: number,
79
+ clientId: string,
80
+ requestId: Buffer,
81
+ poolVersion: number,
82
+ keyIds: string[]
83
+ ): Buffer;
84
+ export function proofMessage(
85
+ protocolVersion: number,
86
+ clientId: string,
87
+ requestId: Buffer,
88
+ nonce: Buffer,
89
+ expiresAt: number,
90
+ method: string,
91
+ target: string,
92
+ bodySha256: Buffer,
93
+ poolVersion: number,
94
+ keyIds: string[]
95
+ ): Buffer;
96
+ export function hmacSha256(key: Buffer, message: Buffer): Buffer;