appmesh 3.1.15 → 3.1.19
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/README.md +3 -5
- package/dist/appmesh.esm.js +1 -1
- package/package.json +1 -1
- package/src/appmesh.js +392 -16
- package/src/appmesh_tcp.js +146 -35
- package/src/request_signature.js +33 -18
- package/src/worker.js +47 -8
package/src/appmesh_tcp.js
CHANGED
|
@@ -8,7 +8,7 @@ import { once } from 'events'
|
|
|
8
8
|
import { v1 as uuidv1 } from 'uuid'
|
|
9
9
|
import msgpack from 'msgpack-lite'
|
|
10
10
|
import AppMeshClient, {
|
|
11
|
-
AppMeshError, AppRemovedError, TransportDisconnectedError, DEFAULT_CA_FILE,
|
|
11
|
+
AppMeshError, AppRemovedError, TransportDisconnectedError, DEFAULT_CA_FILE, CONSTANTS,
|
|
12
12
|
_resolveUid, _resolveGid, _resolveUserName, _resolveGroupName,
|
|
13
13
|
} from './appmesh.js'
|
|
14
14
|
import { canonicalQuery } from './request_signature.js'
|
|
@@ -30,10 +30,16 @@ const ENCODING_UTF8 = 'utf-8'
|
|
|
30
30
|
const HTTP_USER_AGENT_TCP = 'appmesh/nodejs/tcp'
|
|
31
31
|
const HTTP_HEADER_KEY_X_SEND_FILE_SOCKET = 'X-Send-File-Socket'
|
|
32
32
|
const HTTP_HEADER_KEY_X_RECV_FILE_SOCKET = 'X-Recv-File-Socket'
|
|
33
|
-
|
|
34
|
-
const
|
|
35
|
-
const
|
|
36
|
-
const
|
|
33
|
+
// Wire-header names come from the shared CONSTANTS block.
|
|
34
|
+
const HTTP_HEADER_KEY_USER_AGENT = CONSTANTS.HTTP_USER_AGENT_HEADER_NAME
|
|
35
|
+
const HTTP_HEADER_KEY_X_FILE_PATH = CONSTANTS.HTTP_HEADER_KEY_X_FILE_PATH
|
|
36
|
+
const HTTP_HEADER_KEY_X_FILE_OVERWRITE = CONSTANTS.HTTP_HEADER_KEY_X_FILE_OVERWRITE
|
|
37
|
+
const HTTP_HEADER_KEY_AUTH = CONSTANTS.HTTP_HEADER_KEY_AUTH
|
|
38
|
+
const HTTP_HEADER_KEY_X_TARGET_HOST = CONSTANTS.HTTP_HEADER_KEY_X_TARGET_HOST
|
|
39
|
+
const HTTP_HEADER_KEY_X_SUBSCRIPTION_ID = CONSTANTS.HTTP_HEADER_KEY_X_SUBSCRIPTION_ID
|
|
40
|
+
const HTTP_HEADER_KEY_X_FILE_MODE = CONSTANTS.HTTP_HEADER_KEY_X_FILE_MODE
|
|
41
|
+
const HTTP_HEADER_KEY_X_FILE_USER = CONSTANTS.HTTP_HEADER_KEY_X_FILE_USER
|
|
42
|
+
const HTTP_HEADER_KEY_X_FILE_GROUP = CONSTANTS.HTTP_HEADER_KEY_X_FILE_GROUP
|
|
37
43
|
|
|
38
44
|
/**
|
|
39
45
|
* TCP transport for secure TLS connections and framed App Mesh messages.
|
|
@@ -43,10 +49,10 @@ const HTTP_HEADER_KEY_X_TARGET_HOST = 'X-Target-Host'
|
|
|
43
49
|
*/
|
|
44
50
|
class TCPTransport {
|
|
45
51
|
/**
|
|
46
|
-
* @param {Array<string, number>} [address=['127.0.0.1',
|
|
52
|
+
* @param {Array<string, number>} [address=['127.0.0.1', 6062]] - Server address [host, port]
|
|
47
53
|
* @param {Object|false|null} [sslConfig=null] - TLS tri-state (see class doc)
|
|
48
54
|
*/
|
|
49
|
-
constructor (address = ['127.0.0.1',
|
|
55
|
+
constructor (address = ['127.0.0.1', 6062], sslConfig = null) {
|
|
50
56
|
this.address = address
|
|
51
57
|
this.sslConfig = sslConfig
|
|
52
58
|
this.socket = null
|
|
@@ -347,7 +353,7 @@ function _isAddressObject (value) {
|
|
|
347
353
|
*/
|
|
348
354
|
function _normalizeTcpAddress (address) {
|
|
349
355
|
if (_isAddressObject(address)) {
|
|
350
|
-
return [address.host ?? '127.0.0.1', address.port ??
|
|
356
|
+
return [address.host ?? '127.0.0.1', address.port ?? 6062]
|
|
351
357
|
}
|
|
352
358
|
return address
|
|
353
359
|
}
|
|
@@ -487,7 +493,7 @@ class MessageDemuxer {
|
|
|
487
493
|
try {
|
|
488
494
|
const bodyStr = typeof resp.body === 'string' ? resp.body : resp.body.toString('utf-8')
|
|
489
495
|
const event = JSON.parse(bodyStr)
|
|
490
|
-
const subId = event.subscription_id || _headerValue(resp.headers,
|
|
496
|
+
const subId = event.subscription_id || _headerValue(resp.headers, HTTP_HEADER_KEY_X_SUBSCRIPTION_ID)
|
|
491
497
|
const cb = this._eventCallbacks.get(subId)
|
|
492
498
|
if (cb) {
|
|
493
499
|
try { cb(event) } catch (e) { console.error('Event callback error:', e) }
|
|
@@ -540,16 +546,21 @@ class AppMeshClientTCP extends AppMeshClient {
|
|
|
540
546
|
* `{host, port}` object in either position.
|
|
541
547
|
*
|
|
542
548
|
* @param {Object|false|null} [sslConfig=null] - TLS config; same tri-state as AppMeshClient
|
|
543
|
-
|
|
544
|
-
* @param {Array<string, number>|{host: string, port: number}} [tcpAddress=['127.0.0.1',
|
|
549
|
+
* (null=default CA, object=custom ca/cert/key, false=insecure).
|
|
550
|
+
* @param {Array<string, number>|{host: string, port: number}} [tcpAddress=['127.0.0.1', 6062]] - TCP server address
|
|
551
|
+
* @param {number} [restPort=6063] - REST port of the same daemon for the streaming side channel
|
|
552
|
+
* (followOutput / runTaskStream); also honored as a `restPort` key on the `{host, port}` address object
|
|
545
553
|
*/
|
|
546
|
-
constructor (sslConfig = null, tcpAddress = ['127.0.0.1',
|
|
554
|
+
constructor (sslConfig = null, tcpAddress = ['127.0.0.1', 6062], restPort = null) {
|
|
547
555
|
// Accept the address-first object form: new AppMeshClientTCP({host, port}, sslConfig)
|
|
548
556
|
if (_isAddressObject(sslConfig)) {
|
|
549
557
|
const addr = sslConfig
|
|
550
558
|
sslConfig = (Array.isArray(tcpAddress) || _isAddressObject(tcpAddress)) ? null : tcpAddress
|
|
551
559
|
tcpAddress = addr
|
|
552
560
|
}
|
|
561
|
+
if (_isAddressObject(tcpAddress) && restPort == null) {
|
|
562
|
+
restPort = tcpAddress.restPort
|
|
563
|
+
}
|
|
553
564
|
tcpAddress = _normalizeTcpAddress(tcpAddress)
|
|
554
565
|
|
|
555
566
|
// Pass dummy baseURL to parent - not used for TCP communication
|
|
@@ -557,6 +568,15 @@ class AppMeshClientTCP extends AppMeshClient {
|
|
|
557
568
|
this.tcpTransport = new TCPTransport(tcpAddress, sslConfig)
|
|
558
569
|
this._demuxer = null
|
|
559
570
|
this._demuxerEnablePromise = null
|
|
571
|
+
// Upgrading from a legacy direct read to the demuxer must not put two
|
|
572
|
+
// readers on one socket; these track the transition and in-flight reads.
|
|
573
|
+
this._demuxerStarting = false
|
|
574
|
+
this._directReads = 0
|
|
575
|
+
this._directReadWaiters = []
|
|
576
|
+
// The SSE side channel (_sseRequest) dials the daemon's REST listener on the same host.
|
|
577
|
+
this._restHost = tcpAddress[0]
|
|
578
|
+
this._restPort = restPort ?? 6063
|
|
579
|
+
this._restChannelClient = null
|
|
560
580
|
}
|
|
561
581
|
|
|
562
582
|
/**
|
|
@@ -571,6 +591,11 @@ class AppMeshClientTCP extends AppMeshClient {
|
|
|
571
591
|
this.tcpTransport.close()
|
|
572
592
|
this.tcpTransport = null
|
|
573
593
|
}
|
|
594
|
+
if (this._restChannelClient) {
|
|
595
|
+
// Release the streaming side channel's keep-alive sockets.
|
|
596
|
+
this._restChannelClient._client.defaults.httpsAgent?.destroy?.()
|
|
597
|
+
this._restChannelClient = null
|
|
598
|
+
}
|
|
574
599
|
}
|
|
575
600
|
|
|
576
601
|
/**
|
|
@@ -579,6 +604,13 @@ class AppMeshClientTCP extends AppMeshClient {
|
|
|
579
604
|
* @override
|
|
580
605
|
*/
|
|
581
606
|
async _request (method, path, body = null, options = {}) {
|
|
607
|
+
// A subscribe upgrade in progress owns the read side; wait for it so this
|
|
608
|
+
// request is routed by UUID instead of racing the new reader for frames
|
|
609
|
+
// (the subscribe ack could otherwise resolve this request, stranding
|
|
610
|
+
// subscribe). The wait precedes construction so signatures stay fresh.
|
|
611
|
+
if (this._demuxerStarting) {
|
|
612
|
+
await this._demuxerEnablePromise
|
|
613
|
+
}
|
|
582
614
|
if (!this.tcpTransport.connected()) {
|
|
583
615
|
await this.tcpTransport.connect()
|
|
584
616
|
}
|
|
@@ -657,14 +689,27 @@ class AppMeshClientTCP extends AppMeshClient {
|
|
|
657
689
|
}
|
|
658
690
|
response = await respPromise
|
|
659
691
|
} else {
|
|
660
|
-
//
|
|
661
|
-
|
|
662
|
-
|
|
663
|
-
if (
|
|
664
|
-
this.
|
|
665
|
-
|
|
692
|
+
// An upgrade claimed the read side while this request was being built;
|
|
693
|
+
// nothing has been sent yet, so rebuild behind the upgrade (fresh token
|
|
694
|
+
// and signature) and route by UUID instead of opening a second reader.
|
|
695
|
+
if (this._demuxerStarting) {
|
|
696
|
+
await this._demuxerEnablePromise
|
|
697
|
+
return this._request(method, path, body, options)
|
|
698
|
+
}
|
|
699
|
+
// Legacy synchronous mode: read directly. Track the read so a concurrent
|
|
700
|
+
// subscribe waits for this response before starting the demuxer.
|
|
701
|
+
this._directReads++
|
|
702
|
+
try {
|
|
703
|
+
this.tcpTransport.sendMessage(serialized)
|
|
704
|
+
const respData = await this.tcpTransport.receiveMessage()
|
|
705
|
+
if (!respData || respData.length === 0) {
|
|
706
|
+
this.tcpTransport.close()
|
|
707
|
+
throw new Error('Socket connection broken')
|
|
708
|
+
}
|
|
709
|
+
response = new ResponseMessage().deserialize(respData)
|
|
710
|
+
} finally {
|
|
711
|
+
this._releaseDirectRead()
|
|
666
712
|
}
|
|
667
|
-
response = new ResponseMessage().deserialize(respData)
|
|
668
713
|
}
|
|
669
714
|
|
|
670
715
|
// Convert to standard response format matching axios structure
|
|
@@ -763,6 +808,32 @@ class AppMeshClientTCP extends AppMeshClient {
|
|
|
763
808
|
return statusTexts[code] || 'Unknown'
|
|
764
809
|
}
|
|
765
810
|
|
|
811
|
+
/**
|
|
812
|
+
* Lazily build the direct-HTTPS client the streaming side channel uses.
|
|
813
|
+
* @private
|
|
814
|
+
*/
|
|
815
|
+
_ensureRestChannel () {
|
|
816
|
+
if (!this._restChannelClient) {
|
|
817
|
+
this._restChannelClient = new AppMeshClient(`https://${this._restHost}:${this._restPort}`, this._sslConfig)
|
|
818
|
+
}
|
|
819
|
+
// Re-sync the token provider on every use so a later setBearerToken() reaches the side channel too.
|
|
820
|
+
if (this._tokenProvider && this._restChannelClient._tokenProvider !== this._tokenProvider) {
|
|
821
|
+
this._restChannelClient.setTokenProvider(this._tokenProvider)
|
|
822
|
+
}
|
|
823
|
+
return this._restChannelClient
|
|
824
|
+
}
|
|
825
|
+
|
|
826
|
+
/**
|
|
827
|
+
* Open an SSE stream over direct HTTPS to the daemon's REST listener: the framed transport
|
|
828
|
+
* answers one buffered frame and cannot carry a chunked event stream (bypassed like the
|
|
829
|
+
* WSS file data channel); plain request/response routes stay on the framed transport.
|
|
830
|
+
* @private
|
|
831
|
+
* @override
|
|
832
|
+
*/
|
|
833
|
+
async _sseRequest (method, path, options = {}) {
|
|
834
|
+
return this._ensureRestChannel()._sseRequest(method, path, options)
|
|
835
|
+
}
|
|
836
|
+
|
|
766
837
|
/**
|
|
767
838
|
* Download a file through the TCP file-socket side channel.
|
|
768
839
|
*
|
|
@@ -820,20 +891,20 @@ class AppMeshClientTCP extends AppMeshClient {
|
|
|
820
891
|
// Apply file attributes on Unix systems
|
|
821
892
|
if (applyAttrs && process.platform !== 'win32') {
|
|
822
893
|
// Mode is sent as a decimal string (matches the HTTP transport and Python SDK)
|
|
823
|
-
if (response.headers[
|
|
824
|
-
const mode = parseInt(response.headers[
|
|
894
|
+
if (response.headers[HTTP_HEADER_KEY_X_FILE_MODE]) {
|
|
895
|
+
const mode = parseInt(response.headers[HTTP_HEADER_KEY_X_FILE_MODE], 10)
|
|
825
896
|
// A malformed or out-of-range remote value must not fail the finished download
|
|
826
897
|
if (Number.isInteger(mode) && mode >= 0 && mode <= 0o777) {
|
|
827
898
|
fs.chmodSync(localFile, mode)
|
|
828
899
|
} else {
|
|
829
|
-
console.warn(`Warning: Invalid X-File-Mode value: ${response.headers[
|
|
900
|
+
console.warn(`Warning: Invalid X-File-Mode value: ${response.headers[HTTP_HEADER_KEY_X_FILE_MODE]}`)
|
|
830
901
|
}
|
|
831
902
|
}
|
|
832
|
-
if (response.headers[
|
|
903
|
+
if (response.headers[HTTP_HEADER_KEY_X_FILE_USER] && response.headers[HTTP_HEADER_KEY_X_FILE_GROUP]) {
|
|
833
904
|
// The daemon sends user/group *names* (os::fileStat); resolve them to
|
|
834
905
|
// numeric uid/gid locally before chown, same as the HTTP transport.
|
|
835
|
-
const uid = await _resolveUid(response.headers[
|
|
836
|
-
const gid = await _resolveGid(response.headers[
|
|
906
|
+
const uid = await _resolveUid(response.headers[HTTP_HEADER_KEY_X_FILE_USER])
|
|
907
|
+
const gid = await _resolveGid(response.headers[HTTP_HEADER_KEY_X_FILE_GROUP])
|
|
837
908
|
if (uid !== null && gid !== null) {
|
|
838
909
|
try {
|
|
839
910
|
fs.chownSync(localFile, uid, gid)
|
|
@@ -854,9 +925,11 @@ class AppMeshClientTCP extends AppMeshClient {
|
|
|
854
925
|
* @param {string} [filePath=null] - Remote destination path; defaults to the basename of localFile
|
|
855
926
|
* @param {boolean} [applyAttrs=false] - Send local mode and best-effort user/group name
|
|
856
927
|
* metadata so the server can recreate permissions and ownership when supported
|
|
928
|
+
* @param {boolean} [overwrite=false] - Replace an existing remote file; the
|
|
929
|
+
* default keeps the server's 409 refusal
|
|
857
930
|
* @override
|
|
858
931
|
*/
|
|
859
|
-
async uploadFile(localFile, filePath = null, applyAttrs = false) {
|
|
932
|
+
async uploadFile(localFile, filePath = null, applyAttrs = false, overwrite = false) {
|
|
860
933
|
this._ensureNoActiveDemuxer()
|
|
861
934
|
if (!filePath) filePath = localFile.split(/[\\/]/).pop()
|
|
862
935
|
if (!fs.existsSync(localFile)) {
|
|
@@ -868,18 +941,21 @@ class AppMeshClientTCP extends AppMeshClient {
|
|
|
868
941
|
'Content-Type': 'text/plain',
|
|
869
942
|
[HTTP_HEADER_KEY_X_SEND_FILE_SOCKET]: 'true'
|
|
870
943
|
}
|
|
944
|
+
if (overwrite) {
|
|
945
|
+
headers[HTTP_HEADER_KEY_X_FILE_OVERWRITE] = 'true'
|
|
946
|
+
}
|
|
871
947
|
|
|
872
948
|
// Add file attributes
|
|
873
949
|
if (applyAttrs) {
|
|
874
950
|
const stats = fs.statSync(localFile)
|
|
875
|
-
headers[
|
|
951
|
+
headers[HTTP_HEADER_KEY_X_FILE_MODE] = (stats.mode & 0o777).toString()
|
|
876
952
|
// Send user/group names when resolvable; the daemon also accepts
|
|
877
953
|
// all-digit values (Utility::applyFilePermission -> os::chown ->
|
|
878
954
|
// getUidByName numeric fallback), so fall back to numeric ids.
|
|
879
955
|
const username = await _resolveUserName(stats.uid)
|
|
880
956
|
const groupName = await _resolveGroupName(stats.gid)
|
|
881
|
-
headers[
|
|
882
|
-
headers[
|
|
957
|
+
headers[HTTP_HEADER_KEY_X_FILE_USER] = username || String(stats.uid)
|
|
958
|
+
headers[HTTP_HEADER_KEY_X_FILE_GROUP] = groupName || String(stats.gid)
|
|
883
959
|
}
|
|
884
960
|
|
|
885
961
|
const response = await this._request('post', '/appmesh/file/upload', null, {
|
|
@@ -908,6 +984,9 @@ class AppMeshClientTCP extends AppMeshClient {
|
|
|
908
984
|
/**
|
|
909
985
|
* Subscribe to app events over TCP.
|
|
910
986
|
*
|
|
987
|
+
* Resolves when the daemon acknowledges the subscription; it does not wait
|
|
988
|
+
* for the first event. Later events are delivered to `callback`.
|
|
989
|
+
*
|
|
911
990
|
* @param {string} appName - Application name, or "*" for all apps.
|
|
912
991
|
* @param {string[]} [events] - Event types: "START", "EXIT", "STDOUT", etc.
|
|
913
992
|
* @param {function} callback - Called with event object for each received event.
|
|
@@ -996,6 +1075,28 @@ class AppMeshClientTCP extends AppMeshClient {
|
|
|
996
1075
|
}
|
|
997
1076
|
}
|
|
998
1077
|
|
|
1078
|
+
/**
|
|
1079
|
+
* Resolve when no legacy direct read owns the socket.
|
|
1080
|
+
* @private
|
|
1081
|
+
*/
|
|
1082
|
+
_waitForDirectReads () {
|
|
1083
|
+
if (this._directReads === 0) return Promise.resolve()
|
|
1084
|
+
return new Promise(resolve => this._directReadWaiters.push(resolve))
|
|
1085
|
+
}
|
|
1086
|
+
|
|
1087
|
+
/**
|
|
1088
|
+
* Account for a finished legacy direct read and wake a waiting upgrade.
|
|
1089
|
+
* @private
|
|
1090
|
+
*/
|
|
1091
|
+
_releaseDirectRead () {
|
|
1092
|
+
this._directReads--
|
|
1093
|
+
if (this._directReads === 0 && this._directReadWaiters.length > 0) {
|
|
1094
|
+
const waiters = this._directReadWaiters
|
|
1095
|
+
this._directReadWaiters = []
|
|
1096
|
+
for (const resolve of waiters) resolve()
|
|
1097
|
+
}
|
|
1098
|
+
}
|
|
1099
|
+
|
|
999
1100
|
/**
|
|
1000
1101
|
* Enable demuxer for concurrent request-response and event routing.
|
|
1001
1102
|
* Serialized: two concurrent subscribe() calls on an unconnected transport
|
|
@@ -1009,13 +1110,23 @@ class AppMeshClientTCP extends AppMeshClient {
|
|
|
1009
1110
|
await this._demuxerEnablePromise
|
|
1010
1111
|
return
|
|
1011
1112
|
}
|
|
1113
|
+
// Set before any await so requests starting during the upgrade route through
|
|
1114
|
+
// the demuxer instead of opening a second, competing direct read.
|
|
1115
|
+
this._demuxerStarting = true
|
|
1012
1116
|
this._demuxerEnablePromise = (async () => {
|
|
1013
|
-
|
|
1014
|
-
|
|
1015
|
-
|
|
1016
|
-
|
|
1017
|
-
|
|
1018
|
-
|
|
1117
|
+
try {
|
|
1118
|
+
if (!this.tcpTransport.connected()) {
|
|
1119
|
+
await this.tcpTransport.connect()
|
|
1120
|
+
}
|
|
1121
|
+
// A legacy direct read consumes frames itself; starting the demuxer now
|
|
1122
|
+
// would race it and can strand either response forever.
|
|
1123
|
+
await this._waitForDirectReads()
|
|
1124
|
+
if (!this._demuxer || !this._demuxer._running) {
|
|
1125
|
+
this._demuxer = new MessageDemuxer(this.tcpTransport)
|
|
1126
|
+
this._demuxer.start()
|
|
1127
|
+
}
|
|
1128
|
+
} finally {
|
|
1129
|
+
this._demuxerStarting = false
|
|
1019
1130
|
}
|
|
1020
1131
|
})()
|
|
1021
1132
|
try {
|
package/src/request_signature.js
CHANGED
|
@@ -10,8 +10,8 @@
|
|
|
10
10
|
// - sortedQuery: decoded k=v pairs joined with '&', sorted by key then value, empty
|
|
11
11
|
// string when there is no query (%XX-decoding only; '+' stays literal)
|
|
12
12
|
// - body: lowercase hex SHA-256 of the raw body bytes; no body hashes the empty string
|
|
13
|
-
// - streamed
|
|
14
|
-
// empty-string body hash (documented exemption: the
|
|
13
|
+
// - streamed endpoints (/appmesh/file/download|upload|delete and the SSE output|task streams)
|
|
14
|
+
// sign the empty-string body hash (documented exemption: the streamed content is not bound)
|
|
15
15
|
//
|
|
16
16
|
// The secret is never logged and never exposed through a getter or toString().
|
|
17
17
|
// Node.js only: signing uses node:crypto (no npm dependencies).
|
|
@@ -33,6 +33,10 @@ async function nodeCrypto () {
|
|
|
33
33
|
* The exact daemon set (RequestHardening::canonicalFileRoute) — subpaths are not exempt. */
|
|
34
34
|
const EMPTY_BODY_EXEMPT_PATHS = new Set(['/appmesh/file/download', '/appmesh/file/upload', '/appmesh/file/delete'])
|
|
35
35
|
|
|
36
|
+
/** SSE stream routes (/appmesh/app/{name}/output|task/stream): the daemon's SSE hardening
|
|
37
|
+
* check ignores the request body, so these sign the empty-string hash (docs/source/Streaming.md). */
|
|
38
|
+
const EMPTY_BODY_EXEMPT_STREAM_RE = /^\/appmesh\/app\/[^/]+\/(output|task)\/stream$/
|
|
39
|
+
|
|
36
40
|
/** Header names (must match HTTP_HEADER_KEY_* in src/common/Utility.h). */
|
|
37
41
|
export const REQUEST_SIGNATURE_HEADERS = Object.freeze({
|
|
38
42
|
KEY_ID: 'X-Request-Key',
|
|
@@ -41,10 +45,11 @@ export const REQUEST_SIGNATURE_HEADERS = Object.freeze({
|
|
|
41
45
|
SIGNATURE: 'X-Signature'
|
|
42
46
|
})
|
|
43
47
|
|
|
44
|
-
/** True for
|
|
48
|
+
/** True for streamed endpoints (file transfer, SSE streams) that sign the empty-string body hash. */
|
|
45
49
|
export function isEmptyBodyExemptPath (path) {
|
|
46
50
|
if (typeof path !== 'string') return false
|
|
47
|
-
|
|
51
|
+
const signingPath = canonicalSigningPath(path)
|
|
52
|
+
return EMPTY_BODY_EXEMPT_PATHS.has(signingPath) || EMPTY_BODY_EXEMPT_STREAM_RE.test(signingPath)
|
|
48
53
|
}
|
|
49
54
|
|
|
50
55
|
/**
|
|
@@ -81,8 +86,10 @@ export class RequestSigner {
|
|
|
81
86
|
if (typeof secret !== 'string' || secret === '') {
|
|
82
87
|
throw new TypeError('secret must be a non-empty string')
|
|
83
88
|
}
|
|
84
|
-
|
|
85
|
-
|
|
89
|
+
// Non-enumerable (never leaked by JSON.stringify / object spread of the
|
|
90
|
+
// signer); writable stays true so tests and subclasses may replace them.
|
|
91
|
+
Object.defineProperty(this, '_keyId', { value: keyId, writable: true })
|
|
92
|
+
Object.defineProperty(this, '_secret', { value: secret, writable: true })
|
|
86
93
|
}
|
|
87
94
|
|
|
88
95
|
/** The API key id this signer advertises. */
|
|
@@ -180,26 +187,34 @@ export function canonicalQuery (params) {
|
|
|
180
187
|
|
|
181
188
|
/**
|
|
182
189
|
* Canonical query built from the encoded query string exactly as it goes on the
|
|
183
|
-
* wire (HTTP transport). Mirrors the daemon parser: split on '&', split
|
|
184
|
-
* pair at the first '=', decode each component with %XX-only decoding
|
|
185
|
-
* stays literal, a malformed escape keeps the whole raw component,
|
|
186
|
-
* key
|
|
190
|
+
* wire (HTTP transport). Mirrors the daemon parser loop: split on '&', split
|
|
191
|
+
* each pair at the first '=', decode each component with %XX-only decoding
|
|
192
|
+
* ('+' stays literal, a malformed escape keeps the whole raw component), then
|
|
193
|
+
* dedup decoded-key-first-wins (daemon std::map::emplace) and sort. An empty
|
|
194
|
+
* segment (e.g. "a=1&&b=2") inserts ("", "") and the canonical output keeps
|
|
195
|
+
* its "="; a trailing '&' adds no segment (the daemon loop ends at its bounds).
|
|
187
196
|
*/
|
|
188
197
|
export function canonicalQueryFromEncoded (encodedQuery) {
|
|
189
198
|
if (!encodedQuery) return ''
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
199
|
+
// Null prototype: query keys like "toString" or "__proto__" are plain data
|
|
200
|
+
// here, never shadowed or dropped by Object prototype members.
|
|
201
|
+
const decoded = Object.create(null)
|
|
202
|
+
for (let pos = 0; pos < encodedQuery.length;) {
|
|
203
|
+
const amp = encodedQuery.indexOf('&', pos)
|
|
204
|
+
const pair = amp < 0 ? encodedQuery.slice(pos) : encodedQuery.slice(pos, amp)
|
|
193
205
|
const eq = pair.indexOf('=')
|
|
194
206
|
const key = eq < 0 ? pair : pair.slice(0, eq)
|
|
195
207
|
const value = eq < 0 ? '' : pair.slice(eq + 1)
|
|
196
|
-
//
|
|
197
|
-
|
|
198
|
-
|
|
208
|
+
// Decode first, then dedup: the daemon decodes each component and emplaces,
|
|
209
|
+
// so the first value for a DECODED key wins (e.g. "a=1&a%61=2" keeps "a=1").
|
|
210
|
+
const decodedKey = percentDecode(key)
|
|
211
|
+
if (!Object.prototype.hasOwnProperty.call(decoded, decodedKey)) {
|
|
212
|
+
decoded[decodedKey] = percentDecode(value)
|
|
199
213
|
}
|
|
214
|
+
if (amp < 0) break
|
|
215
|
+
pos = amp + 1
|
|
200
216
|
}
|
|
201
|
-
|
|
202
|
-
const decodedPairs = Object.entries(decoded).map(([k, v]) => [percentDecode(k), percentDecode(v)])
|
|
217
|
+
const decodedPairs = Object.entries(decoded)
|
|
203
218
|
// Order by UTF-8 bytes, matching the daemon (not UTF-16 code units: a
|
|
204
219
|
// non-BMP character sorts before U+E000..U+FFFF in UTF-16, after it in UTF-8).
|
|
205
220
|
decodedPairs.sort((a, b) => {
|
package/src/worker.js
CHANGED
|
@@ -6,7 +6,7 @@ if (typeof window !== 'undefined' && typeof window.document !== 'undefined') {
|
|
|
6
6
|
throw new Error('AppMeshWorker is only available in Node.js environment. Use AppMeshClient for browser applications.')
|
|
7
7
|
}
|
|
8
8
|
|
|
9
|
-
import AppMeshClient, { AppMeshError } from './appmesh.js'
|
|
9
|
+
import AppMeshClient, { AppMeshError, CONSTANTS } from './appmesh.js'
|
|
10
10
|
|
|
11
11
|
/**
|
|
12
12
|
* Error thrown when the daemon reports HTTP 412: this process key was superseded
|
|
@@ -189,7 +189,7 @@ class AppMeshWorker {
|
|
|
189
189
|
const attemptStart = Date.now()
|
|
190
190
|
try {
|
|
191
191
|
const response = await this._client.request('get', path, null, {
|
|
192
|
-
headers: {
|
|
192
|
+
headers: { [CONSTANTS.HTTP_HEADER_KEY_X_APPMESH_PROCESS_KEY]: processKey }
|
|
193
193
|
})
|
|
194
194
|
|
|
195
195
|
if (response.status === 200) {
|
|
@@ -255,7 +255,7 @@ class AppMeshWorker {
|
|
|
255
255
|
let response
|
|
256
256
|
try {
|
|
257
257
|
response = await this._client.request('put', path, result, {
|
|
258
|
-
headers: {
|
|
258
|
+
headers: { [CONSTANTS.HTTP_HEADER_KEY_X_APPMESH_PROCESS_KEY]: processKey }
|
|
259
259
|
})
|
|
260
260
|
} catch (error) {
|
|
261
261
|
// request() throws AppMeshError on non-200
|
|
@@ -270,6 +270,37 @@ class AppMeshWorker {
|
|
|
270
270
|
}
|
|
271
271
|
}
|
|
272
272
|
|
|
273
|
+
/**
|
|
274
|
+
* Push an incremental result before the final reply. Delivered only to a caller
|
|
275
|
+
* streaming via `runTaskStream`; a one-shot `runTask` caller silently ignores it.
|
|
276
|
+
*
|
|
277
|
+
* @param {string|Buffer} partial - Incremental payload delivered to the streaming caller in order
|
|
278
|
+
* @returns {Promise<boolean>} `true` when a streaming client received the partial
|
|
279
|
+
* @throws {Error} If the partial push fails
|
|
280
|
+
*/
|
|
281
|
+
async sendTaskPartial(partial) {
|
|
282
|
+
const { processKey, appName } = this._getRuntimeEnv()
|
|
283
|
+
const path = `/appmesh/app/${appName}/task/partial`
|
|
284
|
+
|
|
285
|
+
let response
|
|
286
|
+
try {
|
|
287
|
+
response = await this._client.request('post', path, partial, {
|
|
288
|
+
headers: { [CONSTANTS.HTTP_HEADER_KEY_X_APPMESH_PROCESS_KEY]: processKey }
|
|
289
|
+
})
|
|
290
|
+
} catch (error) {
|
|
291
|
+
// request() throws AppMeshError on non-200
|
|
292
|
+
this._logger.error(`sendTaskPartial failed with status ${error.statusCode}: ${error.message}`)
|
|
293
|
+
throw error
|
|
294
|
+
}
|
|
295
|
+
|
|
296
|
+
if (response.status !== 200) {
|
|
297
|
+
const msg = `sendTaskPartial failed with status ${response.status}: ${response.data}`
|
|
298
|
+
this._logger.error(msg)
|
|
299
|
+
throw new AppMeshError(msg)
|
|
300
|
+
}
|
|
301
|
+
return Boolean(response.data && response.data.delivered)
|
|
302
|
+
}
|
|
303
|
+
|
|
273
304
|
/**
|
|
274
305
|
* Sleep utility for retry logic
|
|
275
306
|
* @private
|
|
@@ -314,7 +345,7 @@ class AppMeshWorkerTCP extends AppMeshWorker {
|
|
|
314
345
|
* @param {Buffer|string} [sslConfig.cert] - Client certificate
|
|
315
346
|
* @param {Buffer|string} [sslConfig.key] - Client key
|
|
316
347
|
* @param {boolean} [sslConfig.rejectUnauthorized=true] - Whether to verify SSL
|
|
317
|
-
* @param {Array<string, number>|{host: string, port: number}} [tcpAddress=['127.0.0.1',
|
|
348
|
+
* @param {Array<string, number>|{host: string, port: number}} [tcpAddress=['127.0.0.1', 6062]] - TCP server address
|
|
318
349
|
* @param {Object} [options={}] - Additional options
|
|
319
350
|
* @param {Object} [options.logger=console] - Logger instance
|
|
320
351
|
* @param {AppMeshClientTCP} [options.client] - Pre-built client to reuse (shares its caller-owned bearer);
|
|
@@ -327,18 +358,18 @@ class AppMeshWorkerTCP extends AppMeshWorker {
|
|
|
327
358
|
* cert: fs.readFileSync('/opt/appmesh/ssl/client.pem'),
|
|
328
359
|
* key: fs.readFileSync('/opt/appmesh/ssl/client-key.pem')
|
|
329
360
|
* };
|
|
330
|
-
* const worker = new AppMeshWorkerTCP(sslConfig, ['127.0.0.1',
|
|
361
|
+
* const worker = new AppMeshWorkerTCP(sslConfig, ['127.0.0.1', 6062]);
|
|
331
362
|
*
|
|
332
363
|
* @example
|
|
333
364
|
* // Share a single TCP client between client-role and worker-role usage:
|
|
334
365
|
* import { AppMeshClientTCP } from 'appmesh/tcp';
|
|
335
|
-
* const client = new AppMeshClientTCP(sslConfig, ['127.0.0.1',
|
|
366
|
+
* const client = new AppMeshClientTCP(sslConfig, ['127.0.0.1', 6062]);
|
|
336
367
|
* client.setBearerToken(process.env.APPMESH_BEARER_TOKEN);
|
|
337
|
-
* const worker = new AppMeshWorkerTCP(sslConfig, ['127.0.0.1',
|
|
368
|
+
* const worker = new AppMeshWorkerTCP(sslConfig, ['127.0.0.1', 6062], { client });
|
|
338
369
|
*/
|
|
339
370
|
constructor (
|
|
340
371
|
sslConfig = null,
|
|
341
|
-
tcpAddress = ['127.0.0.1',
|
|
372
|
+
tcpAddress = ['127.0.0.1', 6062],
|
|
342
373
|
options = {}
|
|
343
374
|
) {
|
|
344
375
|
// Accept the address-first object form: new AppMeshWorkerTCP({host, port}, sslConfig)
|
|
@@ -382,6 +413,14 @@ class AppMeshWorkerTCP extends AppMeshWorker {
|
|
|
382
413
|
return super.sendTaskResult(result)
|
|
383
414
|
}
|
|
384
415
|
|
|
416
|
+
/**
|
|
417
|
+
* Push a task partial (overrides parent to ensure TCP client is initialized)
|
|
418
|
+
*/
|
|
419
|
+
async sendTaskPartial(partial) {
|
|
420
|
+
await this._ensureClient()
|
|
421
|
+
return super.sendTaskPartial(partial)
|
|
422
|
+
}
|
|
423
|
+
|
|
385
424
|
/**
|
|
386
425
|
* Close the TCP connection and release resources.
|
|
387
426
|
* Should be called when done using the server.
|