From 9117c9c0a447e66ace851bdc686b701388849913 Mon Sep 17 00:00:00 2001 From: Park Dahyeon Date: Sat, 7 Nov 2026 20:21:54 +0900 Subject: [PATCH] fix(deps): resolve production high and critical vulnerabilities Pin vulnerable transitive dependencies to patched releases and replace Infisical SDK bootstrap calls with a compatible HTTP client. Add dependency-security and secret-loading regression coverage. --- .../global/secret/infisical-client.spec.ts | 183 +++++++++++++++++ .../modules/global/secret/infisical-client.ts | 123 +++++++++++ .../global/secret/secret.service.spec.ts | 86 ++++++++ .../modules/global/secret/secret.service.ts | 15 +- package.json | 15 +- pnpm-lock.yaml | 191 +++++++++++------- scripts/dependency-security.test.mjs | 160 +++++++++++++++ 7 files changed, 685 insertions(+), 88 deletions(-) create mode 100644 apps/api/src/modules/global/secret/infisical-client.spec.ts create mode 100644 apps/api/src/modules/global/secret/infisical-client.ts create mode 100644 scripts/dependency-security.test.mjs diff --git a/apps/api/src/modules/global/secret/infisical-client.spec.ts b/apps/api/src/modules/global/secret/infisical-client.spec.ts new file mode 100644 index 00000000..c90afe25 --- /dev/null +++ b/apps/api/src/modules/global/secret/infisical-client.spec.ts @@ -0,0 +1,183 @@ +import { loadInfisicalSecrets } from './infisical-client'; + +const options = { + siteUrl: 'https://infisical.example.test/prefix', + clientId: 'test-client', + clientSecret: 'test-secret', + projectId: 'test-project', + environment: 'staging', +}; +const secrets = [{ secretKey: 'TEST_SECRET', secretValue: 'value' }]; +const json = (value: unknown, status = 200) => + new Response(JSON.stringify(value), { status }); + +describe('Infisical bootstrap client', () => { + const originalFetch = global.fetch; + let fetchMock: jest.Mock; + + beforeEach(() => { + fetchMock = jest.fn(); + global.fetch = fetchMock; + }); + + afterEach(() => { + global.fetch = originalFetch; + jest.useRealTimers(); + jest.restoreAllMocks(); + }); + + it.each([ + 'https://infisical.example.test/prefix', + 'https://infisical.example.test/prefix/', + ])( + 'preserves SDK URLs, auth headers and list defaults for %s', + async (siteUrl) => { + fetchMock + .mockResolvedValueOnce(json({ accessToken: 'token' })) + .mockResolvedValueOnce(json({ secrets })); + await expect( + loadInfisicalSecrets({ ...options, siteUrl }), + ).resolves.toEqual({ secrets }); + expect(fetchMock).toHaveBeenNthCalledWith( + 1, + 'https://infisical.example.test/prefix/api/v1/auth/universal-auth/login', + expect.objectContaining({ + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ + clientId: options.clientId, + clientSecret: options.clientSecret, + }), + }), + ); + expect(fetchMock).toHaveBeenNthCalledWith( + 2, + 'https://infisical.example.test/prefix/api/v3/secrets/raw?workspaceId=test-project&environment=staging&expandSecretReferences=true&include_imports=false&recursive=false&viewSecretValue=true', + expect.objectContaining({ + method: 'GET', + headers: { Authorization: 'Bearer token' }, + }), + ); + }, + ); + + it('retries network errors and 429 using the same request', async () => { + jest.useFakeTimers(); + jest.spyOn(Math, 'random').mockReturnValue(0.5); + fetchMock + .mockRejectedValueOnce(new Error('network error')) + .mockResolvedValueOnce(json({}, 429)) + .mockResolvedValueOnce(json({ accessToken: 'token' })) + .mockResolvedValueOnce(json({ secrets })); + const result = loadInfisicalSecrets(options); + await jest.runAllTimersAsync(); + await expect(result).resolves.toEqual({ secrets }); + expect(fetchMock).toHaveBeenCalledTimes(4); + expect(fetchMock.mock.calls.slice(0, 3).map(([url]) => url)).toEqual( + Array(3).fill( + 'https://infisical.example.test/prefix/api/v1/auth/universal-auth/login', + ), + ); + expect(jest.getTimerCount()).toBe(0); + }); + + it.each([401, 403, 500])( + 'does not retry HTTP %i or fetch secrets after failed login', + async (status) => { + fetchMock.mockResolvedValueOnce(json({ message: 'test-secret' }, status)); + await expect(loadInfisicalSecrets(options)).rejects.toThrow( + `failed with ${status}`, + ); + expect(fetchMock).toHaveBeenCalledTimes(1); + }, + ); + + it('stops after four retries and does not expose response bodies', async () => { + jest.useFakeTimers(); + fetchMock.mockImplementation(() => + Promise.resolve(json({ message: 'test-secret' }, 429)), + ); + const error = loadInfisicalSecrets(options).catch( + (value: unknown) => value, + ); + await jest.runAllTimersAsync(); + expect(await error).toEqual( + expect.objectContaining({ + message: expect.stringContaining('failed with 429'), + }), + ); + expect(((await error) as Error).message).not.toContain('test-secret'); + expect(fetchMock).toHaveBeenCalledTimes(5); + expect(jest.getTimerCount()).toBe(0); + }); + + it('aborts each stalled attempt after ten seconds and bounds the retries', async () => { + jest.useFakeTimers(); + jest.spyOn(Math, 'random').mockReturnValue(0.5); + fetchMock.mockImplementation( + (_url: string, init: RequestInit) => + new Promise((_resolve, reject) => { + init.signal!.addEventListener( + 'abort', + () => reject(new Error('aborted')), + { once: true }, + ); + }), + ); + const error = loadInfisicalSecrets(options).catch( + (value: unknown) => value, + ); + await jest.advanceTimersByTimeAsync(9_999); + expect(fetchMock).toHaveBeenCalledTimes(1); + expect((fetchMock.mock.calls[0][1] as RequestInit).signal!.aborted).toBe( + false, + ); + await jest.runAllTimersAsync(); + expect(await error).toEqual(new Error('aborted')); + expect(fetchMock).toHaveBeenCalledTimes(5); + expect(jest.getTimerCount()).toBe(0); + }); + + it.each([{}, { accessToken: '' }, { accessToken: 123 }])( + 'rejects invalid login response %j', + async (login) => { + fetchMock.mockResolvedValueOnce(json(login)); + await expect(loadInfisicalSecrets(options)).rejects.toThrow( + 'did not return an access token', + ); + expect(fetchMock).toHaveBeenCalledTimes(1); + }, + ); + + it.each(['login', 'secrets'])( + 'does not leak malformed %s response bodies through errors', + async (operation) => { + if (operation === 'secrets') { + fetchMock.mockResolvedValueOnce(json({ accessToken: 'token' })); + } + fetchMock.mockResolvedValueOnce(new Response('sensitive-secret')); + const error = await loadInfisicalSecrets(options).catch( + (value: unknown) => value, + ); + expect(error).toHaveProperty( + 'message', + 'Infisical returned an invalid JSON response', + ); + expect((error as Error).stack).not.toContain('sensitive-secret'); + expect(fetchMock).toHaveBeenCalledTimes(operation === 'login' ? 1 : 2); + }, + ); + + it.each([ + {}, + { secrets: null }, + { secrets: [{ secretKey: 'KEY', secretValue: 123 }] }, + ])('rejects invalid secrets response %j', async (result) => { + fetchMock + .mockResolvedValueOnce(json({ accessToken: 'token' })) + .mockResolvedValueOnce(json(result)); + await expect(loadInfisicalSecrets(options)).rejects.toThrow( + 'invalid secrets response', + ); + }); +}); diff --git a/apps/api/src/modules/global/secret/infisical-client.ts b/apps/api/src/modules/global/secret/infisical-client.ts new file mode 100644 index 00000000..a94ec60e --- /dev/null +++ b/apps/api/src/modules/global/secret/infisical-client.ts @@ -0,0 +1,123 @@ +interface InfisicalOptions { + siteUrl: string; + clientId: string; + clientSecret: string; + projectId: string; + environment: string; +} + +interface InfisicalSecret { + secretKey: string; + secretValue: string; +} + +const REQUEST_TIMEOUT_MS = 10_000; +const MAX_RETRIES = 4; + +/** The two Infisical operations used during SecretService initialization. */ +export async function loadInfisicalSecrets( + options: InfisicalOptions, +): Promise<{ secrets: InfisicalSecret[] }> { + const baseUrl = options.siteUrl.endsWith('/') + ? options.siteUrl + : `${options.siteUrl}/`; + const login = await requestJson( + new URL('api/v1/auth/universal-auth/login', baseUrl), + { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ + clientId: options.clientId, + clientSecret: options.clientSecret, + }), + }, + ); + if ( + !isRecord(login) || + typeof login.accessToken !== 'string' || + !login.accessToken + ) { + throw new Error('Infisical login did not return an access token'); + } + + // Preserve the SDK's v3 endpoint and defaults, including self-hosted URL prefixes. + const url = new URL('api/v3/secrets/raw', baseUrl); + url.search = new URLSearchParams({ + workspaceId: options.projectId, + environment: options.environment, + expandSecretReferences: 'true', + include_imports: 'false', + recursive: 'false', + viewSecretValue: 'true', + }).toString(); + const result = await requestJson(url, { + method: 'GET', + headers: { Authorization: `Bearer ${login.accessToken}` }, + }); + if ( + !isRecord(result) || + !Array.isArray(result.secrets) || + !result.secrets.every(isSecret) + ) { + throw new Error('Infisical returned an invalid secrets response'); + } + return { secrets: result.secrets }; +} + +async function requestJson(url: URL, init: RequestInit): Promise { + for (let attempt = 0; ; attempt += 1) { + const controller = new AbortController(); + const timeout = setTimeout(() => controller.abort(), REQUEST_TIMEOUT_MS); + let response: Response; + try { + response = await fetch(url.toString(), { + ...init, + signal: controller.signal, + }); + } catch (error) { + if (attempt >= MAX_RETRIES) throw error; + clearTimeout(timeout); + await retryDelay(attempt); + continue; + } finally { + clearTimeout(timeout); + } + + // Match the SDK: retry network errors and 429, but not other HTTP errors. + if (response.status === 429 && attempt < MAX_RETRIES) { + await response.body?.cancel(); + await retryDelay(attempt); + continue; + } + if (!response.ok) { + await response.body?.cancel(); + throw new Error( + `Infisical ${init.method} ${url.pathname} failed with ${response.status}`, + ); + } + try { + return await response.json(); + } catch { + // JSON parse errors can contain secrets from the response body. + throw new Error('Infisical returned an invalid JSON response'); + } + } +} + +function retryDelay(attempt: number): Promise { + const base = 1_000 * 2 ** attempt; + const delay = base + base * 0.2 * (Math.random() * 2 - 1); + return new Promise((resolve) => setTimeout(resolve, delay)); +} + +function isRecord(value: unknown): value is Record { + return typeof value === 'object' && value !== null; +} + +function isSecret(value: unknown): value is InfisicalSecret { + return ( + isRecord(value) && + typeof value.secretKey === 'string' && + typeof value.secretValue === 'string' + ); +} diff --git a/apps/api/src/modules/global/secret/secret.service.spec.ts b/apps/api/src/modules/global/secret/secret.service.spec.ts index d0282c2d..b0f4d84d 100644 --- a/apps/api/src/modules/global/secret/secret.service.spec.ts +++ b/apps/api/src/modules/global/secret/secret.service.spec.ts @@ -9,6 +9,7 @@ function makeConfig(values: Record = {}) { describe('SecretService', () => { const originalEnv = process.env; + const originalFetch = global.fetch; let fetchMock: jest.Mock; beforeEach(() => { @@ -23,9 +24,94 @@ describe('SecretService', () => { afterEach(() => { process.env = originalEnv; + global.fetch = originalFetch; jest.restoreAllMocks(); }); + function infisicalConfig() { + return makeConfig({ + SECRET_SOURCE: 'infisical', + INFISICAL_SITE_URL: 'https://infisical.example.test/', + INFISICAL_CLIENT_ID: 'test-client', + INFISICAL_CLIENT_SECRET: 'test-secret', + INFISICAL_PROJECT_ID: 'test-project', + CONFIG_FALLBACK: 'config-value', + }); + } + + it.each([ + ['prod', 'prod'], + ['staging', 'staging'], + ['dev', 'dev'], + ['production', 'dev'], + ])('preserves environment mapping %s -> %s', async (nodeEnv, environment) => { + process.env.NODE_ENV = nodeEnv; + fetchMock + .mockResolvedValueOnce(Response.json({ accessToken: 'token' })) + .mockResolvedValueOnce(Response.json({ secrets: [] })); + await new SecretService(infisicalConfig()).ready(); + const url = new URL(fetchMock.mock.calls[1][0] as string); + expect(url.searchParams.get('environment')).toBe(environment); + }); + + it('shares initialization, caches secrets, and preserves empty values and fallbacks', async () => { + process.env.TEST_EMPTY = 'existing-value'; + fetchMock + .mockResolvedValueOnce(Response.json({ accessToken: 'token' })) + .mockResolvedValueOnce( + Response.json({ + secrets: [ + { secretKey: 'TEST_SECRET', secretValue: 'first' }, + { secretKey: 'TEST_SECRET', secretValue: 'last' }, + { secretKey: 'TEST_EMPTY', secretValue: '' }, + ], + imports: [ + { secrets: [{ secretKey: 'TEST_IMPORT', secretValue: 'ignored' }] }, + ], + }), + ); + const service = new SecretService(infisicalConfig()); + await Promise.all([ + service.ready(), + service.get('TEST_SECRET'), + service.ready(), + ]); + await expect(service.get('TEST_SECRET')).resolves.toBe('last'); + await expect(service.get('TEST_EMPTY')).resolves.toBe(''); + await expect(service.get('CONFIG_FALLBACK')).resolves.toBe('config-value'); + await expect(service.get('TEST_IMPORT', 'missing')).resolves.toBe( + 'missing', + ); + expect(process.env.TEST_SECRET).toBe('last'); + expect(process.env.TEST_EMPTY).toBe('existing-value'); + expect(fetchMock).toHaveBeenCalledTimes(2); + }); + + it('does not publish partial secrets after failure and permits a later retry', async () => { + fetchMock + .mockResolvedValueOnce(Response.json({ accessToken: 'token' })) + .mockResolvedValueOnce( + Response.json({ + secrets: [ + { secretKey: 'TEST_SECRET', secretValue: 'partial' }, + { secretKey: 'INVALID', secretValue: 123 }, + ], + }), + ) + .mockResolvedValueOnce(Response.json({ accessToken: 'new-token' })) + .mockResolvedValueOnce( + Response.json({ + secrets: [{ secretKey: 'TEST_SECRET', secretValue: 'complete' }], + }), + ); + const service = new SecretService(infisicalConfig()); + await expect(service.ready()).rejects.toThrow('invalid secrets response'); + expect(process.env.TEST_SECRET).toBeUndefined(); + await service.ready(); + await expect(service.get('TEST_SECRET')).resolves.toBe('complete'); + expect(fetchMock).toHaveBeenCalledTimes(4); + }); + it('defaults to environment-provided secrets without IMDS lookup', async () => { process.env.TEST_SECRET = 'from-env'; const service = new SecretService(makeConfig()); diff --git a/apps/api/src/modules/global/secret/secret.service.ts b/apps/api/src/modules/global/secret/secret.service.ts index 1be29d05..4b6e5480 100644 --- a/apps/api/src/modules/global/secret/secret.service.ts +++ b/apps/api/src/modules/global/secret/secret.service.ts @@ -1,6 +1,6 @@ import { Injectable, Logger } from '@nestjs/common'; -import { InfisicalSDK } from '@infisical/sdk'; import { ConfigService } from '@nestjs/config'; +import { loadInfisicalSecrets } from './infisical-client'; type SecretMap = Record; type SecretSource = 'env' | 'infisical'; @@ -71,23 +71,14 @@ export class SecretService { private async fetchInfisicalSecrets(): Promise { const bootstrapConfig = await this.resolveInfisicalBootstrapConfig(); - const infisicalClient = new InfisicalSDK({ - siteUrl: bootstrapConfig.siteUrl, - }); - - await infisicalClient.auth().universalAuth.login({ - clientId: bootstrapConfig.clientId, - clientSecret: bootstrapConfig.clientSecret, - }); - - const res = await infisicalClient.secrets().listSecrets({ + const res = await loadInfisicalSecrets({ + ...bootstrapConfig, environment: process.env.NODE_ENV === 'prod' ? 'prod' : process.env.NODE_ENV === 'staging' ? 'staging' : 'dev', - projectId: bootstrapConfig.projectId, }); // 임시 객체에 채운 뒤 한 번에 교체(일관성 보장) diff --git a/package.json b/package.json index 5f9c1091..9d47d2ef 100644 --- a/package.json +++ b/package.json @@ -16,7 +16,8 @@ "build:web:prod": "pnpm --filter web build:prod", "deploy:web:staging": "node scripts/deploy-cloudflare-pages.mjs staging", "deploy:web:prod": "node scripts/deploy-cloudflare-pages.mjs prod", - "test": "echo \"Error: no test specified\" && exit 1" + "test": "echo \"Error: no test specified\" && exit 1", + "test:dependency-security": "node --test scripts/dependency-security.test.mjs" }, "keywords": [], "author": "", @@ -25,9 +26,6 @@ "node": ">=26 <27" }, "packageManager": "pnpm@10.4.1", - "dependencies": { - "@infisical/sdk": "^5.0.2" - }, "pnpm": { "auditConfig": { "ignoreGhsas": [ @@ -36,18 +34,23 @@ }, "overrides": { "@babel/core@7.29.0": "7.29.6", + "@grpc/grpc-js@>=1.14.0 <1.14.5": "1.14.7", + "body-parser@>=2.0.0 <2.4.0": "2.4.0", "brace-expansion@1.1.13": "1.1.16", "brace-expansion@2.0.3": "2.1.2", "brace-expansion@5.0.5": "5.0.8", - "engine.io@6.6.6": "6.6.7", + "engine.io@>=6.6.0 <6.6.10": "6.6.11", "fast-uri@3.1.0": "3.1.4", "form-data@4.0.5": "4.0.6", "js-yaml@4.1.1": "4.3.0", "js-yaml@5.2.1": "5.2.2", - "multer@2.2.0": "2.3.0", + "multer@>=2.0.0 <2.5.0": "2.5.0", "nanoid@3.3.16": "3.3.18", + "proxy-addr@>=2.0.0 <2.0.8": "2.0.8", "qs@6.15.1": "6.15.2", "socket.io-parser@4.2.6": "4.2.7", + "source-map-js@>=1.0.0 <1.2.2": "1.2.2", + "undici@>=7.0.0 <7.30.1": "7.30.2", "ws@8.18.3": "8.21.0" } } diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index c1412153..ebf28313 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -6,27 +6,28 @@ settings: overrides: '@babel/core@7.29.0': 7.29.6 + '@grpc/grpc-js@>=1.14.0 <1.14.5': 1.14.7 + body-parser@>=2.0.0 <2.4.0: 2.4.0 brace-expansion@1.1.13: 1.1.16 brace-expansion@2.0.3: 2.1.2 brace-expansion@5.0.5: 5.0.8 - engine.io@6.6.6: 6.6.7 + engine.io@>=6.6.0 <6.6.10: 6.6.11 fast-uri@3.1.0: 3.1.4 form-data@4.0.5: 4.0.6 js-yaml@4.1.1: 4.3.0 js-yaml@5.2.1: 5.2.2 - multer@2.2.0: 2.3.0 + multer@>=2.0.0 <2.5.0: 2.5.0 nanoid@3.3.16: 3.3.18 + proxy-addr@>=2.0.0 <2.0.8: 2.0.8 qs@6.15.1: 6.15.2 socket.io-parser@4.2.6: 4.2.7 + source-map-js@>=1.0.0 <1.2.2: 1.2.2 + undici@>=7.0.0 <7.30.1: 7.30.2 ws@8.18.3: 8.21.0 importers: - .: - dependencies: - '@infisical/sdk': - specifier: ^5.0.2 - version: 5.0.2 + .: {} apps/api: dependencies: @@ -311,6 +312,9 @@ packages: '@aws-sdk/core@3.977.1': resolution: {integrity: sha512-KVtQRtc00ES/y+Sc3vYXeP6pCIcNlBJCZOwvqSy8ZpVGmbM5+IG+AfhuTKQ2oXmIVqZJewaGMMpzPkywC6xg0w==} engines: {node: '>=20.0.0'} + deprecated: |- + Deprecated due to Document number parsing bug in JSON, see + https://github.com/aws/aws-sdk-js-v3/issues/8246. Newer version available. '@aws-sdk/credential-provider-cognito-identity@3.972.60': resolution: {integrity: sha512-16Fxa3veKIO6nHJr+vN76z3BkSU7725lzruc5S2SQSTUTbK4TXtmi8033WQljZj4k1+383UsMaNOHN6B76fK5A==} @@ -890,8 +894,8 @@ packages: resolution: {integrity: sha512-43/qtrDUokr7LJqoF2c3+RInu/t4zfrpYdoSDfYyhg52rwLV6TnOvdG4fXm7IkSB3wErkcmJS9iEhjVtOSEjjA==} engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0} - '@grpc/grpc-js@1.14.4': - resolution: {integrity: sha512-k9Dj3DV/itK9D06Y8f190Qgop7/Ui+D0njFV3LHMPwPT75DpXLQohE9Wmz0QElrJnzsjB7KPWiKJbOl7IPDArQ==} + '@grpc/grpc-js@1.14.7': + resolution: {integrity: sha512-W4W/fcBMGRVtG6dW2c7cw2mnpS3hvbBd+oQXjh2iYFTZDk1JJmcNqkM5KSaPubQpamlUUurrlb7G1s9NJeERmQ==} engines: {node: '>=12.10.0'} '@grpc/proto-loader@0.8.1': @@ -1061,10 +1065,6 @@ packages: cpu: [x64] os: [win32] - '@infisical/sdk@5.0.2': - resolution: {integrity: sha512-mkgghtmIgBOEOFj1gb2n/AoiroFvN+NqaEEwC8ezEQ87V55yf2yksHhnBMU2MiZ26n6b3sGcpDZHF1/H6JrgyA==} - engines: {node: '>=20'} - '@inquirer/ansi@1.0.2': resolution: {integrity: sha512-S8qNSZiYzFd0wAcyG5AXCvUHC5Sr7xpZ9wZ2py9XR88jUz8wooStVx5M6dRzczbBWjic9NP7+rY0Xi7qqK/aMQ==} engines: {node: '>=18'} @@ -1812,6 +1812,9 @@ packages: '@smithy/core@3.30.0': resolution: {integrity: sha512-dl2yRglDxfzH9uJ4fSo4zTaAHa0zH7+V7BZMRWy8hEYIKT1BiqMUK/CN6T3ADQ3kbA5N1tmUulroJ2UtONS7Kw==} engines: {node: '>=18.0.0'} + deprecated: |- + Deprecated due to a bug in custom logger data redaction. Upgrade to the latest version. If you used a custom logger with this + version, review your logs and rotate any credentials or other secrets. See https://github.com/aws/aws-sdk-js-v3/issues/8393. '@smithy/credential-provider-imds@4.4.14': resolution: {integrity: sha512-QgbuahIb2qxQeZQvNK0sw3aF3JH5zwH8j2lLp5DUasVXexGGMWULAR+7z0omPXFolCP/m5wN9M5lm9EGdSviTQ==} @@ -2633,8 +2636,8 @@ packages: blake3-wasm@2.1.5: resolution: {integrity: sha512-F1+K8EbfOZE49dtoPtmxUQrpXaBIl3ICvasLh+nJta0xkz+9kF/7uet9fLnwKqhDrmj6g+6K3Tw9yQPUg2ka5g==} - body-parser@2.3.0: - resolution: {integrity: sha512-2cGmJupaNgg+QUwVLAucDuWuoMZ6EX9iHDRswZ5lsNYEmwPaRknMPCLZz07yTzVq/83p4o/wzbDZbBrTvGGTIw==} + body-parser@2.4.0: + resolution: {integrity: sha512-Ifk1KcLrxaGt1occQagQNFNNOqRt1LFuehEnHHzB8Z6cRgIxRU1TBaiIsUiCdA+gy5PL7Y1IX31DNKkRmxtXjQ==} engines: {node: '>=18'} bowser@2.14.1: @@ -2829,6 +2832,10 @@ packages: resolution: {integrity: sha512-j/O/d7GcZCyNl7/hwZAb606rzqkyvaDctLmckbxLzHvFBzTJHuGEdodATcP3yIRoDrLHkIATJuvzbFlp/ki2cQ==} engines: {node: '>=18'} + content-type@2.1.0: + resolution: {integrity: sha512-mj7UPXE0jaqaOsukNZRUEfEi2AcL7C/vwmwcHV0O97eO1E1pxBZuyjlZrx5seTaNBg1U6+o35wpa35Qfcc+7ag==} + engines: {node: '>=18'} + convert-source-map@2.0.0: resolution: {integrity: sha512-Kvp459HrV2FEJ1CAsi1Ku+MY3kasH19TFykTz2xWmMeq6bk2NU3XXvfJ+Q61m0xktWwt+1HSYf3JZsTms3aRJg==} @@ -3035,8 +3042,8 @@ packages: resolution: {integrity: sha512-HqD3yTBfnBxIrbnM1DoD6Pcq8NECnh8d4As1Qgh0z5Gg3jRRIqijury0CL3ghu/edArpUYiYqQiDUQBIs4np3Q==} engines: {node: '>=10.0.0'} - engine.io@6.6.7: - resolution: {integrity: sha512-DgOngfDKM2EviOH3Mr9m7ks1q8roetLy/IMmYthAYzbpInMbYc/GS+fWFA3rl1gvwKVsQrVV61fo5emD1y3OJQ==} + engine.io@6.6.11: + resolution: {integrity: sha512-z34mGpLoY/82ZbkX1LqGMIaf3wjVMPL6gVC681QDqnmzJ26synI8qAE32P+a7UazmpJZ8UGrFIeAavgRfXzYrg==} engines: {node: '>=10.2.0'} enhanced-resolve@5.20.1: @@ -4161,8 +4168,8 @@ packages: ms@2.1.3: resolution: {integrity: sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==} - multer@2.3.0: - resolution: {integrity: sha512-cjNbm3sttszgZeGfJR124D+jFEfkXCVAsoPBmFn9X7UxmDSFHWqE2CoEj0vrmSpuAFnqWR1Szcm9QTsiHr60Xw==} + multer@2.5.0: + resolution: {integrity: sha512-BsqOzYGVq49JcW2IzoSAxeKYRevb+dGGPPWleOR8Lrlk4igwxu1/9pwSXlByhCb7MVZDrNJFC0IBP5/O5nLYRw==} engines: {node: '>= 10.16.0'} mute-stream@2.0.0: @@ -4407,8 +4414,8 @@ packages: resolution: {integrity: sha512-/FPD0nUc9jH6rfFjji9IBqOz4pcSE3CsT1m7Ep6Mdb0LxSUMj8hgl6GomOvZzpNpAqqGaXA0P3VSrZLFzIhQrw==} engines: {node: '>=12.0.0'} - proxy-addr@2.0.7: - resolution: {integrity: sha512-llQsMLSUDUPT44jdrU/O37qlnifitDP+ZwrmmZcoSKyLKvtZxpyV0n2/bD/N4tBAAZ/gJEdZU7KMraoK1+XYAg==} + proxy-addr@2.0.8: + resolution: {integrity: sha512-5nnx0yGyVUcY6t9RnWcARWtwT9F1D8O9rt08htPvnd49W1IgZtmLkhu9WfMzQj1cFxjHIO6connUNVW5k7AVyQ==} engines: {node: '>= 0.10'} proxy-agent-negotiate@1.1.0: @@ -4434,8 +4441,8 @@ packages: resolution: {integrity: sha512-Rzq0KEyX/w/tEybncDgdkZrJgVUsUMk3xjh3t5bv3S1HTAtg+uOYt72+ZfwiQwKdysThkTBdL/rTi6HDmX9Ddw==} engines: {node: '>=0.6'} - qs@6.15.3: - resolution: {integrity: sha512-O9gl3zCl5h5blw1KGUzQKhA5oUXSl8rwUIM5o0S3nCXMliSvy5Dzx7/DJcI+SwgICv+IneSZwhBh1oSyEHA71A==} + qs@6.17.1: + resolution: {integrity: sha512-jd3COkaKVgGUW+ZHyEHCG9bH7RoaaiWuMgzsIBjUMVjLAaWGWpoUAVwljVvBHxRu/2qEHnadLGZrkutYUBPQJA==} engines: {node: '>=0.6'} range-parser@1.3.0: @@ -4672,8 +4679,8 @@ packages: resolution: {integrity: sha512-2Dd78bqzzjE6KPkD5fHZmDAKRNe3J15q+YHDrIsy9WEkqttc7GY+kT9OBLSMaPbQaEd0x1BjcmtMtXkfpc+T5A==} engines: {node: '>=10.2.0'} - source-map-js@1.2.1: - resolution: {integrity: sha512-UXWMKhLOwVKb728IUtQPXxfYU+usdybtUrK/8uGE8CQMvrhOpwvzDBwj0QhSL7MQc7vIsISBG8VQ8+IDQxpfQA==} + source-map-js@1.2.2: + resolution: {integrity: sha512-KGj/8Y43x35aZVDtt+J4mK1hoLGHULMYfSkODJNQjNDC3oW1PqPoxMwo0pLUsWM/UEGzON/NxeHywEfNXNP3Vw==} engines: {node: '>=0.10.0'} source-map-support@0.5.13: @@ -5008,12 +5015,8 @@ packages: undici-types@8.3.0: resolution: {integrity: sha512-j375ScV60dom+YkPFIfTLcOiPxkN/buHz5GobjLhixFuANaNs3C9l4GmrWqejgXWJ7BbJcFYpTEUkS1Ge8bpZQ==} - undici@7.28.0: - resolution: {integrity: sha512-cRZYrTDwWznlnRiPjggAGxZXanty6M8RV1ff8Wm4LWXBp7/IG8v5DnOm74DtUBp9OONpK75YlPnIjQqX0dBDtA==} - engines: {node: '>=20.18.1'} - - undici@7.29.0: - resolution: {integrity: sha512-IDxfleLmmbSskfWSUATiN1nfn2rDuvnMOqb5CWR92iIfojA0Ud+ulOAAEQ57LPr9rWmsreUyf5lwyao+7GNNVw==} + undici@7.30.2: + resolution: {integrity: sha512-mLyPQnHwUxaM/rideoK/+KL8DaAJLRl4aBCfmX444aCSLnIaomqPLtNRe2jdCYcsk5wZzXrDIQC8ZeYNRAYyIA==} engines: {node: '>=20.18.1'} unenv@2.0.0-rc.24: @@ -5267,9 +5270,6 @@ packages: peerDependencies: zod: ^3.25.0 || ^4.0.0 - zod@3.25.76: - resolution: {integrity: sha512-gzUt/qt81nXsFGKIFcC3YnfEAx5NkunCfnDlvuBSSFS02bcXu4Lmea0AFIUwbLWxWPx3d9p8S5QoaujKcNQxcQ==} - zod@4.3.6: resolution: {integrity: sha512-rftlrkhHZOcjDwkGlnUtZZkvaPHCsDATp4pGpuOOMDaTdDDXF91wuVDJoWoPsKX/3YPQ5fHuF3STjcYyKr+Qhg==} @@ -5355,22 +5355,26 @@ snapshots: '@aws-sdk/util-locate-window': 3.965.8 '@smithy/util-utf8': 2.3.0 tslib: 2.8.1 + optional: true '@aws-crypto/sha256-js@5.2.0': dependencies: '@aws-crypto/util': 5.2.0 '@aws-sdk/types': 3.974.2 tslib: 2.8.1 + optional: true '@aws-crypto/supports-web-crypto@5.2.0': dependencies: tslib: 2.8.1 + optional: true '@aws-crypto/util@5.2.0': dependencies: '@aws-sdk/types': 3.974.2 '@smithy/util-utf8': 2.3.0 tslib: 2.8.1 + optional: true '@aws-sdk/client-cognito-identity@3.993.0': dependencies: @@ -5413,6 +5417,7 @@ snapshots: '@smithy/util-retry': 4.5.14 '@smithy/util-utf8': 4.4.14 tslib: 2.8.1 + optional: true '@aws-sdk/core@3.977.1': dependencies: @@ -5424,6 +5429,7 @@ snapshots: '@smithy/types': 4.16.1 bowser: 2.14.1 tslib: 2.8.1 + optional: true '@aws-sdk/credential-provider-cognito-identity@3.972.60': dependencies: @@ -5432,6 +5438,7 @@ snapshots: '@smithy/core': 3.30.0 '@smithy/types': 4.16.1 tslib: 2.8.1 + optional: true '@aws-sdk/credential-provider-env@3.972.61': dependencies: @@ -5440,6 +5447,7 @@ snapshots: '@smithy/core': 3.30.0 '@smithy/types': 4.16.1 tslib: 2.8.1 + optional: true '@aws-sdk/credential-provider-http@3.972.63': dependencies: @@ -5450,6 +5458,7 @@ snapshots: '@smithy/node-http-handler': 4.9.11 '@smithy/types': 4.16.1 tslib: 2.8.1 + optional: true '@aws-sdk/credential-provider-ini@3.973.6': dependencies: @@ -5466,6 +5475,7 @@ snapshots: '@smithy/credential-provider-imds': 4.4.14 '@smithy/types': 4.16.1 tslib: 2.8.1 + optional: true '@aws-sdk/credential-provider-login@3.972.68': dependencies: @@ -5475,6 +5485,7 @@ snapshots: '@smithy/core': 3.30.0 '@smithy/types': 4.16.1 tslib: 2.8.1 + optional: true '@aws-sdk/credential-provider-node@3.972.72': dependencies: @@ -5489,6 +5500,7 @@ snapshots: '@smithy/credential-provider-imds': 4.4.14 '@smithy/types': 4.16.1 tslib: 2.8.1 + optional: true '@aws-sdk/credential-provider-process@3.972.61': dependencies: @@ -5497,6 +5509,7 @@ snapshots: '@smithy/core': 3.30.0 '@smithy/types': 4.16.1 tslib: 2.8.1 + optional: true '@aws-sdk/credential-provider-sso@3.973.5': dependencies: @@ -5507,6 +5520,7 @@ snapshots: '@smithy/core': 3.30.0 '@smithy/types': 4.16.1 tslib: 2.8.1 + optional: true '@aws-sdk/credential-provider-web-identity@3.972.67': dependencies: @@ -5516,6 +5530,7 @@ snapshots: '@smithy/core': 3.30.0 '@smithy/types': 4.16.1 tslib: 2.8.1 + optional: true '@aws-sdk/credential-providers@3.993.0': dependencies: @@ -5539,26 +5554,31 @@ snapshots: '@smithy/property-provider': 4.4.14 '@smithy/types': 4.16.1 tslib: 2.8.1 + optional: true '@aws-sdk/middleware-host-header@3.972.36': dependencies: '@aws-sdk/core': 3.977.1 tslib: 2.8.1 + optional: true '@aws-sdk/middleware-logger@3.972.35': dependencies: '@aws-sdk/core': 3.977.1 tslib: 2.8.1 + optional: true '@aws-sdk/middleware-recursion-detection@3.972.37': dependencies: '@aws-sdk/core': 3.977.1 tslib: 2.8.1 + optional: true '@aws-sdk/middleware-user-agent@3.972.65': dependencies: '@aws-sdk/core': 3.977.1 tslib: 2.8.1 + optional: true '@aws-sdk/nested-clients@3.993.0': dependencies: @@ -5600,6 +5620,7 @@ snapshots: '@smithy/util-retry': 4.5.14 '@smithy/util-utf8': 4.4.14 tslib: 2.8.1 + optional: true '@aws-sdk/nested-clients@3.997.35': dependencies: @@ -5611,11 +5632,13 @@ snapshots: '@smithy/node-http-handler': 4.9.11 '@smithy/types': 4.16.1 tslib: 2.8.1 + optional: true '@aws-sdk/region-config-resolver@3.972.39': dependencies: '@aws-sdk/core': 3.977.1 tslib: 2.8.1 + optional: true '@aws-sdk/signature-v4-multi-region@3.996.42': dependencies: @@ -5623,6 +5646,7 @@ snapshots: '@smithy/signature-v4': 5.6.10 '@smithy/types': 4.16.1 tslib: 2.8.1 + optional: true '@aws-sdk/token-providers@3.1095.0': dependencies: @@ -5632,11 +5656,13 @@ snapshots: '@smithy/core': 3.30.0 '@smithy/types': 4.16.1 tslib: 2.8.1 + optional: true '@aws-sdk/types@3.974.2': dependencies: '@smithy/types': 4.16.1 tslib: 2.8.1 + optional: true '@aws-sdk/util-endpoints@3.993.0': dependencies: @@ -5645,27 +5671,33 @@ snapshots: '@smithy/url-parser': 4.4.14 '@smithy/util-endpoints': 3.6.14 tslib: 2.8.1 + optional: true '@aws-sdk/util-locate-window@3.965.8': dependencies: tslib: 2.8.1 + optional: true '@aws-sdk/util-user-agent-browser@3.972.36': dependencies: '@aws-sdk/core': 3.977.1 tslib: 2.8.1 + optional: true '@aws-sdk/util-user-agent-node@3.973.51': dependencies: '@aws-sdk/core': 3.977.1 tslib: 2.8.1 + optional: true '@aws-sdk/xml-builder@3.972.37': dependencies: '@smithy/types': 4.16.1 tslib: 2.8.1 + optional: true - '@aws/lambda-invoke-store@0.3.0': {} + '@aws/lambda-invoke-store@0.3.0': + optional: true '@azure/msal-browser@5.8.0': dependencies: @@ -6085,7 +6117,7 @@ snapshots: '@eslint/core': 0.17.0 levn: 0.4.1 - '@grpc/grpc-js@1.14.4': + '@grpc/grpc-js@1.14.7': dependencies: '@grpc/proto-loader': 0.8.1 '@js-sdsl/ordered-map': 4.4.2 @@ -6214,15 +6246,6 @@ snapshots: '@img/sharp-win32-x64@0.35.2': optional: true - '@infisical/sdk@5.0.2': - dependencies: - '@aws-crypto/sha256-js': 5.2.0 - '@aws-sdk/credential-providers': 3.993.0 - '@smithy/protocol-http': 5.5.14 - '@smithy/signature-v4': 5.6.10 - typescript: 5.9.3 - zod: 3.25.76 - '@inquirer/ansi@1.0.2': {} '@inquirer/checkbox@4.3.2(@types/node@26.1.1)': @@ -6689,7 +6712,7 @@ snapshots: '@nestjs/core': 11.1.28(@nestjs/common@11.1.28(class-transformer@0.5.1)(class-validator@0.15.1)(reflect-metadata@0.2.2)(rxjs@7.8.2))(@nestjs/platform-express@11.1.28)(@nestjs/websockets@11.1.28)(reflect-metadata@0.2.2)(rxjs@7.8.2) cors: 2.8.6 express: 5.2.1 - multer: 2.3.0 + multer: 2.5.0 path-to-regexp: 8.4.2 tslib: 2.8.1 transitivePeerDependencies: @@ -6811,7 +6834,7 @@ snapshots: request-ip: 3.3.0 ringbufferjs: 2.0.0 semver: 7.8.5 - undici: 7.29.0 + undici: 7.30.2 unescape: 1.0.1 unescape-js: 1.1.4 ws: 8.21.0 @@ -7070,159 +7093,190 @@ snapshots: dependencies: '@smithy/core': 3.30.0 tslib: 2.8.1 + optional: true '@smithy/core@3.30.0': dependencies: '@smithy/types': 4.16.1 tslib: 2.8.1 + optional: true '@smithy/credential-provider-imds@4.4.14': dependencies: '@smithy/core': 3.30.0 '@smithy/types': 4.16.1 tslib: 2.8.1 + optional: true '@smithy/fetch-http-handler@5.6.11': dependencies: '@smithy/core': 3.30.0 '@smithy/types': 4.16.1 tslib: 2.8.1 + optional: true '@smithy/hash-node@4.4.14': dependencies: '@smithy/core': 3.30.0 tslib: 2.8.1 + optional: true '@smithy/invalid-dependency@4.4.14': dependencies: '@smithy/core': 3.30.0 tslib: 2.8.1 + optional: true '@smithy/is-array-buffer@2.2.0': dependencies: tslib: 2.8.1 + optional: true '@smithy/middleware-content-length@4.4.14': dependencies: '@smithy/core': 3.30.0 tslib: 2.8.1 + optional: true '@smithy/middleware-endpoint@4.6.14': dependencies: '@smithy/core': 3.30.0 tslib: 2.8.1 + optional: true '@smithy/middleware-retry@4.7.14': dependencies: '@smithy/core': 3.30.0 tslib: 2.8.1 + optional: true '@smithy/middleware-serde@4.4.14': dependencies: '@smithy/core': 3.30.0 tslib: 2.8.1 + optional: true '@smithy/middleware-stack@4.4.14': dependencies: '@smithy/core': 3.30.0 tslib: 2.8.1 + optional: true '@smithy/node-config-provider@4.5.14': dependencies: '@smithy/core': 3.30.0 tslib: 2.8.1 + optional: true '@smithy/node-http-handler@4.9.11': dependencies: '@smithy/core': 3.30.0 '@smithy/types': 4.16.1 tslib: 2.8.1 + optional: true '@smithy/property-provider@4.4.14': dependencies: '@smithy/core': 3.30.0 tslib: 2.8.1 + optional: true '@smithy/protocol-http@5.5.14': dependencies: '@smithy/core': 3.30.0 tslib: 2.8.1 + optional: true '@smithy/signature-v4@5.6.10': dependencies: '@smithy/core': 3.30.0 '@smithy/types': 4.16.1 tslib: 2.8.1 + optional: true '@smithy/smithy-client@4.14.14': dependencies: '@smithy/core': 3.30.0 '@smithy/types': 4.16.1 tslib: 2.8.1 + optional: true '@smithy/types@4.16.1': dependencies: tslib: 2.8.1 + optional: true '@smithy/url-parser@4.4.14': dependencies: '@smithy/core': 3.30.0 tslib: 2.8.1 + optional: true '@smithy/util-base64@4.5.14': dependencies: '@smithy/core': 3.30.0 tslib: 2.8.1 + optional: true '@smithy/util-body-length-browser@4.4.14': dependencies: '@smithy/core': 3.30.0 tslib: 2.8.1 + optional: true '@smithy/util-body-length-node@4.4.14': dependencies: '@smithy/core': 3.30.0 tslib: 2.8.1 + optional: true '@smithy/util-buffer-from@2.2.0': dependencies: '@smithy/is-array-buffer': 2.2.0 tslib: 2.8.1 + optional: true '@smithy/util-defaults-mode-browser@4.5.14': dependencies: '@smithy/core': 3.30.0 tslib: 2.8.1 + optional: true '@smithy/util-defaults-mode-node@4.4.14': dependencies: '@smithy/core': 3.30.0 tslib: 2.8.1 + optional: true '@smithy/util-endpoints@3.6.14': dependencies: '@smithy/core': 3.30.0 tslib: 2.8.1 + optional: true '@smithy/util-middleware@4.4.14': dependencies: '@smithy/core': 3.30.0 tslib: 2.8.1 + optional: true '@smithy/util-retry@4.5.14': dependencies: '@smithy/core': 3.30.0 tslib: 2.8.1 + optional: true '@smithy/util-utf8@2.3.0': dependencies: '@smithy/util-buffer-from': 2.2.0 tslib: 2.8.1 + optional: true '@smithy/util-utf8@4.4.14': dependencies: '@smithy/core': 3.30.0 tslib: 2.8.1 + optional: true '@socket.io/component-emitter@3.1.2': {} @@ -7248,7 +7302,7 @@ snapshots: jiti: 2.6.1 lightningcss: 1.32.0 magic-string: 0.30.21 - source-map-js: 1.2.1 + source-map-js: 1.2.2 tailwindcss: 4.2.2 '@tailwindcss/oxide-android-arm64@4.2.2': @@ -8010,21 +8064,22 @@ snapshots: blake3-wasm@2.1.5: {} - body-parser@2.3.0: + body-parser@2.4.0: dependencies: bytes: 3.1.2 - content-type: 2.0.0 + content-type: 2.1.0 debug: 4.4.3 http-errors: 2.0.1 iconv-lite: 0.7.3 on-finished: 2.4.1 - qs: 6.15.3 + qs: 6.17.1 raw-body: 3.0.2 type-is: 2.1.0 transitivePeerDependencies: - supports-color - bowser@2.14.1: {} + bowser@2.14.1: + optional: true brace-expansion@1.1.16: dependencies: @@ -8190,6 +8245,8 @@ snapshots: content-type@2.0.0: {} + content-type@2.1.0: {} + convert-source-map@2.0.0: {} cookie-es@3.1.1: {} @@ -8350,13 +8407,12 @@ snapshots: engine.io-parser@5.2.3: {} - engine.io@6.6.7: + engine.io@6.6.11: dependencies: '@types/cors': 2.8.19 '@types/node': 26.1.1 '@types/ws': 8.18.1 accepts: 1.3.8 - base64id: 2.0.0 cookie: 0.7.2 cors: 2.8.6 debug: 4.4.3 @@ -8576,7 +8632,7 @@ snapshots: express@5.2.1: dependencies: accepts: 2.0.0 - body-parser: 2.3.0 + body-parser: 2.4.0 content-disposition: 1.1.0 content-type: 1.0.5 cookie: 0.7.2 @@ -8594,7 +8650,7 @@ snapshots: on-finished: 2.4.1 once: 1.4.0 parseurl: 1.3.3 - proxy-addr: 2.0.7 + proxy-addr: 2.0.8 qs: 6.15.2 range-parser: 1.3.0 router: 2.2.0 @@ -9593,7 +9649,7 @@ snapshots: dependencies: '@cspotcode/source-map-support': 0.8.1 sharp: 0.35.2 - undici: 7.28.0 + undici: 7.30.2 workerd: 1.20260722.1 ws: 8.21.0 youch: 4.1.0-beta.10 @@ -9662,11 +9718,10 @@ snapshots: ms@2.1.3: {} - multer@2.3.0: + multer@2.5.0: dependencies: append-field: 1.0.0 busboy: 1.6.0 - concat-stream: 2.0.0 type-is: 1.6.18 mute-stream@2.0.0: {} @@ -9693,7 +9748,7 @@ snapshots: newrelic@14.3.3: dependencies: '@apm-js-collab/tracing-hooks': 0.9.1 - '@grpc/grpc-js': 1.14.4 + '@grpc/grpc-js': 1.14.7 '@grpc/proto-loader': 0.8.1 '@newrelic/security-agent': 3.0.4 '@opentelemetry/api': 1.9.1 @@ -9880,7 +9935,7 @@ snapshots: dependencies: nanoid: 3.3.18 picocolors: 1.1.1 - source-map-js: 1.2.1 + source-map-js: 1.2.2 pprof-format@2.3.0: optional: true @@ -9923,7 +9978,7 @@ snapshots: '@types/node': 26.1.1 long: 5.3.2 - proxy-addr@2.0.7: + proxy-addr@2.0.8: dependencies: forwarded: 0.2.0 ipaddr.js: 1.9.1 @@ -9944,7 +9999,7 @@ snapshots: dependencies: side-channel: 1.1.1 - qs@6.15.3: + qs@6.17.1: dependencies: es-define-property: 1.0.1 side-channel: 1.1.1 @@ -10264,7 +10319,7 @@ snapshots: base64id: 2.0.0 cors: 2.8.6 debug: 4.4.3 - engine.io: 6.6.7 + engine.io: 6.6.11 socket.io-adapter: 2.5.6 socket.io-parser: 4.2.7 transitivePeerDependencies: @@ -10272,7 +10327,7 @@ snapshots: - supports-color - utf-8-validate - source-map-js@1.2.1: {} + source-map-js@1.2.2: {} source-map-support@0.5.13: dependencies: @@ -10615,9 +10670,7 @@ snapshots: undici-types@8.3.0: {} - undici@7.28.0: {} - - undici@7.29.0: {} + undici@7.30.2: {} unenv@2.0.0-rc.24: dependencies: @@ -10894,6 +10947,4 @@ snapshots: dependencies: zod: 4.3.6 - zod@3.25.76: {} - zod@4.3.6: {} diff --git a/scripts/dependency-security.test.mjs b/scripts/dependency-security.test.mjs new file mode 100644 index 00000000..4e850e34 --- /dev/null +++ b/scripts/dependency-security.test.mjs @@ -0,0 +1,160 @@ +import assert from "node:assert/strict"; +import { once } from "node:events"; +import http from "node:http"; +import { createRequire } from "node:module"; +import { test } from "node:test"; +import { gzipSync } from "node:zlib"; + +const apiRequire = createRequire( + new URL("../apps/api/package.json", import.meta.url), +); +const webRequire = createRequire( + new URL("../apps/web/package.json", import.meta.url), +); +const expressRequire = createRequire( + apiRequire.resolve("@nestjs/platform-express"), +); +const proxyaddr = createRequire(expressRequire.resolve("express"))( + "proxy-addr", +); +const { ExpressAdapter } = apiRequire("@nestjs/platform-express"); +const { Server } = apiRequire("socket.io"); +const { io } = webRequire("socket.io-client"); +const engineRequire = createRequire( + createRequire(apiRequire.resolve("socket.io")).resolve("engine.io"), +); +const WebSocket = engineRequire("ws"); + +test("proxy trust does not accept unrelated IPv4 addresses through IPv6 subnets", () => { + for (const subnet of ["::ffff:10.0.0.0/8", "::/1"]) { + const trust = proxyaddr.compile(subnet); + assert.equal(trust("203.0.113.9"), false, subnet); + } + for (const subnet of ["10.0.0.0/8", "::ffff:10.0.0.0/104"]) { + const trust = proxyaddr.compile(subnet); + assert.equal(trust("10.1.2.3"), true); + assert.equal(trust("::ffff:10.1.2.3"), true); + assert.equal(trust("203.0.113.9"), false); + } +}); + +test( + "Socket.IO rejects mismatched and omitted upgrade protocol versions", + { timeout: 10000 }, + async (t) => { + const server = http.createServer(); + const sockets = new Server(server); + t.after(() => new Promise((resolve) => sockets.close(resolve))); + server.listen(0, "127.0.0.1"); + await once(server, "listening"); + const origin = `http://127.0.0.1:${server.address().port}`; + + for (const protocol of ["3", undefined]) { + const response = await fetch( + `${origin}/socket.io/?EIO=4&transport=polling`, + ); + const handshake = await response.text(); + assert.equal(handshake[0], "0"); + const { sid } = JSON.parse(handshake.slice(1)); + const query = new URLSearchParams({ transport: "websocket", sid }); + if (protocol) query.set("EIO", protocol); + const status = await new Promise((resolve, reject) => { + const socket = new WebSocket( + `${origin.replace("http:", "ws:")}/socket.io/?${query}`, + ); + socket.once("unexpected-response", (_, incoming) => { + incoming.resume(); + resolve(incoming.statusCode); + }); + socket.once("open", () => { + socket.close(); + resolve(101); + }); + socket.once("error", reject); + }); + assert.equal(status, 400, `upgrade EIO=${protocol ?? "(omitted)"}`); + } + + sockets.on("connection", (socket) => + socket.on("echo", (value, ack) => ack(value)), + ); + const client = io(origin, { autoConnect: false, reconnection: false }); + t.after(() => client.disconnect()); + const connected = once(client, "connect"); + client.connect(); + const upgraded = once(client.io.engine, "upgrade"); + await connected; + await upgraded; + assert.equal(client.io.engine.transport.name, "websocket"); + assert.deepEqual( + await client.timeout(2000).emitWithAck("echo", { bid: 42 }), + { bid: 42 }, + ); + }, +); + +test( + "Nest Express preserves raw JSON and survives compressed trailing data", + { timeout: 10000 }, + async (t) => { + const adapter = new ExpressAdapter(); + adapter.registerParserMiddleware("", true); + const app = adapter.getInstance(); + app.post("/echo", (req, res) => + res.json({ body: req.body, raw: req.rawBody.toString() }), + ); + app.get("/health", (_, res) => res.send("ok")); + app.use((error, _req, res, _next) => res.status(error.status ?? 500).end()); + const server = http.createServer(app); + t.after( + () => + new Promise((resolve) => { + server.closeAllConnections(); + server.close(resolve); + }), + ); + server.listen(0, "127.0.0.1"); + await once(server, "listening"); + const origin = `http://127.0.0.1:${server.address().port}`; + const json = JSON.stringify({ bid: 42 }); + for (const compressed of [false, true]) { + const response = await fetch(`${origin}/echo`, { + method: "POST", + headers: { + "content-type": "application/json", + ...(compressed ? { "content-encoding": "gzip" } : {}), + }, + body: compressed ? gzipSync(json) : json, + }); + assert.equal(response.status, 200); + assert.deepEqual(await response.json(), { body: { bid: 42 }, raw: json }); + } + for (const trailing of [ + Buffer.from("invalid trailing bytes"), + Buffer.from([0x1f, 0x8b, 0xff]), + ]) { + const payload = Buffer.concat([gzipSync(json), trailing]); + const status = await new Promise((resolve, reject) => { + const request = http.request( + `${origin}/echo`, + { + method: "POST", + headers: { + "content-type": "application/json", + "content-encoding": "gzip", + "content-length": payload.length, + }, + }, + (response) => { + response.resume(); + response.on("end", () => resolve(response.statusCode)); + }, + ); + request.on("error", reject); + request.end(payload); + }); + assert.equal(status, 400); + assert.equal(await (await fetch(`${origin}/health`)).text(), "ok"); + } + }, +);