@venizia/ignis-helpers 0.3.6 → 0.4.1
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.md +1 -1
- package/dist/cjs/common/redact.js +1 -1
- package/dist/cjs/common/redact.js.map +1 -1
- package/dist/cjs/modules/base.js +1 -1
- package/dist/cjs/modules/base.js.map +1 -1
- package/dist/cjs/modules/crypto/algorithms/aes.algorithm.js +1 -1
- package/dist/cjs/modules/crypto/algorithms/aes.algorithm.js.map +1 -1
- package/dist/cjs/modules/logger/common/constants.js +1 -1
- package/dist/cjs/modules/logger/common/constants.js.map +1 -1
- package/dist/cjs/modules/logger/factory.js +1 -1
- package/dist/cjs/modules/logger/factory.js.map +1 -1
- package/dist/cjs/modules/logger/formatting/deep-splat.js +1 -1
- package/dist/cjs/modules/logger/formatting/deep-splat.js.map +1 -1
- package/dist/cjs/modules/logger/formatting/error-prettier.js +4 -4
- package/dist/cjs/modules/logger/formatting/error-prettier.js.map +1 -1
- package/dist/cjs/modules/logger/hf/flusher.js +3 -3
- package/dist/cjs/modules/logger/hf/flusher.js.map +1 -1
- package/dist/cjs/modules/logger/resolver.js +3 -3
- package/dist/cjs/modules/logger/resolver.js.map +1 -1
- package/dist/cjs/modules/logger/winston/formatters/deep-splat.js +1 -1
- package/dist/cjs/modules/logger/winston/formatters/deep-splat.js.map +1 -1
- package/dist/cjs/modules/logger/winston/logger-factory.js +1 -1
- package/dist/cjs/modules/logger/winston/logger-factory.js.map +1 -1
- package/dist/cjs/modules/logger/winston/transports/dgram.transport.js +2 -2
- package/dist/cjs/modules/logger/winston/transports/dgram.transport.js.map +1 -1
- package/dist/cjs/modules/network/http-request/fetcher/axios-fetcher.js +1 -1
- package/dist/cjs/modules/network/http-request/fetcher/axios-fetcher.js.map +1 -1
- package/dist/cjs/modules/network/http-request/fetcher/base-fetcher.d.ts +17 -14
- package/dist/cjs/modules/network/http-request/fetcher/base-fetcher.d.ts.map +1 -1
- package/dist/cjs/modules/network/http-request/fetcher/base-fetcher.js +3 -0
- package/dist/cjs/modules/network/http-request/fetcher/base-fetcher.js.map +1 -1
- package/dist/cjs/modules/network/http-request/fetcher/node-fetcher.d.ts +13 -4
- package/dist/cjs/modules/network/http-request/fetcher/node-fetcher.d.ts.map +1 -1
- package/dist/cjs/modules/network/http-request/fetcher/node-fetcher.js +34 -11
- package/dist/cjs/modules/network/http-request/fetcher/node-fetcher.js.map +1 -1
- package/dist/cjs/modules/network/tcp-socket/base-tcp-client.helper.js +1 -1
- package/dist/cjs/modules/network/tcp-socket/base-tcp-client.helper.js.map +1 -1
- package/dist/cjs/modules/network/tcp-socket/base-tcp-server.helper.js +4 -4
- package/dist/cjs/modules/network/tcp-socket/base-tcp-server.helper.js.map +1 -1
- package/dist/cjs/modules/network/udp-socket/network-udp-client.helper.js +1 -1
- package/dist/cjs/modules/network/udp-socket/network-udp-client.helper.js.map +1 -1
- package/dist/cjs/modules/network/utilities/query-string.d.ts +27 -2
- package/dist/cjs/modules/network/utilities/query-string.d.ts.map +1 -1
- package/dist/cjs/modules/network/utilities/query-string.js +34 -2
- package/dist/cjs/modules/network/utilities/query-string.js.map +1 -1
- package/dist/cjs/modules/network/utilities/url-safety/ingest.js +1 -1
- package/dist/cjs/modules/network/utilities/url-safety/ingest.js.map +1 -1
- package/dist/cjs/modules/network/utilities/url-safety/policy.js +1 -1
- package/dist/cjs/modules/network/utilities/url-safety/policy.js.map +1 -1
- package/dist/cjs/modules/pool/abstract.js +4 -4
- package/dist/cjs/modules/pool/abstract.js.map +1 -1
- package/dist/cjs/modules/queue/bullmq/helper.js +2 -2
- package/dist/cjs/modules/queue/bullmq/helper.js.map +1 -1
- package/dist/cjs/modules/queue/kafka/bundler/platformatic-require.plugin.js.map +1 -1
- package/dist/cjs/modules/queue/kafka/bundler/platformatic-wasm.plugin.js +1 -1
- package/dist/cjs/modules/queue/kafka/bundler/platformatic-wasm.plugin.js.map +1 -1
- package/dist/cjs/modules/queue/kafka/consumer.js +2 -2
- package/dist/cjs/modules/queue/kafka/consumer.js.map +1 -1
- package/dist/cjs/modules/queue/mqtt/helper.js +4 -4
- package/dist/cjs/modules/queue/mqtt/helper.js.map +1 -1
- package/dist/cjs/modules/redis/base/abstract.helper.js +4 -4
- package/dist/cjs/modules/redis/base/abstract.helper.js.map +1 -1
- package/dist/cjs/modules/redis/cluster/cluster.helper.js +1 -1
- package/dist/cjs/modules/redis/cluster/cluster.helper.js.map +1 -1
- package/dist/cjs/modules/redis/sentinel/sentinel.helper.js +1 -1
- package/dist/cjs/modules/redis/sentinel/sentinel.helper.js.map +1 -1
- package/dist/cjs/modules/secrets/base/abstract.helper.js +2 -2
- package/dist/cjs/modules/secrets/base/abstract.helper.js.map +1 -1
- package/dist/cjs/modules/secrets/hashicorp/hashicorp.helper.js +2 -2
- package/dist/cjs/modules/secrets/hashicorp/hashicorp.helper.js.map +1 -1
- package/dist/cjs/modules/socket/socket-io/browser.d.ts +5 -0
- package/dist/cjs/modules/socket/socket-io/browser.d.ts.map +1 -0
- package/dist/cjs/modules/socket/socket-io/browser.js +21 -0
- package/dist/cjs/modules/socket/socket-io/browser.js.map +1 -0
- package/dist/cjs/modules/socket/socket-io/client/browser-helper.d.ts +61 -0
- package/dist/cjs/modules/socket/socket-io/client/browser-helper.d.ts.map +1 -0
- package/dist/cjs/modules/socket/socket-io/client/browser-helper.js +250 -0
- package/dist/cjs/modules/socket/socket-io/client/browser-helper.js.map +1 -0
- package/dist/cjs/modules/socket/socket-io/client/helper.d.ts +8 -51
- package/dist/cjs/modules/socket/socket-io/client/helper.d.ts.map +1 -1
- package/dist/cjs/modules/socket/socket-io/client/helper.js +12 -230
- package/dist/cjs/modules/socket/socket-io/client/helper.js.map +1 -1
- package/dist/cjs/modules/socket/socket-io/server/helper.js +5 -5
- package/dist/cjs/modules/socket/socket-io/server/helper.js.map +1 -1
- package/dist/cjs/modules/socket/websocket/server/delivery.js +2 -2
- package/dist/cjs/modules/socket/websocket/server/delivery.js.map +1 -1
- package/dist/cjs/modules/socket/websocket/server/helper.js +4 -4
- package/dist/cjs/modules/socket/websocket/server/helper.js.map +1 -1
- package/dist/cjs/modules/storage/base.js +3 -3
- package/dist/cjs/modules/storage/base.js.map +1 -1
- package/dist/cjs/modules/storage/bun-s3/helper.js +1 -1
- package/dist/cjs/modules/storage/bun-s3/helper.js.map +1 -1
- package/dist/cjs/modules/storage/bun-s3/utility.js +6 -6
- package/dist/cjs/modules/storage/bun-s3/utility.js.map +1 -1
- package/dist/cjs/modules/storage/common/errors.js +1 -1
- package/dist/cjs/modules/storage/common/errors.js.map +1 -1
- package/dist/cjs/modules/storage/minio/helper.js +4 -4
- package/dist/cjs/modules/storage/minio/helper.js.map +1 -1
- package/dist/cjs/modules/temporal/abstract.js +5 -5
- package/dist/cjs/modules/temporal/abstract.js.map +1 -1
- package/dist/cjs/modules/temporal/adapters/intl.d.ts.map +1 -1
- package/dist/cjs/modules/temporal/adapters/intl.js +3 -1
- package/dist/cjs/modules/temporal/adapters/intl.js.map +1 -1
- package/dist/cjs/modules/temporal/locale/locale.js +4 -4
- package/dist/cjs/modules/temporal/locale/locale.js.map +1 -1
- package/dist/cjs/modules/tree/builder.js +2 -2
- package/dist/cjs/modules/tree/builder.js.map +1 -1
- package/dist/cjs/modules/uid/opaque.js +2 -2
- package/dist/cjs/modules/uid/opaque.js.map +1 -1
- package/dist/cjs/modules/uid/uuid/v5.js +1 -1
- package/dist/cjs/modules/uid/uuid/v5.js.map +1 -1
- package/dist/cjs/modules/worker-thread/bus/base.js +4 -4
- package/dist/cjs/modules/worker-thread/bus/base.js.map +1 -1
- package/dist/cjs/modules/worker-thread/worker/base.js +4 -4
- package/dist/cjs/modules/worker-thread/worker/base.js.map +1 -1
- package/dist/cjs/utilities/parse.utility.js +4 -4
- package/dist/cjs/utilities/parse.utility.js.map +1 -1
- package/dist/cjs/utilities/promise.utility.js +1 -1
- package/dist/cjs/utilities/promise.utility.js.map +1 -1
- package/dist/cjs/utilities/request.utility.js +1 -1
- package/dist/cjs/utilities/request.utility.js.map +1 -1
- package/dist/cjs/utilities/sleep.utility.js +1 -1
- package/dist/cjs/utilities/sleep.utility.js.map +1 -1
- package/dist/esm/common/redact.js +1 -1
- package/dist/esm/common/redact.js.map +1 -1
- package/dist/esm/modules/base.js +1 -1
- package/dist/esm/modules/base.js.map +1 -1
- package/dist/esm/modules/crypto/algorithms/aes.algorithm.js +1 -1
- package/dist/esm/modules/crypto/algorithms/aes.algorithm.js.map +1 -1
- package/dist/esm/modules/logger/common/constants.js +1 -1
- package/dist/esm/modules/logger/common/constants.js.map +1 -1
- package/dist/esm/modules/logger/factory.js +1 -1
- package/dist/esm/modules/logger/factory.js.map +1 -1
- package/dist/esm/modules/logger/formatting/deep-splat.js +1 -1
- package/dist/esm/modules/logger/formatting/deep-splat.js.map +1 -1
- package/dist/esm/modules/logger/formatting/error-prettier.js +4 -4
- package/dist/esm/modules/logger/formatting/error-prettier.js.map +1 -1
- package/dist/esm/modules/logger/hf/flusher.js +3 -3
- package/dist/esm/modules/logger/hf/flusher.js.map +1 -1
- package/dist/esm/modules/logger/resolver.js +3 -3
- package/dist/esm/modules/logger/resolver.js.map +1 -1
- package/dist/esm/modules/logger/winston/formatters/deep-splat.js +1 -1
- package/dist/esm/modules/logger/winston/formatters/deep-splat.js.map +1 -1
- package/dist/esm/modules/logger/winston/logger-factory.js +1 -1
- package/dist/esm/modules/logger/winston/logger-factory.js.map +1 -1
- package/dist/esm/modules/logger/winston/transports/dgram.transport.js +2 -2
- package/dist/esm/modules/logger/winston/transports/dgram.transport.js.map +1 -1
- package/dist/esm/modules/network/http-request/fetcher/axios-fetcher.js +1 -1
- package/dist/esm/modules/network/http-request/fetcher/axios-fetcher.js.map +1 -1
- package/dist/esm/modules/network/http-request/fetcher/base-fetcher.d.ts +17 -14
- package/dist/esm/modules/network/http-request/fetcher/base-fetcher.d.ts.map +1 -1
- package/dist/esm/modules/network/http-request/fetcher/base-fetcher.js +3 -0
- package/dist/esm/modules/network/http-request/fetcher/base-fetcher.js.map +1 -1
- package/dist/esm/modules/network/http-request/fetcher/node-fetcher.d.ts +13 -4
- package/dist/esm/modules/network/http-request/fetcher/node-fetcher.d.ts.map +1 -1
- package/dist/esm/modules/network/http-request/fetcher/node-fetcher.js +36 -13
- package/dist/esm/modules/network/http-request/fetcher/node-fetcher.js.map +1 -1
- package/dist/esm/modules/network/tcp-socket/base-tcp-client.helper.js +1 -1
- package/dist/esm/modules/network/tcp-socket/base-tcp-client.helper.js.map +1 -1
- package/dist/esm/modules/network/tcp-socket/base-tcp-server.helper.js +4 -4
- package/dist/esm/modules/network/tcp-socket/base-tcp-server.helper.js.map +1 -1
- package/dist/esm/modules/network/udp-socket/network-udp-client.helper.js +1 -1
- package/dist/esm/modules/network/udp-socket/network-udp-client.helper.js.map +1 -1
- package/dist/esm/modules/network/utilities/query-string.d.ts +27 -2
- package/dist/esm/modules/network/utilities/query-string.d.ts.map +1 -1
- package/dist/esm/modules/network/utilities/query-string.js +31 -1
- package/dist/esm/modules/network/utilities/query-string.js.map +1 -1
- package/dist/esm/modules/network/utilities/url-safety/ingest.js +1 -1
- package/dist/esm/modules/network/utilities/url-safety/ingest.js.map +1 -1
- package/dist/esm/modules/network/utilities/url-safety/policy.js +1 -1
- package/dist/esm/modules/network/utilities/url-safety/policy.js.map +1 -1
- package/dist/esm/modules/pool/abstract.js +4 -4
- package/dist/esm/modules/pool/abstract.js.map +1 -1
- package/dist/esm/modules/queue/bullmq/helper.js +2 -2
- package/dist/esm/modules/queue/bullmq/helper.js.map +1 -1
- package/dist/esm/modules/queue/kafka/bundler/platformatic-require.plugin.js.map +1 -1
- package/dist/esm/modules/queue/kafka/bundler/platformatic-wasm.plugin.js +1 -1
- package/dist/esm/modules/queue/kafka/bundler/platformatic-wasm.plugin.js.map +1 -1
- package/dist/esm/modules/queue/kafka/consumer.js +2 -2
- package/dist/esm/modules/queue/kafka/consumer.js.map +1 -1
- package/dist/esm/modules/queue/mqtt/helper.js +4 -4
- package/dist/esm/modules/queue/mqtt/helper.js.map +1 -1
- package/dist/esm/modules/redis/base/abstract.helper.js +4 -4
- package/dist/esm/modules/redis/base/abstract.helper.js.map +1 -1
- package/dist/esm/modules/redis/cluster/cluster.helper.js +1 -1
- package/dist/esm/modules/redis/cluster/cluster.helper.js.map +1 -1
- package/dist/esm/modules/redis/sentinel/sentinel.helper.js +1 -1
- package/dist/esm/modules/redis/sentinel/sentinel.helper.js.map +1 -1
- package/dist/esm/modules/secrets/base/abstract.helper.js +2 -2
- package/dist/esm/modules/secrets/base/abstract.helper.js.map +1 -1
- package/dist/esm/modules/secrets/hashicorp/hashicorp.helper.js +2 -2
- package/dist/esm/modules/secrets/hashicorp/hashicorp.helper.js.map +1 -1
- package/dist/esm/modules/socket/socket-io/browser.d.ts +5 -0
- package/dist/esm/modules/socket/socket-io/browser.d.ts.map +1 -0
- package/dist/esm/modules/socket/socket-io/browser.js +5 -0
- package/dist/esm/modules/socket/socket-io/browser.js.map +1 -0
- package/dist/esm/modules/socket/socket-io/client/browser-helper.d.ts +61 -0
- package/dist/esm/modules/socket/socket-io/client/browser-helper.d.ts.map +1 -0
- package/dist/esm/modules/socket/socket-io/client/browser-helper.js +246 -0
- package/dist/esm/modules/socket/socket-io/client/browser-helper.js.map +1 -0
- package/dist/esm/modules/socket/socket-io/client/helper.d.ts +8 -51
- package/dist/esm/modules/socket/socket-io/client/helper.d.ts.map +1 -1
- package/dist/esm/modules/socket/socket-io/client/helper.js +12 -230
- package/dist/esm/modules/socket/socket-io/client/helper.js.map +1 -1
- package/dist/esm/modules/socket/socket-io/server/helper.js +5 -5
- package/dist/esm/modules/socket/socket-io/server/helper.js.map +1 -1
- package/dist/esm/modules/socket/websocket/server/delivery.js +2 -2
- package/dist/esm/modules/socket/websocket/server/delivery.js.map +1 -1
- package/dist/esm/modules/socket/websocket/server/helper.js +4 -4
- package/dist/esm/modules/socket/websocket/server/helper.js.map +1 -1
- package/dist/esm/modules/storage/base.js +3 -3
- package/dist/esm/modules/storage/base.js.map +1 -1
- package/dist/esm/modules/storage/bun-s3/helper.js +1 -1
- package/dist/esm/modules/storage/bun-s3/helper.js.map +1 -1
- package/dist/esm/modules/storage/bun-s3/utility.js +6 -6
- package/dist/esm/modules/storage/bun-s3/utility.js.map +1 -1
- package/dist/esm/modules/storage/common/errors.js +1 -1
- package/dist/esm/modules/storage/common/errors.js.map +1 -1
- package/dist/esm/modules/storage/minio/helper.js +4 -4
- package/dist/esm/modules/storage/minio/helper.js.map +1 -1
- package/dist/esm/modules/temporal/abstract.js +5 -5
- package/dist/esm/modules/temporal/abstract.js.map +1 -1
- package/dist/esm/modules/temporal/adapters/intl.d.ts.map +1 -1
- package/dist/esm/modules/temporal/adapters/intl.js +3 -1
- package/dist/esm/modules/temporal/adapters/intl.js.map +1 -1
- package/dist/esm/modules/temporal/locale/locale.js +4 -4
- package/dist/esm/modules/temporal/locale/locale.js.map +1 -1
- package/dist/esm/modules/tree/builder.js +2 -2
- package/dist/esm/modules/tree/builder.js.map +1 -1
- package/dist/esm/modules/uid/opaque.js +2 -2
- package/dist/esm/modules/uid/opaque.js.map +1 -1
- package/dist/esm/modules/uid/uuid/v5.js +1 -1
- package/dist/esm/modules/uid/uuid/v5.js.map +1 -1
- package/dist/esm/modules/worker-thread/bus/base.js +4 -4
- package/dist/esm/modules/worker-thread/bus/base.js.map +1 -1
- package/dist/esm/modules/worker-thread/worker/base.js +4 -4
- package/dist/esm/modules/worker-thread/worker/base.js.map +1 -1
- package/dist/esm/utilities/parse.utility.js +4 -4
- package/dist/esm/utilities/parse.utility.js.map +1 -1
- package/dist/esm/utilities/promise.utility.js +1 -1
- package/dist/esm/utilities/promise.utility.js.map +1 -1
- package/dist/esm/utilities/request.utility.js +1 -1
- package/dist/esm/utilities/request.utility.js.map +1 -1
- package/dist/esm/utilities/sleep.utility.js +1 -1
- package/dist/esm/utilities/sleep.utility.js.map +1 -1
- package/package.json +69 -64
|
@@ -1 +1 @@
|
|
|
1
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CACF;AA/ND,oDA+NC","sourcesContent":["import { isEmpty } from '@venizia/ignis-inversion';\nimport { redactSecrets } from '@/common/redact';\nimport { BaseHelper } from '@/modules/base';\nimport { type ValueOrPromise } from '@/common';\nimport {\n type TcpSocketConnectOpts as PlainConnectionOptions,\n type Socket as PlainSocketClient,\n} from 'node:net';\nimport {\n type ConnectionOptions as TlsConnectionOptions,\n type TLSSocket as TlsSocketClient,\n} from 'node:tls';\n\nconst DEFAULT_MAX_RETRY = 5;\n\nexport interface INetworkTcpClientProps<\n SocketClientOptions extends PlainConnectionOptions | TlsConnectionOptions,\n SocketClientType extends PlainSocketClient | TlsSocketClient,\n> {\n identifier: string;\n scope?: string;\n\n options: SocketClientOptions;\n reconnect?: boolean;\n maxRetry?: number;\n encoding?: BufferEncoding;\n\n createClientFn: (\n options: SocketClientOptions,\n connectionListener?: () => void,\n ) => SocketClientType;\n\n onConnected?: (opts: { client: SocketClientType }) => ValueOrPromise<void>;\n onData?: (opts: { identifier: string; message: string | Buffer }) => ValueOrPromise<void>;\n onClosed?: (opts: { client: SocketClientType }) => void;\n onError?: (error: any) => void;\n}\n\nexport class BaseNetworkTcpClient<\n SocketClientOptions extends PlainConnectionOptions | TlsConnectionOptions,\n SocketClientType extends PlainSocketClient | TlsSocketClient,\n> extends BaseHelper {\n protected client?: SocketClientType | null;\n\n protected options: SocketClientOptions;\n protected reconnect?: boolean;\n protected retry: { maxReconnect: number; currentReconnect: number } = {\n maxReconnect: DEFAULT_MAX_RETRY,\n currentReconnect: 0,\n };\n protected reconnectTimeout: any;\n protected encoding?: BufferEncoding;\n\n protected createClientFn: (\n options: SocketClientOptions,\n connectionListener?: () => void,\n ) => SocketClientType;\n\n protected onConnected: (opts: { client: SocketClientType }) => void;\n protected onData: (opts: { identifier: string; message: string | Buffer }) => void;\n protected onClosed?: (opts: { client: SocketClientType }) => void;\n protected onError?: (error: any) => void;\n\n constructor(opts: INetworkTcpClientProps<SocketClientOptions, SocketClientType>) {\n super({\n scope: opts.scope ?? opts.identifier ?? BaseNetworkTcpClient.name,\n identifier: opts.identifier,\n });\n this.options = opts.options;\n\n this.retry = {\n maxReconnect: opts.maxRetry ?? DEFAULT_MAX_RETRY,\n currentReconnect: 0,\n };\n\n this.createClientFn = opts.createClientFn;\n\n this.onConnected = opts?.onConnected ?? this.handleConnected;\n this.onData = opts?.onData ?? this.handleData;\n this.onClosed = opts?.onClosed ?? this.handleClosed;\n this.onError = opts?.onError ?? this.handleError;\n this.reconnect = opts?.reconnect ?? false;\n this.encoding = opts?.encoding;\n }\n\n getClient() {\n return this.client;\n }\n\n /** Redacts before logging - a TLS client's options ARE its private key (`key`/`cert`/`passphrase`). */\n protected getLoggableOptions(): unknown {\n return redactSecrets(this.options);\n }\n\n handleConnected() {\n this.logger\n .for(this.handleConnected.name)\n .info(\n '[%s] Connected to TCP Server | Options: %j',\n this.identifier,\n this.getLoggableOptions(),\n );\n this.retry.currentReconnect = 0;\n }\n\n handleData(_opts: { identifier: string; message: string | Buffer }) {}\n\n handleClosed() {\n this.logger\n .for(this.handleClosed.name)\n .info(\n '[%s] Closed connection TCP Server | Options: %j',\n this.identifier,\n this.getLoggableOptions(),\n );\n }\n\n handleError(error: any) {\n this.logger\n .for(this.handleError.name)\n .error(\n '[%s] Connection error | Options: %j | Error: %s',\n this.identifier,\n this.getLoggableOptions(),\n error,\n );\n\n if (!this.reconnect || this.retry.currentReconnect >= this.retry.maxReconnect) {\n return;\n }\n\n const { currentReconnect, maxReconnect } = this.retry;\n if (maxReconnect > -1 && currentReconnect >= maxReconnect) {\n this.logger\n .for(this.handleData.name)\n .info(\n 'Exceeded max retry to reconnect! Max: %d | Current: %d',\n maxReconnect,\n currentReconnect,\n );\n return;\n }\n\n this.reconnectTimeout = setTimeout(() => {\n this.client?.destroy();\n this.client = null;\n\n this.logger\n .for(this.handleClosed.name)\n .info(\n '[%s] Retrying to establish TCP Connection | Options: %j',\n this.identifier,\n this.getLoggableOptions(),\n );\n\n this.connect({ resetReconnectCounter: false });\n this.retry.currentReconnect++;\n }, 5000);\n }\n\n connect(opts: { resetReconnectCounter: boolean }) {\n if (this.isConnected()) {\n this.logger\n .for(this.connect.name)\n .info('[%s] NetworkTcpClient is already initialized!', this.identifier);\n return;\n }\n\n if (isEmpty({ value: this.options })) {\n this.logger\n .for(this.connect.name)\n .info('[%s] Cannot init TCP Client with null options', this.identifier);\n return;\n }\n\n this.logger\n .for(this.connect.name)\n .info(\n '[%s] New network tcp client | Options: %j',\n this.identifier,\n this.getLoggableOptions(),\n );\n\n if (opts?.resetReconnectCounter) {\n this.retry.currentReconnect = 0;\n }\n\n if (this.client !== null && this.client !== undefined) {\n this.client?.destroy();\n this.client = null;\n }\n\n // The listeners close over THIS socket: `this.client` is nulled by disconnect() and swapped by a reconnect, so reading it back would drop the close hook - or hand it the wrong socket.\n const client = this.createClientFn(this.options, () => {\n this.onConnected?.({ client });\n });\n\n this.client = client;\n\n if (this.encoding) {\n client.setEncoding(this.encoding);\n }\n\n client.on('data', (message: string | Buffer) => {\n this.onData({ identifier: this.identifier, message });\n });\n\n client.on('close', () => {\n this.onClosed?.({ client });\n });\n\n client.on('error', error => {\n this.onError?.(error);\n });\n }\n\n disconnect() {\n if (!this.client) {\n this.logger\n .for(this.disconnect.name)\n .info('[%s] NetworkTcpClient is not initialized yet!', this.identifier);\n return;\n }\n\n this.client?.destroy();\n this.client = null;\n\n clearTimeout(this.reconnectTimeout);\n this.reconnectTimeout = null;\n this.logger\n .for(this.disconnect.name)\n .info('[%s] NetworkTcpClient is destroyed!', this.identifier);\n }\n\n forceReconnect() {\n this.disconnect();\n this.connect({ resetReconnectCounter: true });\n }\n\n isConnected() {\n return this.client && this.client.readyState !== 'closed';\n }\n\n emit(opts: { payload: Buffer | string }) {\n if (!this.client) {\n this.logger\n .for(this.emit.name)\n .info('[%s] TPC Client is not configured yet!', this.identifier);\n return;\n }\n\n const { payload } = opts;\n if (!payload?.length) {\n this.logger\n .for(this.emit.name)\n .info('[%s] Invalid payload to write to TCP Socket!', this.identifier);\n return;\n }\n\n this.client.write(payload);\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"base-tcp-client.helper.js","sourceRoot":"","sources":["../../../../../src/modules/network/tcp-socket/base-tcp-client.helper.ts"],"names":[],"mappings":";;;AAAA,8DAAmD;AACnD,4CAAgD;AAChD,yCAA4C;AAW5C,MAAM,iBAAiB,GAAG,CAAC,CAAC;AAyB5B,MAAa,oBAGX,SAAQ,iBAAU;IAsBlB,YAAY,IAAmE;QAC7E,KAAK,CAAC;YACJ,KAAK,EAAE,IAAI,CAAC,KAAK,IAAI,IAAI,CAAC,UAAU,IAAI,oBAAoB,CAAC,IAAI;YACjE,UAAU,EAAE,IAAI,CAAC,UAAU;SAC5B,CAAC,CAAC;QArBK,UAAK,GAAuD;YACpE,YAAY,EAAE,iBAAiB;YAC/B,gBAAgB,EAAE,CAAC;SACpB,CAAC;QAmBA,IAAI,CAAC,OAAO,GAAG,IAAI,CAAC,OAAO,CAAC;QAE5B,IAAI,CAAC,KAAK,GAAG;YACX,YAAY,EAAE,IAAI,CAAC,QAAQ,IAAI,iBAAiB;YAChD,gBAAgB,EAAE,CAAC;SACpB,CAAC;QAEF,IAAI,CAAC,cAAc,GAAG,IAAI,CAAC,cAAc,CAAC;QAE1C,IAAI,CAAC,WAAW,GAAG,IAAI,EAAE,WAAW,IAAI,IAAI,CAAC,eAAe,CAAC;QAC7D,IAAI,CAAC,MAAM,GAAG,IAAI,EAAE,MAAM,IAAI,IAAI,CAAC,UAAU,CAAC;QAC9C,IAAI,CAAC,QAAQ,GAAG,IAAI,EAAE,QAAQ,IAAI,IAAI,CAAC,YAAY,CAAC;QACpD,IAAI,CAAC,OAAO,GAAG,IAAI,EAAE,OAAO,IAAI,IAAI,CAAC,WAAW,CAAC;QACjD,IAAI,CAAC,SAAS,GAAG,IAAI,EAAE,SAAS,IAAI,KAAK,CAAC;QAC1C,IAAI,CAAC,QAAQ,GAAG,IAAI,EAAE,QAAQ,CAAC;IACj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AED,IAAI,CAAC,MAAM,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC;IAC7B,CAAC;CACF;AA/ND,oDA+NC","sourcesContent":["import { isEmpty } from '@venizia/ignis-inversion';\nimport { redactSecrets } from '@/common/redact';\nimport { BaseHelper } from '@/modules/base';\nimport { type ValueOrPromise } from '@/common';\nimport {\n type TcpSocketConnectOpts as PlainConnectionOptions,\n type Socket as PlainSocketClient,\n} from 'node:net';\nimport {\n type ConnectionOptions as TlsConnectionOptions,\n type TLSSocket as TlsSocketClient,\n} from 'node:tls';\n\nconst DEFAULT_MAX_RETRY = 5;\n\nexport interface INetworkTcpClientProps<\n SocketClientOptions extends PlainConnectionOptions | TlsConnectionOptions,\n SocketClientType extends PlainSocketClient | TlsSocketClient,\n> {\n identifier: string;\n scope?: string;\n\n options: SocketClientOptions;\n reconnect?: boolean;\n maxRetry?: number;\n encoding?: BufferEncoding;\n\n createClientFn: (\n options: SocketClientOptions,\n connectionListener?: () => void,\n ) => SocketClientType;\n\n onConnected?: (opts: { client: SocketClientType }) => ValueOrPromise<void>;\n onData?: (opts: { identifier: string; message: string | Buffer }) => ValueOrPromise<void>;\n onClosed?: (opts: { client: SocketClientType }) => void;\n onError?: (error: any) => void;\n}\n\nexport class BaseNetworkTcpClient<\n SocketClientOptions extends PlainConnectionOptions | TlsConnectionOptions,\n SocketClientType extends PlainSocketClient | TlsSocketClient,\n> extends BaseHelper {\n protected client?: SocketClientType | null;\n\n protected options: SocketClientOptions;\n protected reconnect?: boolean;\n protected retry: { maxReconnect: number; currentReconnect: number } = {\n maxReconnect: DEFAULT_MAX_RETRY,\n currentReconnect: 0,\n };\n protected reconnectTimeout: any;\n protected encoding?: BufferEncoding;\n\n protected createClientFn: (\n options: SocketClientOptions,\n connectionListener?: () => void,\n ) => SocketClientType;\n\n protected onConnected: (opts: { client: SocketClientType }) => void;\n protected onData: (opts: { identifier: string; message: string | Buffer }) => void;\n protected onClosed?: (opts: { client: SocketClientType }) => void;\n protected onError?: (error: any) => void;\n\n constructor(opts: INetworkTcpClientProps<SocketClientOptions, SocketClientType>) {\n super({\n scope: opts.scope ?? opts.identifier ?? BaseNetworkTcpClient.name,\n identifier: opts.identifier,\n });\n this.options = opts.options;\n\n this.retry = {\n maxReconnect: opts.maxRetry ?? DEFAULT_MAX_RETRY,\n currentReconnect: 0,\n };\n\n this.createClientFn = opts.createClientFn;\n\n this.onConnected = opts?.onConnected ?? this.handleConnected;\n this.onData = opts?.onData ?? this.handleData;\n this.onClosed = opts?.onClosed ?? this.handleClosed;\n this.onError = opts?.onError ?? this.handleError;\n this.reconnect = opts?.reconnect ?? false;\n this.encoding = opts?.encoding;\n }\n\n getClient() {\n return this.client;\n }\n\n /** Redacts before logging - a TLS client's options ARE its private key (`key`/`cert`/`passphrase`). */\n protected getLoggableOptions(): unknown {\n return redactSecrets(this.options);\n }\n\n handleConnected() {\n this.logger\n .for(this.handleConnected.name)\n .info(\n '[%s] Connected to TCP Server | Options: %j',\n this.identifier,\n this.getLoggableOptions(),\n );\n this.retry.currentReconnect = 0;\n }\n\n handleData(_opts: { identifier: string; message: string | Buffer }) {}\n\n handleClosed() {\n this.logger\n .for(this.handleClosed.name)\n .info(\n '[%s] Closed connection TCP Server | Options: %j',\n this.identifier,\n this.getLoggableOptions(),\n );\n }\n\n handleError(error: any) {\n this.logger\n .for(this.handleError.name)\n .error(\n '[%s] Connection error | Options: %j | Error: %s',\n this.identifier,\n this.getLoggableOptions(),\n error,\n );\n\n if (!this.reconnect || this.retry.currentReconnect >= this.retry.maxReconnect) {\n return;\n }\n\n const { currentReconnect, maxReconnect } = this.retry;\n if (maxReconnect > -1 && currentReconnect >= maxReconnect) {\n this.logger\n .for(this.handleData.name)\n .info(\n 'Exceeded max retry to reconnect! Max: %d | Current: %d',\n maxReconnect,\n currentReconnect,\n );\n return;\n }\n\n this.reconnectTimeout = setTimeout(() => {\n this.client?.destroy();\n this.client = null;\n\n this.logger\n .for(this.handleClosed.name)\n .info(\n '[%s] Retrying to establish TCP Connection | Options: %j',\n this.identifier,\n this.getLoggableOptions(),\n );\n\n this.connect({ resetReconnectCounter: false });\n this.retry.currentReconnect++;\n }, 5000);\n }\n\n connect(opts: { resetReconnectCounter: boolean }) {\n if (this.isConnected()) {\n this.logger\n .for(this.connect.name)\n .info('[%s] NetworkTcpClient is already initialized!', this.identifier);\n return;\n }\n\n if (isEmpty({ value: this.options })) {\n this.logger\n .for(this.connect.name)\n .info('[%s] Cannot init TCP Client with null options', this.identifier);\n return;\n }\n\n this.logger\n .for(this.connect.name)\n .info(\n '[%s] New network tcp client | Options: %j',\n this.identifier,\n this.getLoggableOptions(),\n );\n\n if (opts?.resetReconnectCounter) {\n this.retry.currentReconnect = 0;\n }\n\n if (this.client !== null && this.client !== undefined) {\n this.client?.destroy();\n this.client = null;\n }\n\n // The listeners close over THIS socket: `this.client` is nulled by disconnect() and swapped by a reconnect, so reading it back would drop the close hook - or hand it the wrong socket.\n const client = this.createClientFn(this.options, () => {\n this.onConnected?.({ client });\n });\n\n this.client = client;\n\n if (this.encoding) {\n client.setEncoding(this.encoding);\n }\n\n client.on('data', (message: string | Buffer) => {\n this.onData({ identifier: this.identifier, message });\n });\n\n client.on('close', () => {\n this.onClosed?.({ client });\n });\n\n client.on('error', (error) => {\n this.onError?.(error);\n });\n }\n\n disconnect() {\n if (!this.client) {\n this.logger\n .for(this.disconnect.name)\n .info('[%s] NetworkTcpClient is not initialized yet!', this.identifier);\n return;\n }\n\n this.client?.destroy();\n this.client = null;\n\n clearTimeout(this.reconnectTimeout);\n this.reconnectTimeout = null;\n this.logger\n .for(this.disconnect.name)\n .info('[%s] NetworkTcpClient is destroyed!', this.identifier);\n }\n\n forceReconnect() {\n this.disconnect();\n this.connect({ resetReconnectCounter: true });\n }\n\n isConnected() {\n return this.client && this.client.readyState !== 'closed';\n }\n\n emit(opts: { payload: Buffer | string }) {\n if (!this.client) {\n this.logger\n .for(this.emit.name)\n .info('[%s] TPC Client is not configured yet!', this.identifier);\n return;\n }\n\n const { payload } = opts;\n if (!payload?.length) {\n this.logger\n .for(this.emit.name)\n .info('[%s] Invalid payload to write to TCP Socket!', this.identifier);\n return;\n }\n\n this.client.write(payload);\n }\n}\n"]}
|
|
@@ -44,7 +44,7 @@ class BaseNetworkTcpServer extends base_1.BaseHelper {
|
|
|
44
44
|
}
|
|
45
45
|
}
|
|
46
46
|
configure() {
|
|
47
|
-
this.server = this.createServerFn(this.serverOptions, socket => {
|
|
47
|
+
this.server = this.createServerFn(this.serverOptions, (socket) => {
|
|
48
48
|
this.onNewConnection({ socket });
|
|
49
49
|
});
|
|
50
50
|
// Without this listener a failed listen - a port already in use is the commonest boot failure there is - emits an unhandled 'error' event, which takes the whole process down with it.
|
|
@@ -111,7 +111,7 @@ class BaseNetworkTcpServer extends base_1.BaseHelper {
|
|
|
111
111
|
delete this.clients[id];
|
|
112
112
|
});
|
|
113
113
|
for (const extraEvent in this.extraEvents) {
|
|
114
|
-
socket.on(extraEvent, args => {
|
|
114
|
+
socket.on(extraEvent, (args) => {
|
|
115
115
|
(0, promise_utility_1.voidExecution)({
|
|
116
116
|
logger: this.logger,
|
|
117
117
|
scope: 'onClientConnect',
|
|
@@ -188,8 +188,8 @@ class BaseNetworkTcpServer extends base_1.BaseHelper {
|
|
|
188
188
|
return;
|
|
189
189
|
}
|
|
190
190
|
// Not guarded on `listening`: listen() is async (DNS lookup), so a shutdown() racing startup could skip close() and leave the server bound forever; close() on a never-listened server just logs ERR_SERVER_NOT_RUNNING below.
|
|
191
|
-
await new Promise(resolve => {
|
|
192
|
-
server.close(error => {
|
|
191
|
+
await new Promise((resolve) => {
|
|
192
|
+
server.close((error) => {
|
|
193
193
|
if (error) {
|
|
194
194
|
this.logger.for(this.shutdown.name).error('Failed to close server | Error: %s', error);
|
|
195
195
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"base-tcp-server.helper.js","sourceRoot":"","sources":["../../../../../src/modules/network/tcp-socket/base-tcp-server.helper.ts"],"names":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import { type ValueOrPromise } from '@/common/types';\nimport { BaseHelper } from '@/modules/base';\nimport { getError } from '@/modules/error';\nimport { getUID } from '@/utilities/parse.utility';\nimport { voidExecution } from '@/utilities/promise.utility';\nimport {\n type ListenOptions,\n type ServerOpts,\n type Socket as SocketClient,\n type Server as SocketServer,\n} from 'node:net';\n\nexport interface ITcpSocketClient<SocketClientType> {\n id: string;\n socket: SocketClientType;\n state: 'unauthorized' | 'authenticating' | 'authenticated';\n subscriptions: Set<string>;\n storage: {\n connectedAt: Date;\n authenticatedAt: Date | null;\n authenticateTimeout?: ReturnType<typeof setTimeout> | null;\n [additionField: symbol | string]: any;\n };\n}\n\nexport interface ITcpSocketServerOptions<\n SocketServerOptions extends ServerOpts = ServerOpts,\n SocketServerType extends SocketServer = SocketServer,\n SocketClientType extends SocketClient = SocketClient,\n> {\n scope?: string;\n identifier: string;\n\n serverOptions: Partial<SocketServerOptions>;\n listenOptions: Partial<ListenOptions>;\n authenticateOptions: { required: boolean; duration?: number };\n\n extraEvents?: Record<\n string,\n (opts: { id: string; socket: SocketClientType; args: any }) => ValueOrPromise<void>\n >;\n\n createServerFn: (\n options: Partial<SocketServerOptions>,\n connectionListener: (socket: SocketClientType) => void,\n ) => SocketServerType;\n\n onServerReady?: (opts: { server: SocketServerType }) => void;\n onClientConnected?: (opts: { id: string; socket: SocketClientType }) => void;\n onClientData?: (opts: { id: string; socket: SocketClientType; data: Buffer | string }) => void;\n onClientClose?: (opts: { id: string; socket: SocketClientType }) => void;\n onClientError?: (opts: { id: string; socket: SocketClientType; error: Error }) => void;\n onServerError?: (opts: { server: SocketServerType; error: Error }) => void;\n}\n\nexport class BaseNetworkTcpServer<\n SocketServerOptions extends ServerOpts = ServerOpts,\n SocketServerType extends SocketServer = SocketServer,\n SocketClientType extends SocketClient = SocketClient,\n> extends BaseHelper {\n protected serverOptions: Partial<SocketServerOptions> = {};\n protected listenOptions: Partial<ListenOptions> = {};\n protected authenticateOptions: { required: boolean; duration?: number };\n\n protected clients: Record<string, ITcpSocketClient<SocketClientType>>;\n protected server: SocketServerType;\n\n protected extraEvents: Record<\n string,\n (opts: { id: string; socket: SocketClientType; args: any }) => ValueOrPromise<void>\n >;\n\n protected createServerFn: (\n options: Partial<SocketServerOptions>,\n connectionListener: (socket: SocketClientType) => void,\n ) => SocketServerType;\n\n protected onServerReady?: (opts: { server: SocketServerType }) => void;\n protected onClientConnected?: (opts: { id: string; socket: SocketClientType }) => void;\n protected onClientData?: (opts: {\n id: string;\n socket: SocketClientType;\n data: Buffer | string;\n }) => void;\n protected onClientClose?: (opts: { id: string; socket: SocketClientType }) => void;\n protected onClientError?: (opts: { id: string; socket: SocketClientType; error: Error }) => void;\n protected onServerError?: (opts: { server: SocketServerType; error: Error }) => void;\n\n constructor(\n opts: ITcpSocketServerOptions<SocketServerOptions, SocketServerType, SocketClientType>,\n ) {\n super({\n scope: opts.scope ?? opts.identifier ?? BaseNetworkTcpServer.name,\n identifier: opts.identifier,\n });\n\n this.clients = Object.assign({});\n\n this.serverOptions = opts.serverOptions;\n this.listenOptions = opts.listenOptions;\n this.authenticateOptions = opts.authenticateOptions;\n\n if (\n this.authenticateOptions.required &&\n (!this.authenticateOptions.duration || this.authenticateOptions.duration < 0)\n ) {\n throw getError({\n message:\n 'TCP Server | Invalid authenticate duration | Required duration for authenticateOptions',\n });\n }\n\n this.extraEvents = opts.extraEvents ?? {};\n\n this.createServerFn = opts.createServerFn;\n\n this.onServerReady = opts.onServerReady;\n this.onClientConnected = opts.onClientConnected;\n this.onClientData = opts.onClientData;\n this.onClientClose = opts.onClientClose;\n this.onClientError = opts.onClientError;\n this.onServerError = opts.onServerError;\n\n this.configure();\n }\n\n // Hooks run inside socket event listeners: a synchronous throw there is an uncaught exception that kills the process and skips the client-registry cleanup that follows it.\n protected invokeHook(opts: { scope: string; execution: () => void }) {\n const { scope, execution } = opts;\n\n try {\n execution();\n } catch (error) {\n this.logger.for(scope).error('Hook execution FAILED | Error: %s', error);\n }\n }\n\n configure() {\n this.server = this.createServerFn(this.serverOptions, socket => {\n this.onNewConnection({ socket });\n });\n\n // Without this listener a failed listen - a port already in use is the commonest boot failure there is - emits an unhandled 'error' event, which takes the whole process down with it.\n this.server.on('error', (error: Error) => {\n this.logger\n .for(this.configure.name)\n .error('TCP Socket Server error | Options: %j | Error: %s', this.listenOptions, error);\n\n this.invokeHook({\n scope: this.configure.name,\n execution: () => {\n this.onServerError?.({ server: this.server, error });\n },\n });\n });\n\n this.server.listen(this.listenOptions, () => {\n this.logger\n .for(this.configure.name)\n .info('TCP Socket Server is now listening | Options: %j', this.listenOptions);\n\n this.invokeHook({\n scope: this.configure.name,\n execution: () => {\n this.onServerReady?.({ server: this.server });\n },\n });\n });\n }\n\n onNewConnection(opts: { socket: SocketClientType }) {\n const { socket } = opts;\n\n const id = getUID();\n\n socket.on('data', (data: Buffer | string) => {\n this.invokeHook({\n scope: 'onClientData',\n execution: () => {\n this.onClientData?.({ id, socket, data });\n },\n });\n });\n\n socket.on('error', (error: Error) => {\n this.logger.for('onClientConnect').error('Socket Error | ID: %s | Error: %s', id, error);\n\n this.invokeHook({\n scope: 'onClientError',\n execution: () => {\n this.onClientError?.({ id, socket, error });\n },\n });\n\n socket.end();\n });\n\n socket.on('close', (hasError: boolean) => {\n this.logger\n .for('onClientConnect')\n .info('Socket Closed | ID: %s | hasError: %s', id, hasError);\n\n this.invokeHook({\n scope: 'onClientClose',\n execution: () => {\n this.onClientClose?.({ id, socket });\n },\n });\n\n const authenticateTimeout = this.getClient({ id })?.storage?.authenticateTimeout;\n if (authenticateTimeout) {\n clearTimeout(authenticateTimeout);\n }\n\n // `delete`, not `omit`: omit rebuilds the WHOLE registry per disconnect, so a disconnect\n // storm is O(n^2) - measured at 5000 clients, 2.3s of drain with a 2.2s worst-case stall.\n delete this.clients[id];\n });\n\n for (const extraEvent in this.extraEvents) {\n socket.on(extraEvent, args => {\n voidExecution({\n logger: this.logger,\n scope: 'onClientConnect',\n // The async wrapper turns a SYNCHRONOUS throw from the handler into a rejection; calling it bare would throw out of this listener as an uncaught exception.\n execution: (async () => this.extraEvents[extraEvent]({ id, socket, args }))(),\n });\n });\n }\n\n this.clients[id] = {\n id,\n socket,\n state: this.authenticateOptions.required ? 'unauthorized' : 'authenticated',\n subscriptions: new Set([]),\n storage: {\n connectedAt: new Date(),\n authenticatedAt: this.authenticateOptions.required ? null : new Date(),\n },\n };\n\n this.logger\n .for('onClientConnect')\n .info(\n 'New TCP SocketClient | Client: %s | authenticateOptions: %s %s',\n `${id} - ${socket.remoteAddress} - ${socket.remotePort} - ${socket.remoteFamily}`,\n this.authenticateOptions.required,\n this.authenticateOptions.duration,\n );\n\n this.invokeHook({\n scope: 'onClientConnected',\n execution: () => {\n this.onClientConnected?.({ id, socket });\n },\n });\n\n if (\n this.authenticateOptions.required &&\n this.authenticateOptions.duration &&\n this.authenticateOptions.duration > 0\n ) {\n const authenticateTimeout = setTimeout(() => {\n const client = this.getClient({ id });\n if (!client) {\n return;\n }\n\n client.storage.authenticateTimeout = null;\n\n if (client.state === 'authenticated') {\n return;\n }\n\n this.emit({ clientId: id, payload: 'Unauthorized Client' });\n client.socket.end();\n }, this.authenticateOptions.duration);\n\n const client = this.getClient({ id });\n if (!client) {\n clearTimeout(authenticateTimeout);\n return;\n }\n\n client.storage.authenticateTimeout = authenticateTimeout;\n }\n }\n\n getClients() {\n return this.clients;\n }\n\n getClient(opts: { id: string }) {\n return this.clients?.[opts.id];\n }\n\n getServer() {\n return this.server;\n }\n\n /** Clears timers and destroys all client sockets before closing the listener - `server.close()` alone never settles while a socket stays attached. Idempotent; safe if never listened. */\n async shutdown(): Promise<void> {\n const clientsValues = Object.values(this.clients);\n for (const client of clientsValues) {\n const { authenticateTimeout } = client.storage;\n if (authenticateTimeout) {\n clearTimeout(authenticateTimeout);\n client.storage.authenticateTimeout = null;\n }\n\n client.socket.destroy();\n }\n\n this.clients = {};\n\n const server = this.server;\n if (!server) {\n return;\n }\n\n // Not guarded on `listening`: listen() is async (DNS lookup), so a shutdown() racing startup could skip close() and leave the server bound forever; close() on a never-listened server just logs ERR_SERVER_NOT_RUNNING below.\n\n await new Promise<void>(resolve => {\n server.close(error => {\n if (error) {\n this.logger.for(this.shutdown.name).error('Failed to close server | Error: %s', error);\n }\n\n resolve();\n });\n });\n\n this.logger.for(this.shutdown.name).info('Server closed | Identifier: %s', this.identifier);\n }\n\n doAuthenticate(opts: { id: string; state: 'unauthorized' | 'authenticating' | 'authenticated' }) {\n const { id, state } = opts;\n\n const client = this.getClient({ id });\n if (!client) {\n this.logger.for('authenticateClient').error('Client NOT FOUND | ID: %s', id);\n return;\n }\n\n client.state = state;\n\n switch (state) {\n case 'unauthorized':\n case 'authenticating': {\n client.storage.authenticatedAt = null;\n break;\n }\n case 'authenticated': {\n client.storage.authenticatedAt = new Date();\n\n if (client.storage.authenticateTimeout) {\n clearTimeout(client.storage.authenticateTimeout);\n client.storage.authenticateTimeout = null;\n }\n break;\n }\n default: {\n break;\n }\n }\n }\n\n emit(opts: { clientId: string; payload: Buffer | string }) {\n const { clientId, payload } = opts;\n const client = this.getClient({ id: clientId });\n\n if (!client) {\n this.logger.for(this.emit.name).error('Client NOT FOUND | ID: %s', clientId);\n return;\n }\n\n const { socket } = client;\n if (!socket.writable) {\n this.logger.for(this.emit.name).error('Client NOT WRITABLE | ID: %s', clientId);\n return;\n }\n\n if (!payload?.length) {\n this.logger\n .for(this.emit.name)\n .info(\n '[%s] Client %s | Invalid payload to write to TCP Socket!',\n this.identifier,\n clientId,\n );\n return;\n }\n\n socket.write(payload);\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"base-tcp-server.helper.js","sourceRoot":"","sources":["../../../../../src/modules/network/tcp-socket/base-tcp-server.helper.ts"],"names":[],"mappings":";;;AACA,yCAA4C;AAC5C,2CAA2C;AAC3C,6DAAmD;AACnD,iEAA4D;AAmD5D,MAAa,oBAIX,SAAQ,iBAAU;IA6BlB,YACE,IAAsF;QAEtF,KAAK,CAAC;YACJ,KAAK,EA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ACjD,MAAM,CAAC,OAAO,CAAC,mBAAmB,GAAG,IAAI,CAAC;gBAC5C,CAAC;gBACD,MAAM;YACR,CAAC;YACD,OAAO,CAAC,CAAC,CAAC;gBACR,MAAM;YACR,CAAC;QACH,CAAC;IACH,CAAC;IAED,IAAI,CAAC,IAAoD;QACvD,MAAM,EAAE,QAAQ,EAAE,OAAO,EAAE,GAAG,IAAI,CAAC;QACnC,MAAM,MAAM,GAAG,IAAI,CAAC,SAAS,CAAC,EAAE,EAAE,EAAE,QAAQ,EAAE,CAAC,CAAC;QAEhD,IAAI,CAAC,MAAM,EAAE,CAAC;YACZ,IAAI,CAAC,MAAM,CAAC,GAAG,CAAC,IAAI,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,KAAK,CAAC,2BAA2B,EAAE,QAAQ,CAAC,CAAC;YAC7E,OAAO;QACT,CAAC;QAED,MAAM,EAAE,MAAM,EAAE,GAAG,MAAM,CAAC;QAC1B,IAAI,CAAC,MAAM,CAAC,QAAQ,EAAE,CAAC;YACrB,IAAI,CAAC,MAAM,CAAC,GAAG,CAAC,IAAI,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,KAAK,CAAC,8BAA8B,EAAE,QAAQ,CAAC,CAAC;YAChF,OAAO;QACT,CAAC;QAED,IAAI,CAAC,OAAO,EAAE,MAAM,EAAE,CAAC;YACrB,IAAI,CAAC,MAAM;iBACR,GAAG,CAAC,IAAI,CAAC,IAAI,CAAC,IAAI,CAAC;iBACnB,IAAI,CACH,0DAA0D,EAC1D,IAAI,CAAC,UAAU,EACf,QAAQ,CACT,CAAC;YACJ,OAAO;QACT,CAAC;QAED,MAAM,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC;IACxB,CAAC;CACF;AApVD,oDAoVC","sourcesContent":["import { type ValueOrPromise } from '@/common/types';\nimport { BaseHelper } from '@/modules/base';\nimport { getError } from '@/modules/error';\nimport { getUID } from '@/utilities/parse.utility';\nimport { voidExecution } from '@/utilities/promise.utility';\nimport {\n type ListenOptions,\n type ServerOpts,\n type Socket as SocketClient,\n type Server as SocketServer,\n} from 'node:net';\n\nexport interface ITcpSocketClient<SocketClientType> {\n id: string;\n socket: SocketClientType;\n state: 'unauthorized' | 'authenticating' | 'authenticated';\n subscriptions: Set<string>;\n storage: {\n connectedAt: Date;\n authenticatedAt: Date | null;\n authenticateTimeout?: ReturnType<typeof setTimeout> | null;\n [additionField: symbol | string]: any;\n };\n}\n\nexport interface ITcpSocketServerOptions<\n SocketServerOptions extends ServerOpts = ServerOpts,\n SocketServerType extends SocketServer = SocketServer,\n SocketClientType extends SocketClient = SocketClient,\n> {\n scope?: string;\n identifier: string;\n\n serverOptions: Partial<SocketServerOptions>;\n listenOptions: Partial<ListenOptions>;\n authenticateOptions: { required: boolean; duration?: number };\n\n extraEvents?: Record<\n string,\n (opts: { id: string; socket: SocketClientType; args: any }) => ValueOrPromise<void>\n >;\n\n createServerFn: (\n options: Partial<SocketServerOptions>,\n connectionListener: (socket: SocketClientType) => void,\n ) => SocketServerType;\n\n onServerReady?: (opts: { server: SocketServerType }) => void;\n onClientConnected?: (opts: { id: string; socket: SocketClientType }) => void;\n onClientData?: (opts: { id: string; socket: SocketClientType; data: Buffer | string }) => void;\n onClientClose?: (opts: { id: string; socket: SocketClientType }) => void;\n onClientError?: (opts: { id: string; socket: SocketClientType; error: Error }) => void;\n onServerError?: (opts: { server: SocketServerType; error: Error }) => void;\n}\n\nexport class BaseNetworkTcpServer<\n SocketServerOptions extends ServerOpts = ServerOpts,\n SocketServerType extends SocketServer = SocketServer,\n SocketClientType extends SocketClient = SocketClient,\n> extends BaseHelper {\n protected serverOptions: Partial<SocketServerOptions> = {};\n protected listenOptions: Partial<ListenOptions> = {};\n protected authenticateOptions: { required: boolean; duration?: number };\n\n protected clients: Record<string, ITcpSocketClient<SocketClientType>>;\n protected server: SocketServerType;\n\n protected extraEvents: Record<\n string,\n (opts: { id: string; socket: SocketClientType; args: any }) => ValueOrPromise<void>\n >;\n\n protected createServerFn: (\n options: Partial<SocketServerOptions>,\n connectionListener: (socket: SocketClientType) => void,\n ) => SocketServerType;\n\n protected onServerReady?: (opts: { server: SocketServerType }) => void;\n protected onClientConnected?: (opts: { id: string; socket: SocketClientType }) => void;\n protected onClientData?: (opts: {\n id: string;\n socket: SocketClientType;\n data: Buffer | string;\n }) => void;\n protected onClientClose?: (opts: { id: string; socket: SocketClientType }) => void;\n protected onClientError?: (opts: { id: string; socket: SocketClientType; error: Error }) => void;\n protected onServerError?: (opts: { server: SocketServerType; error: Error }) => void;\n\n constructor(\n opts: ITcpSocketServerOptions<SocketServerOptions, SocketServerType, SocketClientType>,\n ) {\n super({\n scope: opts.scope ?? opts.identifier ?? BaseNetworkTcpServer.name,\n identifier: opts.identifier,\n });\n\n this.clients = Object.assign({});\n\n this.serverOptions = opts.serverOptions;\n this.listenOptions = opts.listenOptions;\n this.authenticateOptions = opts.authenticateOptions;\n\n if (\n this.authenticateOptions.required &&\n (!this.authenticateOptions.duration || this.authenticateOptions.duration < 0)\n ) {\n throw getError({\n message:\n 'TCP Server | Invalid authenticate duration | Required duration for authenticateOptions',\n });\n }\n\n this.extraEvents = opts.extraEvents ?? {};\n\n this.createServerFn = opts.createServerFn;\n\n this.onServerReady = opts.onServerReady;\n this.onClientConnected = opts.onClientConnected;\n this.onClientData = opts.onClientData;\n this.onClientClose = opts.onClientClose;\n this.onClientError = opts.onClientError;\n this.onServerError = opts.onServerError;\n\n this.configure();\n }\n\n // Hooks run inside socket event listeners: a synchronous throw there is an uncaught exception that kills the process and skips the client-registry cleanup that follows it.\n protected invokeHook(opts: { scope: string; execution: () => void }) {\n const { scope, execution } = opts;\n\n try {\n execution();\n } catch (error) {\n this.logger.for(scope).error('Hook execution FAILED | Error: %s', error);\n }\n }\n\n configure() {\n this.server = this.createServerFn(this.serverOptions, (socket) => {\n this.onNewConnection({ socket });\n });\n\n // Without this listener a failed listen - a port already in use is the commonest boot failure there is - emits an unhandled 'error' event, which takes the whole process down with it.\n this.server.on('error', (error: Error) => {\n this.logger\n .for(this.configure.name)\n .error('TCP Socket Server error | Options: %j | Error: %s', this.listenOptions, error);\n\n this.invokeHook({\n scope: this.configure.name,\n execution: () => {\n this.onServerError?.({ server: this.server, error });\n },\n });\n });\n\n this.server.listen(this.listenOptions, () => {\n this.logger\n .for(this.configure.name)\n .info('TCP Socket Server is now listening | Options: %j', this.listenOptions);\n\n this.invokeHook({\n scope: this.configure.name,\n execution: () => {\n this.onServerReady?.({ server: this.server });\n },\n });\n });\n }\n\n onNewConnection(opts: { socket: SocketClientType }) {\n const { socket } = opts;\n\n const id = getUID();\n\n socket.on('data', (data: Buffer | string) => {\n this.invokeHook({\n scope: 'onClientData',\n execution: () => {\n this.onClientData?.({ id, socket, data });\n },\n });\n });\n\n socket.on('error', (error: Error) => {\n this.logger.for('onClientConnect').error('Socket Error | ID: %s | Error: %s', id, error);\n\n this.invokeHook({\n scope: 'onClientError',\n execution: () => {\n this.onClientError?.({ id, socket, error });\n },\n });\n\n socket.end();\n });\n\n socket.on('close', (hasError: boolean) => {\n this.logger\n .for('onClientConnect')\n .info('Socket Closed | ID: %s | hasError: %s', id, hasError);\n\n this.invokeHook({\n scope: 'onClientClose',\n execution: () => {\n this.onClientClose?.({ id, socket });\n },\n });\n\n const authenticateTimeout = this.getClient({ id })?.storage?.authenticateTimeout;\n if (authenticateTimeout) {\n clearTimeout(authenticateTimeout);\n }\n\n // `delete`, not `omit`: omit rebuilds the WHOLE registry per disconnect, so a disconnect\n // storm is O(n^2) - measured at 5000 clients, 2.3s of drain with a 2.2s worst-case stall.\n delete this.clients[id];\n });\n\n for (const extraEvent in this.extraEvents) {\n socket.on(extraEvent, (args) => {\n voidExecution({\n logger: this.logger,\n scope: 'onClientConnect',\n // The async wrapper turns a SYNCHRONOUS throw from the handler into a rejection; calling it bare would throw out of this listener as an uncaught exception.\n execution: (async () => this.extraEvents[extraEvent]({ id, socket, args }))(),\n });\n });\n }\n\n this.clients[id] = {\n id,\n socket,\n state: this.authenticateOptions.required ? 'unauthorized' : 'authenticated',\n subscriptions: new Set([]),\n storage: {\n connectedAt: new Date(),\n authenticatedAt: this.authenticateOptions.required ? null : new Date(),\n },\n };\n\n this.logger\n .for('onClientConnect')\n .info(\n 'New TCP SocketClient | Client: %s | authenticateOptions: %s %s',\n `${id} - ${socket.remoteAddress} - ${socket.remotePort} - ${socket.remoteFamily}`,\n this.authenticateOptions.required,\n this.authenticateOptions.duration,\n );\n\n this.invokeHook({\n scope: 'onClientConnected',\n execution: () => {\n this.onClientConnected?.({ id, socket });\n },\n });\n\n if (\n this.authenticateOptions.required &&\n this.authenticateOptions.duration &&\n this.authenticateOptions.duration > 0\n ) {\n const authenticateTimeout = setTimeout(() => {\n const client = this.getClient({ id });\n if (!client) {\n return;\n }\n\n client.storage.authenticateTimeout = null;\n\n if (client.state === 'authenticated') {\n return;\n }\n\n this.emit({ clientId: id, payload: 'Unauthorized Client' });\n client.socket.end();\n }, this.authenticateOptions.duration);\n\n const client = this.getClient({ id });\n if (!client) {\n clearTimeout(authenticateTimeout);\n return;\n }\n\n client.storage.authenticateTimeout = authenticateTimeout;\n }\n }\n\n getClients() {\n return this.clients;\n }\n\n getClient(opts: { id: string }) {\n return this.clients?.[opts.id];\n }\n\n getServer() {\n return this.server;\n }\n\n /** Clears timers and destroys all client sockets before closing the listener - `server.close()` alone never settles while a socket stays attached. Idempotent; safe if never listened. */\n async shutdown(): Promise<void> {\n const clientsValues = Object.values(this.clients);\n for (const client of clientsValues) {\n const { authenticateTimeout } = client.storage;\n if (authenticateTimeout) {\n clearTimeout(authenticateTimeout);\n client.storage.authenticateTimeout = null;\n }\n\n client.socket.destroy();\n }\n\n this.clients = {};\n\n const server = this.server;\n if (!server) {\n return;\n }\n\n // Not guarded on `listening`: listen() is async (DNS lookup), so a shutdown() racing startup could skip close() and leave the server bound forever; close() on a never-listened server just logs ERR_SERVER_NOT_RUNNING below.\n\n await new Promise<void>((resolve) => {\n server.close((error) => {\n if (error) {\n this.logger.for(this.shutdown.name).error('Failed to close server | Error: %s', error);\n }\n\n resolve();\n });\n });\n\n this.logger.for(this.shutdown.name).info('Server closed | Identifier: %s', this.identifier);\n }\n\n doAuthenticate(opts: { id: string; state: 'unauthorized' | 'authenticating' | 'authenticated' }) {\n const { id, state } = opts;\n\n const client = this.getClient({ id });\n if (!client) {\n this.logger.for('authenticateClient').error('Client NOT FOUND | ID: %s', id);\n return;\n }\n\n client.state = state;\n\n switch (state) {\n case 'unauthorized':\n case 'authenticating': {\n client.storage.authenticatedAt = null;\n break;\n }\n case 'authenticated': {\n client.storage.authenticatedAt = new Date();\n\n if (client.storage.authenticateTimeout) {\n clearTimeout(client.storage.authenticateTimeout);\n client.storage.authenticateTimeout = null;\n }\n break;\n }\n default: {\n break;\n }\n }\n }\n\n emit(opts: { clientId: string; payload: Buffer | string }) {\n const { clientId, payload } = opts;\n const client = this.getClient({ id: clientId });\n\n if (!client) {\n this.logger.for(this.emit.name).error('Client NOT FOUND | ID: %s', clientId);\n return;\n }\n\n const { socket } = client;\n if (!socket.writable) {\n this.logger.for(this.emit.name).error('Client NOT WRITABLE | ID: %s', clientId);\n return;\n }\n\n if (!payload?.length) {\n this.logger\n .for(this.emit.name)\n .info(\n '[%s] Client %s | Invalid payload to write to TCP Socket!',\n this.identifier,\n clientId,\n );\n return;\n }\n\n socket.write(payload);\n }\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"network-udp-client.helper.js","sourceRoot":"","sources":["../../../../../src/modules/network/udp-socket/network-udp-client.helper.ts"],"names":[],"mappings":";;;;;;AACA,yCAA4C;AAC5C,iEAA4D;AAC5D,4DAA+B;AAgC/B,MAAa,gBAAiB,SAAQ,iBAAU;IAkC9C,YAAY,IAA4B;QACtC,KAAK,CAAC,EAAE,KAAK,EAAE,gBAAgB,CAAC,IAAI,EAAE,UAAU,EAAE,IAAI,CAAC,UAAU,EAAE,CAAC,CAAC;QAErE,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC,I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AAC,CAAC;IACL,CAAC;IAED,8FAA8F;IACtF,UAAU,CAAC,IAA8C;QAC/D,MAAM,EAAE,KAAK,EAAE,SAAS,EAAE,GAAG,IAAI,CAAC;QAElC,IAAI,CAAC;YACH,SAAS,EAAE,CAAC;QACd,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACf,IAAI,CAAC,MAAM,CAAC,GAAG,CAAC,KAAK,CAAC,CAAC,KAAK,CAAC,mCAAmC,EAAE,KAAK,CAAC,CAAC;QAC3E,CAAC;IACH,CAAC;IAED,UAAU;QACR,IAAI,CAAC,IAAI,CAAC,MAAM,EAAE,CAAC;YACjB,IAAI,CAAC,MAAM;iBACR,GAAG,CAAC,IAAI,CAAC,UAAU,CAAC,IAAI,CAAC;iBACzB,IAAI,CAAC,wCAAwC,EAAE,IAAI,CAAC,UAAU,CAAC,CAAC;YACnE,OAAO;QACT,CAAC;QAED,IAAI,CAAC,MAAM,EAAE,KAAK,EAAE,CAAC;QAErB,IAAI,CAAC,MAAM,GAAG,IAAI,CAAC;QACnB,IAAI,CAAC,MAAM,CAAC,GAAG,CAAC,IAAI,CAAC,UAAU,CAAC,IAAI,CAAC,CAAC,IAAI,CAAC,kCAAkC,EAAE,IAAI,CAAC,UAAU,CAAC,CAAC;IAClG,CAAC;IAED,WAAW;QACT,OAAO,IAAI,CAAC,MAAM,CAAC;IACrB,CAAC;CACF;AAnND,4CAmNC","sourcesContent":["import { type ValueOrPromise } from '@/common';\nimport { BaseHelper } from '@/modules/base';\nimport { voidExecution } from '@/utilities/promise.utility';\nimport dgram from 'node:dgram';\n\ninterface INetworkUdpClientProps {\n identifier: string;\n\n host?: string;\n port: number;\n reuseAddr?: boolean;\n\n multicastAddress?: {\n groups?: Array<string>;\n interface?: string;\n };\n\n onConnected?: (opts: { identifier: string; host?: string; port: number }) => void;\n onData?: (opts: {\n identifier: string;\n message: string | Buffer;\n remoteInfo: dgram.RemoteInfo;\n }) => void;\n onClosed?: (opts: { identifier: string; host?: string; port: number }) => void;\n onError?: (opts: { identifier: string; host?: string; port: number; error: Error }) => void;\n onBind?: (opts: {\n identifier: string;\n socket: dgram.Socket;\n host?: string;\n port: number;\n reuseAddr?: boolean;\n multicastAddress?: { groups?: Array<string>; interface?: string };\n }) => ValueOrPromise<void>;\n}\n\nexport class NetworkUdpClient extends BaseHelper {\n private host?: string;\n private port: number;\n private reuseAddr?: boolean;\n\n private multicastAddress?: {\n groups?: Array<string>;\n interface?: string;\n };\n\n private onConnected: (opts: { identifier: string; host?: string; port: number }) => void;\n private onData: (opts: {\n identifier: string;\n message: string | Buffer;\n remoteInfo: dgram.RemoteInfo;\n }) => void;\n private onClosed?: (opts: { identifier: string; host?: string; port: number }) => void;\n private onError?: (opts: {\n identifier: string;\n host?: string;\n port: number;\n error: Error;\n }) => void;\n private onBind?: (opts: {\n identifier: string;\n socket: dgram.Socket;\n host?: string;\n port: number;\n reuseAddr?: boolean;\n multicastAddress?: { groups?: Array<string>; interface?: string };\n }) => ValueOrPromise<void>;\n\n private client?: dgram.Socket | null;\n\n constructor(opts: INetworkUdpClientProps) {\n super({ scope: NetworkUdpClient.name, identifier: opts.identifier });\n\n this.host = opts.host;\n this.port = opts.port;\n this.reuseAddr = opts.reuseAddr;\n this.multicastAddress = opts.multicastAddress;\n\n this.onConnected = opts?.onConnected ?? this.handleConnected;\n this.onData = opts?.onData ?? this.handleData;\n this.onClosed = opts?.onClosed ?? this.handleClosed;\n this.onError = opts?.onError ?? this.handleError;\n this.onBind = opts?.onBind;\n }\n\n static newInstance(opts: INetworkUdpClientProps) {\n return new NetworkUdpClient(opts);\n }\n\n getClient() {\n return this.client;\n }\n\n handleConnected() {\n this.logger\n .for(this.handleConnected.name)\n .info('[%s] Successfully bind connection | Options: %j', this.identifier, {\n host: this.host,\n port: this.port,\n multicastAddress: this.multicastAddress,\n });\n }\n\n handleData(opts: { identifier: string; message: string | Buffer; remoteInfo: dgram.RemoteInfo }) {\n this.logger\n .for(this.handleData.name)\n .info('[%s][%s:%d][<==] Raw: %s', this.identifier, this.host, this.port, {\n message: opts.message,\n remoteInfo: opts.remoteInfo,\n });\n }\n\n handleClosed() {\n this.logger\n .for(this.handleClosed.name)\n .info('[%s] Closed connection UDP Server | Options: %j', this.identifier, {\n host: this.host,\n port: this.port,\n multicastAddress: this.multicastAddress,\n });\n }\n\n handleError(opts: { identifier: string; error: Error }) {\n this.logger.for(this.handleError.name).error(\n '[%s] Connection error | Options: %j | Error: %s',\n this.identifier,\n {\n host: this.host,\n port: this.port,\n },\n opts.error,\n );\n }\n\n connect() {\n if (this.client) {\n this.logger\n .for(this.connect.name)\n .info('[%s] UdpClient is already initialized!', this.identifier);\n return;\n }\n\n // Port 0 is a VALID request for an OS assigned port - only a missing / negative port is invalid.\n if (!Number.isInteger(this.port) || this.port < 0) {\n this.logger\n .for(this.connect.name)\n .info(\n '[%s] Cannot init UDP Client with invalid port | Port: %s',\n this.identifier,\n this.port,\n );\n return;\n }\n\n this.logger\n .for(this.connect.name)\n .info(\n '[%s] New network udp client | Host: %s | Port: %s | multicastAddress: %j',\n this.identifier,\n this.host,\n this.port,\n this.multicastAddress,\n );\n\n this.client = dgram.createSocket({ type: 'udp4', reuseAddr: this.reuseAddr });\n this.client.on('close', () => {\n this.invokeHook({\n scope: this.handleClosed.name,\n execution: () => {\n this.onClosed?.({ identifier: this.identifier, host: this.host, port: this.port });\n },\n });\n });\n\n this.client.on('error', error => {\n this.invokeHook({\n scope: this.handleError.name,\n execution: () => {\n this.onError?.({ identifier: this.identifier, host: this.host, port: this.port, error });\n },\n });\n });\n\n this.client.on('listening', () => {\n this.invokeHook({\n scope: this.handleConnected.name,\n execution: () => {\n this.onConnected?.({ identifier: this.identifier, host: this.host, port: this.port });\n },\n });\n });\n\n this.client.on('message', (message: string | Buffer, remoteInfo: dgram.RemoteInfo) => {\n this.invokeHook({\n scope: this.handleData.name,\n execution: () => {\n this.onData?.({ identifier: this.identifier, message, remoteInfo });\n },\n });\n });\n\n this.client.bind({ port: this.port, address: this.host }, () => {\n voidExecution({\n logger: this.logger,\n scope: 'bind',\n // The async wrapper turns a SYNCHRONOUS throw from onBind into a rejection; calling it bare would throw out of the dgram listening listener as an uncaught exception.\n execution: (async () =>\n this.onBind?.({\n identifier: this.identifier,\n socket: this.client!,\n host: this.host,\n port: this.port,\n reuseAddr: this.reuseAddr,\n multicastAddress: this.multicastAddress,\n }))(),\n });\n });\n }\n\n // Hooks run inside dgram event listeners: a synchronous throw there is an uncaught exception.\n private invokeHook(opts: { scope: string; execution: () => void }) {\n const { scope, execution } = opts;\n\n try {\n execution();\n } catch (error) {\n this.logger.for(scope).error('Hook execution FAILED | Error: %s', error);\n }\n }\n\n disconnect() {\n if (!this.client) {\n this.logger\n .for(this.disconnect.name)\n .info('[%s] UdpClient is not initialized yet!', this.identifier);\n return;\n }\n\n this.client?.close();\n\n this.client = null;\n this.logger.for(this.disconnect.name).info('UdpClient is destroyed! | ID: %s', this.identifier);\n }\n\n isConnected() {\n return this.client;\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"network-udp-client.helper.js","sourceRoot":"","sources":["../../../../../src/modules/network/udp-socket/network-udp-client.helper.ts"],"names":[],"mappings":";;;;;;AACA,yCAA4C;AAC5C,iEAA4D;AAC5D,4DAA+B;AAgC/B,MAAa,gBAAiB,SAAQ,iBAAU;IAkC9C,YAAY,IAA4B;QACtC,KAAK,CAAC,EAAE,KAAK,EAAE,gBAAgB,CAAC,IAAI,EAAE,UAAU,EAAE,IAAI,CAAC,UAAU,EAAE,CAAC,CAAC;QAErE,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC,IAAI,CAAC;QACtB,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC,IAAI,CAAC;QACtB,IAAI,CAAC,SAAS,GAAG,IAAI,CAAC,SAAS,CAAC;QAChC,IAAI,CAAC,gBAAgB,GAAG,IAAI,CAAC,gBAAgB,CAAC;QAE9C,IAAI,CAAC,WAAW,GAAG,IAAI,EAAE,WAAW,IAAI,IAAI,CAA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CAAC,KAAK,CAAC,CAAC,KAAK,CAAC,mCAAmC,EAAE,KAAK,CAAC,CAAC;QAC3E,CAAC;IACH,CAAC;IAED,UAAU;QACR,IAAI,CAAC,IAAI,CAAC,MAAM,EAAE,CAAC;YACjB,IAAI,CAAC,MAAM;iBACR,GAAG,CAAC,IAAI,CAAC,UAAU,CAAC,IAAI,CAAC;iBACzB,IAAI,CAAC,wCAAwC,EAAE,IAAI,CAAC,UAAU,CAAC,CAAC;YACnE,OAAO;QACT,CAAC;QAED,IAAI,CAAC,MAAM,EAAE,KAAK,EAAE,CAAC;QAErB,IAAI,CAAC,MAAM,GAAG,IAAI,CAAC;QACnB,IAAI,CAAC,MAAM,CAAC,GAAG,CAAC,IAAI,CAAC,UAAU,CAAC,IAAI,CAAC,CAAC,IAAI,CAAC,kCAAkC,EAAE,IAAI,CAAC,UAAU,CAAC,CAAC;IAClG,CAAC;IAED,WAAW;QACT,OAAO,IAAI,CAAC,MAAM,CAAC;IACrB,CAAC;CACF;AAnND,4CAmNC","sourcesContent":["import { type ValueOrPromise } from '@/common';\nimport { BaseHelper } from '@/modules/base';\nimport { voidExecution } from '@/utilities/promise.utility';\nimport dgram from 'node:dgram';\n\ninterface INetworkUdpClientProps {\n identifier: string;\n\n host?: string;\n port: number;\n reuseAddr?: boolean;\n\n multicastAddress?: {\n groups?: Array<string>;\n interface?: string;\n };\n\n onConnected?: (opts: { identifier: string; host?: string; port: number }) => void;\n onData?: (opts: {\n identifier: string;\n message: string | Buffer;\n remoteInfo: dgram.RemoteInfo;\n }) => void;\n onClosed?: (opts: { identifier: string; host?: string; port: number }) => void;\n onError?: (opts: { identifier: string; host?: string; port: number; error: Error }) => void;\n onBind?: (opts: {\n identifier: string;\n socket: dgram.Socket;\n host?: string;\n port: number;\n reuseAddr?: boolean;\n multicastAddress?: { groups?: Array<string>; interface?: string };\n }) => ValueOrPromise<void>;\n}\n\nexport class NetworkUdpClient extends BaseHelper {\n private host?: string;\n private port: number;\n private reuseAddr?: boolean;\n\n private multicastAddress?: {\n groups?: Array<string>;\n interface?: string;\n };\n\n private onConnected: (opts: { identifier: string; host?: string; port: number }) => void;\n private onData: (opts: {\n identifier: string;\n message: string | Buffer;\n remoteInfo: dgram.RemoteInfo;\n }) => void;\n private onClosed?: (opts: { identifier: string; host?: string; port: number }) => void;\n private onError?: (opts: {\n identifier: string;\n host?: string;\n port: number;\n error: Error;\n }) => void;\n private onBind?: (opts: {\n identifier: string;\n socket: dgram.Socket;\n host?: string;\n port: number;\n reuseAddr?: boolean;\n multicastAddress?: { groups?: Array<string>; interface?: string };\n }) => ValueOrPromise<void>;\n\n private client?: dgram.Socket | null;\n\n constructor(opts: INetworkUdpClientProps) {\n super({ scope: NetworkUdpClient.name, identifier: opts.identifier });\n\n this.host = opts.host;\n this.port = opts.port;\n this.reuseAddr = opts.reuseAddr;\n this.multicastAddress = opts.multicastAddress;\n\n this.onConnected = opts?.onConnected ?? this.handleConnected;\n this.onData = opts?.onData ?? this.handleData;\n this.onClosed = opts?.onClosed ?? this.handleClosed;\n this.onError = opts?.onError ?? this.handleError;\n this.onBind = opts?.onBind;\n }\n\n static newInstance(opts: INetworkUdpClientProps) {\n return new NetworkUdpClient(opts);\n }\n\n getClient() {\n return this.client;\n }\n\n handleConnected() {\n this.logger\n .for(this.handleConnected.name)\n .info('[%s] Successfully bind connection | Options: %j', this.identifier, {\n host: this.host,\n port: this.port,\n multicastAddress: this.multicastAddress,\n });\n }\n\n handleData(opts: { identifier: string; message: string | Buffer; remoteInfo: dgram.RemoteInfo }) {\n this.logger\n .for(this.handleData.name)\n .info('[%s][%s:%d][<==] Raw: %s', this.identifier, this.host, this.port, {\n message: opts.message,\n remoteInfo: opts.remoteInfo,\n });\n }\n\n handleClosed() {\n this.logger\n .for(this.handleClosed.name)\n .info('[%s] Closed connection UDP Server | Options: %j', this.identifier, {\n host: this.host,\n port: this.port,\n multicastAddress: this.multicastAddress,\n });\n }\n\n handleError(opts: { identifier: string; error: Error }) {\n this.logger.for(this.handleError.name).error(\n '[%s] Connection error | Options: %j | Error: %s',\n this.identifier,\n {\n host: this.host,\n port: this.port,\n },\n opts.error,\n );\n }\n\n connect() {\n if (this.client) {\n this.logger\n .for(this.connect.name)\n .info('[%s] UdpClient is already initialized!', this.identifier);\n return;\n }\n\n // Port 0 is a VALID request for an OS assigned port - only a missing / negative port is invalid.\n if (!Number.isInteger(this.port) || this.port < 0) {\n this.logger\n .for(this.connect.name)\n .info(\n '[%s] Cannot init UDP Client with invalid port | Port: %s',\n this.identifier,\n this.port,\n );\n return;\n }\n\n this.logger\n .for(this.connect.name)\n .info(\n '[%s] New network udp client | Host: %s | Port: %s | multicastAddress: %j',\n this.identifier,\n this.host,\n this.port,\n this.multicastAddress,\n );\n\n this.client = dgram.createSocket({ type: 'udp4', reuseAddr: this.reuseAddr });\n this.client.on('close', () => {\n this.invokeHook({\n scope: this.handleClosed.name,\n execution: () => {\n this.onClosed?.({ identifier: this.identifier, host: this.host, port: this.port });\n },\n });\n });\n\n this.client.on('error', (error) => {\n this.invokeHook({\n scope: this.handleError.name,\n execution: () => {\n this.onError?.({ identifier: this.identifier, host: this.host, port: this.port, error });\n },\n });\n });\n\n this.client.on('listening', () => {\n this.invokeHook({\n scope: this.handleConnected.name,\n execution: () => {\n this.onConnected?.({ identifier: this.identifier, host: this.host, port: this.port });\n },\n });\n });\n\n this.client.on('message', (message: string | Buffer, remoteInfo: dgram.RemoteInfo) => {\n this.invokeHook({\n scope: this.handleData.name,\n execution: () => {\n this.onData?.({ identifier: this.identifier, message, remoteInfo });\n },\n });\n });\n\n this.client.bind({ port: this.port, address: this.host }, () => {\n voidExecution({\n logger: this.logger,\n scope: 'bind',\n // The async wrapper turns a SYNCHRONOUS throw from onBind into a rejection; calling it bare would throw out of the dgram listening listener as an uncaught exception.\n execution: (async () =>\n this.onBind?.({\n identifier: this.identifier,\n socket: this.client!,\n host: this.host,\n port: this.port,\n reuseAddr: this.reuseAddr,\n multicastAddress: this.multicastAddress,\n }))(),\n });\n });\n }\n\n // Hooks run inside dgram event listeners: a synchronous throw there is an uncaught exception.\n private invokeHook(opts: { scope: string; execution: () => void }) {\n const { scope, execution } = opts;\n\n try {\n execution();\n } catch (error) {\n this.logger.for(scope).error('Hook execution FAILED | Error: %s', error);\n }\n }\n\n disconnect() {\n if (!this.client) {\n this.logger\n .for(this.disconnect.name)\n .info('[%s] UdpClient is not initialized yet!', this.identifier);\n return;\n }\n\n this.client?.close();\n\n this.client = null;\n this.logger.for(this.disconnect.name).info('UdpClient is destroyed! | ID: %s', this.identifier);\n }\n\n isConnected() {\n return this.client;\n }\n}\n"]}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { type AnyObject } from '../../../common/types';
|
|
1
|
+
import { type AnyObject, type TConstValue } from '../../../common/types';
|
|
2
2
|
/** The punctuation of a query string, named so a reader sees the role rather than the character. */
|
|
3
3
|
export declare class QueryStringSeparators {
|
|
4
4
|
/** Between the path and the first pair. */
|
|
@@ -8,6 +8,27 @@ export declare class QueryStringSeparators {
|
|
|
8
8
|
/** Between a name and its value. */
|
|
9
9
|
static readonly ASSIGN = "=";
|
|
10
10
|
}
|
|
11
|
+
/** What a `null` or `undefined` value becomes. */
|
|
12
|
+
export declare class QueryStringNullishModes {
|
|
13
|
+
/** An empty value (`a=`): what `node:querystring` does. */
|
|
14
|
+
static readonly EMPTY = "empty";
|
|
15
|
+
/** The pair is left out. */
|
|
16
|
+
static readonly SKIP = "skip";
|
|
17
|
+
}
|
|
18
|
+
export type TQueryStringNullishMode = TConstValue<typeof QueryStringNullishModes>;
|
|
19
|
+
/** What an object or an array value becomes. */
|
|
20
|
+
export declare class QueryStringNestedModes {
|
|
21
|
+
/** An empty value (an array repeats its key instead): what `node:querystring` does. */
|
|
22
|
+
static readonly DROP = "drop";
|
|
23
|
+
/** One JSON-encoded parameter (`ids=[1,2]`, `filter={"where":{}}`), the shape a JSON filter travels in. */
|
|
24
|
+
static readonly JSON = "json";
|
|
25
|
+
}
|
|
26
|
+
export type TQueryStringNestedMode = TConstValue<typeof QueryStringNestedModes>;
|
|
27
|
+
/** How {@link toQueryString} treats the values `node:querystring` has no answer for. Both default to its behavior. */
|
|
28
|
+
export interface IQueryStringOptions {
|
|
29
|
+
nullish?: TQueryStringNullishMode;
|
|
30
|
+
nested?: TQueryStringNestedMode;
|
|
31
|
+
}
|
|
11
32
|
/**
|
|
12
33
|
* `node:querystring`'s `stringify`, written out so nothing on the HTTP path carries a node builtin -
|
|
13
34
|
* that one import is what kept the whole network layer out of a browser bundle.
|
|
@@ -19,8 +40,12 @@ export declare class QueryStringSeparators {
|
|
|
19
40
|
* reading "undefined".
|
|
20
41
|
*
|
|
21
42
|
* Diffed against `node:querystring` across 22 shapes with zero mismatches.
|
|
43
|
+
*
|
|
44
|
+
* `nullish: 'skip'` leaves a null or undefined pair out. `nested: 'json'` sends an object or an
|
|
45
|
+
* array as ONE JSON parameter instead (an array does not repeat its key), so a filter object survives
|
|
46
|
+
* the trip. The defaults keep the behavior above.
|
|
22
47
|
*/
|
|
23
48
|
export declare const toQueryString: (opts: {
|
|
24
49
|
params: AnyObject;
|
|
25
|
-
}) => string;
|
|
50
|
+
} & IQueryStringOptions) => string;
|
|
26
51
|
//# sourceMappingURL=query-string.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"query-string.d.ts","sourceRoot":"","sources":["../../../../../src/modules/network/utilities/query-string.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,SAAS,EAAE,MAAM,gBAAgB,CAAC;
|
|
1
|
+
{"version":3,"file":"query-string.d.ts","sourceRoot":"","sources":["../../../../../src/modules/network/utilities/query-string.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,SAAS,EAAE,KAAK,WAAW,EAAE,MAAM,gBAAgB,CAAC;AAElE,oGAAoG;AACpG,qBAAa,qBAAqB;IAChC,2CAA2C;IAC3C,MAAM,CAAC,QAAQ,CAAC,KAAK,OAAO;IAC5B,yBAAyB;IACzB,MAAM,CAAC,QAAQ,CAAC,IAAI,OAAO;IAC3B,oCAAoC;IACpC,MAAM,CAAC,QAAQ,CAAC,MAAM,OAAO;CAC9B;AAED,kDAAkD;AAClD,qBAAa,uBAAuB;IAClC,2DAA2D;IAC3D,MAAM,CAAC,QAAQ,CAAC,KAAK,WAAW;IAChC,4BAA4B;IAC5B,MAAM,CAAC,QAAQ,CAAC,IAAI,UAAU;CAC/B;AACD,MAAM,MAAM,uBAAuB,GAAG,WAAW,CAAC,OAAO,uBAAuB,CAAC,CAAC;AAElF,gDAAgD;AAChD,qBAAa,sBAAsB;IACjC,uFAAuF;IACvF,MAAM,CAAC,QAAQ,CAAC,IAAI,UAAU;IAC9B,2GAA2G;IAC3G,MAAM,CAAC,QAAQ,CAAC,IAAI,UAAU;CAC/B;AACD,MAAM,MAAM,sBAAsB,GAAG,WAAW,CAAC,OAAO,sBAAsB,CAAC,CAAC;AAEhF,sHAAsH;AACtH,MAAM,WAAW,mBAAmB;IAClC,OAAO,CAAC,EAAE,uBAAuB,CAAC;IAClC,MAAM,CAAC,EAAE,sBAAsB,CAAC;CACjC;AAED;;;;;;;;;;;;;;;GAeG;AACH,eAAO,MAAM,aAAa,GAAI,MAAM;IAAE,MAAM,EAAE,SAAS,CAAA;CAAE,GAAG,mBAAmB,KAAG,MAkDjF,CAAC"}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.toQueryString = exports.QueryStringSeparators = void 0;
|
|
3
|
+
exports.toQueryString = exports.QueryStringNestedModes = exports.QueryStringNullishModes = exports.QueryStringSeparators = void 0;
|
|
4
4
|
/** The punctuation of a query string, named so a reader sees the role rather than the character. */
|
|
5
5
|
class QueryStringSeparators {
|
|
6
6
|
/** Between the path and the first pair. */
|
|
@@ -11,6 +11,22 @@ class QueryStringSeparators {
|
|
|
11
11
|
static { this.ASSIGN = '='; }
|
|
12
12
|
}
|
|
13
13
|
exports.QueryStringSeparators = QueryStringSeparators;
|
|
14
|
+
/** What a `null` or `undefined` value becomes. */
|
|
15
|
+
class QueryStringNullishModes {
|
|
16
|
+
/** An empty value (`a=`): what `node:querystring` does. */
|
|
17
|
+
static { this.EMPTY = 'empty'; }
|
|
18
|
+
/** The pair is left out. */
|
|
19
|
+
static { this.SKIP = 'skip'; }
|
|
20
|
+
}
|
|
21
|
+
exports.QueryStringNullishModes = QueryStringNullishModes;
|
|
22
|
+
/** What an object or an array value becomes. */
|
|
23
|
+
class QueryStringNestedModes {
|
|
24
|
+
/** An empty value (an array repeats its key instead): what `node:querystring` does. */
|
|
25
|
+
static { this.DROP = 'drop'; }
|
|
26
|
+
/** One JSON-encoded parameter (`ids=[1,2]`, `filter={"where":{}}`), the shape a JSON filter travels in. */
|
|
27
|
+
static { this.JSON = 'json'; }
|
|
28
|
+
}
|
|
29
|
+
exports.QueryStringNestedModes = QueryStringNestedModes;
|
|
14
30
|
/**
|
|
15
31
|
* `node:querystring`'s `stringify`, written out so nothing on the HTTP path carries a node builtin -
|
|
16
32
|
* that one import is what kept the whole network layer out of a browser bundle.
|
|
@@ -22,10 +38,16 @@ exports.QueryStringSeparators = QueryStringSeparators;
|
|
|
22
38
|
* reading "undefined".
|
|
23
39
|
*
|
|
24
40
|
* Diffed against `node:querystring` across 22 shapes with zero mismatches.
|
|
41
|
+
*
|
|
42
|
+
* `nullish: 'skip'` leaves a null or undefined pair out. `nested: 'json'` sends an object or an
|
|
43
|
+
* array as ONE JSON parameter instead (an array does not repeat its key), so a filter object survives
|
|
44
|
+
* the trip. The defaults keep the behavior above.
|
|
25
45
|
*/
|
|
26
46
|
const toQueryString = (opts) => {
|
|
27
|
-
const { params } = opts;
|
|
47
|
+
const { params, nullish = QueryStringNullishModes.EMPTY, nested = QueryStringNestedModes.DROP, } = opts;
|
|
28
48
|
const parts = [];
|
|
49
|
+
const isSkipped = (value) => nullish === QueryStringNullishModes.SKIP && (value === null || value === undefined);
|
|
50
|
+
const isJson = nested === QueryStringNestedModes.JSON;
|
|
29
51
|
// A primitive only. `querystring` drops an object or a nested array to an empty value rather than
|
|
30
52
|
// stringifying it, and a caller that passed one meant something this format cannot carry anyway.
|
|
31
53
|
const encode = (value) => value === null || value === undefined || typeof value === 'object'
|
|
@@ -34,9 +56,19 @@ const toQueryString = (opts) => {
|
|
|
34
56
|
const entries = Object.entries(params);
|
|
35
57
|
for (const [key, value] of entries) {
|
|
36
58
|
const name = encodeURIComponent(key);
|
|
59
|
+
if (isSkipped(value)) {
|
|
60
|
+
continue;
|
|
61
|
+
}
|
|
62
|
+
if (isJson && typeof value === 'object' && value !== null) {
|
|
63
|
+
parts.push(`${name}${QueryStringSeparators.ASSIGN}${encodeURIComponent(JSON.stringify(value))}`);
|
|
64
|
+
continue;
|
|
65
|
+
}
|
|
37
66
|
// An array repeats the key, which is what a server reading a list expects.
|
|
38
67
|
if (Array.isArray(value)) {
|
|
39
68
|
for (const entry of value) {
|
|
69
|
+
if (isSkipped(entry)) {
|
|
70
|
+
continue;
|
|
71
|
+
}
|
|
40
72
|
parts.push(`${name}${QueryStringSeparators.ASSIGN}${encode(entry)}`);
|
|
41
73
|
}
|
|
42
74
|
continue;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"query-string.js","sourceRoot":"","sources":["../../../../../src/modules/network/utilities/query-string.ts"],"names":[],"mappings":";;;AAEA,oGAAoG;AACpG,MAAa,qBAAqB;IAChC,2CAA2C;aAC3B,UAAK,GAAG,GAAG,CAAC;IAC5B,yBAAyB;aACT,SAAI,GAAG,GAAG,CAAC;IAC3B,oCAAoC;aACpB,WAAM,GAAG,GAAG,CAAC;;AAN/B,sDAOC;AAED
|
|
1
|
+
{"version":3,"file":"query-string.js","sourceRoot":"","sources":["../../../../../src/modules/network/utilities/query-string.ts"],"names":[],"mappings":";;;AAEA,oGAAoG;AACpG,MAAa,qBAAqB;IAChC,2CAA2C;aAC3B,UAAK,GAAG,GAAG,CAAC;IAC5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M,IAAI,GAAG,kBAAkB,CAAC,GAAG,CAAC,CAAC;QAErC,IAAI,SAAS,CAAC,KAAK,CAAC,EAAE,CAAC;YACrB,SAAS;QACX,CAAC;QAED,IAAI,MAAM,IAAI,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,KAAK,IAAI,EAAE,CAAC;YAC1D,KAAK,CAAC,IAAI,CACR,GAAG,IAAI,GAAG,qBAAqB,CAAC,MAAM,GAAG,kBAAkB,CAAC,IAAI,CAAC,SAAS,CAAC,KAAK,CAAC,CAAC,EAAE,CACrF,CAAC;YACF,SAAS;QACX,CAAC;QAED,2EAA2E;QAC3E,IAAI,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,EAAE,CAAC;YACzB,KAAK,MAAM,KAAK,IAAI,KAAK,EAAE,CAAC;gBAC1B,IAAI,SAAS,CAAC,KAAK,CAAC,EAAE,CAAC;oBACrB,SAAS;gBACX,CAAC;gBAED,KAAK,CAAC,IAAI,CAAC,GAAG,IAAI,GAAG,qBAAqB,CAAC,MAAM,GAAG,MAAM,CAAC,KAAK,CAAC,EAAE,CAAC,CAAC;YACvE,CAAC;YAED,SAAS;QACX,CAAC;QAED,KAAK,CAAC,IAAI,CAAC,GAAG,IAAI,GAAG,qBAAqB,CAAC,MAAM,GAAG,MAAM,CAAC,KAAK,CAAC,EAAE,CAAC,CAAC;IACvE,CAAC;IAED,OAAO,KAAK,CAAC,IAAI,CAAC,qBAAqB,CAAC,IAAI,CAAC,CAAC;AAChD,CAAC,CAAC;AAlDW,QAAA,aAAa,iBAkDxB","sourcesContent":["import { type AnyObject, type TConstValue } from '@/common/types';\n\n/** The punctuation of a query string, named so a reader sees the role rather than the character. */\nexport class QueryStringSeparators {\n /** Between the path and the first pair. */\n static readonly START = '?';\n /** Between two pairs. */\n static readonly PAIR = '&';\n /** Between a name and its value. */\n static readonly ASSIGN = '=';\n}\n\n/** What a `null` or `undefined` value becomes. */\nexport class QueryStringNullishModes {\n /** An empty value (`a=`): what `node:querystring` does. */\n static readonly EMPTY = 'empty';\n /** The pair is left out. */\n static readonly SKIP = 'skip';\n}\nexport type TQueryStringNullishMode = TConstValue<typeof QueryStringNullishModes>;\n\n/** What an object or an array value becomes. */\nexport class QueryStringNestedModes {\n /** An empty value (an array repeats its key instead): what `node:querystring` does. */\n static readonly DROP = 'drop';\n /** One JSON-encoded parameter (`ids=[1,2]`, `filter={\"where\":{}}`), the shape a JSON filter travels in. */\n static readonly JSON = 'json';\n}\nexport type TQueryStringNestedMode = TConstValue<typeof QueryStringNestedModes>;\n\n/** How {@link toQueryString} treats the values `node:querystring` has no answer for. Both default to its behavior. */\nexport interface IQueryStringOptions {\n nullish?: TQueryStringNullishMode;\n nested?: TQueryStringNestedMode;\n}\n\n/**\n * `node:querystring`'s `stringify`, written out so nothing on the HTTP path carries a node builtin -\n * that one import is what kept the whole network layer out of a browser bundle.\n *\n * Not `new URLSearchParams(params).toString()`, which differs on four counts measured against the\n * original: an array becomes `a=1%2C2` instead of `a=1&a=2`, `undefined` and `null` become the\n * STRINGS \"undefined\" and \"null\" instead of an empty value, and a space encodes as `+` rather than\n * `%20`. The first changes what a server parses; the second is the same coercion that sends a header\n * reading \"undefined\".\n *\n * Diffed against `node:querystring` across 22 shapes with zero mismatches.\n *\n * `nullish: 'skip'` leaves a null or undefined pair out. `nested: 'json'` sends an object or an\n * array as ONE JSON parameter instead (an array does not repeat its key), so a filter object survives\n * the trip. The defaults keep the behavior above.\n */\nexport const toQueryString = (opts: { params: AnyObject } & IQueryStringOptions): string => {\n const {\n params,\n nullish = QueryStringNullishModes.EMPTY,\n nested = QueryStringNestedModes.DROP,\n } = opts;\n const parts: string[] = [];\n const isSkipped = (value: unknown) =>\n nullish === QueryStringNullishModes.SKIP && (value === null || value === undefined);\n const isJson = nested === QueryStringNestedModes.JSON;\n\n // A primitive only. `querystring` drops an object or a nested array to an empty value rather than\n // stringifying it, and a caller that passed one meant something this format cannot carry anyway.\n const encode = (value: unknown) =>\n value === null || value === undefined || typeof value === 'object'\n ? ''\n : encodeURIComponent(String(value));\n\n const entries = Object.entries(params);\n for (const [key, value] of entries) {\n const name = encodeURIComponent(key);\n\n if (isSkipped(value)) {\n continue;\n }\n\n if (isJson && typeof value === 'object' && value !== null) {\n parts.push(\n `${name}${QueryStringSeparators.ASSIGN}${encodeURIComponent(JSON.stringify(value))}`,\n );\n continue;\n }\n\n // An array repeats the key, which is what a server reading a list expects.\n if (Array.isArray(value)) {\n for (const entry of value) {\n if (isSkipped(entry)) {\n continue;\n }\n\n parts.push(`${name}${QueryStringSeparators.ASSIGN}${encode(entry)}`);\n }\n\n continue;\n }\n\n parts.push(`${name}${QueryStringSeparators.ASSIGN}${encode(value)}`);\n }\n\n return parts.join(QueryStringSeparators.PAIR);\n};\n"]}
|
|
@@ -34,7 +34,7 @@ class UrlIngest {
|
|
|
34
34
|
message: `[assertPublicHost] Host resolves to nothing | host: ${hostname}`,
|
|
35
35
|
});
|
|
36
36
|
}
|
|
37
|
-
const offender = addresses.find(entry => policy_1.UrlPolicy.isNonPublicAddress({ address: entry.address }));
|
|
37
|
+
const offender = addresses.find((entry) => policy_1.UrlPolicy.isNonPublicAddress({ address: entry.address }));
|
|
38
38
|
if (offender) {
|
|
39
39
|
throw (0, error_1.getError)({
|
|
40
40
|
error: errors_1.UrlSafetyErrors.URL_REFUSED,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ingest.js","sourceRoot":"","sources":["../../../../../../src/modules/network/utilities/url-safety/ingest.ts"],"names":[],"mappings":";AAAA,gGAAgG;AAChG,yCAAyC;;;AAEzC,0DAAkE;AAClE,2CAA2C;AAC3C,gDAA2C;AAC3C,kDAAuD;AACvD,4CAAkD;AAElD,qCAAqC;AAErC,6EAA6E;AAC7E,MAAa,SAAS;IACpB;;;;;;;OAOG;IACH,MAAM,CAAC,KAAK,CAAC,gBAAgB,CAAC,IAG7B;QACC,MAAM,EAAE,QAAQ,EAAE,MAAM,EAAE,GAAG,IAAI,CAAC;QAElC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AC;YAED,QAAQ,IAAI,KAAK,CAAC,MAAM,CAAC;YACzB,IAAI,QAAQ,GAAG,QAAQ,EAAE,CAAC;gBACxB,MAAM,MAAM,CAAC,MAAM,EAAE,CAAC;gBACtB,MAAM,IAAA,gBAAQ,EAAC;oBACb,KAAK,EAAE,wBAAe,CAAC,WAAW;oBAClC,OAAO,EAAE,qDAAqD,QAAQ,WAAW,QAAQ,EAAE;iBAC5F,CAAC,CAAC;YACL,CAAC;YAED,MAAM,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;QACrB,CAAC;QAED,OAAO,MAAM,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC;IAC/B,CAAC;CACF;AAvMD,8BAuMC","sourcesContent":["// The half `policy.ts` cannot do: resolving a hostname needs `node:dns`, so nothing here may be\n// re-exported from the `./core` subpath.\n\nimport { DurationMultipliers } from '@/common/constants/duration';\nimport { getError } from '@/modules/error';\nimport { lookup } from 'node:dns/promises';\nimport { UrlSafetyDefaults } from './common/constants';\nimport { UrlSafetyErrors } from './common/errors';\nimport type { IUrlSafetyPolicy } from './common/types';\nimport { UrlPolicy } from './policy';\n\n/** Fetching an untrusted url without letting it reach inside the network. */\nexport class UrlIngest {\n /**\n * Rejects when ANY resolved address is non-public. Checking only the first walks straight into a\n * host that publishes one public A record beside an internal one.\n *\n * A rebinding window remains: the address can change between this check and the connect. Closing\n * it means connecting to the resolved address and setting `Host` by hand, which no fetch API\n * exposes.\n */\n static async assertPublicHost(opts: {\n hostname: string;\n policy?: IUrlSafetyPolicy;\n }): Promise<void> {\n const { hostname, policy } = opts;\n\n if (policy?.allowPrivateAddress ?? UrlSafetyDefaults.ALLOW_PRIVATE_ADDRESS) {\n return;\n }\n\n // `URL.hostname` keeps the brackets on an IPv6 literal; `lookup` does not accept them, and the\n // ENOTFOUND that follows reads as a transient DNS failure rather than the refusal it should be.\n const address = UrlPolicy.readHostAddress({ hostname });\n const addresses = await lookup(address, { all: true });\n\n if (!addresses.length) {\n throw getError({\n error: UrlSafetyErrors.URL_REFUSED,\n message: `[assertPublicHost] Host resolves to nothing | host: ${hostname}`,\n });\n }\n\n const offender = addresses.find(entry =>\n UrlPolicy.isNonPublicAddress({ address: entry.address }),\n );\n\n if (offender) {\n throw getError({\n error: UrlSafetyErrors.URL_REFUSED,\n message: `[assertPublicHost] Host resolves to a non-public address | host: ${hostname} | address: ${offender.address}`,\n });\n }\n }\n\n /** Both halves, in the order they must run: shape first, then the network. */\n static async assertReachableUrl(opts: { url: string; policy?: IUrlSafetyPolicy }): Promise<URL> {\n const parsed = UrlPolicy.assertSafeUrl(opts);\n await UrlIngest.assertPublicHost({ hostname: parsed.hostname, policy: opts.policy });\n return parsed;\n }\n\n private static readTimeoutMilliseconds(opts: { policy?: IUrlSafetyPolicy }): number {\n const { timeout } = opts.policy ?? {};\n const milliseconds = timeout ? DurationMultipliers.toMilliseconds(timeout) : null;\n return milliseconds ?? UrlSafetyDefaults.TIMEOUT_MILLISECONDS;\n }\n\n /**\n * A GET that an untrusted url cannot steer inside the network. Redirects are followed by hand so\n * every hop is re-checked - `redirect: 'follow'` would land on an internal host with no second\n * look.\n *\n * The body is returned unread: the caller decides whether to stream it onward or cap it with\n * {@link UrlIngest.readCappedBody}. Nothing is buffered here.\n */\n static async fetchGuarded(opts: {\n url: string;\n policy?: IUrlSafetyPolicy;\n headers?: Record<string, string>;\n }): Promise<Response> {\n const { url, policy, headers } = opts;\n const maxRedirects = policy?.maxRedirects ?? UrlSafetyDefaults.MAX_REDIRECTS;\n const timeoutMilliseconds = UrlIngest.readTimeoutMilliseconds({ policy });\n\n let target = await UrlIngest.assertReachableUrl({ url, policy });\n\n for (let hop = 0; hop <= maxRedirects; hop += 1) {\n const response = await fetch(target, {\n redirect: 'manual',\n signal: AbortSignal.timeout(timeoutMilliseconds),\n ...(headers ? { headers } : {}),\n });\n\n if (response.status < 300 || response.status > 399) {\n if (!response.ok) {\n // Cancelled, or the socket stays open on every 4xx and 5xx.\n await response.body?.cancel();\n throw getError({\n message: `[fetchGuarded] Request failed | status: ${response.status} | url: ${url}`,\n });\n }\n\n return response;\n }\n\n const location = response.headers.get('location');\n await response.body?.cancel();\n\n if (!location) {\n throw getError({\n error: UrlSafetyErrors.URL_REFUSED,\n message: `[fetchGuarded] Redirect carried no location | url: ${url}`,\n });\n }\n\n target = await UrlIngest.assertReachableUrl({\n url: new URL(location, target).toString(),\n policy,\n });\n }\n\n throw getError({\n error: UrlSafetyErrors.URL_REFUSED,\n message: `[fetchGuarded] Too many redirects | max: ${maxRedirects} | url: ${url}`,\n });\n }\n\n /**\n * Enforces `maxBytes` on a stream nothing reads into this process - the shape a caller wants when\n * the body is piped onward rather than held. Without it a `maxBytes` policy is inert on that path.\n */\n static capStream(opts: {\n source: ReadableStream<Uint8Array>;\n policy?: IUrlSafetyPolicy;\n }): ReadableStream<Uint8Array> {\n const { source } = opts;\n const maxBytes = opts.policy?.maxBytes ?? UrlSafetyDefaults.MAX_BYTES;\n let received = 0;\n\n return source.pipeThrough(\n new TransformStream<Uint8Array, Uint8Array>({\n transform(chunk, controller) {\n received += chunk.byteLength;\n\n if (received > maxBytes) {\n controller.error(\n getError({\n error: UrlSafetyErrors.URL_REFUSED,\n message: `[capStream] Body exceeds the cap | received: ${received} | max: ${maxBytes}`,\n }),\n );\n return;\n }\n\n controller.enqueue(chunk);\n },\n }),\n );\n }\n\n /**\n * Reads a body that must not exceed `maxBytes`, cancelling the moment it does. `content-length` is\n * checked first because it is free, and counted anyway because it may be absent or lie.\n */\n static async readCappedBody(opts: {\n response: Response;\n policy?: IUrlSafetyPolicy;\n }): Promise<Buffer> {\n const { response, policy } = opts;\n const maxBytes = policy?.maxBytes ?? UrlSafetyDefaults.MAX_BYTES;\n\n const declaredLength = Number(response.headers.get('content-length') ?? 0);\n if (declaredLength > maxBytes) {\n await response.body?.cancel();\n // The same fact as the streaming branch below, so the same verdict: a caller must not retry an\n // oversized body when the server sends `content-length` and drop it when the server omits one.\n throw getError({\n error: UrlSafetyErrors.URL_REFUSED,\n message: `[readCappedBody] Body exceeds the cap | declared: ${declaredLength} | max: ${maxBytes}`,\n });\n }\n\n const reader = response.body?.getReader();\n if (!reader) {\n throw getError({ message: '[readCappedBody] Response carried no body' });\n }\n\n const chunks: Uint8Array[] = [];\n let received = 0;\n\n for (;;) {\n const { done, value } = await reader.read();\n if (done) {\n break;\n }\n\n received += value.length;\n if (received > maxBytes) {\n await reader.cancel();\n throw getError({\n error: UrlSafetyErrors.URL_REFUSED,\n message: `[readCappedBody] Body exceeds the cap | received: ${received} | max: ${maxBytes}`,\n });\n }\n\n chunks.push(value);\n }\n\n return Buffer.concat(chunks);\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"ingest.js","sourceRoot":"","sources":["../../../../../../src/modules/network/utilities/url-safety/ingest.ts"],"names":[],"mappings":";AAAA,gGAAgG;AAChG,yCAAyC;;;AAEzC,0DAAkE;AAClE,2CAA2C;AAC3C,gDAA2C;AAC3C,kDAAuD;AACvD,4CAAkD;AAElD,qCAAqC;AAErC,6EAA6E;AAC7E,MAAa,SAAS;IACpB;;;;;;;OAOG;IACH,MAAM,CAAC,KAAK,CAAC,gBAAgB,CAAC,IAG7B;QACC,MAAM,EAAE,QAAQ,EAAE,MAAM,EAAE,GAAG,IAAI,CAAC;QAElC,IAAI,MAAM,EAAE,mBAAmB,IAAI,6BAAiB,CAAC,qBAAqB,EAAE,CAAC;YAC3E,OAAO;QACT,CAAC;QAED,+FAA+F;QAC/F,gGAAgG;QAChG,MAAM,OAAO,GAAG,kBAAS,CAAC,eAAe,CAAC,EAAE,QAAQ,EAAE,CAAC,CAAC;QACxD,MAAM,SAAS,GAAG,MAAM,IAAA,iBAAM,EAAC,OAAO,EAAE,EAAE,GAAG,EAAE,IAAI,EAAE,CAAC,CAAC;QAEvD,IAAI,CAAC,SAAS,CAAC,MAAM,EAAE,CAAC;YACtB,MAAM,IAAA,gBAAQ,EAAC;gBACb,KAAK,EAAE,wBAAe,CAAC,WAAW;gBAClC,OAAO,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MC","sourcesContent":["// The half `policy.ts` cannot do: resolving a hostname needs `node:dns`, so nothing here may be\n// re-exported from the `./core` subpath.\n\nimport { DurationMultipliers } from '@/common/constants/duration';\nimport { getError } from '@/modules/error';\nimport { lookup } from 'node:dns/promises';\nimport { UrlSafetyDefaults } from './common/constants';\nimport { UrlSafetyErrors } from './common/errors';\nimport type { IUrlSafetyPolicy } from './common/types';\nimport { UrlPolicy } from './policy';\n\n/** Fetching an untrusted url without letting it reach inside the network. */\nexport class UrlIngest {\n /**\n * Rejects when ANY resolved address is non-public. Checking only the first walks straight into a\n * host that publishes one public A record beside an internal one.\n *\n * A rebinding window remains: the address can change between this check and the connect. Closing\n * it means connecting to the resolved address and setting `Host` by hand, which no fetch API\n * exposes.\n */\n static async assertPublicHost(opts: {\n hostname: string;\n policy?: IUrlSafetyPolicy;\n }): Promise<void> {\n const { hostname, policy } = opts;\n\n if (policy?.allowPrivateAddress ?? UrlSafetyDefaults.ALLOW_PRIVATE_ADDRESS) {\n return;\n }\n\n // `URL.hostname` keeps the brackets on an IPv6 literal; `lookup` does not accept them, and the\n // ENOTFOUND that follows reads as a transient DNS failure rather than the refusal it should be.\n const address = UrlPolicy.readHostAddress({ hostname });\n const addresses = await lookup(address, { all: true });\n\n if (!addresses.length) {\n throw getError({\n error: UrlSafetyErrors.URL_REFUSED,\n message: `[assertPublicHost] Host resolves to nothing | host: ${hostname}`,\n });\n }\n\n const offender = addresses.find((entry) =>\n UrlPolicy.isNonPublicAddress({ address: entry.address }),\n );\n\n if (offender) {\n throw getError({\n error: UrlSafetyErrors.URL_REFUSED,\n message: `[assertPublicHost] Host resolves to a non-public address | host: ${hostname} | address: ${offender.address}`,\n });\n }\n }\n\n /** Both halves, in the order they must run: shape first, then the network. */\n static async assertReachableUrl(opts: { url: string; policy?: IUrlSafetyPolicy }): Promise<URL> {\n const parsed = UrlPolicy.assertSafeUrl(opts);\n await UrlIngest.assertPublicHost({ hostname: parsed.hostname, policy: opts.policy });\n return parsed;\n }\n\n private static readTimeoutMilliseconds(opts: { policy?: IUrlSafetyPolicy }): number {\n const { timeout } = opts.policy ?? {};\n const milliseconds = timeout ? DurationMultipliers.toMilliseconds(timeout) : null;\n return milliseconds ?? UrlSafetyDefaults.TIMEOUT_MILLISECONDS;\n }\n\n /**\n * A GET that an untrusted url cannot steer inside the network. Redirects are followed by hand so\n * every hop is re-checked - `redirect: 'follow'` would land on an internal host with no second\n * look.\n *\n * The body is returned unread: the caller decides whether to stream it onward or cap it with\n * {@link UrlIngest.readCappedBody}. Nothing is buffered here.\n */\n static async fetchGuarded(opts: {\n url: string;\n policy?: IUrlSafetyPolicy;\n headers?: Record<string, string>;\n }): Promise<Response> {\n const { url, policy, headers } = opts;\n const maxRedirects = policy?.maxRedirects ?? UrlSafetyDefaults.MAX_REDIRECTS;\n const timeoutMilliseconds = UrlIngest.readTimeoutMilliseconds({ policy });\n\n let target = await UrlIngest.assertReachableUrl({ url, policy });\n\n for (let hop = 0; hop <= maxRedirects; hop += 1) {\n const response = await fetch(target, {\n redirect: 'manual',\n signal: AbortSignal.timeout(timeoutMilliseconds),\n ...(headers ? { headers } : {}),\n });\n\n if (response.status < 300 || response.status > 399) {\n if (!response.ok) {\n // Cancelled, or the socket stays open on every 4xx and 5xx.\n await response.body?.cancel();\n throw getError({\n message: `[fetchGuarded] Request failed | status: ${response.status} | url: ${url}`,\n });\n }\n\n return response;\n }\n\n const location = response.headers.get('location');\n await response.body?.cancel();\n\n if (!location) {\n throw getError({\n error: UrlSafetyErrors.URL_REFUSED,\n message: `[fetchGuarded] Redirect carried no location | url: ${url}`,\n });\n }\n\n target = await UrlIngest.assertReachableUrl({\n url: new URL(location, target).toString(),\n policy,\n });\n }\n\n throw getError({\n error: UrlSafetyErrors.URL_REFUSED,\n message: `[fetchGuarded] Too many redirects | max: ${maxRedirects} | url: ${url}`,\n });\n }\n\n /**\n * Enforces `maxBytes` on a stream nothing reads into this process - the shape a caller wants when\n * the body is piped onward rather than held. Without it a `maxBytes` policy is inert on that path.\n */\n static capStream(opts: {\n source: ReadableStream<Uint8Array>;\n policy?: IUrlSafetyPolicy;\n }): ReadableStream<Uint8Array> {\n const { source } = opts;\n const maxBytes = opts.policy?.maxBytes ?? UrlSafetyDefaults.MAX_BYTES;\n let received = 0;\n\n return source.pipeThrough(\n new TransformStream<Uint8Array, Uint8Array>({\n transform(chunk, controller) {\n received += chunk.byteLength;\n\n if (received > maxBytes) {\n controller.error(\n getError({\n error: UrlSafetyErrors.URL_REFUSED,\n message: `[capStream] Body exceeds the cap | received: ${received} | max: ${maxBytes}`,\n }),\n );\n return;\n }\n\n controller.enqueue(chunk);\n },\n }),\n );\n }\n\n /**\n * Reads a body that must not exceed `maxBytes`, cancelling the moment it does. `content-length` is\n * checked first because it is free, and counted anyway because it may be absent or lie.\n */\n static async readCappedBody(opts: {\n response: Response;\n policy?: IUrlSafetyPolicy;\n }): Promise<Buffer> {\n const { response, policy } = opts;\n const maxBytes = policy?.maxBytes ?? UrlSafetyDefaults.MAX_BYTES;\n\n const declaredLength = Number(response.headers.get('content-length') ?? 0);\n if (declaredLength > maxBytes) {\n await response.body?.cancel();\n // The same fact as the streaming branch below, so the same verdict: a caller must not retry an\n // oversized body when the server sends `content-length` and drop it when the server omits one.\n throw getError({\n error: UrlSafetyErrors.URL_REFUSED,\n message: `[readCappedBody] Body exceeds the cap | declared: ${declaredLength} | max: ${maxBytes}`,\n });\n }\n\n const reader = response.body?.getReader();\n if (!reader) {\n throw getError({ message: '[readCappedBody] Response carried no body' });\n }\n\n const chunks: Uint8Array[] = [];\n let received = 0;\n\n for (;;) {\n const { done, value } = await reader.read();\n if (done) {\n break;\n }\n\n received += value.length;\n if (received > maxBytes) {\n await reader.cancel();\n throw getError({\n error: UrlSafetyErrors.URL_REFUSED,\n message: `[readCappedBody] Body exceeds the cap | received: ${received} | max: ${maxBytes}`,\n });\n }\n\n chunks.push(value);\n }\n\n return Buffer.concat(chunks);\n }\n}\n"]}
|
|
@@ -16,7 +16,7 @@ class UrlPolicy {
|
|
|
16
16
|
static isNonPublicIPv4(opts) {
|
|
17
17
|
const parts = opts.address.split('.').map(Number);
|
|
18
18
|
if (parts.length !== 4 ||
|
|
19
|
-
parts.some(part => !Number.isInteger(part) || part < 0 || part > 255)) {
|
|
19
|
+
parts.some((part) => !Number.isInteger(part) || part < 0 || part > 255)) {
|
|
20
20
|
return true;
|
|
21
21
|
}
|
|
22
22
|
const [first, second] = parts;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"policy.js","sourceRoot":"","sources":["../../../../../../src/modules/network/utilities/url-safety/policy.ts"],"names":[],"mappings":";AAAA,8FAA8F;AAC9F,gGAAgG;AAChG,gGAAgG;AAChG,iBAAiB;;;AAEjB,2CAA2C;AAC3C,kDAAmE;AA+H1D,kGA/HA,6BAAiB,OA+HA;AAAE,2FA/HA,sBAAU,OA+HA;AA9HtC,4CAAkD;AAGlD,+EAA+E;AAC/E,MAAa,SAAS;IACpB,4GAA4G;IACpG,MAAM,CAAC,eAAe,CAAC,IAAyB;QACtD,MAAM,KAAK,GAAG,IAAI,CAAC,OAAO,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,GAAG,CAAC,MAAM,CAAC,CAAC;QAElD,IACE,KAAK,CAAC,MAAM,KAAK,CAAC;YAClB,KAAK,CAAC,IAAI,CAAC,IAAI,
|
|
1
|
+
{"version":3,"file":"policy.js","sourceRoot":"","sources":["../../../../../../src/modules/network/utilities/url-safety/policy.ts"],"names":[],"mappings":";AAAA,8FAA8F;AAC9F,gGAAgG;AAChG,gGAAgG;AAChG,iBAAiB;;;AAEjB,2CAA2C;AAC3C,kDAAmE;AA+H1D,kGA/HA,6BAAiB,OA+HA;AAAE,2FA/HA,sBAAU,OA+HA;AA9HtC,4CAAkD;AAGlD,+EAA+E;AAC/E,MAAa,SAAS;IACpB,4GAA4G;IACpG,MAAM,CAAC,eAAe,CAAC,IAAyB;QACtD,MAAM,KAAK,GAAG,IAAI,CAAC,OAAO,CAAC,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;QAED,IAAI,MAAM,EAAE,YAAY,IAAI,CAAC,MAAM,CAAC,YAAY,CAAC,QAAQ,CAAC,MAAM,CAAC,QAAQ,CAAC,EAAE,CAAC;YAC3E,MAAM,IAAA,gBAAQ,EAAC;gBACb,KAAK,EAAE,wBAAe,CAAC,WAAW;gBAClC,OAAO,EAAE,yDAAyD,MAAM,CAAC,QAAQ,EAAE;aACpF,CAAC,CAAC;QACL,CAAC;QAED,MAAM,OAAO,GAAG,SAAS,CAAC,eAAe,CAAC,EAAE,QAAQ,EAAE,MAAM,CAAC,QAAQ,EAAE,CAAC,CAAC;QACzE,MAAM,gBAAgB,GAAG,UAAU,CAAC,IAAI,CAAC,OAAO,CAAC,IAAI,OAAO,CAAC,QAAQ,CAAC,GAAG,CAAC,CAAC;QAE3E,IAAI,CAAC,mBAAmB,IAAI,gBAAgB,IAAI,SAAS,CAAC,kBAAkB,CAAC,EAAE,OAAO,EAAE,CAAC,EAAE,CAAC;YAC1F,MAAM,IAAA,gBAAQ,EAAC;gBACb,KAAK,EAAE,wBAAe,CAAC,WAAW;gBAClC,OAAO,EAAE,iEAAiE,OAAO,EAAE;aACpF,CAAC,CAAC;QACL,CAAC;QAED,OAAO,MAAM,CAAC;IAChB,CAAC;CACF;AAxHD,8BAwHC","sourcesContent":["// The browser-pure half of the guard: a url and a literal address are decided with string and\n// number work alone. Resolving a hostname needs `node:dns` and lives in `ingest.ts`, which this\n// file must never import - `policy.ts` is re-exported from the `./core` subpath and is gated by\n// `make purity`.\n\nimport { getError } from '@/modules/error';\nimport { UrlSafetyDefaults, UrlSchemes } from './common/constants';\nimport { UrlSafetyErrors } from './common/errors';\nimport type { IUrlSafetyPolicy } from './common/types';\n\n/** Everything about a url that can be decided without touching the network. */\nexport class UrlPolicy {\n /** A dotted-quad that is not routable on the public internet. An unparseable input counts as non-public. */\n private static isNonPublicIPv4(opts: { address: string }): boolean {\n const parts = opts.address.split('.').map(Number);\n\n if (\n parts.length !== 4 ||\n parts.some((part) => !Number.isInteger(part) || part < 0 || part > 255)\n ) {\n return true;\n }\n\n const [first, second] = parts;\n\n return (\n first === 0 || // this host\n first === 10 || // private\n first === 127 || // loopback\n (first === 100 && second >= 64 && second <= 127) || // carrier-grade NAT\n (first === 169 && second === 254) || // link-local, and the cloud metadata address\n (first === 172 && second >= 16 && second <= 31) || // private\n (first === 192 && second === 0) || // IETF protocol assignments\n (first === 192 && second === 168) || // private\n (first === 198 && (second === 18 || second === 19)) || // benchmarking\n first >= 224 // multicast and reserved\n );\n }\n\n /**\n * An address that must never be reached with an untrusted url. Anything unrecognised answers\n * `true`: a guard that fails open on a string it cannot parse is not a guard.\n */\n static isNonPublicAddress(opts: { address: string }): boolean {\n const normalized = opts.address.toLowerCase().split('%')[0];\n\n if (!normalized.includes(':')) {\n return UrlPolicy.isNonPublicIPv4({ address: normalized });\n }\n\n // An IPv4 address wearing an IPv6 coat walks past every naive v6 check. Both spellings must be\n // unwrapped: `new URL` rewrites `::ffff:169.254.169.254` into the hex form `::ffff:a9fe:a9fe`,\n // so a dotted-quad-only check is green on a value the parser never actually produces.\n const dottedMapped = /^::ffff:(\\d+\\.\\d+\\.\\d+\\.\\d+)$/.exec(normalized)?.[1];\n if (dottedMapped) {\n return UrlPolicy.isNonPublicIPv4({ address: dottedMapped });\n }\n\n const hexMapped = /^::ffff:([\\da-f]{1,4}):([\\da-f]{1,4})$/.exec(normalized);\n if (hexMapped) {\n const high = Number.parseInt(hexMapped[1], 16);\n const low = Number.parseInt(hexMapped[2], 16);\n const dotted = [high >> 8, high & 0xff, low >> 8, low & 0xff].join('.');\n\n return UrlPolicy.isNonPublicIPv4({ address: dotted });\n }\n\n return (\n normalized === '::' ||\n normalized === '::1' ||\n normalized.startsWith('fc') || // unique local\n normalized.startsWith('fd') ||\n normalized.startsWith('fe8') || // link-local\n normalized.startsWith('fe9') ||\n normalized.startsWith('fea') ||\n normalized.startsWith('feb')\n );\n }\n\n /** A bracketed IPv6 literal arrives as `[::1]`; the brackets are not part of the address. */\n static readHostAddress(opts: { hostname: string }): string {\n const { hostname } = opts;\n return hostname.startsWith('[') && hostname.endsWith(']') ? hostname.slice(1, -1) : hostname;\n }\n\n /**\n * A hostname that RESOLVES to a private address passes here on purpose - `UrlIngest` catches that,\n * and this half runs where `node:dns` does not exist.\n */\n static assertSafeUrl(opts: { url: string; policy?: IUrlSafetyPolicy }): URL {\n const { url, policy } = opts;\n const allowedSchemes = policy?.allowedSchemes ?? UrlSafetyDefaults.ALLOWED_SCHEMES;\n const allowPrivateAddress =\n policy?.allowPrivateAddress ?? UrlSafetyDefaults.ALLOW_PRIVATE_ADDRESS;\n\n let parsed: URL;\n try {\n parsed = new URL(url);\n } catch {\n throw getError({\n error: UrlSafetyErrors.URL_REFUSED,\n message: `[assertSafeUrl] Malformed url | url: ${url}`,\n });\n }\n\n if (!allowedSchemes.includes(parsed.protocol)) {\n throw getError({\n error: UrlSafetyErrors.URL_REFUSED,\n message: `[assertSafeUrl] Disallowed scheme | scheme: ${parsed.protocol} | allowed: ${allowedSchemes.join(', ')}`,\n });\n }\n\n if (policy?.allowedHosts && !policy.allowedHosts.includes(parsed.hostname)) {\n throw getError({\n error: UrlSafetyErrors.URL_REFUSED,\n message: `[assertSafeUrl] Host is not in the allow-list | host: ${parsed.hostname}`,\n });\n }\n\n const address = UrlPolicy.readHostAddress({ hostname: parsed.hostname });\n const isLiteralAddress = /^[\\d.]+$/.test(address) || address.includes(':');\n\n if (!allowPrivateAddress && isLiteralAddress && UrlPolicy.isNonPublicAddress({ address })) {\n throw getError({\n error: UrlSafetyErrors.URL_REFUSED,\n message: `[assertSafeUrl] Url points at a non-public address | address: ${address}`,\n });\n }\n\n return parsed;\n }\n}\n\nexport { UrlSafetyDefaults, UrlSchemes };\nexport type { IUrlSafetyPolicy };\n"]}
|
|
@@ -76,7 +76,7 @@ class AbstractPoolHelper extends base_1.BaseHelper {
|
|
|
76
76
|
}
|
|
77
77
|
this.borrowed.delete(resource);
|
|
78
78
|
if (this.isDestroyed) {
|
|
79
|
-
this.destroyResource({ resource }).catch(error => {
|
|
79
|
+
this.destroyResource({ resource }).catch((error) => {
|
|
80
80
|
logger.warn('destroyResource error on release: %s', error);
|
|
81
81
|
});
|
|
82
82
|
return;
|
|
@@ -128,7 +128,7 @@ class AbstractPoolHelper extends base_1.BaseHelper {
|
|
|
128
128
|
waiter.reject(error);
|
|
129
129
|
}
|
|
130
130
|
const toDestroy = this.idle.splice(0);
|
|
131
|
-
await Promise.all(toDestroy.map(resource => this.destroyResource({ resource })));
|
|
131
|
+
await Promise.all(toDestroy.map((resource) => this.destroyResource({ resource })));
|
|
132
132
|
}
|
|
133
133
|
// ----------------------------------------------------------------------------------------------------------
|
|
134
134
|
async createResource() {
|
|
@@ -157,7 +157,7 @@ class AbstractPoolHelper extends base_1.BaseHelper {
|
|
|
157
157
|
// ----------------------------------------------------------------------------------------------------------
|
|
158
158
|
/** Fire-and-forget dispatch with logged rejection; shared by all dispatch call sites. */
|
|
159
159
|
safeDispatch(opts) {
|
|
160
|
-
this.dispatch().catch(error => {
|
|
160
|
+
this.dispatch().catch((error) => {
|
|
161
161
|
this.logger
|
|
162
162
|
.for(this.dispatch.name)
|
|
163
163
|
.warn('dispatch error | action: %s | Error: %s', opts.action, error);
|
|
@@ -243,7 +243,7 @@ class AbstractPoolHelper extends base_1.BaseHelper {
|
|
|
243
243
|
const { resource } = opts;
|
|
244
244
|
// `destroy()` tears down what it can SEE - the waiter queue and the idle list. A resource whose create() was still in flight is in neither, so parking it in idle now would leave it alive with nothing left to reclaim it.
|
|
245
245
|
if (this.isDestroyed) {
|
|
246
|
-
this.destroyResource({ resource }).catch(error => {
|
|
246
|
+
this.destroyResource({ resource }).catch((error) => {
|
|
247
247
|
this.logger
|
|
248
248
|
.for(this.handToWaiter.name)
|
|
249
249
|
.warn('destroyResource error on a resource created after destroy(): %s', error);
|