From 22e90ac3d5c00b8f220c1c35867e18e5643efb7b Mon Sep 17 00:00:00 2001 From: shubh-bruno Date: Wed, 15 Jul 2026 16:16:43 +0530 Subject: [PATCH 01/13] fix(interpolation): add interpolation for akamai-auth --- packages/bruno-cli/src/runner/interpolate-vars.js | 11 +++++++++++ .../src/ipc/network/interpolate-vars.js | 11 +++++++++++ 2 files changed, 22 insertions(+) diff --git a/packages/bruno-cli/src/runner/interpolate-vars.js b/packages/bruno-cli/src/runner/interpolate-vars.js index eb3b4f95f5f..0910edc23a1 100644 --- a/packages/bruno-cli/src/runner/interpolate-vars.js +++ b/packages/bruno-cli/src/runner/interpolate-vars.js @@ -302,6 +302,17 @@ const interpolateVars = (request, envVariables = {}, runtimeVariables = {}, proc request.ntlmConfig.domain = _interpolate(request.ntlmConfig.domain) || ''; } + // interpolate vars for edgegrid auth + if (request.edgeGridConfig) { + request.edgeGridConfig.accessToken = _interpolate(request.edgeGridConfig.accessToken) || ''; + request.edgeGridConfig.clientToken = _interpolate(request.edgeGridConfig.clientToken) || ''; + request.edgeGridConfig.clientSecret = _interpolate(request.edgeGridConfig.clientSecret) || ''; + request.edgeGridConfig.nonce = _interpolate(request.edgeGridConfig.nonce) || ''; + request.edgeGridConfig.timestamp = _interpolate(request.edgeGridConfig.timestamp) || ''; + request.edgeGridConfig.baseURL = _interpolate(request.edgeGridConfig.baseURL) || ''; + request.edgeGridConfig.headersToSign = _interpolate(request.edgeGridConfig.headersToSign) || ''; + } + // interpolate vars for oauth1config auth if (request.oauth1config) { request.oauth1config.consumerKey = _interpolate(request.oauth1config.consumerKey) || ''; diff --git a/packages/bruno-electron/src/ipc/network/interpolate-vars.js b/packages/bruno-electron/src/ipc/network/interpolate-vars.js index 33800a123e8..5ce2efa3711 100644 --- a/packages/bruno-electron/src/ipc/network/interpolate-vars.js +++ b/packages/bruno-electron/src/ipc/network/interpolate-vars.js @@ -387,6 +387,17 @@ const interpolateVars = (request, envVariables = {}, runtimeVariables = {}, proc request.ntlmConfig.domain = _interpolate(request.ntlmConfig.domain) || ''; } + // interpolate vars for edgegrid auth + if (request.edgeGridConfig) { + request.edgeGridConfig.accessToken = _interpolate(request.edgeGridConfig.accessToken) || ''; + request.edgeGridConfig.clientToken = _interpolate(request.edgeGridConfig.clientToken) || ''; + request.edgeGridConfig.clientSecret = _interpolate(request.edgeGridConfig.clientSecret) || ''; + request.edgeGridConfig.nonce = _interpolate(request.edgeGridConfig.nonce) || ''; + request.edgeGridConfig.timestamp = _interpolate(request.edgeGridConfig.timestamp) || ''; + request.edgeGridConfig.baseURL = _interpolate(request.edgeGridConfig.baseURL) || ''; + request.edgeGridConfig.headersToSign = _interpolate(request.edgeGridConfig.headersToSign) || ''; + } + // interpolate vars for oauth1config auth if (request.oauth1config) { request.oauth1config.consumerKey = _interpolate(request.oauth1config.consumerKey) || ''; From 3978782a479a6416a99771e9bb4e52978bb0e66e Mon Sep 17 00:00:00 2001 From: shubh-bruno Date: Wed, 15 Jul 2026 20:02:22 +0530 Subject: [PATCH 02/13] feat(generate-code): sign akamai-edgegrid Authorization header in snippets --- packages/bruno-common/package.json | 4 +- packages/bruno-common/src/crypto-js.d.ts | 3 + .../src/generate-code/har/edgegrid.spec.ts | 43 ++++++ .../src/generate-code/har/edgegrid.ts | 137 ++++++++++++++++++ .../src/generate-code/har/index.ts | 30 +++- 5 files changed, 213 insertions(+), 4 deletions(-) create mode 100644 packages/bruno-common/src/crypto-js.d.ts create mode 100644 packages/bruno-common/src/generate-code/har/edgegrid.spec.ts create mode 100644 packages/bruno-common/src/generate-code/har/edgegrid.ts diff --git a/packages/bruno-common/package.json b/packages/bruno-common/package.json index f3b6840243e..db5863f4894 100644 --- a/packages/bruno-common/package.json +++ b/packages/bruno-common/package.json @@ -36,7 +36,9 @@ "watch": "rollup -c -w", "prepack": "npm run test && npm run build" }, - "dependencies": {}, + "dependencies": { + "crypto-js": "4.2.0" + }, "devDependencies": { "@babel/preset-env": "^7.26.9", "@babel/preset-typescript": "^7.27.0", diff --git a/packages/bruno-common/src/crypto-js.d.ts b/packages/bruno-common/src/crypto-js.d.ts new file mode 100644 index 00000000000..d87995c35f7 --- /dev/null +++ b/packages/bruno-common/src/crypto-js.d.ts @@ -0,0 +1,3 @@ +// crypto-js ships no bundled types and @types/crypto-js is not a repo dependency. +// We only use HmacSHA256, SHA256 and enc.Base64, so a permissive ambient module is sufficient. +declare module 'crypto-js'; diff --git a/packages/bruno-common/src/generate-code/har/edgegrid.spec.ts b/packages/bruno-common/src/generate-code/har/edgegrid.spec.ts new file mode 100644 index 00000000000..998012f6b09 --- /dev/null +++ b/packages/bruno-common/src/generate-code/har/edgegrid.spec.ts @@ -0,0 +1,43 @@ +import { signEdgeGridRequest } from './edgegrid'; + +/** + * Akamai's OFFICIAL EdgeGrid vectors (github.com/akamai/AkamaiOPEN-edgegrid-node). Matching them + * byte-for-byte proves the crypto-js (browser) signer here produces the same signature as the + * Node runtime signer, so Generate Code snippets validate against the real gateway. + */ +const CREDS = { + clientToken: 'akab-client-token-xxx-xxxxxxxxxxxxxxxx', + accessToken: 'akab-access-token-xxx-xxxxxxxxxxxxxxxx', + clientSecret: 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx=', + nonce: 'nonce-xx-xxxx-xxxx-xxxx-xxxxxxxxxxxx', + timestamp: '20140321T19:34:21+0000' +}; +const HOST = 'https://akaa-baseurl-xxxxxxxxxxx-xxxxxxxxxxxxx.luna.akamaiapis.net'; + +const sig = (header: string | null) => (header || '').split('signature=')[1]; + +describe('signEdgeGridRequest (codegen) - Akamai official vectors', () => { + const cases = [ + { name: 'simple GET', request: { method: 'GET', url: `${HOST}/` }, expected: 'tL+y4hxyHxgWVD30X3pWnGKHcPzmrIF+LThiAOhMxYU=' }, + { name: 'GET with query string', request: { method: 'GET', url: `${HOST}/testapi/v1/t1?p1=1&p2=2` }, expected: 'hKDH1UlnQySSHjvIcZpDMbQHihTQ0XyVAKZaApabdeA=' }, + { name: 'POST within body limit', request: { method: 'POST', url: `${HOST}/testapi/v1/t3`, bodyText: 'datadatadatadatadatadatadatadata' }, expected: 'hXm4iCxtpN22m4cbZb4lVLW5rhX8Ca82vCFqXzSTPe4=' }, + { name: 'POST with empty body', request: { method: 'POST', url: `${HOST}/testapi/v1/t6`, bodyText: '' }, expected: '1gEDxeQGD5GovIkJJGcBaKnZ+VaPtrc4qBUHixjsPCQ=' } + ]; + + test.each(cases)('$name', ({ request, expected }) => { + expect(sig(signEdgeGridRequest(CREDS, request))).toBe(expected); + }); + + it('returns null when required credentials are missing (caller omits the header)', () => { + expect(signEdgeGridRequest({ ...CREDS, clientSecret: '' }, { method: 'GET', url: `${HOST}/` })).toBeNull(); + }); + + it('emits a placeholder signature when credentials are unresolved {{var}} (interpolation off)', () => { + const header = signEdgeGridRequest( + { ...CREDS, clientToken: '{{client_token}}', clientSecret: '{{client_secret}}' }, + { method: 'POST', url: `${HOST}/edgegrid/verify` } + ); + expect(header).toContain('client_token={{client_token}}'); + expect(sig(header)).toBe(''); + }); +}); diff --git a/packages/bruno-common/src/generate-code/har/edgegrid.ts b/packages/bruno-common/src/generate-code/har/edgegrid.ts new file mode 100644 index 00000000000..617a2a3a9c9 --- /dev/null +++ b/packages/bruno-common/src/generate-code/har/edgegrid.ts @@ -0,0 +1,137 @@ +import * as CryptoJS from 'crypto-js'; + +/** + * Browser-safe EG1-HMAC-SHA256 signer for Generate Code snippets. + * + * Ported from the runtime signer (packages/bruno-requests/src/auth/edgegrid-helper.js) so the + * generated `Authorization` header validates against the real Akamai gateway - the difference is + * this variant uses crypto-js (works in the browser) instead of Node's `crypto`, since codegen + * runs in the renderer. Kept byte-for-byte compatible with Akamai's reference implementation. + */ + +const MAX_BODY_SIZE_DEFAULT = 131072; // 128 KB + +const isStrPresent = (str?: string | null): boolean => + !!str && String(str).trim() !== '' && String(str).trim() !== 'undefined'; + +// base64(HMAC-SHA256(data, key)) - key is a UTF-8 string, matching the runtime signer. +const base64HmacSha256 = (data: string, key: string): string => + CryptoJS.HmacSHA256(data, key).toString(CryptoJS.enc.Base64); + +// base64(SHA256(data)) +const base64Sha256 = (data: string): string => CryptoJS.SHA256(data).toString(CryptoJS.enc.Base64); + +// UTC timestamp in EdgeGrid format: YYYYMMDDTHH:MM:SS+0000 +const makeEdgeGridTimestamp = (): string => { + const [datePart, timePart] = new Date().toISOString().split('T'); + return `${datePart.replace(/-/g, '')}T${timePart.replace(/\.\d+Z$/, '')}+0000`; +}; + +// UUID v4 for the nonce. A snippet nonce need not be cryptographically strong. +const makeNonce = (): string => + 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => { + const r = (Math.random() * 16) | 0; + return (c === 'x' ? r : (r & 0x3) | 0x8).toString(16); + }); + +// `name:value` per signed header (lowercased name, trimmed + whitespace-collapsed value), +// tab-joined. Only headers present on the request are emitted, preserving config order. +const canonicalizeHeaders = (headersToSign?: string, requestHeaders: Record = {}): string => { + if (!isStrPresent(headersToSign)) return ''; + const lookup: Record = {}; + Object.keys(requestHeaders || {}).forEach((name) => { + lookup[name.toLowerCase()] = requestHeaders[name]; + }); + return (headersToSign as string) + .split(',') + .map((name) => name.trim().toLowerCase()) + .filter((name) => name.length > 0) + .filter((name) => Object.prototype.hasOwnProperty.call(lookup, name)) + .map((name) => `${name}:${String(lookup[name]).trim().replace(/\s+/g, ' ')}`) + .join('\t'); +}; + +// Akamai hashes the body for POST only, over the bytes as sent, truncated to maxBodySize. +const makeContentHash = (method: string, bodyText: string | undefined, maxBodySize: number): string => { + if (!method || method.toUpperCase() !== 'POST' || !bodyText) return ''; + let body = bodyText; + if (body.length === 0) return ''; + if (body.length > maxBodySize) body = body.substring(0, maxBodySize); + return base64Sha256(body); +}; + +export interface EdgeGridSignConfig { + accessToken?: string | null; + clientToken?: string | null; + clientSecret?: string | null; + baseURL?: string | null; + nonce?: string | null; + timestamp?: string | null; + headersToSign?: string | null; + maxBodySize?: number | string | null; +} + +export interface EdgeGridSignRequest { + method: string; + url: string; + headers?: Record; + bodyText?: string; +} + +/** + * Compute the EG1-HMAC-SHA256 `Authorization` header value, or `null` when the + * required credentials / a valid URL are missing (so the caller can omit the header). + */ +export const signEdgeGridRequest = ( + config: EdgeGridSignConfig, + request: EdgeGridSignRequest +): string | null => { + const { accessToken, clientToken, clientSecret, baseURL, headersToSign } = config; + if (!isStrPresent(accessToken) || !isStrPresent(clientToken) || !isStrPresent(clientSecret)) return null; + if (!request?.url || !request?.method) return null; + + const maxBodySize = config.maxBodySize ? parseInt(String(config.maxBodySize), 10) : MAX_BODY_SIZE_DEFAULT; + const nonce = isStrPresent(config.nonce) ? (config.nonce as string) : makeNonce(); + const timestamp = isStrPresent(config.timestamp) ? (config.timestamp as string) : makeEdgeGridTimestamp(); + + let parsedUrl: URL; + try { + let urlToSign = request.url; + if (isStrPresent(baseURL)) { + const requestUrl = new URL(request.url); + const trimmed = (baseURL as string).trim(); + // A scheme-less baseURL ("localhost:6000") mis-parses; borrow the request scheme. + const normalized = /^[a-z][a-z0-9+.-]*:\/\//i.test(trimmed) ? trimmed : `${requestUrl.protocol}//${trimmed}`; + const baseParsed = new URL(normalized); + urlToSign = `${baseParsed.protocol}//${baseParsed.host}${requestUrl.pathname}${requestUrl.search}`; + } + parsedUrl = new URL(urlToSign); + } catch { + return null; + } + + // The auth header (sans signature) is also the last field of the data-to-sign, per spec. + const authHeader = `EG1-HMAC-SHA256 client_token=${clientToken};access_token=${accessToken};timestamp=${timestamp};nonce=${nonce};`; + + // With variables unresolved (Generate Code, interpolation off) a real signature can't be + // produced - it would sign literal `{{var}}` tokens. Emit a placeholder the user replaces + // once the request is signed at send time. + if (/\{\{.+?\}\}/.test(authHeader) || /\{\{.+?\}\}/.test(clientSecret as string)) { + return `${authHeader}signature=`; + } + + const dataToSign = [ + request.method.toUpperCase(), + parsedUrl.protocol.replace(':', ''), + parsedUrl.host, + parsedUrl.pathname + parsedUrl.search, + canonicalizeHeaders(headersToSign as string, request.headers), + makeContentHash(request.method, request.bodyText, maxBodySize), + authHeader + ].join('\t'); + + const signingKey = base64HmacSha256(timestamp, clientSecret as string); + const signature = base64HmacSha256(dataToSign, signingKey); + + return `${authHeader}signature=${signature}`; +}; diff --git a/packages/bruno-common/src/generate-code/har/index.ts b/packages/bruno-common/src/generate-code/har/index.ts index 23afc678b2a..b6d0e0b07fd 100644 --- a/packages/bruno-common/src/generate-code/har/index.ts +++ b/packages/bruno-common/src/generate-code/har/index.ts @@ -30,6 +30,7 @@ import { cloneDeep, find, get } from 'lodash'; import interpolate, { interpolateObject } from '../../interpolate'; import { encodeUrl, parseQueryParams, patternHasher } from '../../utils'; +import { signEdgeGridRequest } from './edgegrid'; // --------------------------------------------------------------------------- // Types @@ -352,7 +353,8 @@ const authToHeaders = ( auth: BrunoAuth | undefined, variables: Record, oauth2Credentials: OAuth2CredentialRecord[] | undefined, - collectionUid: string | undefined + collectionUid: string | undefined, + request?: { method?: string; url?: string; headers?: BrunoKV[]; bodyText?: string } ): BrunoKV[] => { if (!auth || !auth.mode || auth.mode === 'none' || auth.mode === 'inherit') return []; @@ -414,6 +416,22 @@ const authToHeaders = ( return [{ name: 'Authorization', value: headerValue, enabled: true }]; } + case 'akamai-edgegrid': { + if (!request?.url || !request?.method) return []; + // EG1-HMAC-SHA256 signs the request itself, so we build the header from the request context. + const requestHeaders: Record = {}; + (request.headers || []).forEach((h) => { + if (h?.enabled !== false && h?.name) requestHeaders[h.name] = String(h.value ?? ''); + }); + const value = signEdgeGridRequest(get(auth, 'akamaiEdgegrid') || {}, { + method: request.method, + url: request.url, + headers: requestHeaders, + bodyText: request.bodyText + }); + return value ? [{ name: 'Authorization', value, enabled: true }] : []; + } + // OAuth1 cannot pre-compute the signature for a static snippet. // Digest/NTLM/AWS/WSSE are runtime-signed. default: @@ -609,8 +627,14 @@ export function buildHar(input: BuildHarInput): BuildHarOutput { throw new Error('invalid request url'); } - // Step 5 — Auth → headers. Append to request headers. - const authHeaders = authToHeaders(working.auth, variables, input.oauth2Credentials, input.collectionUid); + // Step 5 — Auth → headers. Append to request headers. Request-signing auth (EdgeGrid) must + // sign the same `encodedUrl` the snippet transmits, or the signature won't cover the sent bytes. + const authHeaders = authToHeaders(working.auth, variables, input.oauth2Credentials, input.collectionUid, { + method: working.method || 'GET', + url: encodedUrl, + headers: working.headers, + bodyText: buildPostData(working.body)?.text + }); const allHeaders = mergeAndDedupeHeaders(working.headers, authHeaders); // Step 6 — Finalize headers (filter enabled, lowercase, default content-type). From 9710246ff28b013f4aa9e3ba9ddf1d9c087a1909 Mon Sep 17 00:00:00 2001 From: shubh-bruno Date: Wed, 15 Jul 2026 20:03:09 +0530 Subject: [PATCH 03/13] test(akamai-edgegrid): cover generate-code and timeline e2e --- .../akamai-edgegrid-generate-code.spec.ts | 104 ++++++++++++++++++ .../akamai-edgegrid-levels.spec.ts | 6 +- .../akamai-edgegrid-runner.spec.ts | 2 +- .../akamai-edgegrid/akamai-edgegrid.spec.ts | 68 ++++++++++-- 4 files changed, 168 insertions(+), 12 deletions(-) create mode 100644 tests/auth/akamai-edgegrid/akamai-edgegrid-generate-code.spec.ts diff --git a/tests/auth/akamai-edgegrid/akamai-edgegrid-generate-code.spec.ts b/tests/auth/akamai-edgegrid/akamai-edgegrid-generate-code.spec.ts new file mode 100644 index 00000000000..af963a01134 --- /dev/null +++ b/tests/auth/akamai-edgegrid/akamai-edgegrid-generate-code.spec.ts @@ -0,0 +1,104 @@ +import { expect, Page, test } from '../../../playwright'; +import { + closeAllCollections, + closeGenerateCodeDialog, + createCollection, + createRequest, + getGeneratedSnippet, + openRequest, + saveRequest, + selectAuthMode, + selectRequestPaneTab, + typeIntoField +} from '../../utils/page'; + +/** + * Generate Code for Akamai EdgeGrid. The snippet must carry a real EG1-HMAC-SHA256 + * `Authorization` header - computed at codegen time (bruno-common signs the HAR) - for both + * request-level and inherited auth. When a credential is an unresolved `{{var}}`, no real + * signature can be produced, so a placeholder stands in. + */ + +const { TEST_EDGEGRID } = require('../../../packages/bruno-tests/src/auth/edgegrid'); +const REQUEST_URL = 'http://localhost:8081/api/auth/edgegrid/resource'; + +// The credential tokens are embedded verbatim in the header; asserting the prefix proves both +// tokens made it in, in the right order. +const authHeaderPrefix = `EG1-HMAC-SHA256 client_token=${TEST_EDGEGRID.clientToken};access_token=${TEST_EDGEGRID.accessToken};`; +// A real signature is base64; the placeholder is the literal sentinel below. +const SIGNATURE_PLACEHOLDER = 'signature='; +const realSignature = /signature=[A-Za-z0-9+/]{20,}={0,2}/; + +const fillEdgeGridCredentials = async (page: Page) => { + await typeIntoField(page, 'Access Token', TEST_EDGEGRID.accessToken); + await typeIntoField(page, 'Client Token', TEST_EDGEGRID.clientToken); + await typeIntoField(page, 'Client Secret', TEST_EDGEGRID.clientSecret); +}; + +test.describe('Akamai EdgeGrid - Generate Code', () => { + test.afterEach(async ({ page }) => { + await closeAllCollections(page); + }); + + test('request-level auth produces a signed EG1-HMAC-SHA256 Authorization header', async ({ page, createTmpDir }) => { + await createCollection(page, 'edgegrid-gencode-request', await createTmpDir()); + await createRequest(page, 'signed-request', 'edgegrid-gencode-request', { url: REQUEST_URL }); + await openRequest(page, 'edgegrid-gencode-request', 'signed-request'); + await selectRequestPaneTab(page, 'Auth'); + await selectAuthMode(page, 'Akamai EdgeGrid'); + await fillEdgeGridCredentials(page); + await saveRequest(page); + + const snippet = await getGeneratedSnippet(page); + + expect(snippet).toContain(authHeaderPrefix); + expect(snippet).toMatch(realSignature); + expect(snippet).not.toContain(SIGNATURE_PLACEHOLDER); + + await closeGenerateCodeDialog(page); + }); + + test('inherited collection auth is resolved and signed in the snippet', async ({ page, createTmpDir }) => { + await createCollection(page, 'edgegrid-gencode-inherit', await createTmpDir()); + // Collection settings open on creation - configure collection-level EdgeGrid auth. + await page.locator('.tab.auth').click(); + await selectAuthMode(page, 'Akamai EdgeGrid'); + await fillEdgeGridCredentials(page); + await page.getByRole('button', { name: 'Save' }).click(); + + await createRequest(page, 'inheriting-request', 'edgegrid-gencode-inherit', { url: REQUEST_URL }); + await openRequest(page, 'edgegrid-gencode-inherit', 'inheriting-request'); + await selectRequestPaneTab(page, 'Auth'); + // A new request already defaults to Inherit; Generate Code reads the draft and resolves + // inheritance from the collection, so no save is needed here. + await expect(page.locator('.inherit-mode-text')).toHaveText('Akamai EdgeGrid'); + + const snippet = await getGeneratedSnippet(page); + + expect(snippet).toContain(authHeaderPrefix); + expect(snippet).toMatch(realSignature); + expect(snippet).not.toContain(SIGNATURE_PLACEHOLDER); + + await closeGenerateCodeDialog(page); + }); + + test('unresolved {{variable}} credentials produce a placeholder signature', async ({ page, createTmpDir }) => { + await createCollection(page, 'edgegrid-gencode-vars', await createTmpDir()); + await createRequest(page, 'templated-request', 'edgegrid-gencode-vars', { url: REQUEST_URL }); + await openRequest(page, 'edgegrid-gencode-vars', 'templated-request'); + await selectRequestPaneTab(page, 'Auth'); + await selectAuthMode(page, 'Akamai EdgeGrid'); + await typeIntoField(page, 'Access Token', TEST_EDGEGRID.accessToken); + await typeIntoField(page, 'Client Token', '{{clientToken}}'); + await typeIntoField(page, 'Client Secret', '{{clientSecret}}'); + await saveRequest(page); + + const snippet = await getGeneratedSnippet(page); + + // Unresolved token stays verbatim in the header; the signature can't be computed from it. + expect(snippet).toContain('client_token={{clientToken}}'); + expect(snippet).toContain(SIGNATURE_PLACEHOLDER); + + await closeGenerateCodeDialog(page); + }); +}); diff --git a/tests/auth/akamai-edgegrid/akamai-edgegrid-levels.spec.ts b/tests/auth/akamai-edgegrid/akamai-edgegrid-levels.spec.ts index 4919aecd40c..4ca6f771568 100644 --- a/tests/auth/akamai-edgegrid/akamai-edgegrid-levels.spec.ts +++ b/tests/auth/akamai-edgegrid/akamai-edgegrid-levels.spec.ts @@ -16,7 +16,7 @@ import { * EdgeGrid is configurable at collection settings, folder settings, and request level. These * tests verify each renders without crashing (collection-level was a `null` crash regression), * persists all 8 fields across a save, and that a request which inherits the auth actually - * signs and is accepted by the local simulator — asserting the echoed effective values. + * signs and is accepted by the local simulator - asserting the echoed effective values. */ const { TEST_EDGEGRID } = require('../../../packages/bruno-tests/src/auth/edgegrid'); @@ -74,13 +74,12 @@ const expectInheritedEdgeGridSignature = async (page, expectedNonce: string) => expect(body).toContain('localhost:8081'); }; -test.describe('Akamai EdgeGrid Authentication — collection, folder & inherit', () => { +test.describe('Akamai EdgeGrid Authentication - collection, folder & inherit', () => { test.afterEach(async ({ page }) => { await closeAllCollections(page); }); test('Collection level: renders, persists, and an inheriting request signs', async ({ page, createTmpDir }) => { - test.setTimeout(120_000); const values = valuesFor('collection-nonce'); await createCollection(page, 'edgegrid-collection', await createTmpDir()); @@ -116,7 +115,6 @@ test.describe('Akamai EdgeGrid Authentication — collection, folder & inherit', }); test('Folder level: renders, persists, and an inheriting request signs', async ({ page, createTmpDir }) => { - test.setTimeout(120_000); const values = valuesFor('folder-nonce'); await createCollection(page, 'edgegrid-collection', await createTmpDir()); await createFolder(page, 'folder-1', 'edgegrid-collection', true); diff --git a/tests/auth/akamai-edgegrid/akamai-edgegrid-runner.spec.ts b/tests/auth/akamai-edgegrid/akamai-edgegrid-runner.spec.ts index a45285ebb6f..fbe06dad7bf 100644 --- a/tests/auth/akamai-edgegrid/akamai-edgegrid-runner.spec.ts +++ b/tests/auth/akamai-edgegrid/akamai-edgegrid-runner.spec.ts @@ -10,7 +10,7 @@ import { /** * End-to-end EdgeGrid (EG1-HMAC-SHA256) auth against the local simulator * (packages/bruno-tests/src/auth/edgegrid.js, mounted at /api/auth/edgegrid). The simulator - * independently re-derives the signature and returns 200/401 — so a green run proves the full + * independently re-derives the signature and returns 200/401 - so a green run proves the full * UI → prepare-request → interceptor → wire → server-validation path, with no real Akamai API. */ diff --git a/tests/auth/akamai-edgegrid/akamai-edgegrid.spec.ts b/tests/auth/akamai-edgegrid/akamai-edgegrid.spec.ts index 2ddbcaa1262..cac3587d884 100644 --- a/tests/auth/akamai-edgegrid/akamai-edgegrid.spec.ts +++ b/tests/auth/akamai-edgegrid/akamai-edgegrid.spec.ts @@ -1,17 +1,23 @@ import { expect, test } from '../../../playwright'; import { + addEnvironmentVariable, + buildCommonLocators, closeAllCollections, closeAllTabs, createCollection, + createEnvironment, createRequest, getResponseBody, openRequest, + saveEnvironment, saveRequest, + selectEnvironment, selectRequestPaneTab, + selectResponsePaneTab, sendRequestAndWaitForResponse } from '../../utils/page'; -// Shared test creds — the local simulator (packages/bruno-tests/src/auth/edgegrid.js) knows +// Shared test creds - the local simulator (packages/bruno-tests/src/auth/edgegrid.js) knows // this secret, so signed requests validate (200) and the response echoes the effective values. const { TEST_EDGEGRID } = require('../../../packages/bruno-tests/src/auth/edgegrid'); const SIMULATOR_URL = 'http://localhost:8081/api/auth/edgegrid/resource'; @@ -62,8 +68,6 @@ test.describe('Akamai EdgeGrid Authentication (request level)', () => { }); test('Configure, sign against the simulator, and persist all fields', async ({ page, createTmpDir }) => { - test.setTimeout(90_000); - await createCollection(page, 'edgegrid-ui-test', await createTmpDir()); await createRequest(page, 'edgegrid-request', 'edgegrid-ui-test', { url: SIMULATOR_URL }); await openRequest(page, 'edgegrid-ui-test', 'edgegrid-request'); @@ -87,7 +91,7 @@ test.describe('Akamai EdgeGrid Authentication (request level)', () => { await saveRequest(page); }); - await test.step('Send the request — simulator validates and echoes the configured values', async () => { + await test.step('Send the request - simulator validates and echoes the configured values', async () => { await sendRequestAndWaitForResponse(page, 200); const body = await getResponseBody(page); expect(body).toContain('ui-nonce-123'); // configured nonce was signed & sent @@ -105,8 +109,6 @@ test.describe('Akamai EdgeGrid Authentication (request level)', () => { }); test('Empty Advanced Settings fall back to auto-generated defaults', async ({ page, createTmpDir }) => { - test.setTimeout(90_000); - await createCollection(page, 'edgegrid-defaults-test', await createTmpDir()); await createRequest(page, 'edgegrid-defaults', 'edgegrid-defaults-test', { url: SIMULATOR_URL }); await openRequest(page, 'edgegrid-defaults-test', 'edgegrid-defaults'); @@ -120,7 +122,7 @@ test.describe('Akamai EdgeGrid Authentication (request level)', () => { await saveRequest(page); }); - await test.step('Send request — simulator echoes the auto-generated defaults', async () => { + await test.step('Send request - simulator echoes the auto-generated defaults', async () => { await sendRequestAndWaitForResponse(page, 200); const body = await getResponseBody(page); // nonce auto-generated as a UUID v4 @@ -133,4 +135,56 @@ test.describe('Akamai EdgeGrid Authentication (request level)', () => { expect(body).toContain('131072'); }); }); + + test('Timeline network log shows resolved variables, nonce, timestamp, and signature of a sent request', async ({ page, createTmpDir }) => { + const { timeline } = buildCommonLocators(page); + const nonce = 'timeline-nonce'; + const timestamp = '20240101T00:00:00+0000'; + + await createCollection(page, 'edgegrid-timeline-test', await createTmpDir()); + + await test.step('Define every credential as an environment variable', async () => { + await createEnvironment(page, 'Local'); + await addEnvironmentVariable(page, { name: 'egAccessToken', value: TEST_EDGEGRID.accessToken }); + await addEnvironmentVariable(page, { name: 'egClientToken', value: TEST_EDGEGRID.clientToken }); + await addEnvironmentVariable(page, { name: 'egClientSecret', value: TEST_EDGEGRID.clientSecret }); + await saveEnvironment(page); + }); + + await test.step('Configure EdgeGrid auth with all credentials sourced from variables', async () => { + await createRequest(page, 'edgegrid-timeline-request', 'edgegrid-timeline-test', { url: SIMULATOR_URL }); + await openRequest(page, 'edgegrid-timeline-test', 'edgegrid-timeline-request'); + await selectRequestPaneTab(page, 'Auth'); + await selectEdgeGridMode(page); + await setField(page, 'Access Token', '{{egAccessToken}}'); + await setField(page, 'Client Token', '{{egClientToken}}'); + await setField(page, 'Client Secret', '{{egClientSecret}}'); + await setField(page, 'Nonce', nonce); + await setField(page, 'Timestamp', timestamp); + await saveRequest(page); + }); + + await test.step('Send against the simulator (validates the signature)', async () => { + await selectEnvironment(page, 'Local'); + await sendRequestAndWaitForResponse(page, 200); + }); + + await test.step('Timeline → Network shows the signed header exactly as sent on the wire', async () => { + await selectResponsePaneTab(page, 'Timeline'); + const entry = timeline.items().first(); + await timeline.itemHeader(entry).click(); + await entry.getByRole('button', { name: 'Network' }).click(); + const networkLogs = entry.locator('.network-logs-container'); + + // Credentials were interpolated from the variables before signing - no unresolved tokens. + await expect(networkLogs).toContainText(`access_token=${TEST_EDGEGRID.accessToken}`); + await expect(networkLogs).toContainText(`client_token=${TEST_EDGEGRID.clientToken}`); + await expect(networkLogs).not.toContainText('{{'); + // The EG1-HMAC-SHA256 header carries the configured nonce/timestamp and a computed signature + // (the 200 above already proves the resolved clientSecret produced a valid signature). + await expect(networkLogs).toContainText(`nonce=${nonce}`); + await expect(networkLogs).toContainText(`timestamp=${timestamp}`); + await expect(networkLogs).toContainText('signature='); + }); + }); }); From 6dd89399c3ebf93a32865a1ab1b441e211bd2636 Mon Sep 17 00:00:00 2001 From: shubh-bruno Date: Wed, 15 Jul 2026 20:14:59 +0530 Subject: [PATCH 04/13] chore(generate-code): drop crypto-js.d.ts --- packages/bruno-common/src/crypto-js.d.ts | 3 --- 1 file changed, 3 deletions(-) delete mode 100644 packages/bruno-common/src/crypto-js.d.ts diff --git a/packages/bruno-common/src/crypto-js.d.ts b/packages/bruno-common/src/crypto-js.d.ts deleted file mode 100644 index d87995c35f7..00000000000 --- a/packages/bruno-common/src/crypto-js.d.ts +++ /dev/null @@ -1,3 +0,0 @@ -// crypto-js ships no bundled types and @types/crypto-js is not a repo dependency. -// We only use HmacSHA256, SHA256 and enc.Base64, so a permissive ambient module is sufficient. -declare module 'crypto-js'; From 6b69318a63be1e182b235c9ad01f79203218f09d Mon Sep 17 00:00:00 2001 From: shubh-bruno Date: Thu, 16 Jul 2026 14:54:41 +0530 Subject: [PATCH 05/13] fix: resolved comments --- package-lock.json | 12 + .../Auth/EdgeGridAuth/index.tsx | 8 +- .../RequestPane/Auth/EdgeGridAuth/index.tsx | 8 +- .../GenerateCodeItem/CodeView/index.js | 15 +- .../utils/snippet-generator.js | 4 +- .../utils/snippet-generator.spec.js | 216 ++++----- packages/bruno-common/package.json | 3 +- .../src/generate-code/har/edgegrid.spec.ts | 16 +- .../src/generate-code/har/edgegrid.ts | 88 +--- .../src/generate-code/har/index.spec.ts | 442 +++++++++--------- .../src/generate-code/har/index.ts | 10 +- packages/bruno-common/src/utils/edgegrid.ts | 71 +++ packages/bruno-common/src/utils/index.ts | 9 + .../src/formats/yml/common/auth.ts | 10 +- packages/bruno-requests/package.json | 1 + packages/bruno-requests/rollup.config.js | 5 +- .../src/auth/edgegrid-helper.js | 150 ++---- .../src/auth/edgegrid-helper.spec.js | 60 +-- .../bruno-schema-types/src/common/auth.ts | 8 +- 19 files changed, 558 insertions(+), 578 deletions(-) create mode 100644 packages/bruno-common/src/utils/edgegrid.ts diff --git a/package-lock.json b/package-lock.json index 13635e6626c..f5defd3af30 100644 --- a/package-lock.json +++ b/package-lock.json @@ -13176,6 +13176,13 @@ "resolved": "https://registry.npmjs.org/@types/use-sync-external-store/-/use-sync-external-store-0.0.6.tgz", "integrity": "sha512-zFDAD+tlpf2r4asuHEj0XH6pY6i0g5NeAHPn+15wk3BV6JA69eERFXC1gyGThDkVa1zCyKr5jox1+2LbV/AMLg==" }, + "node_modules/@types/uuid": { + "version": "10.0.0", + "resolved": "https://registry.npmjs.org/@types/uuid/-/uuid-10.0.0.tgz", + "integrity": "sha512-7gqG38EyHgyP1S+7+xomFtL+ZNHcKv6DwNaCZmJmo1vgMugyF3TCnXVg4t1uk89mLNwnLtnY3TpOpCOyp1/xHQ==", + "dev": true, + "license": "MIT" + }, "node_modules/@types/verror": { "version": "1.10.10", "resolved": "https://registry.npmjs.org/@types/verror/-/verror-1.10.10.tgz", @@ -34627,6 +34634,9 @@ "name": "@usebruno/common", "version": "0.1.0", "license": "MIT", + "dependencies": { + "uuid": "^10.0.0" + }, "devDependencies": { "@babel/preset-env": "^7.26.9", "@babel/preset-typescript": "^7.27.0", @@ -34637,6 +34647,7 @@ "@rollup/plugin-terser": "^1.0.0", "@rollup/plugin-typescript": "^12.1.2", "@types/jest": "^29.5.14", + "@types/uuid": "^10.0.0", "babel-jest": "^29.7.0", "form-data": "4.0.4", "is-ip": "^5.0.1", @@ -36219,6 +36230,7 @@ "@grpc/grpc-js": "^1.13.3", "@grpc/proto-loader": "^0.7.15", "@types/qs": "^6.9.18", + "@usebruno/common": "0.1.0", "axios": "1.16.0", "debug": "^4.4.3", "google-protobuf": "^4.0.0", diff --git a/packages/bruno-app/src/components/CollectionSettings/Auth/EdgeGridAuth/index.tsx b/packages/bruno-app/src/components/CollectionSettings/Auth/EdgeGridAuth/index.tsx index 2d0dfae4ad1..4a573d5700b 100644 --- a/packages/bruno-app/src/components/CollectionSettings/Auth/EdgeGridAuth/index.tsx +++ b/packages/bruno-app/src/components/CollectionSettings/Auth/EdgeGridAuth/index.tsx @@ -15,10 +15,10 @@ interface AkamaiEdgeGridAuthValues { accessToken?: string; clientToken?: string; clientSecret?: string; - nonce?: string; - timestamp?: string; - baseURL?: string; - headersToSign?: string; + baseURL?: string | null; + nonce?: string | null; + timestamp?: string | null; + headersToSign?: string | null; maxBodySize?: number | null; } diff --git a/packages/bruno-app/src/components/RequestPane/Auth/EdgeGridAuth/index.tsx b/packages/bruno-app/src/components/RequestPane/Auth/EdgeGridAuth/index.tsx index 1d08bb50904..549ac809ce4 100644 --- a/packages/bruno-app/src/components/RequestPane/Auth/EdgeGridAuth/index.tsx +++ b/packages/bruno-app/src/components/RequestPane/Auth/EdgeGridAuth/index.tsx @@ -14,10 +14,10 @@ interface AkamaiEdgeGridAuthValues { accessToken?: string; clientToken?: string; clientSecret?: string; - nonce?: string; - timestamp?: string; - baseURL?: string; - headersToSign?: string; + baseURL?: string | null; + nonce?: string | null; + timestamp?: string | null; + headersToSign?: string | null; maxBodySize?: number | null; } diff --git a/packages/bruno-app/src/components/Sidebar/Collections/Collection/CollectionItem/GenerateCodeItem/CodeView/index.js b/packages/bruno-app/src/components/Sidebar/Collections/Collection/CollectionItem/GenerateCodeItem/CodeView/index.js index 44d527c6334..fab4a4ce10a 100644 --- a/packages/bruno-app/src/components/Sidebar/Collections/Collection/CollectionItem/GenerateCodeItem/CodeView/index.js +++ b/packages/bruno-app/src/components/Sidebar/Collections/Collection/CollectionItem/GenerateCodeItem/CodeView/index.js @@ -8,7 +8,7 @@ import toast from 'react-hot-toast'; import { IconCopy } from '@tabler/icons'; import { findCollectionByItemUid, getGlobalEnvironmentVariables } from 'utils/collections/index'; import { cloneDeep } from 'lodash'; -import { useMemo } from 'react'; +import { useEffect, useMemo, useState } from 'react'; import { generateSnippet } from '../utils/snippet-generator'; const CodeView = ({ language, item }) => { const { displayedTheme } = useTheme(); @@ -31,13 +31,22 @@ const CodeView = ({ language, item }) => { return c; }, [collectionOriginal, globalEnvironments, activeGlobalEnvironmentUid]); - const snippet = useMemo(() => { - return generateSnippet({ + // generateSnippet is async (EdgeGrid signs via Web Crypto), so the snippet is produced in an + // effect; the cancelled flag drops results from a superseded render. + const [snippet, setSnippet] = useState(''); + useEffect(() => { + let cancelled = false; + generateSnippet({ language, item, collection, shouldInterpolate: generateCodePrefs.shouldInterpolate + }).then((result) => { + if (!cancelled) setSnippet(result); }); + return () => { + cancelled = true; + }; }, [language, item, collection, generateCodePrefs.shouldInterpolate]); return ( diff --git a/packages/bruno-app/src/components/Sidebar/Collections/Collection/CollectionItem/GenerateCodeItem/utils/snippet-generator.js b/packages/bruno-app/src/components/Sidebar/Collections/Collection/CollectionItem/GenerateCodeItem/utils/snippet-generator.js index 0712b1c53ff..b5c92549357 100644 --- a/packages/bruno-app/src/components/Sidebar/Collections/Collection/CollectionItem/GenerateCodeItem/utils/snippet-generator.js +++ b/packages/bruno-app/src/components/Sidebar/Collections/Collection/CollectionItem/GenerateCodeItem/utils/snippet-generator.js @@ -31,7 +31,7 @@ const addCurlAuthFlags = (curlCommand, auth) => { return curlCommand; }; -const generateSnippet = ({ language, item, collection, shouldInterpolate = false }) => { +const generateSnippet = async ({ language, item, collection, shouldInterpolate = false }) => { try { // Get HTTPSnippet dynamically so mocks can be applied in tests const { HTTPSnippet } = require('httpsnippet'); @@ -51,7 +51,7 @@ const generateSnippet = ({ language, item, collection, shouldInterpolate = false const settings = item.draft ? get(item, 'draft.settings') : get(item, 'settings'); const sourceUrl = item.rawUrl || request.url; - const { har, rawUrl, encodedUrl, unhash } = buildHar({ + const { har, rawUrl, encodedUrl, unhash } = await buildHar({ request: { method: request.method, url: sourceUrl, diff --git a/packages/bruno-app/src/components/Sidebar/Collections/Collection/CollectionItem/GenerateCodeItem/utils/snippet-generator.spec.js b/packages/bruno-app/src/components/Sidebar/Collections/Collection/CollectionItem/GenerateCodeItem/utils/snippet-generator.spec.js index cc08aad55c9..feed9b96be2 100644 --- a/packages/bruno-app/src/components/Sidebar/Collections/Collection/CollectionItem/GenerateCodeItem/utils/snippet-generator.spec.js +++ b/packages/bruno-app/src/components/Sidebar/Collections/Collection/CollectionItem/GenerateCodeItem/utils/snippet-generator.spec.js @@ -112,8 +112,8 @@ describe('Snippet Generator - Simple Tests', () => { })); }); - it('should generate curl for POST request with JSON body', () => { - const result = generateSnippet({ + it('should generate curl for POST request with JSON body', async () => { + const result = await generateSnippet({ language: curlLanguage, item: testRequest, collection: testCollection, @@ -123,8 +123,8 @@ describe('Snippet Generator - Simple Tests', () => { expect(result).toBe('curl -X POST https://api.example.com/{{endpoint}} -H "Content-Type: application/json" -d \'{"message": "{{greeting}}", "count": {{number}}}\''); }); - it('should interpolate variables when enabled', () => { - const result = generateSnippet({ + it('should interpolate variables when enabled', async () => { + const result = await generateSnippet({ language: curlLanguage, item: testRequest, collection: testCollection, @@ -138,7 +138,7 @@ describe('Snippet Generator - Simple Tests', () => { expect(result).toBe(`curl -X POST https://api.example.com/{{endpoint}} -H "Content-Type: application/json" -d '${expectedBody}'`); }); - it('should handle GET requests', () => { + it('should handle GET requests', async () => { const getRequest = { ...testRequest, request: { @@ -148,7 +148,7 @@ describe('Snippet Generator - Simple Tests', () => { } }; - const result = generateSnippet({ + const result = await generateSnippet({ language: curlLanguage, item: getRequest, collection: testCollection, @@ -158,7 +158,7 @@ describe('Snippet Generator - Simple Tests', () => { expect(result).toBe('curl -X GET https://api.example.com/{{endpoint}}'); }); - it('should handle requests with different headers', () => { + it('should handle requests with different headers', async () => { const requestWithDifferentHeaders = { ...testRequest, request: { @@ -180,7 +180,7 @@ describe('Snippet Generator - Simple Tests', () => { } }; - const result = generateSnippet({ + const result = await generateSnippet({ language: curlLanguage, item: requestWithDifferentHeaders, collection: collectionWithDifferentVars, @@ -195,7 +195,7 @@ describe('Snippet Generator - Simple Tests', () => { expect(result).toBe(`curl -X POST https://api.example.com/{{endpoint}} -H "Content-Type: application/json" -d '${expectedBody}'`); }); - it('should handle complex nested JSON body', () => { + it('should handle complex nested JSON body', async () => { const complexBody = { user: { name: '{{userName}}', @@ -233,7 +233,7 @@ describe('Snippet Generator - Simple Tests', () => { } }; - const result = generateSnippet({ + const result = await generateSnippet({ language: curlLanguage, item: requestWithComplexBody, collection: collectionWithComplexVars, @@ -257,7 +257,7 @@ describe('Snippet Generator - Simple Tests', () => { expect(result).toBe(`curl -X POST https://api.example.com/{{endpoint}} -H "Content-Type: application/json" -d '${expectedComplexBody}'`); }); - it('should handle errors gracefully', () => { + it('should handle errors gracefully', async () => { // Set up the error mock after beforeEach has run const originalHTTPSnippet = require('httpsnippet').HTTPSnippet; require('httpsnippet').HTTPSnippet = jest.fn(() => { @@ -267,7 +267,7 @@ describe('Snippet Generator - Simple Tests', () => { const originalConsoleError = console.error; console.error = jest.fn(); - const result = generateSnippet({ + const result = await generateSnippet({ language: curlLanguage, item: testRequest, collection: testCollection, @@ -280,7 +280,7 @@ describe('Snippet Generator - Simple Tests', () => { console.error = originalConsoleError; }); - it('should work with JavaScript language', () => { + it('should work with JavaScript language', async () => { const javascriptLanguage = { target: 'javascript', client: 'fetch' }; const expectedJavaScriptCode = `fetch("https://api.example.com/data", { @@ -294,7 +294,7 @@ describe('Snippet Generator - Simple Tests', () => { convert: jest.fn(() => expectedJavaScriptCode) })); - const result = generateSnippet({ + const result = await generateSnippet({ language: javascriptLanguage, item: testRequest, collection: testCollection, @@ -307,7 +307,7 @@ describe('Snippet Generator - Simple Tests', () => { require('httpsnippet').HTTPSnippet = originalHTTPSnippet; }); - it('should interpolate simple headers and body variables', () => { + it('should interpolate simple headers and body variables', async () => { const simpleTestRequest = { uid: 'test-123', name: 'simple test', @@ -347,7 +347,7 @@ describe('Snippet Generator - Simple Tests', () => { processEnvVariables: {} }; - const result = generateSnippet({ + const result = await generateSnippet({ language: curlLanguage, item: simpleTestRequest, collection: simpleTestCollection, @@ -363,7 +363,7 @@ describe('Snippet Generator - Simple Tests', () => { expect(result).toBe(`curl -X POST https://api.test.com/{{endpoint}} -H "Content-Type: application/json" -d '${expectedInterpolatedBody}'`); }); - it('should NOT interpolate when shouldInterpolate is false', () => { + it('should NOT interpolate when shouldInterpolate is false', async () => { const simpleTestRequest = { uid: 'test-123', name: 'simple test', @@ -402,7 +402,7 @@ describe('Snippet Generator - Simple Tests', () => { processEnvVariables: {} }; - const result = generateSnippet({ + const result = await generateSnippet({ language: curlLanguage, item: simpleTestRequest, collection: simpleTestCollection, @@ -412,7 +412,7 @@ describe('Snippet Generator - Simple Tests', () => { expect(result).toBe('curl -X POST https://api.test.com/{{endpoint}} -H "Content-Type: application/json" -d \'{"name": "{{userName}}", "email": "{{userEmail}}", "age": {{userAge}}}\''); }); - it('should interpolate auth credentials correctly', () => { + it('should interpolate auth credentials correctly', async () => { // Auth inheritance is resolved upstream in index.js before calling generateSnippet // So the item already has the resolved auth (not 'inherit' mode) const item = { @@ -443,7 +443,7 @@ describe('Snippet Generator - Simple Tests', () => { const { HTTPSnippet: mockedHTTPSnippet } = require('httpsnippet'); const language = { target: 'shell', client: 'curl' }; - generateSnippet({ + await generateSnippet({ language, item, collection, @@ -464,7 +464,7 @@ describe('Snippet Generator - Simple Tests', () => { // Snippet should include inherited headers describe('generateSnippet – header inclusion in output', () => { - it('should include collection and folder headers in generated snippet', () => { + it('should include collection and folder headers in generated snippet', async () => { const language = { target: 'shell', client: 'curl' }; const collection = { @@ -510,7 +510,7 @@ describe('generateSnippet – header inclusion in output', () => { convert: jest.fn(() => `HEADERS:${harRequest.headers.map((h) => h.name).join(',')}`) })); - const result = generateSnippet({ language, item, collection, shouldInterpolate: false }); + const result = await generateSnippet({ language, item, collection, shouldInterpolate: false }); // Restore original mock require('httpsnippet').HTTPSnippet = originalHTTPSnippet; @@ -525,7 +525,7 @@ describe('generateSnippet with edge-case bodies', () => { const language = { target: 'shell', client: 'curl' }; const baseCollection = { root: { request: { auth: { mode: 'none' }, headers: [] } } }; - it('should generate snippet for empty formUrlEncoded body when interpolation is disabled', () => { + it('should generate snippet for empty formUrlEncoded body when interpolation is disabled', async () => { const item = { uid: 'req1', request: { @@ -537,11 +537,11 @@ describe('generateSnippet with edge-case bodies', () => { } }; - const result = generateSnippet({ language, item, collection: baseCollection, shouldInterpolate: false }); + const result = await generateSnippet({ language, item, collection: baseCollection, shouldInterpolate: false }); expect(result).toMatch(/^curl -X POST/); }); - it('should generate snippet for empty multipartForm body when interpolation is disabled', () => { + it('should generate snippet for empty multipartForm body when interpolation is disabled', async () => { const item = { uid: 'req2', request: { @@ -553,11 +553,11 @@ describe('generateSnippet with edge-case bodies', () => { } }; - const result = generateSnippet({ language, item, collection: baseCollection, shouldInterpolate: false }); + const result = await generateSnippet({ language, item, collection: baseCollection, shouldInterpolate: false }); expect(result).toMatch(/^curl -X POST/); }); - it('should generate snippet for undefined formUrlEncoded array with interpolation enabled', () => { + it('should generate snippet for undefined formUrlEncoded array with interpolation enabled', async () => { const item = { uid: 'req3', request: { @@ -569,11 +569,11 @@ describe('generateSnippet with edge-case bodies', () => { } }; - const result = generateSnippet({ language, item, collection: baseCollection, shouldInterpolate: true }); + const result = await generateSnippet({ language, item, collection: baseCollection, shouldInterpolate: true }); expect(result).toMatch(/^curl -X POST/); }); - it('should generate snippet for empty multipartForm array with interpolation enabled', () => { + it('should generate snippet for empty multipartForm array with interpolation enabled', async () => { const item = { uid: 'req4', request: { @@ -585,7 +585,7 @@ describe('generateSnippet with edge-case bodies', () => { } }; - const result = generateSnippet({ language, item, collection: baseCollection, shouldInterpolate: true }); + const result = await generateSnippet({ language, item, collection: baseCollection, shouldInterpolate: true }); expect(result).toMatch(/^curl -X POST/); }); }); @@ -613,7 +613,7 @@ describe('generateSnippet with OAuth2 authentication', () => { })); }); - it('should include OAuth2 Bearer token in Authorization header when tokenPlacement is header', () => { + it('should include OAuth2 Bearer token in Authorization header when tokenPlacement is header', async () => { const item = { uid: 'oauth-req', request: { @@ -632,7 +632,7 @@ describe('generateSnippet with OAuth2 authentication', () => { } }; - generateSnippet({ language, item, collection: baseCollection, shouldInterpolate: false }); + await generateSnippet({ language, item, collection: baseCollection, shouldInterpolate: false }); const { HTTPSnippet: mockedHTTPSnippet } = require('httpsnippet'); const harCall = mockedHTTPSnippet.mock.calls[0][0]; @@ -646,7 +646,7 @@ describe('generateSnippet with OAuth2 authentication', () => { ); }); - it('should use custom tokenHeaderPrefix when provided', () => { + it('should use custom tokenHeaderPrefix when provided', async () => { const item = { uid: 'oauth-req-custom', request: { @@ -665,7 +665,7 @@ describe('generateSnippet with OAuth2 authentication', () => { } }; - generateSnippet({ language, item, collection: baseCollection, shouldInterpolate: false }); + await generateSnippet({ language, item, collection: baseCollection, shouldInterpolate: false }); const { HTTPSnippet: mockedHTTPSnippet } = require('httpsnippet'); const harCall = mockedHTTPSnippet.mock.calls[0][0]; @@ -679,7 +679,7 @@ describe('generateSnippet with OAuth2 authentication', () => { ); }); - it('should not include Authorization header when tokenPlacement is url', () => { + it('should not include Authorization header when tokenPlacement is url', async () => { const item = { uid: 'oauth-req-url', request: { @@ -698,7 +698,7 @@ describe('generateSnippet with OAuth2 authentication', () => { } }; - generateSnippet({ language, item, collection: baseCollection, shouldInterpolate: false }); + await generateSnippet({ language, item, collection: baseCollection, shouldInterpolate: false }); const { HTTPSnippet: mockedHTTPSnippet } = require('httpsnippet'); const harCall = mockedHTTPSnippet.mock.calls[0][0]; @@ -706,7 +706,7 @@ describe('generateSnippet with OAuth2 authentication', () => { expect(authHeader).toBeUndefined(); }); - it('should use placeholder when accessToken is not available', () => { + it('should use placeholder when accessToken is not available', async () => { const item = { uid: 'oauth-req-placeholder', request: { @@ -724,7 +724,7 @@ describe('generateSnippet with OAuth2 authentication', () => { } }; - generateSnippet({ language, item, collection: baseCollection, shouldInterpolate: false }); + await generateSnippet({ language, item, collection: baseCollection, shouldInterpolate: false }); const { HTTPSnippet: mockedHTTPSnippet } = require('httpsnippet'); const harCall = mockedHTTPSnippet.mock.calls[0][0]; @@ -738,7 +738,7 @@ describe('generateSnippet with OAuth2 authentication', () => { ); }); - it('should handle empty tokenHeaderPrefix', () => { + it('should handle empty tokenHeaderPrefix', async () => { const item = { uid: 'oauth-req-no-prefix', request: { @@ -757,7 +757,7 @@ describe('generateSnippet with OAuth2 authentication', () => { } }; - generateSnippet({ language, item, collection: baseCollection, shouldInterpolate: false }); + await generateSnippet({ language, item, collection: baseCollection, shouldInterpolate: false }); const { HTTPSnippet: mockedHTTPSnippet } = require('httpsnippet'); const harCall = mockedHTTPSnippet.mock.calls[0][0]; @@ -784,7 +784,7 @@ describe('generateSnippet – digest and NTLM auth curl export', () => { } }; - it('should add --digest flag and --user for digest auth', () => { + it('should add --digest flag and --user for digest auth', async () => { const item = { uid: 'digest-req', request: { @@ -802,11 +802,11 @@ describe('generateSnippet – digest and NTLM auth curl export', () => { } }; - const result = generateSnippet({ language, item, collection: baseCollection, shouldInterpolate: false }); + const result = await generateSnippet({ language, item, collection: baseCollection, shouldInterpolate: false }); expect(result).toMatch(/^curl --digest --user 'myuser:mypass'/); }); - it('should add --ntlm flag and --user for NTLM auth', () => { + it('should add --ntlm flag and --user for NTLM auth', async () => { const item = { uid: 'ntlm-req', request: { @@ -824,11 +824,11 @@ describe('generateSnippet – digest and NTLM auth curl export', () => { } }; - const result = generateSnippet({ language, item, collection: baseCollection, shouldInterpolate: false }); + const result = await generateSnippet({ language, item, collection: baseCollection, shouldInterpolate: false }); expect(result).toMatch(/^curl --ntlm --user 'myuser:mypass'/); }); - it('should handle digest auth with username only (no password)', () => { + it('should handle digest auth with username only (no password)', async () => { const item = { uid: 'digest-no-pass', request: { @@ -846,7 +846,7 @@ describe('generateSnippet – digest and NTLM auth curl export', () => { } }; - const result = generateSnippet({ language, item, collection: baseCollection, shouldInterpolate: false }); + const result = await generateSnippet({ language, item, collection: baseCollection, shouldInterpolate: false }); expect(result).toMatch(/^curl --digest --user 'myuser'/); }); }); @@ -903,29 +903,29 @@ describe('generateSnippet – encodeUrl setting', () => { })); }); - it('should preserve equals signs in query values when encodeUrl is false', () => { + it('should preserve equals signs in query values when encodeUrl is false', async () => { const rawUrl = 'https://example.com/api?token=abc123==&type=test'; const item = makeItem(rawUrl, { encodeUrl: false }); - const result = generateSnippet({ language, item, collection: baseCollection, shouldInterpolate: false }); + const result = await generateSnippet({ language, item, collection: baseCollection, shouldInterpolate: false }); expect(result).toContain('token=abc123=='); // %3D = encoded '=' expect(result).not.toContain('%3D'); }); - it('should preserve email with plus alias and @ when encodeUrl is false', () => { + it('should preserve email with plus alias and @ when encodeUrl is false', async () => { const rawUrl = 'https://example.com/invite?email=test+alias@example.com'; const item = makeItem(rawUrl, { encodeUrl: false }); - const result = generateSnippet({ language, item, collection: baseCollection, shouldInterpolate: false }); + const result = await generateSnippet({ language, item, collection: baseCollection, shouldInterpolate: false }); expect(result).toContain('email=test+alias@example.com'); }); - it('should preserve redirect URL with colons and slashes when encodeUrl is false', () => { + it('should preserve redirect URL with colons and slashes when encodeUrl is false', async () => { const rawUrl = 'https://example.com/auth?redirect=https://other.com/callback&scope=read'; const item = makeItem(rawUrl, { encodeUrl: false }); - const result = generateSnippet({ language, item, collection: baseCollection, shouldInterpolate: false }); + const result = await generateSnippet({ language, item, collection: baseCollection, shouldInterpolate: false }); expect(result).toContain('redirect=https://other.com/callback'); // %3A = encoded ':' expect(result).not.toContain('%3A'); @@ -933,68 +933,68 @@ describe('generateSnippet – encodeUrl setting', () => { expect(result).not.toContain('%2F'); }); - it('should preserve comma-separated values when encodeUrl is false', () => { + it('should preserve comma-separated values when encodeUrl is false', async () => { const rawUrl = 'https://example.com/filter?tags=a,b,c&time=10:30'; const item = makeItem(rawUrl, { encodeUrl: false }); - const result = generateSnippet({ language, item, collection: baseCollection, shouldInterpolate: false }); + const result = await generateSnippet({ language, item, collection: baseCollection, shouldInterpolate: false }); expect(result).toContain('tags=a,b,c'); expect(result).toContain('time=10:30'); }); - it('should encode URL when encodeUrl is true', () => { + it('should encode URL when encodeUrl is true', async () => { const rawUrl = 'https://example.com/api?token=abc123==&type=test'; const item = makeItem(rawUrl, { encodeUrl: true }); - const result = generateSnippet({ language, item, collection: baseCollection, shouldInterpolate: false }); + const result = await generateSnippet({ language, item, collection: baseCollection, shouldInterpolate: false }); // %3D%3D = encoded '==' expect(result).toContain('%3D%3D'); }); - it('should preserve raw URL when settings are absent (encodeUrl defaults to false)', () => { + it('should preserve raw URL when settings are absent (encodeUrl defaults to false)', async () => { const rawUrl = 'https://example.com/auth?redirect=https://other.com/callback'; const item = makeItem(rawUrl); - const result = generateSnippet({ language, item, collection: baseCollection, shouldInterpolate: false }); + const result = await generateSnippet({ language, item, collection: baseCollection, shouldInterpolate: false }); expect(result).toContain('redirect=https://other.com/callback'); // %3A = encoded ':' expect(result).not.toContain('%3A'); }); - it('should be a no-op for URLs without query params and no encoding needed', () => { + it('should be a no-op for URLs without query params and no encoding needed', async () => { const rawUrl = 'https://example.com/api/users'; const item = makeItem(rawUrl, { encodeUrl: false }); - const result = generateSnippet({ language, item, collection: baseCollection, shouldInterpolate: false }); + const result = await generateSnippet({ language, item, collection: baseCollection, shouldInterpolate: false }); expect(result).toBe(`curl -X GET '${rawUrl}'`); }); - it('should preserve spaces in pathname when encodeUrl is false and rawUrl is provided', () => { + it('should preserve spaces in pathname when encodeUrl is false and rawUrl is provided', async () => { const encodedUrl = 'https://example.com/my%20path/hello%20world?token=abc123=='; const item = { ...makeItem(encodedUrl, { encodeUrl: false }), rawUrl: 'https://example.com/my path/hello world?token=abc123==' }; - const result = generateSnippet({ language, item, collection: baseCollection, shouldInterpolate: false }); + const result = await generateSnippet({ language, item, collection: baseCollection, shouldInterpolate: false }); expect(result).toContain('/my path/hello world?token=abc123=='); expect(result).not.toContain('%20'); expect(result).not.toContain('%3D'); }); - it('should preserve spaces in pathname without query params when encodeUrl is false', () => { + it('should preserve spaces in pathname without query params when encodeUrl is false', async () => { const encodedUrl = 'https://example.com/my%20path/hello%20world'; const item = { ...makeItem(encodedUrl, { encodeUrl: false }), rawUrl: 'https://example.com/my path/hello world' }; - const result = generateSnippet({ language, item, collection: baseCollection, shouldInterpolate: false }); + const result = await generateSnippet({ language, item, collection: baseCollection, shouldInterpolate: false }); expect(result).toContain('/my path/hello world'); expect(result).not.toContain('%20'); }); - it('should preserve spaces in path-only targets (e.g., python) when encodeUrl is false', () => { + it('should preserve spaces in path-only targets (e.g., python) when encodeUrl is false', async () => { const pythonLanguage = { target: 'python', client: 'python3' }; const encodedUrl = 'https://example.com/my%20path/hello%20world?q=test'; const item = { @@ -1002,54 +1002,54 @@ describe('generateSnippet – encodeUrl setting', () => { rawUrl: 'https://example.com/my path/hello world?q=test' }; - const result = generateSnippet({ language: pythonLanguage, item, collection: baseCollection, shouldInterpolate: false }); + const result = await generateSnippet({ language: pythonLanguage, item, collection: baseCollection, shouldInterpolate: false }); expect(result).toContain('/my path/hello world?q=test'); expect(result).not.toContain('%20'); }); - it('should preserve spaces in query values when encodeUrl is false and rawUrl is provided', () => { + it('should preserve spaces in query values when encodeUrl is false and rawUrl is provided', async () => { const encodedUrl = 'https://example.com/api?token=abc%20123==&type=test'; const item = { ...makeItem(encodedUrl, { encodeUrl: false }), rawUrl: 'https://example.com/api?token=abc 123==&type=test' }; - const result = generateSnippet({ language, item, collection: baseCollection, shouldInterpolate: false }); + const result = await generateSnippet({ language, item, collection: baseCollection, shouldInterpolate: false }); expect(result).toContain('token=abc 123=='); expect(result).not.toContain('%20'); expect(result).not.toContain('%3D'); }); - it('should still work when rawUrl is not provided (backward compatibility)', () => { + it('should still work when rawUrl is not provided (backward compatibility)', async () => { const rawUrl = 'https://example.com/api?token=abc123==&type=test'; const item = makeItem(rawUrl, { encodeUrl: false }); - const result = generateSnippet({ language, item, collection: baseCollection, shouldInterpolate: false }); + const result = await generateSnippet({ language, item, collection: baseCollection, shouldInterpolate: false }); expect(result).toContain('token=abc123=='); expect(result).not.toContain('%3D'); }); - it('should keep spaces as %20 for http target when encodeUrl is false (HTTP spec compliance)', () => { + it('should keep spaces as %20 for http target when encodeUrl is false (HTTP spec compliance)', async () => { const httpLanguage = { target: 'http', client: 'http1.1' }; const encodedUrl = 'https://example.com/api?token=abc%20123==&type=test'; const item = { ...makeItem(encodedUrl, { encodeUrl: false }), rawUrl: 'https://example.com/api?token=abc 123==&type=test' }; - const result = generateSnippet({ language: httpLanguage, item, collection: baseCollection, shouldInterpolate: false }); + const result = await generateSnippet({ language: httpLanguage, item, collection: baseCollection, shouldInterpolate: false }); // Spaces must remain encoded for valid HTTP request line expect(result).toContain('%20'); // But other chars like = should still be decoded expect(result).not.toContain('%3D'); }); - it('should preserve user-typed %20 when encodeUrl is false (not decode to space)', () => { + it('should preserve user-typed %20 when encodeUrl is false (not decode to space)', async () => { const preEncodedUrl = 'https://example.com/api?token=abc%20123%3D%3D&type=test'; const item = { ...makeItem(preEncodedUrl, { encodeUrl: false }), rawUrl: preEncodedUrl // rawUrl has %20 intact (no decodeURI applied) }; - const result = generateSnippet({ language, item, collection: baseCollection, shouldInterpolate: false }); + const result = await generateSnippet({ language, item, collection: baseCollection, shouldInterpolate: false }); // %20 should be preserved, not decoded to a literal space expect(result).toContain('%20'); // %3D should also be preserved @@ -1059,26 +1059,26 @@ describe('generateSnippet – encodeUrl setting', () => { expect(result).not.toContain('%253D'); }); - it('should double-encode pre-encoded %20 when encodeUrl is true', () => { + it('should double-encode pre-encoded %20 when encodeUrl is true', async () => { const preEncodedUrl = 'https://example.com/api?token=abc%20123%3D%3D&type=test'; const item = { ...makeItem(preEncodedUrl, { encodeUrl: true }), rawUrl: preEncodedUrl }; - const result = generateSnippet({ language, item, collection: baseCollection, shouldInterpolate: false }); + const result = await generateSnippet({ language, item, collection: baseCollection, shouldInterpolate: false }); // %20 → %2520 because encodeURIComponent encodes the literal '%' in the already-encoded value expect(result).toContain('%2520'); // %3D → %253D for the same reason expect(result).toContain('%253D'); }); - it('should preserve OData-style paths with parenthesized params when encodeUrl is false', () => { + it('should preserve OData-style paths with parenthesized params when encodeUrl is false', async () => { const rawUrl = 'https://example.com/odata/Products(123)/Categories(456)?$expand=Items&$filter=Price gt 10'; const item = { ...makeItem(rawUrl, { encodeUrl: false }), rawUrl }; - const result = generateSnippet({ language, item, collection: baseCollection, shouldInterpolate: false }); + const result = await generateSnippet({ language, item, collection: baseCollection, shouldInterpolate: false }); expect(result).toContain('Products(123)/Categories(456)'); expect(result).toContain('$expand=Items'); expect(result).toContain('$filter=Price gt 10'); @@ -1086,45 +1086,45 @@ describe('generateSnippet – encodeUrl setting', () => { expect(result).not.toContain('%24'); }); - it('should use draft settings when draft exists', () => { + it('should use draft settings when draft exists', async () => { const rawUrl = 'https://example.com/api?token=abc123==&type=test'; const item = makeItem(rawUrl, { encodeUrl: true }, { settings: { encodeUrl: false } }); - const result = generateSnippet({ language, item, collection: baseCollection, shouldInterpolate: false }); + const result = await generateSnippet({ language, item, collection: baseCollection, shouldInterpolate: false }); expect(result).toContain('token=abc123=='); // %3D%3D = encoded '==' expect(result).not.toContain('%3D%3D'); }); - it('should replace encoded path for targets that use only path+query (e.g., python http.client)', () => { + it('should replace encoded path for targets that use only path+query (e.g., python http.client)', async () => { const pythonLanguage = { target: 'python', client: 'python3' }; const rawUrl = 'https://example.com/api?token=abc123==&type=test'; const item = makeItem(rawUrl, { encodeUrl: false }); - const result = generateSnippet({ language: pythonLanguage, item, collection: baseCollection, shouldInterpolate: false }); + const result = await generateSnippet({ language: pythonLanguage, item, collection: baseCollection, shouldInterpolate: false }); expect(result).toContain('/api?token=abc123==&type=test'); // %3D = encoded '=' expect(result).not.toContain('%3D'); }); - it('should preserve URL fragment (#) in snippet when encodeUrl is false', () => { + it('should preserve URL fragment (#) in snippet when encodeUrl is false', async () => { // OFF preserves the user's URL byte-for-byte, including the literal `#`. // This is the only mode that retains fragment semantics — toggle OFF when // you want `#section` to survive as a fragment. const rawUrl = 'https://example.com/api?token=abc==#section'; const item = makeItem(rawUrl, { encodeUrl: false }); - const result = generateSnippet({ language, item, collection: baseCollection, shouldInterpolate: false }); + const result = await generateSnippet({ language, item, collection: baseCollection, shouldInterpolate: false }); expect(result).toContain('#section'); expect(result).toContain('token=abc=='); expect(result).not.toContain('%3D'); }); - it('should encode URL fragment (#) as %23 data when encodeUrl is true', () => { + it('should encode URL fragment (#) as %23 data when encodeUrl is true', async () => { const rawUrl = 'https://example.com/api?token=abc==#section'; const item = makeItem(rawUrl, { encodeUrl: true }); - const result = generateSnippet({ language, item, collection: baseCollection, shouldInterpolate: false }); + const result = await generateSnippet({ language, item, collection: baseCollection, shouldInterpolate: false }); // Option C: `#` is treated as data, encoded to %23. No literal `#` should // remain — fragment semantics are lost in ON mode by design (predictable // "URL Encoding ON encodes everything special" behavior). @@ -1133,7 +1133,7 @@ describe('generateSnippet – encodeUrl setting', () => { expect(result).toContain('%3D%3D'); }); - it('should single-encode spaces and special chars when encodeUrl is true and rawUrl is provided', () => { + it('should single-encode spaces and special chars when encodeUrl is true and rawUrl is provided', async () => { // The raw URL (before new URL() encoding) contains literal spaces and @. // encodeUrl() should encode them once: space → %20, @ → %40. // Previously this double-encoded because request.url was already encoded by new URL(). @@ -1143,7 +1143,7 @@ describe('generateSnippet – encodeUrl setting', () => { rawUrl: 'https://example.com/api?name=abc os&email=user@test.com' }; - const result = generateSnippet({ language, item, collection: baseCollection, shouldInterpolate: false }); + const result = await generateSnippet({ language, item, collection: baseCollection, shouldInterpolate: false }); // space → %20 (single encoding, not %2520) expect(result).toContain('%20'); expect(result).not.toContain('%2520'); @@ -1152,21 +1152,21 @@ describe('generateSnippet – encodeUrl setting', () => { expect(result).not.toContain('%2540'); }); - it('should encode special chars in query values when encodeUrl is true (e.g., redirect URLs)', () => { + it('should encode special chars in query values when encodeUrl is true (e.g., redirect URLs)', async () => { const rawUrl = 'https://example.com/auth?redirect=https://other.com/callback&scope=read'; const item = makeItem(rawUrl, { encodeUrl: true }); - const result = generateSnippet({ language, item, collection: baseCollection, shouldInterpolate: false }); + const result = await generateSnippet({ language, item, collection: baseCollection, shouldInterpolate: false }); // : → %3A, / → %2F when encodeURIComponent is applied to query values expect(result).toContain('%3A'); expect(result).toContain('%2F'); }); - it('should encode fragment as data and apply encodeUrl when both are present and encodeUrl is true', () => { + it('should encode fragment as data and apply encodeUrl when both are present and encodeUrl is true', async () => { const rawUrl = 'https://example.com/api?redirect=https://other.com/cb#section'; const item = makeItem(rawUrl, { encodeUrl: true }); - const result = generateSnippet({ language, item, collection: baseCollection, shouldInterpolate: false }); + const result = await generateSnippet({ language, item, collection: baseCollection, shouldInterpolate: false }); // `#` encoded to %23 as part of the query value (Option C). expect(result).not.toContain('#section'); expect(result).toContain('%23section'); @@ -1174,35 +1174,35 @@ describe('generateSnippet – encodeUrl setting', () => { expect(result).toContain('%2F'); }); - it('should be a no-op for path-only URLs when encodeUrl is true (no query params to encode)', () => { + it('should be a no-op for path-only URLs when encodeUrl is true (no query params to encode)', async () => { const rawUrl = 'https://example.com/api/users'; const item = makeItem(rawUrl, { encodeUrl: true }); - const result = generateSnippet({ language, item, collection: baseCollection, shouldInterpolate: false }); + const result = await generateSnippet({ language, item, collection: baseCollection, shouldInterpolate: false }); expect(result).toBe(`curl -X GET '${rawUrl}'`); }); - it('should preserve raw URL with multiple query params in non-alphabetical order when encodeUrl is false', () => { + it('should preserve raw URL with multiple query params in non-alphabetical order when encodeUrl is false', async () => { const rawUrl = 'https://example.com/api?start=2026-02-01T00:00:00.000Z&a=b'; const item = makeItem(rawUrl, { encodeUrl: false }); - const result = generateSnippet({ language, item, collection: baseCollection, shouldInterpolate: false }); + const result = await generateSnippet({ language, item, collection: baseCollection, shouldInterpolate: false }); expect(result).toBe(`curl -X GET '${rawUrl}'`); }); - it('should encode URL with multiple query params in non-alphabetical order when encodeUrl is true', () => { + it('should encode URL with multiple query params in non-alphabetical order when encodeUrl is true', async () => { const rawUrl = 'https://example.com/api?start=2026-02-01T00:00:00.000Z&a=b'; const item = makeItem(rawUrl, { encodeUrl: true }); - const result = generateSnippet({ language, item, collection: baseCollection, shouldInterpolate: false }); + const result = await generateSnippet({ language, item, collection: baseCollection, shouldInterpolate: false }); expect(result).toBe('curl -X GET \'https://example.com/api?start=2026-02-01T00%3A00%3A00.000Z&a=b\''); }); - it('should preserve param order in raw URL when encodeUrl is false and params are reverse-alphabetical', () => { + it('should preserve param order in raw URL when encodeUrl is false and params are reverse-alphabetical', async () => { const rawUrl = 'https://example.com/api?z=last&a=first&m=middle'; const item = makeItem(rawUrl, { encodeUrl: false }); - const result = generateSnippet({ language, item, collection: baseCollection, shouldInterpolate: false }); + const result = await generateSnippet({ language, item, collection: baseCollection, shouldInterpolate: false }); expect(result).toBe(`curl -X GET '${rawUrl}'`); }); }); @@ -1229,32 +1229,32 @@ describe('generateSnippet – pre-encode URL before HAR (HTTPSnippet validator r ...(settings !== undefined && { settings }) }); - it('does not throw for path-param value with literal space (user-reported `aaa bbb`)', () => { + it('does not throw for path-param value with literal space (user-reported `aaa bbb`)', async () => { // Repro: URL `https://example.com/users/:id` with `id = aaa bbb`. // After interpolateUrlPathParams (raw mode) the URL has a literal space: // `https://example.com/users/aaa bbb`. HTTPSnippet's HAR validator // rejects it → "Error generating code snippet". Pre-encoding turns the // space into %20 so the validator accepts. const item = makeItem('https://example.com/users/aaa bbb', { encodeUrl: false }); - const result = generateSnippet({ language, item, collection: baseCollection, shouldInterpolate: false }); + const result = await generateSnippet({ language, item, collection: baseCollection, shouldInterpolate: false }); expect(result).not.toBe('Error generating code snippet'); }); - it('does not throw for literal [ and ] in URL path', () => { + it('does not throw for literal [ and ] in URL path', async () => { const item = makeItem('https://example.com/api/list[1]', { encodeUrl: false }); - const result = generateSnippet({ language, item, collection: baseCollection, shouldInterpolate: false }); + const result = await generateSnippet({ language, item, collection: baseCollection, shouldInterpolate: false }); expect(result).not.toBe('Error generating code snippet'); }); - it('does not throw for < and > in URL path', () => { + it('does not throw for < and > in URL path', async () => { const item = makeItem('https://example.com/api/', { encodeUrl: false }); - const result = generateSnippet({ language, item, collection: baseCollection, shouldInterpolate: false }); + const result = await generateSnippet({ language, item, collection: baseCollection, shouldInterpolate: false }); expect(result).not.toBe('Error generating code snippet'); }); - it('does not throw for raw unicode in URL path', () => { + it('does not throw for raw unicode in URL path', async () => { const item = makeItem('https://example.com/users/José', { encodeUrl: false }); - const result = generateSnippet({ language, item, collection: baseCollection, shouldInterpolate: false }); + const result = await generateSnippet({ language, item, collection: baseCollection, shouldInterpolate: false }); expect(result).not.toBe('Error generating code snippet'); }); }); diff --git a/packages/bruno-common/package.json b/packages/bruno-common/package.json index db5863f4894..7237e60fab9 100644 --- a/packages/bruno-common/package.json +++ b/packages/bruno-common/package.json @@ -37,7 +37,7 @@ "prepack": "npm run test && npm run build" }, "dependencies": { - "crypto-js": "4.2.0" + "uuid": "^10.0.0" }, "devDependencies": { "@babel/preset-env": "^7.26.9", @@ -49,6 +49,7 @@ "@rollup/plugin-terser": "^1.0.0", "@rollup/plugin-typescript": "^12.1.2", "@types/jest": "^29.5.14", + "@types/uuid": "^10.0.0", "babel-jest": "^29.7.0", "form-data": "4.0.4", "is-ip": "^5.0.1", diff --git a/packages/bruno-common/src/generate-code/har/edgegrid.spec.ts b/packages/bruno-common/src/generate-code/har/edgegrid.spec.ts index 998012f6b09..efd7f059ba1 100644 --- a/packages/bruno-common/src/generate-code/har/edgegrid.spec.ts +++ b/packages/bruno-common/src/generate-code/har/edgegrid.spec.ts @@ -2,8 +2,8 @@ import { signEdgeGridRequest } from './edgegrid'; /** * Akamai's OFFICIAL EdgeGrid vectors (github.com/akamai/AkamaiOPEN-edgegrid-node). Matching them - * byte-for-byte proves the crypto-js (browser) signer here produces the same signature as the - * Node runtime signer, so Generate Code snippets validate against the real gateway. + * byte-for-byte proves the Web Crypto signer here produces the same signature as the Node runtime + * signer, so Generate Code snippets validate against the real gateway. */ const CREDS = { clientToken: 'akab-client-token-xxx-xxxxxxxxxxxxxxxx', @@ -24,16 +24,16 @@ describe('signEdgeGridRequest (codegen) - Akamai official vectors', () => { { name: 'POST with empty body', request: { method: 'POST', url: `${HOST}/testapi/v1/t6`, bodyText: '' }, expected: '1gEDxeQGD5GovIkJJGcBaKnZ+VaPtrc4qBUHixjsPCQ=' } ]; - test.each(cases)('$name', ({ request, expected }) => { - expect(sig(signEdgeGridRequest(CREDS, request))).toBe(expected); + test.each(cases)('$name', async ({ request, expected }) => { + expect(sig(await signEdgeGridRequest(CREDS, request))).toBe(expected); }); - it('returns null when required credentials are missing (caller omits the header)', () => { - expect(signEdgeGridRequest({ ...CREDS, clientSecret: '' }, { method: 'GET', url: `${HOST}/` })).toBeNull(); + it('returns null when required credentials are missing (caller omits the header)', async () => { + expect(await signEdgeGridRequest({ ...CREDS, clientSecret: '' }, { method: 'GET', url: `${HOST}/` })).toBeNull(); }); - it('emits a placeholder signature when credentials are unresolved {{var}} (interpolation off)', () => { - const header = signEdgeGridRequest( + it('emits a placeholder signature when credentials are unresolved {{var}} (interpolation off)', async () => { + const header = await signEdgeGridRequest( { ...CREDS, clientToken: '{{client_token}}', clientSecret: '{{client_secret}}' }, { method: 'POST', url: `${HOST}/edgegrid/verify` } ); diff --git a/packages/bruno-common/src/generate-code/har/edgegrid.ts b/packages/bruno-common/src/generate-code/har/edgegrid.ts index 617a2a3a9c9..75d185e65bc 100644 --- a/packages/bruno-common/src/generate-code/har/edgegrid.ts +++ b/packages/bruno-common/src/generate-code/har/edgegrid.ts @@ -1,12 +1,18 @@ -import * as CryptoJS from 'crypto-js'; +import { + makeEdgeGridTimestamp, + makeEdgeGridNonce, + canonicalizeHeaders, + base64HmacSha256, + makeContentHash +} from '../../utils/edgegrid'; /** * Browser-safe EG1-HMAC-SHA256 signer for Generate Code snippets. * - * Ported from the runtime signer (packages/bruno-requests/src/auth/edgegrid-helper.js) so the - * generated `Authorization` header validates against the real Akamai gateway - the difference is - * this variant uses crypto-js (works in the browser) instead of Node's `crypto`, since codegen - * runs in the renderer. Kept byte-for-byte compatible with Akamai's reference implementation. + * Mirrors the runtime signer (packages/bruno-requests/src/auth/edgegrid-helper.js) so the + * generated `Authorization` header validates against the real Akamai gateway; both share the + * signing/crypto primitives in ../../utils/edgegrid. Web Crypto is async, so the signer returns a + * Promise. Kept byte-for-byte compatible with Akamai's reference implementation. */ const MAX_BODY_SIZE_DEFAULT = 131072; // 128 KB @@ -14,61 +20,15 @@ const MAX_BODY_SIZE_DEFAULT = 131072; // 128 KB const isStrPresent = (str?: string | null): boolean => !!str && String(str).trim() !== '' && String(str).trim() !== 'undefined'; -// base64(HMAC-SHA256(data, key)) - key is a UTF-8 string, matching the runtime signer. -const base64HmacSha256 = (data: string, key: string): string => - CryptoJS.HmacSHA256(data, key).toString(CryptoJS.enc.Base64); - -// base64(SHA256(data)) -const base64Sha256 = (data: string): string => CryptoJS.SHA256(data).toString(CryptoJS.enc.Base64); - -// UTC timestamp in EdgeGrid format: YYYYMMDDTHH:MM:SS+0000 -const makeEdgeGridTimestamp = (): string => { - const [datePart, timePart] = new Date().toISOString().split('T'); - return `${datePart.replace(/-/g, '')}T${timePart.replace(/\.\d+Z$/, '')}+0000`; -}; - -// UUID v4 for the nonce. A snippet nonce need not be cryptographically strong. -const makeNonce = (): string => - 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => { - const r = (Math.random() * 16) | 0; - return (c === 'x' ? r : (r & 0x3) | 0x8).toString(16); - }); - -// `name:value` per signed header (lowercased name, trimmed + whitespace-collapsed value), -// tab-joined. Only headers present on the request are emitted, preserving config order. -const canonicalizeHeaders = (headersToSign?: string, requestHeaders: Record = {}): string => { - if (!isStrPresent(headersToSign)) return ''; - const lookup: Record = {}; - Object.keys(requestHeaders || {}).forEach((name) => { - lookup[name.toLowerCase()] = requestHeaders[name]; - }); - return (headersToSign as string) - .split(',') - .map((name) => name.trim().toLowerCase()) - .filter((name) => name.length > 0) - .filter((name) => Object.prototype.hasOwnProperty.call(lookup, name)) - .map((name) => `${name}:${String(lookup[name]).trim().replace(/\s+/g, ' ')}`) - .join('\t'); -}; - -// Akamai hashes the body for POST only, over the bytes as sent, truncated to maxBodySize. -const makeContentHash = (method: string, bodyText: string | undefined, maxBodySize: number): string => { - if (!method || method.toUpperCase() !== 'POST' || !bodyText) return ''; - let body = bodyText; - if (body.length === 0) return ''; - if (body.length > maxBodySize) body = body.substring(0, maxBodySize); - return base64Sha256(body); -}; - -export interface EdgeGridSignConfig { - accessToken?: string | null; - clientToken?: string | null; - clientSecret?: string | null; +export interface AkamaiEdgeGridAuthValues { + accessToken?: string; + clientToken?: string; + clientSecret?: string; baseURL?: string | null; nonce?: string | null; timestamp?: string | null; headersToSign?: string | null; - maxBodySize?: number | string | null; + maxBodySize?: number | null; } export interface EdgeGridSignRequest { @@ -82,16 +42,16 @@ export interface EdgeGridSignRequest { * Compute the EG1-HMAC-SHA256 `Authorization` header value, or `null` when the * required credentials / a valid URL are missing (so the caller can omit the header). */ -export const signEdgeGridRequest = ( - config: EdgeGridSignConfig, +export const signEdgeGridRequest = async ( + config: AkamaiEdgeGridAuthValues, request: EdgeGridSignRequest -): string | null => { +): Promise => { const { accessToken, clientToken, clientSecret, baseURL, headersToSign } = config; if (!isStrPresent(accessToken) || !isStrPresent(clientToken) || !isStrPresent(clientSecret)) return null; if (!request?.url || !request?.method) return null; const maxBodySize = config.maxBodySize ? parseInt(String(config.maxBodySize), 10) : MAX_BODY_SIZE_DEFAULT; - const nonce = isStrPresent(config.nonce) ? (config.nonce as string) : makeNonce(); + const nonce = isStrPresent(config.nonce) ? (config.nonce as string) : makeEdgeGridNonce(); const timestamp = isStrPresent(config.timestamp) ? (config.timestamp as string) : makeEdgeGridTimestamp(); let parsedUrl: URL; @@ -114,7 +74,7 @@ export const signEdgeGridRequest = ( const authHeader = `EG1-HMAC-SHA256 client_token=${clientToken};access_token=${accessToken};timestamp=${timestamp};nonce=${nonce};`; // With variables unresolved (Generate Code, interpolation off) a real signature can't be - // produced - it would sign literal `{{var}}` tokens. Emit a placeholder the user replaces + // produced — it would sign literal `{{var}}` tokens. Emit a placeholder the user replaces // once the request is signed at send time. if (/\{\{.+?\}\}/.test(authHeader) || /\{\{.+?\}\}/.test(clientSecret as string)) { return `${authHeader}signature=`; @@ -126,12 +86,12 @@ export const signEdgeGridRequest = ( parsedUrl.host, parsedUrl.pathname + parsedUrl.search, canonicalizeHeaders(headersToSign as string, request.headers), - makeContentHash(request.method, request.bodyText, maxBodySize), + await makeContentHash(request.method, request.bodyText, maxBodySize), authHeader ].join('\t'); - const signingKey = base64HmacSha256(timestamp, clientSecret as string); - const signature = base64HmacSha256(dataToSign, signingKey); + const signingKey = await base64HmacSha256(timestamp, clientSecret as string); + const signature = await base64HmacSha256(dataToSign, signingKey); return `${authHeader}signature=${signature}`; }; diff --git a/packages/bruno-common/src/generate-code/har/index.spec.ts b/packages/bruno-common/src/generate-code/har/index.spec.ts index da12cdc701c..56a182bebf5 100644 --- a/packages/bruno-common/src/generate-code/har/index.spec.ts +++ b/packages/bruno-common/src/generate-code/har/index.spec.ts @@ -11,8 +11,8 @@ const baseRequest = (overrides: any = {}) => ({ }); describe('buildHar — basic HAR shape', () => { - it('returns a HAR-shaped object for a minimal GET', () => { - const { har } = buildHar({ request: baseRequest(), shouldInterpolate: false }); + it('returns a HAR-shaped object for a minimal GET', async () => { + const { har } = await buildHar({ request: baseRequest(), shouldInterpolate: false }); expect(har).toEqual( expect.objectContaining({ method: 'GET', @@ -28,22 +28,22 @@ describe('buildHar — basic HAR shape', () => { expect(Array.isArray(har.headers)).toBe(true); }); - it('throws "invalid request url" for inputs that are not URLs', () => { - expect(() => buildHar({ request: baseRequest({ url: '' }), shouldInterpolate: false })).toThrow('invalid request url'); - expect(() => buildHar({ request: baseRequest({ url: 'not a url' }), shouldInterpolate: false })).toThrow('invalid request url'); - expect(() => buildHar({ request: baseRequest({ url: 'http://' }), shouldInterpolate: false })).toThrow('invalid request url'); + it('throws "invalid request url" for inputs that are not URLs', async () => { + await expect(buildHar({ request: baseRequest({ url: '' }), shouldInterpolate: false })).rejects.toThrow('invalid request url'); + await expect(buildHar({ request: baseRequest({ url: 'not a url' }), shouldInterpolate: false })).rejects.toThrow('invalid request url'); + await expect(buildHar({ request: baseRequest({ url: 'http://' }), shouldInterpolate: false })).rejects.toThrow('invalid request url'); }); - it('accepts URLs with %XX sequences, brackets, OData parens (encoding handled internally)', () => { - expect(() => buildHar({ request: baseRequest({ url: 'https://example.com/list%5B1%5D' }), shouldInterpolate: false })).not.toThrow(); - expect(() => buildHar({ request: baseRequest({ url: 'https://example.com/odata/Products(123)/Categories(456)' }), shouldInterpolate: false })).not.toThrow(); - expect(() => buildHar({ request: baseRequest({ url: 'https://example.com/path%20with%20spaces' }), shouldInterpolate: false })).not.toThrow(); + it('accepts URLs with %XX sequences, brackets, OData parens (encoding handled internally)', async () => { + await expect(buildHar({ request: baseRequest({ url: 'https://example.com/list%5B1%5D' }), shouldInterpolate: false })).resolves.toBeDefined(); + await expect(buildHar({ request: baseRequest({ url: 'https://example.com/odata/Products(123)/Categories(456)' }), shouldInterpolate: false })).resolves.toBeDefined(); + await expect(buildHar({ request: baseRequest({ url: 'https://example.com/path%20with%20spaces' }), shouldInterpolate: false })).resolves.toBeDefined(); }); }); describe('buildHar — encodeUrl toggle (PR #5507 content-blind contract)', () => { - it('OFF: rawUrl matches user-typed URL (path-param substitution happens upstream for Generate Code)', () => { - const { rawUrl } = buildHar({ + it('OFF: rawUrl matches user-typed URL (path-param substitution happens upstream for Generate Code)', async () => { + const { rawUrl } = await buildHar({ request: baseRequest({ url: 'https://example.com/api?name=John Doe', params: [{ name: 'name', value: 'John Doe', type: 'query', enabled: true }], @@ -54,8 +54,8 @@ describe('buildHar — encodeUrl toggle (PR #5507 content-blind contract)', () = expect(rawUrl).toBe('https://example.com/api?name=John Doe'); }); - it('ON: encodedUrl applies encodeUrl() (path encoded, query encoded)', () => { - const { encodedUrl } = buildHar({ + it('ON: encodedUrl applies encodeUrl() (path encoded, query encoded)', async () => { + const { encodedUrl } = await buildHar({ request: baseRequest({ url: 'https://example.com/api?name=John Doe', params: [{ name: 'name', value: 'John Doe', type: 'query', enabled: true }], @@ -66,8 +66,8 @@ describe('buildHar — encodeUrl toggle (PR #5507 content-blind contract)', () = expect(encodedUrl).toBe('https://example.com/api?name=John%20Doe'); }); - it('ON: pre-encoded inputs INTENTIONALLY double-encode (PR #5507)', () => { - const { encodedUrl } = buildHar({ + it('ON: pre-encoded inputs INTENTIONALLY double-encode (PR #5507)', async () => { + const { encodedUrl } = await buildHar({ request: baseRequest({ url: 'https://example.com/api?name=John%20Doe', params: [{ name: 'name', value: 'John%20Doe', type: 'query', enabled: true }], @@ -79,11 +79,11 @@ describe('buildHar — encodeUrl toggle (PR #5507 content-blind contract)', () = expect(encodedUrl).toContain('John%2520Doe'); }); - it('ON: # in URL is encoded as %23 (Option C — # is data, not a fragment delimiter)', () => { + it('ON: # in URL is encoded as %23 (Option C — # is data, not a fragment delimiter)', async () => { // encodeUrl treats `#` as a regular byte and encodes it via // encodeURIComponent in the query-value pipeline. To keep `#section` as a // literal fragment, toggle OFF (OFF preserves the URL byte-for-byte). - const { encodedUrl } = buildHar({ + const { encodedUrl } = await buildHar({ request: baseRequest({ url: 'https://example.com/api?tag=test#section', params: [{ name: 'tag', value: 'test#section', type: 'query', enabled: true }], @@ -96,8 +96,8 @@ describe('buildHar — encodeUrl toggle (PR #5507 content-blind contract)', () = }); describe('buildHar — auth → headers translation', () => { - it('basic auth → Authorization: Basic ', () => { - const { har } = buildHar({ + it('basic auth → Authorization: Basic ', async () => { + const { har } = await buildHar({ request: baseRequest({ auth: { mode: 'basic', basic: { username: 'alice', password: 'pw' } } }), shouldInterpolate: false }); @@ -106,16 +106,16 @@ describe('buildHar — auth → headers translation', () => { expect(auth?.value).toBe(`Basic ${Buffer.from('alice:pw').toString('base64')}`); }); - it('bearer auth → Authorization: Bearer ', () => { - const { har } = buildHar({ + it('bearer auth → Authorization: Bearer ', async () => { + const { har } = await buildHar({ request: baseRequest({ auth: { mode: 'bearer', bearer: { token: 'tk-123' } } }), shouldInterpolate: false }); expect(har.headers).toContainEqual({ name: 'Authorization', value: 'Bearer tk-123' }); }); - it('apikey in header → custom header name + value', () => { - const { har } = buildHar({ + it('apikey in header → custom header name + value', async () => { + const { har } = await buildHar({ request: baseRequest({ auth: { mode: 'apikey', apikey: { key: 'X-API-Key', value: 'secret', placement: 'header' } } }), @@ -124,8 +124,8 @@ describe('buildHar — auth → headers translation', () => { expect(har.headers).toContainEqual({ name: 'X-API-Key', value: 'secret' }); }); - it('apikey with placement=queryparams → goes into queryString, NOT headers', () => { - const { har } = buildHar({ + it('apikey with placement=queryparams → goes into queryString, NOT headers', async () => { + const { har } = await buildHar({ request: baseRequest({ auth: { mode: 'apikey', apikey: { key: 'api_key', value: 'secret', placement: 'queryparams' } } }), @@ -135,8 +135,8 @@ describe('buildHar — auth → headers translation', () => { expect(har.headers.find((h) => h.name === 'api_key')).toBeUndefined(); }); - it('oauth2 header placement with no stored credentials falls back to ', () => { - const { har } = buildHar({ + it('oauth2 header placement with no stored credentials falls back to ', async () => { + const { har } = await buildHar({ request: baseRequest({ auth: { mode: 'oauth2', oauth2: { tokenPlacement: 'header', accessTokenUrl: 'https://x/token', credentialsId: 'creds' } } }), @@ -145,8 +145,8 @@ describe('buildHar — auth → headers translation', () => { expect(har.headers).toContainEqual({ name: 'Authorization', value: 'Bearer ' }); }); - it('oauth2 header placement looks up actual access token from oauth2Credentials', () => { - const { har } = buildHar({ + it('oauth2 header placement looks up actual access token from oauth2Credentials', async () => { + const { har } = await buildHar({ request: baseRequest({ auth: { mode: 'oauth2', @@ -164,16 +164,16 @@ describe('buildHar — auth → headers translation', () => { it.each(['oauth1', 'digest', 'ntlm', 'awsv4', 'wsse', 'none', 'inherit'])( 'auth mode "%s" → no Authorization header (runtime-only or curl-flag-only)', - (mode) => { - const { har } = buildHar({ request: baseRequest({ auth: { mode } }), shouldInterpolate: false }); + async (mode) => { + const { har } = await buildHar({ request: baseRequest({ auth: { mode } }), shouldInterpolate: false }); expect(har.headers.find((h) => h.name === 'Authorization')).toBeUndefined(); } ); // ---- Phase B: oauth2 detail + apikey edge cases + inherit contract ----- - it('oauth2 with custom tokenHeaderPrefix=OAuth → "OAuth "', () => { - const { har } = buildHar({ + it('oauth2 with custom tokenHeaderPrefix=OAuth → "OAuth "', async () => { + const { har } = await buildHar({ request: baseRequest({ auth: { mode: 'oauth2', @@ -189,8 +189,8 @@ describe('buildHar — auth → headers translation', () => { expect(har.headers).toContainEqual({ name: 'Authorization', value: 'OAuth tk-real' }); }); - it('oauth2 with empty tokenHeaderPrefix="" → bare token, no leading space', () => { - const { har } = buildHar({ + it('oauth2 with empty tokenHeaderPrefix="" → bare token, no leading space', async () => { + const { har } = await buildHar({ request: baseRequest({ auth: { mode: 'oauth2', @@ -206,8 +206,8 @@ describe('buildHar — auth → headers translation', () => { expect(har.headers).toContainEqual({ name: 'Authorization', value: 'bare-tk' }); }); - it('oauth2 with tokenPlacement=url → no Authorization header (URL placement is the runtime/snippet caller\'s responsibility)', () => { - const { har } = buildHar({ + it('oauth2 with tokenPlacement=url → no Authorization header (URL placement is the runtime/snippet caller\'s responsibility)', async () => { + const { har } = await buildHar({ request: baseRequest({ auth: { mode: 'oauth2', @@ -219,8 +219,8 @@ describe('buildHar — auth → headers translation', () => { expect(har.headers.find((h) => h.name === 'Authorization')).toBeUndefined(); }); - it('oauth2 implicit grant uses authorizationUrl (not accessTokenUrl) for credential lookup', () => { - const { har } = buildHar({ + it('oauth2 implicit grant uses authorizationUrl (not accessTokenUrl) for credential lookup', async () => { + const { har } = await buildHar({ request: baseRequest({ auth: { mode: 'oauth2', @@ -241,8 +241,8 @@ describe('buildHar — auth → headers translation', () => { expect(har.headers).toContainEqual({ name: 'Authorization', value: 'Bearer implicit-tk' }); }); - it('oauth2 credentialsId defaults to "credentials" when not specified', () => { - const { har } = buildHar({ + it('oauth2 credentialsId defaults to "credentials" when not specified', async () => { + const { har } = await buildHar({ request: baseRequest({ auth: { mode: 'oauth2', @@ -258,8 +258,8 @@ describe('buildHar — auth → headers translation', () => { expect(har.headers).toContainEqual({ name: 'Authorization', value: 'Bearer default-id-tk' }); }); - it('oauth2 missing oauth2Credentials array → falls back to placeholder', () => { - const { har } = buildHar({ + it('oauth2 missing oauth2Credentials array → falls back to placeholder', async () => { + const { har } = await buildHar({ request: baseRequest({ auth: { mode: 'oauth2', @@ -271,8 +271,8 @@ describe('buildHar — auth → headers translation', () => { expect(har.headers).toContainEqual({ name: 'Authorization', value: 'Bearer ' }); }); - it('apikey with placement=queryparams AND empty key → not added to queryString', () => { - const { har } = buildHar({ + it('apikey with placement=queryparams AND empty key → not added to queryString', async () => { + const { har } = await buildHar({ request: baseRequest({ auth: { mode: 'apikey', apikey: { key: '', value: 'secret', placement: 'queryparams' } } }), @@ -281,8 +281,8 @@ describe('buildHar — auth → headers translation', () => { expect(har.queryString).toEqual([]); }); - it('apikey with placement=queryparams AND empty value → not added to queryString', () => { - const { har } = buildHar({ + it('apikey with placement=queryparams AND empty value → not added to queryString', async () => { + const { har } = await buildHar({ request: baseRequest({ auth: { mode: 'apikey', apikey: { key: 'api_key', value: '', placement: 'queryparams' } } }), @@ -291,8 +291,8 @@ describe('buildHar — auth → headers translation', () => { expect(har.queryString).toEqual([]); }); - it('apikey with placement=header AND empty key → no header added', () => { - const { har } = buildHar({ + it('apikey with placement=header AND empty key → no header added', async () => { + const { har } = await buildHar({ request: baseRequest({ auth: { mode: 'apikey', apikey: { key: '', value: 'secret', placement: 'header' } } }), @@ -301,8 +301,8 @@ describe('buildHar — auth → headers translation', () => { expect(har.headers).toEqual(expect.not.arrayContaining([expect.objectContaining({ name: '' })])); }); - it('basic auth with empty username/password → still emits Authorization with base64 of ":"', () => { - const { har } = buildHar({ + it('basic auth with empty username/password → still emits Authorization with base64 of ":"', async () => { + const { har } = await buildHar({ request: baseRequest({ auth: { mode: 'basic', basic: { username: '', password: '' } } }), shouldInterpolate: false }); @@ -310,8 +310,8 @@ describe('buildHar — auth → headers translation', () => { expect(auth?.value).toBe(`Basic ${Buffer.from(':').toString('base64')}`); }); - it('bearer with missing token → "Bearer " with empty string', () => { - const { har } = buildHar({ + it('bearer with missing token → "Bearer " with empty string', async () => { + const { har } = await buildHar({ request: baseRequest({ auth: { mode: 'bearer' } }), shouldInterpolate: false }); @@ -326,8 +326,8 @@ describe('buildHar — header ordering when request + auth produce same name', ( // is intentionally not opinionated about dedup since the layering ambiguity // (which copy wins?) is collection-tree-specific. - it('request.headers Authorization survives alongside auth-generated Authorization', () => { - const { har } = buildHar({ + it('request.headers Authorization survives alongside auth-generated Authorization', async () => { + const { har } = await buildHar({ request: baseRequest({ headers: [{ name: 'Authorization', value: 'Custom token', enabled: true }], auth: { mode: 'bearer', bearer: { token: 'tk-from-auth' } } @@ -342,8 +342,8 @@ describe('buildHar — header ordering when request + auth produce same name', ( }); describe('buildHar — headers finalization (default content-type, lowercase, enabled-only)', () => { - it('lowercases header names and filters disabled', () => { - const { har } = buildHar({ + it('lowercases header names and filters disabled', async () => { + const { har } = await buildHar({ request: baseRequest({ headers: [ { name: 'X-Custom', value: 'v1', enabled: true }, @@ -356,7 +356,7 @@ describe('buildHar — headers finalization (default content-type, lowercase, en expect(har.headers.find((h) => h.name === 'x-disabled')).toBeUndefined(); }); - it('appends default content-type for body mode if none is set', () => { + it('appends default content-type for body mode if none is set', async () => { const cases: Array<[string, string]> = [ ['json', 'application/json'], ['xml', 'application/xml'], @@ -365,13 +365,13 @@ describe('buildHar — headers finalization (default content-type, lowercase, en ['formUrlEncoded', 'application/x-www-form-urlencoded'] ]; for (const [mode, contentType] of cases) { - const { har } = buildHar({ request: baseRequest({ body: { mode } }), shouldInterpolate: false }); + const { har } = await buildHar({ request: baseRequest({ body: { mode } }), shouldInterpolate: false }); expect(har.headers).toContainEqual({ name: 'Content-Type', value: contentType }); } }); - it('does NOT override an explicit content-type header', () => { - const { har } = buildHar({ + it('does NOT override an explicit content-type header', async () => { + const { har } = await buildHar({ request: baseRequest({ body: { mode: 'json' }, headers: [{ name: 'Content-Type', value: 'application/vnd.api+json', enabled: true }] @@ -385,8 +385,8 @@ describe('buildHar — headers finalization (default content-type, lowercase, en }); describe('buildHar — query string assembly', () => { - it('includes only enabled query-type params', () => { - const { har } = buildHar({ + it('includes only enabled query-type params', async () => { + const { har } = await buildHar({ request: baseRequest({ params: [ { name: 'a', value: '1', type: 'query', enabled: true }, @@ -403,8 +403,8 @@ describe('buildHar — query string assembly', () => { ]); }); - it('preserves insertion order (no alphabetical sort)', () => { - const { har } = buildHar({ + it('preserves insertion order (no alphabetical sort)', async () => { + const { har } = await buildHar({ request: baseRequest({ params: [ { name: 'z', value: 'last', type: 'query', enabled: true }, @@ -419,8 +419,8 @@ describe('buildHar — query string assembly', () => { }); describe('buildHar — body / postData', () => { - it('formUrlEncoded → mimeType + text (URL-encoded form) + params array', () => { - const { har } = buildHar({ + it('formUrlEncoded → mimeType + text (URL-encoded form) + params array', async () => { + const { har } = await buildHar({ request: baseRequest({ body: { mode: 'formUrlEncoded', @@ -440,11 +440,11 @@ describe('buildHar — body / postData', () => { ]); }); - it('formUrlEncoded with duplicate names → preserves both entries in text and params', () => { + it('formUrlEncoded with duplicate names → preserves both entries in text and params', async () => { // Regression canary: serializing to a plain object would collapse duplicates // (`{tag: '1', tag: '2'}` → only the last survives). Real APIs use repeated // field names for array-shaped form values; both occurrences must round-trip. - const { har } = buildHar({ + const { har } = await buildHar({ request: baseRequest({ body: { mode: 'formUrlEncoded', @@ -465,8 +465,8 @@ describe('buildHar — body / postData', () => { ]); }); - it('json → mimeType + text (JSON string)', () => { - const { har } = buildHar({ + it('json → mimeType + text (JSON string)', async () => { + const { har } = await buildHar({ request: baseRequest({ body: { mode: 'json', json: '{"hello":"world"}' } }), shouldInterpolate: false }); @@ -474,8 +474,8 @@ describe('buildHar — body / postData', () => { expect(har.postData.text).toBe('{"hello":"world"}'); }); - it('multipartForm → params with optional fileName for type=file', () => { - const { har } = buildHar({ + it('multipartForm → params with optional fileName for type=file', async () => { + const { har } = await buildHar({ request: baseRequest({ body: { mode: 'multipartForm', @@ -497,8 +497,8 @@ describe('buildHar — body / postData', () => { // Each mode is tested for (a) correct mimeType, (b) correct postData shape, // (c) reasonable behavior on empty / missing / disabled inputs. - it('text → mimeType=text/plain, raw body in postData.text', () => { - const { har } = buildHar({ + it('text → mimeType=text/plain, raw body in postData.text', async () => { + const { har } = await buildHar({ request: baseRequest({ body: { mode: 'text', text: 'hello world' } }), shouldInterpolate: false }); @@ -506,9 +506,9 @@ describe('buildHar — body / postData', () => { expect(har.postData.text).toBe('hello world'); }); - it('xml → mimeType=application/xml, raw body in postData.text', () => { + it('xml → mimeType=application/xml, raw body in postData.text', async () => { const xmlBody = 'hi'; - const { har } = buildHar({ + const { har } = await buildHar({ request: baseRequest({ body: { mode: 'xml', xml: xmlBody } }), shouldInterpolate: false }); @@ -516,9 +516,9 @@ describe('buildHar — body / postData', () => { expect(har.postData.text).toBe(xmlBody); }); - it('sparql → mimeType=application/sparql-query, raw body in postData.text', () => { + it('sparql → mimeType=application/sparql-query, raw body in postData.text', async () => { const sparqlBody = 'SELECT ?s WHERE { ?s ?p ?o } LIMIT 10'; - const { har } = buildHar({ + const { har } = await buildHar({ request: baseRequest({ body: { mode: 'sparql', sparql: sparqlBody } }), shouldInterpolate: false }); @@ -526,9 +526,9 @@ describe('buildHar — body / postData', () => { expect(har.postData.text).toBe(sparqlBody); }); - it('graphql → mimeType=application/json, postData.text is JSON.stringify of body.graphql', () => { + it('graphql → mimeType=application/json, postData.text is JSON.stringify of body.graphql', async () => { const graphql = { query: 'query Q { me { id } }', variables: { foo: 'bar' } }; - const { har } = buildHar({ + const { har } = await buildHar({ request: baseRequest({ body: { mode: 'graphql', graphql } }), shouldInterpolate: false }); @@ -536,8 +536,8 @@ describe('buildHar — body / postData', () => { expect(har.postData.text).toBe(JSON.stringify(graphql)); }); - it('file → mimeType from selected file, text=filePath, params has fileName + contentType', () => { - const { har } = buildHar({ + it('file → mimeType from selected file, text=filePath, params has fileName + contentType', async () => { + const { har } = await buildHar({ request: baseRequest({ body: { mode: 'file', @@ -556,8 +556,8 @@ describe('buildHar — body / postData', () => { ]); }); - it('file with no `selected` flag → falls back to first entry', () => { - const { har } = buildHar({ + it('file with no `selected` flag → falls back to first entry', async () => { + const { har } = await buildHar({ request: baseRequest({ body: { mode: 'file', @@ -572,8 +572,8 @@ describe('buildHar — body / postData', () => { expect(har.postData.text).toBe('/tmp/first.txt'); }); - it('file with empty file[] → octet-stream fallback, empty text, empty params', () => { - const { har } = buildHar({ + it('file with empty file[] → octet-stream fallback, empty text, empty params', async () => { + const { har } = await buildHar({ request: baseRequest({ body: { mode: 'file', file: [] } }), shouldInterpolate: false }); @@ -582,8 +582,8 @@ describe('buildHar — body / postData', () => { expect(har.postData.params).toEqual([]); }); - it('formUrlEncoded with empty [] → empty text + empty params, no error', () => { - const { har } = buildHar({ + it('formUrlEncoded with empty [] → empty text + empty params, no error', async () => { + const { har } = await buildHar({ request: baseRequest({ body: { mode: 'formUrlEncoded', formUrlEncoded: [] } }), shouldInterpolate: false }); @@ -592,16 +592,16 @@ describe('buildHar — body / postData', () => { expect(har.postData.params).toEqual([]); }); - it('formUrlEncoded with missing array → treated as empty', () => { - const { har } = buildHar({ + it('formUrlEncoded with missing array → treated as empty', async () => { + const { har } = await buildHar({ request: baseRequest({ body: { mode: 'formUrlEncoded' } }), shouldInterpolate: false }); expect(har.postData.params).toEqual([]); }); - it('formUrlEncoded with disabled entries → filtered from text + params', () => { - const { har } = buildHar({ + it('formUrlEncoded with disabled entries → filtered from text + params', async () => { + const { har } = await buildHar({ request: baseRequest({ body: { mode: 'formUrlEncoded', @@ -621,8 +621,8 @@ describe('buildHar — body / postData', () => { ]); }); - it('multipartForm with empty [] → empty params, no error', () => { - const { har } = buildHar({ + it('multipartForm with empty [] → empty params, no error', async () => { + const { har } = await buildHar({ request: baseRequest({ body: { mode: 'multipartForm', multipartForm: [] } }), shouldInterpolate: false }); @@ -630,16 +630,16 @@ describe('buildHar — body / postData', () => { expect(har.postData.params).toEqual([]); }); - it('multipartForm with missing array → treated as empty', () => { - const { har } = buildHar({ + it('multipartForm with missing array → treated as empty', async () => { + const { har } = await buildHar({ request: baseRequest({ body: { mode: 'multipartForm' } }), shouldInterpolate: false }); expect(har.postData.params).toEqual([]); }); - it('multipartForm with disabled entries → filtered out', () => { - const { har } = buildHar({ + it('multipartForm with disabled entries → filtered out', async () => { + const { har } = await buildHar({ request: baseRequest({ body: { mode: 'multipartForm', @@ -654,8 +654,8 @@ describe('buildHar — body / postData', () => { expect(har.postData.params).toEqual([{ name: 'kept', value: 'a' }]); }); - it('multipartForm type=file → fileName populated only on file entries', () => { - const { har } = buildHar({ + it('multipartForm type=file → fileName populated only on file entries', async () => { + const { har } = await buildHar({ request: baseRequest({ body: { mode: 'multipartForm', @@ -674,14 +674,14 @@ describe('buildHar — body / postData', () => { }); describe('buildHar — interpolation', () => { - it('URL {{var}} tokens are hashed (not substituted) — caller owns URL interpolation', () => { + it('URL {{var}} tokens are hashed (not substituted) — caller owns URL interpolation', async () => { // URL interpolation is intentionally NOT done inside buildHar. The caller // (e.g. GenerateCodeItem in bruno-app, or the runtime adapter) is the only // place that knows whether the user wants templates resolved in the URL. // buildHar's job is to keep the URL parseable through encoding via // patternHasher hashing — the returned `unhash` lets the caller restore // the original `{{var}}` text at the end of their pipeline. - const { har, unhash } = buildHar({ + const { har, unhash } = await buildHar({ request: baseRequest({ url: 'https://{{host}}/api/{{path}}' }), variables: { host: 'example.com', path: 'users' }, shouldInterpolate: true @@ -694,8 +694,8 @@ describe('buildHar — interpolation', () => { expect(unhash(har.url)).toContain('{{path}}'); }); - it('shouldInterpolate=true substitutes {{var}} in headers and body (json)', () => { - const { har } = buildHar({ + it('shouldInterpolate=true substitutes {{var}} in headers and body (json)', async () => { + const { har } = await buildHar({ request: baseRequest({ headers: [{ name: 'X-Token', value: '{{token}}', enabled: true }], body: { mode: 'json', json: '{"user":"{{user}}"}' } @@ -707,8 +707,8 @@ describe('buildHar — interpolation', () => { expect(har.postData.text).toContain('"user": "alice"'); }); - it('shouldInterpolate=false hashes {{var}} so the URL survives parsing, exposes unhash()', () => { - const { har, unhash } = buildHar({ + it('shouldInterpolate=false hashes {{var}} so the URL survives parsing, exposes unhash()', async () => { + const { har, unhash } = await buildHar({ request: baseRequest({ url: 'https://{{host}}/api?key={{secret}}', params: [{ name: 'key', value: '{{secret}}', type: 'query', enabled: true }] }), shouldInterpolate: false }); @@ -722,35 +722,35 @@ describe('buildHar — interpolation', () => { }); describe('buildHar — regression: known issues map to single fixes', () => { - it('path with %20 (issue #6268) — no throw, URL passes the soft gate', () => { - expect(() => buildHar({ + it('path with %20 (issue #6268) — no throw, URL passes the soft gate', async () => { + await expect(buildHar({ request: baseRequest({ url: 'https://example.com/api/v1/roles/test%20-%20test' }), shouldInterpolate: false - })).not.toThrow(); + })).resolves.toBeDefined(); }); - it('square brackets in path (issue #7653) — no throw, URL passes the soft gate', () => { - expect(() => buildHar({ + it('square brackets in path (issue #7653) — no throw, URL passes the soft gate', async () => { + await expect(buildHar({ request: baseRequest({ url: 'https://example.com/list[1]' }), shouldInterpolate: false - })).not.toThrow(); + })).resolves.toBeDefined(); }); - it('JSON-shaped array values (issue #7913) — no throw, URL passes the soft gate', () => { - expect(() => buildHar({ + it('JSON-shaped array values (issue #7913) — no throw, URL passes the soft gate', async () => { + await expect(buildHar({ request: baseRequest({ url: 'https://example.com/api?testArray=[[1, 2, 3], ["a", "b"]]', params: [{ name: 'testArray', value: '[[1, 2, 3], ["a", "b"]]', type: 'query', enabled: true }] }), shouldInterpolate: false - })).not.toThrow(); + })).resolves.toBeDefined(); }); - it('path-param substitution (toggle ON) — built-in capability for runtime (issue #7356)', () => { + it('path-param substitution (toggle ON) — built-in capability for runtime (issue #7356)', async () => { // For Generate Code today, GenerateCodeItem pre-substitutes path params; buildHar // sees no `:id` to act on. But the capability is here for the future runtime // adoption (see Architectural pivot — Phase C in fixings/url-encoding-fix.md). - const { rawUrl, encodedUrl } = buildHar({ + const { rawUrl, encodedUrl } = await buildHar({ request: baseRequest({ url: 'https://example.com/users/:id/profile', pathParams: [{ name: 'id', value: 'aaa/bbb', type: 'path', enabled: true }], @@ -769,8 +769,8 @@ describe('buildHar — regression: known issues map to single fixes', () => { expect(encodedUrl).not.toContain('aaa%252Fbbb'); }); - it('path-param substitution (toggle OFF) — value passed raw', () => { - const { rawUrl, encodedUrl, har } = buildHar({ + it('path-param substitution (toggle OFF) — value passed raw', async () => { + const { rawUrl, encodedUrl, har } = await buildHar({ request: baseRequest({ url: 'https://example.com/users/:id/profile', pathParams: [{ name: 'id', value: 'aaa/bbb', type: 'path', enabled: true }], @@ -783,8 +783,8 @@ describe('buildHar — regression: known issues map to single fixes', () => { expect(har.url).toBe('https://example.com/users/aaa/bbb/profile'); }); - it('OData-style path param (Foo(:productId)) substitutes correctly', () => { - const { rawUrl } = buildHar({ + it('OData-style path param (Foo(:productId)) substitutes correctly', async () => { + const { rawUrl } = await buildHar({ request: baseRequest({ url: 'https://example.com/odata/Products(:productId)', pathParams: [{ name: 'productId', value: 'ABC123', type: 'path', enabled: true }], @@ -797,14 +797,14 @@ describe('buildHar — regression: known issues map to single fixes', () => { }); describe('buildHar — does not mutate caller inputs', () => { - it('caller\'s request object is not mutated by buildHar', () => { + it('caller\'s request object is not mutated by buildHar', async () => { const request = baseRequest({ url: 'https://example.com/api?q=1', params: [{ name: 'q', value: '1', type: 'query', enabled: true }], headers: [{ name: 'X-A', value: 'a', enabled: true }] }); const before = JSON.stringify(request); - buildHar({ request, shouldInterpolate: true, variables: { foo: 'bar' } }); + await buildHar({ request, shouldInterpolate: true, variables: { foo: 'bar' } }); expect(JSON.stringify(request)).toBe(before); }); }); @@ -845,11 +845,11 @@ describe('buildHar — path-param encoding matrix (toggle ON, issue #7356)', () { name: 'unreserved chars only (no encoding)', input: 'a-b_c.d~e', expectedSegment: 'a-b_c.d~e' } ]; - it.each(cases)('encodes path-param value $name: "$input" → "$expectedSegment"', ({ input, expectedSegment }) => { + it.each(cases)('encodes path-param value $name: "$input" → "$expectedSegment"', async ({ input, expectedSegment }) => { // har.url is what reaches the wire. For toggle ON the user expects the // path-param value to be percent-encoded once (matching encodeURIComponent // semantics). - const { har } = buildHar({ + const { har } = await buildHar({ request: baseRequest({ url: 'https://example.com/users/:id', pathParams: [{ name: 'id', value: input, type: 'path', enabled: true }], @@ -900,8 +900,8 @@ describe('buildHar — path-param substitution matrix (toggle OFF)', () => { { name: 'unreserved chars only', input: 'a-b_c.d~e' } ]; - it.each(cases)('passes path-param value through raw $name: "$input"', ({ input }) => { - const { rawUrl } = buildHar({ + it.each(cases)('passes path-param value through raw $name: "$input"', async ({ input }) => { + const { rawUrl } = await buildHar({ request: baseRequest({ url: 'https://example.com/users/:id', pathParams: [{ name: 'id', value: input, type: 'path', enabled: true }], @@ -1023,13 +1023,13 @@ describe('buildHar — query encoding matrix (mirror e2e fixtures)', () => { params: params.map((p) => ({ ...p, type: 'query', enabled: true })) }); - it('ON: encodedUrl runs encodeUrl() (encoded form)', () => { - const { encodedUrl } = buildHar({ request: requestWithEnabled(true), shouldInterpolate: false }); + it('ON: encodedUrl runs encodeUrl() (encoded form)', async () => { + const { encodedUrl } = await buildHar({ request: requestWithEnabled(true), shouldInterpolate: false }); expect(encodedUrl).toBe(encoded); }); - it('OFF: rawUrl preserves user-typed URL byte-for-byte', () => { - const { rawUrl } = buildHar({ request: requestWithEnabled(false), shouldInterpolate: false }); + it('OFF: rawUrl preserves user-typed URL byte-for-byte', async () => { + const { rawUrl } = await buildHar({ request: requestWithEnabled(false), shouldInterpolate: false }); expect(rawUrl).toBe(raw); }); }); @@ -1085,16 +1085,16 @@ describe('buildHar — path encoding matrix (mirror e2e fixtures)', () => { ]; describe.each(cases)('$name', ({ url, encoded, raw }) => { - it('ON: encodedUrl applies encodeUrl()', () => { - const { encodedUrl } = buildHar({ + it('ON: encodedUrl applies encodeUrl()', async () => { + const { encodedUrl } = await buildHar({ request: baseRequest({ url, settings: { encodeUrl: true } }), shouldInterpolate: false }); expect(encodedUrl).toBe(encoded); }); - it('OFF: rawUrl preserves user-typed URL byte-for-byte', () => { - const { rawUrl } = buildHar({ + it('OFF: rawUrl preserves user-typed URL byte-for-byte', async () => { + const { rawUrl } = await buildHar({ request: baseRequest({ url, settings: { encodeUrl: false } }), shouldInterpolate: false }); @@ -1110,8 +1110,8 @@ describe('buildHar — path encoding matrix (mirror e2e fixtures)', () => { // the rendered query string is `har.queryString`. describe('buildHar — bracket-key query regression (post_ids[], key[a][b])', () => { - it('post_ids[]=8647 — har.queryString length 1, har.url has no `?`', () => { - const { har } = buildHar({ + it('post_ids[]=8647 — har.queryString length 1, har.url has no `?`', async () => { + const { har } = await buildHar({ request: baseRequest({ url: 'https://meta.discourse.org/t/173975/posts.json?post_ids%5B%5D=8647', params: [{ name: 'post_ids[]', value: '8647', type: 'query', enabled: true }] @@ -1124,8 +1124,8 @@ describe('buildHar — bracket-key query regression (post_ids[], key[a][b])', () expect(har.queryString[0]).toEqual({ name: 'post_ids[]', value: '8647' }); }); - it('key[a][b]=nested — Rails-style nested brackets, no phantom duplicate', () => { - const { har } = buildHar({ + it('key[a][b]=nested — Rails-style nested brackets, no phantom duplicate', async () => { + const { har } = await buildHar({ request: baseRequest({ url: 'https://example.com/api?key[a][b]=nested', params: [{ name: 'key[a][b]', value: 'nested', type: 'query', enabled: true }] @@ -1137,8 +1137,8 @@ describe('buildHar — bracket-key query regression (post_ids[], key[a][b])', () expect(har.queryString[0]).toEqual({ name: 'key[a][b]', value: 'nested' }); }); - it('repeated array keys ids[]=1&ids[]=2&ids[]=3 → 3 distinct entries preserved in order', () => { - const { har } = buildHar({ + it('repeated array keys ids[]=1&ids[]=2&ids[]=3 → 3 distinct entries preserved in order', async () => { + const { har } = await buildHar({ request: baseRequest({ url: 'https://example.com/api?ids[]=1&ids[]=2&ids[]=3', params: [ @@ -1157,12 +1157,12 @@ describe('buildHar — bracket-key query regression (post_ids[], key[a][b])', () ]); }); - it('# in URL with a query: encodeUrl folds # into the query value as %23, then strip removes the whole query', () => { + it('# in URL with a query: encodeUrl folds # into the query value as %23, then strip removes the whole query', async () => { // Option C contract: encodeUrl no longer splits on `#`. The `#section` // chunk is parsed as part of the query value, encoded to `%23section`, // and then stripped along with the rest of `?q=1%23section` by // stripQueryStringFromUrl. Net result: har.url is just origin + path. - const { har } = buildHar({ + const { har } = await buildHar({ request: baseRequest({ url: 'https://example.com/api?q=1#section', params: [{ name: 'q', value: '1#section', type: 'query', enabled: true }] @@ -1172,19 +1172,19 @@ describe('buildHar — bracket-key query regression (post_ids[], key[a][b])', () expect(har.url).toBe('https://example.com/api'); }); - it('# in URL with NO query: encodeUrl encodes # to %23 in the path; strip is a no-op (no `?` to strip)', () => { + it('# in URL with NO query: encodeUrl encodes # to %23 in the path; strip is a no-op (no `?` to strip)', async () => { // Option C: `#` lands inside the path encoding pipeline because encodeUrl // no longer splits on `#`. encodePathSegments encodes it to `%23` via // encodeURIComponent. stripQueryStringFromUrl does nothing (no `?`). - const { har } = buildHar({ + const { har } = await buildHar({ request: baseRequest({ url: 'https://example.com/api#section' }), shouldInterpolate: false }); expect(har.url).toBe('https://example.com/api%23section'); }); - it('strips queries the same way regardless of bracket presence (multi-param sanity check)', () => { - const { har } = buildHar({ + it('strips queries the same way regardless of bracket presence (multi-param sanity check)', async () => { + const { har } = await buildHar({ request: baseRequest({ url: 'https://example.com/api?a=1&b=2&c=3', params: [ @@ -1207,9 +1207,9 @@ describe('buildHar — bracket-key query regression (post_ids[], key[a][b])', () // which URL each field carries. describe('buildHar — rawUrl vs encodedUrl invariants', () => { - it('OFF: rawUrl equals user-typed URL byte-for-byte', () => { + it('OFF: rawUrl equals user-typed URL byte-for-byte', async () => { const url = 'https://example.com/api?name=John Doe&path=/x/y'; - const { rawUrl } = buildHar({ + const { rawUrl } = await buildHar({ request: baseRequest({ url, params: [ @@ -1223,9 +1223,9 @@ describe('buildHar — rawUrl vs encodedUrl invariants', () => { expect(rawUrl).toBe(url); }); - it('ON: encodedUrl differs from rawUrl when input has non-unreserved chars', () => { + it('ON: encodedUrl differs from rawUrl when input has non-unreserved chars', async () => { const url = 'https://example.com/api?name=John Doe'; - const { rawUrl, encodedUrl } = buildHar({ + const { rawUrl, encodedUrl } = await buildHar({ request: baseRequest({ url, params: [{ name: 'name', value: 'John Doe', type: 'query', enabled: true }], @@ -1237,9 +1237,9 @@ describe('buildHar — rawUrl vs encodedUrl invariants', () => { expect(encodedUrl).toContain('John%20Doe'); }); - it('ON: encodedUrl equals rawUrl when input is already unreserved-only (encoding is a no-op)', () => { + it('ON: encodedUrl equals rawUrl when input is already unreserved-only (encoding is a no-op)', async () => { const url = 'https://example.com/api/foo/bar?a=1&b=2'; - const { rawUrl, encodedUrl } = buildHar({ + const { rawUrl, encodedUrl } = await buildHar({ request: baseRequest({ url, params: [ @@ -1253,8 +1253,8 @@ describe('buildHar — rawUrl vs encodedUrl invariants', () => { expect(encodedUrl).toBe(rawUrl); }); - it('encodedUrl applies Option C — # becomes %23', () => { - const { encodedUrl } = buildHar({ + it('encodedUrl applies Option C — # becomes %23', async () => { + const { encodedUrl } = await buildHar({ request: baseRequest({ url: 'https://example.com/api?q=aaa#bbb', params: [{ name: 'q', value: 'aaa#bbb', type: 'query', enabled: true }], @@ -1266,11 +1266,11 @@ describe('buildHar — rawUrl vs encodedUrl invariants', () => { expect(encodedUrl).not.toContain('#bbb'); }); - it('rawUrl includes literal {{var}} when shouldInterpolate=false (hashed internally, restored by unhash)', () => { + it('rawUrl includes literal {{var}} when shouldInterpolate=false (hashed internally, restored by unhash)', async () => { // While processing, `{{baseUrl}}` is replaced by a URL-safe hash so // parsing/encoding work. buildHar exposes `unhash` which, when applied // to the final string output, restores the literal `{{baseUrl}}` form. - const { rawUrl, unhash } = buildHar({ + const { rawUrl, unhash } = await buildHar({ request: baseRequest({ url: 'https://{{baseUrl}}/api?q=1', params: [{ name: 'q', value: '1', type: 'query', enabled: true }] @@ -1282,8 +1282,8 @@ describe('buildHar — rawUrl vs encodedUrl invariants', () => { expect(restored).toContain('{{baseUrl}}'); }); - it('rawUrl and encodedUrl both reflect path-param substitution from pathParams[]', () => { - const { rawUrl, encodedUrl } = buildHar({ + it('rawUrl and encodedUrl both reflect path-param substitution from pathParams[]', async () => { + const { rawUrl, encodedUrl } = await buildHar({ request: baseRequest({ url: 'https://example.com/users/:id', pathParams: [{ name: 'id', value: 'aaa bbb', type: 'path', enabled: true }], @@ -1301,8 +1301,8 @@ describe('buildHar — rawUrl vs encodedUrl invariants', () => { // ---- Phase D: interpolation edge cases + defensive inputs -------------- describe('buildHar — interpolation edge cases', () => { - it('{{?prompt}} variables in URL survive verbatim through unhash (not substituted at HAR-build time)', () => { - const { unhash, rawUrl } = buildHar({ + it('{{?prompt}} variables in URL survive verbatim through unhash (not substituted at HAR-build time)', async () => { + const { unhash, rawUrl } = await buildHar({ request: baseRequest({ url: 'https://example.com/api?q={{?Prompt Var}}' }), shouldInterpolate: false }); @@ -1311,8 +1311,8 @@ describe('buildHar — interpolation edge cases', () => { expect(unhash(rawUrl)).toContain('{{?Prompt Var}}'); }); - it('missing variable {{undefined_var}} passes through as literal placeholder when shouldInterpolate=true', () => { - const { har } = buildHar({ + it('missing variable {{undefined_var}} passes through as literal placeholder when shouldInterpolate=true', async () => { + const { har } = await buildHar({ request: baseRequest({ headers: [{ name: 'X-Foo', value: '{{undefined_var}}', enabled: true }] }), @@ -1323,8 +1323,8 @@ describe('buildHar — interpolation edge cases', () => { expect(header?.value).toContain('{{undefined_var}}'); }); - it('shouldInterpolate=true resolves headers with {{var}}', () => { - const { har } = buildHar({ + it('shouldInterpolate=true resolves headers with {{var}}', async () => { + const { har } = await buildHar({ request: baseRequest({ headers: [{ name: 'X-Token', value: '{{token}}', enabled: true }] }), @@ -1334,8 +1334,8 @@ describe('buildHar — interpolation edge cases', () => { expect(har.headers).toContainEqual({ name: 'X-Token', value: 'tk-resolved' }); }); - it('shouldInterpolate=true resolves body text with {{var}} (text mode)', () => { - const { har } = buildHar({ + it('shouldInterpolate=true resolves body text with {{var}} (text mode)', async () => { + const { har } = await buildHar({ request: baseRequest({ body: { mode: 'text', text: 'hello {{name}}' } }), variables: { name: 'world' }, shouldInterpolate: true @@ -1343,8 +1343,8 @@ describe('buildHar — interpolation edge cases', () => { expect(har.postData.text).toBe('hello world'); }); - it('shouldInterpolate=true resolves body xml with {{var}}', () => { - const { har } = buildHar({ + it('shouldInterpolate=true resolves body xml with {{var}}', async () => { + const { har } = await buildHar({ request: baseRequest({ body: { mode: 'xml', xml: '{{name}}' } }), variables: { name: 'alice' }, shouldInterpolate: true @@ -1352,8 +1352,8 @@ describe('buildHar — interpolation edge cases', () => { expect(har.postData.text).toBe('alice'); }); - it('shouldInterpolate=true resolves body sparql with {{var}}', () => { - const { har } = buildHar({ + it('shouldInterpolate=true resolves body sparql with {{var}}', async () => { + const { har } = await buildHar({ request: baseRequest({ body: { mode: 'sparql', sparql: 'SELECT ?{{var}} WHERE { ?s ?p ?o }' } }), variables: { var: 'x' }, shouldInterpolate: true @@ -1361,8 +1361,8 @@ describe('buildHar — interpolation edge cases', () => { expect(har.postData.text).toBe('SELECT ?x WHERE { ?s ?p ?o }'); }); - it('shouldInterpolate=true resolves formUrlEncoded values with {{var}}', () => { - const { har } = buildHar({ + it('shouldInterpolate=true resolves formUrlEncoded values with {{var}}', async () => { + const { har } = await buildHar({ request: baseRequest({ body: { mode: 'formUrlEncoded', @@ -1375,8 +1375,8 @@ describe('buildHar — interpolation edge cases', () => { expect(har.postData.text).toBe('role=admin'); }); - it('shouldInterpolate=true resolves multipartForm values with {{var}}', () => { - const { har } = buildHar({ + it('shouldInterpolate=true resolves multipartForm values with {{var}}', async () => { + const { har } = await buildHar({ request: baseRequest({ body: { mode: 'multipartForm', @@ -1389,8 +1389,8 @@ describe('buildHar — interpolation edge cases', () => { expect(har.postData.params).toContainEqual({ name: 'caption', value: 'hello' }); }); - it('shouldInterpolate=true resolves auth fields (basic password)', () => { - const { har } = buildHar({ + it('shouldInterpolate=true resolves auth fields (basic password)', async () => { + const { har } = await buildHar({ request: baseRequest({ auth: { mode: 'basic', basic: { username: 'u', password: '{{pw}}' } } }), @@ -1403,33 +1403,33 @@ describe('buildHar — interpolation edge cases', () => { }); describe('buildHar — defensive / robustness', () => { - it('empty headers array → still adds default content-type for body mode', () => { - const { har } = buildHar({ + it('empty headers array → still adds default content-type for body mode', async () => { + const { har } = await buildHar({ request: baseRequest({ headers: [], body: { mode: 'json', json: '{}' } }), shouldInterpolate: false }); expect(har.headers).toContainEqual({ name: 'Content-Type', value: 'application/json' }); }); - it('malformed auth (missing .basic.username) → empty string substituted, no throw', () => { - const { har } = buildHar({ + it('malformed auth (missing .basic.username) → empty string substituted, no throw', async () => { + const { har } = await buildHar({ request: baseRequest({ auth: { mode: 'basic', basic: {} } }), shouldInterpolate: false }); expect(har.headers.find((h) => h.name === 'Authorization')).toBeDefined(); }); - it('encoded-only-once for unreserved-chars-only path (no-op encoding)', () => { + it('encoded-only-once for unreserved-chars-only path (no-op encoding)', async () => { const url = 'https://example.com/api/users/abc-123_.~/profile'; - const { encodedUrl } = buildHar({ + const { encodedUrl } = await buildHar({ request: baseRequest({ url, settings: { encodeUrl: true } }), shouldInterpolate: false }); expect(encodedUrl).toBe(url); }); - it('missing body → har.postData is undefined / empty (no throw)', () => { - const { har } = buildHar({ + it('missing body → har.postData is undefined / empty (no throw)', async () => { + const { har } = await buildHar({ request: { method: 'GET', url: 'https://example.com/api', params: [], headers: [], auth: { mode: 'none' } } as any, shouldInterpolate: false }); @@ -1437,8 +1437,8 @@ describe('buildHar — defensive / robustness', () => { expect(har.method).toBe('GET'); }); - it('disabled query params filtered before stripping/encoding (do not leak into queryString)', () => { - const { har } = buildHar({ + it('disabled query params filtered before stripping/encoding (do not leak into queryString)', async () => { + const { har } = await buildHar({ request: baseRequest({ url: 'https://example.com/api?keep=yes&drop=no', params: [ @@ -1453,8 +1453,8 @@ describe('buildHar — defensive / robustness', () => { expect(names).not.toContain('drop'); }); - it('headers with disabled flag false → not present in har.headers', () => { - const { har } = buildHar({ + it('headers with disabled flag false → not present in har.headers', async () => { + const { har } = await buildHar({ request: baseRequest({ headers: [ { name: 'X-Keep', value: 'on', enabled: true }, @@ -1476,10 +1476,10 @@ describe('buildHar — defensive / robustness', () => { * encoding contracts). `b` variants test pre-encoded URL-bar input. */ describe('buildHar — # encoding scenarios (decision-tree coverage)', () => { - it('Scenario 1: # at fragment position (/docs/api#authentication) — anchor for SPA/static docs', () => { + it('Scenario 1: # at fragment position (/docs/api#authentication) — anchor for SPA/static docs', async () => { const url = 'https://example.com/docs/api#authentication'; - const off = buildHar({ request: baseRequest({ url, settings: { encodeUrl: false } }), shouldInterpolate: false }); - const on = buildHar({ request: baseRequest({ url, settings: { encodeUrl: true } }), shouldInterpolate: false }); + const off = await buildHar({ request: baseRequest({ url, settings: { encodeUrl: false } }), shouldInterpolate: false }); + const on = await buildHar({ request: baseRequest({ url, settings: { encodeUrl: true } }), shouldInterpolate: false }); // OFF: snippet shows the literal `#authentication` (user intent preserved) expect(off.rawUrl).toBe('https://example.com/docs/api#authentication'); @@ -1487,10 +1487,10 @@ describe('buildHar — # encoding scenarios (decision-tree coverage)', () => { expect(on.encodedUrl).toBe('https://example.com/docs/api%23authentication'); }); - it('Scenario 2: # inside a query value (?query=aaa#bbb)', () => { + it('Scenario 2: # inside a query value (?query=aaa#bbb)', async () => { const url = 'http://localhost:6000/request-echo?query=aaa#bbb'; - const off = buildHar({ request: baseRequest({ url, settings: { encodeUrl: false } }), shouldInterpolate: false }); - const on = buildHar({ + const off = await buildHar({ request: baseRequest({ url, settings: { encodeUrl: false } }), shouldInterpolate: false }); + const on = await buildHar({ request: baseRequest({ url, params: [{ name: 'query', value: 'aaa#bbb', type: 'query', enabled: true }], @@ -1503,12 +1503,12 @@ describe('buildHar — # encoding scenarios (decision-tree coverage)', () => { expect(on.encodedUrl).toBe('http://localhost:6000/request-echo?query=aaa%23bbb'); }); - it('Scenario 2b: pre-encoded query (?query=aaa%23bbb) — ON double-encodes %23 → %2523', () => { + it('Scenario 2b: pre-encoded query (?query=aaa%23bbb) — ON double-encodes %23 → %2523', async () => { // Pre-encoded URL bar — `%23` is in the typed input. Per PR #5507's // content-blind contract, ON mode re-encodes content-blindly so `%23` // becomes `%2523` (one more encoding pass). OFF preserves byte-for-byte. const url = 'https://example.com/api?query=aaa%23bbb'; - const off = buildHar({ + const off = await buildHar({ request: baseRequest({ url, params: [{ name: 'query', value: 'aaa%23bbb', type: 'query', enabled: true }], @@ -1516,7 +1516,7 @@ describe('buildHar — # encoding scenarios (decision-tree coverage)', () => { }), shouldInterpolate: false }); - const on = buildHar({ + const on = await buildHar({ request: baseRequest({ url, params: [{ name: 'query', value: 'aaa%23bbb', type: 'query', enabled: true }], @@ -1529,80 +1529,80 @@ describe('buildHar — # encoding scenarios (decision-tree coverage)', () => { expect(on.encodedUrl).toBe('https://example.com/api?query=aaa%2523bbb'); }); - it('Scenario 3: # in path-param value with trailing path (:id=john#doe, /users/:id/profile)', () => { + it('Scenario 3: # in path-param value with trailing path (:id=john#doe, /users/:id/profile)', async () => { // The trailing /profile demonstrates the "silent data loss" case in OFF mode: // axios on the wire treats `#doe/profile` as a fragment and strips it, so the // server only sees `/users/john`. ON mode encodes `#` to `%23`, preserving // both the value AND the /profile suffix on the wire. const url = 'https://example.com/users/:id/profile'; const pathParams = [{ name: 'id', value: 'john#doe', type: 'path', enabled: true }]; - const off = buildHar({ request: baseRequest({ url, pathParams, settings: { encodeUrl: false } }), shouldInterpolate: false }); - const on = buildHar({ request: baseRequest({ url, pathParams, settings: { encodeUrl: true } }), shouldInterpolate: false }); + const off = await buildHar({ request: baseRequest({ url, pathParams, settings: { encodeUrl: false } }), shouldInterpolate: false }); + const on = await buildHar({ request: baseRequest({ url, pathParams, settings: { encodeUrl: true } }), shouldInterpolate: false }); expect(off.rawUrl).toBe('https://example.com/users/john#doe/profile'); expect(on.encodedUrl).toBe('https://example.com/users/john%23doe/profile'); }); - it('Scenario 4: # in semantic path with trailing data (/issues/#1234)', () => { + it('Scenario 4: # in semantic path with trailing data (/issues/#1234)', async () => { const url = 'https://example.com/issues/#1234'; - const off = buildHar({ request: baseRequest({ url, settings: { encodeUrl: false } }), shouldInterpolate: false }); - const on = buildHar({ request: baseRequest({ url, settings: { encodeUrl: true } }), shouldInterpolate: false }); + const off = await buildHar({ request: baseRequest({ url, settings: { encodeUrl: false } }), shouldInterpolate: false }); + const on = await buildHar({ request: baseRequest({ url, settings: { encodeUrl: true } }), shouldInterpolate: false }); expect(off.rawUrl).toBe('https://example.com/issues/#1234'); expect(on.encodedUrl).toBe('https://example.com/issues/%231234'); }); - it('Scenario 4b: pre-encoded issue tracker path (/issues/%231234) — idempotent path encoding', () => { + it('Scenario 4b: pre-encoded issue tracker path (/issues/%231234) — idempotent path encoding', async () => { // Pre-encoded URL bar with `%23` in the path. Path-side encoding is // idempotent (decode-then-encode via safeDecodeURIComponent), so ON mode // keeps `%231234` exactly — it does NOT double-encode like the query side. // This is the key asymmetry between path and query encoding contracts. const url = 'https://example.com/issues/%231234'; - const off = buildHar({ request: baseRequest({ url, settings: { encodeUrl: false } }), shouldInterpolate: false }); - const on = buildHar({ request: baseRequest({ url, settings: { encodeUrl: true } }), shouldInterpolate: false }); + const off = await buildHar({ request: baseRequest({ url, settings: { encodeUrl: false } }), shouldInterpolate: false }); + const on = await buildHar({ request: baseRequest({ url, settings: { encodeUrl: true } }), shouldInterpolate: false }); expect(off.rawUrl).toBe('https://example.com/issues/%231234'); expect(on.encodedUrl).toBe('https://example.com/issues/%231234'); }); - it('Scenario 5: SPA hash-router URL (/#/dashboard/settings)', () => { + it('Scenario 5: SPA hash-router URL (/#/dashboard/settings)', async () => { const url = 'https://yourapp.com/#/dashboard/settings'; - const off = buildHar({ request: baseRequest({ url, settings: { encodeUrl: false } }), shouldInterpolate: false }); - const on = buildHar({ request: baseRequest({ url, settings: { encodeUrl: true } }), shouldInterpolate: false }); + const off = await buildHar({ request: baseRequest({ url, settings: { encodeUrl: false } }), shouldInterpolate: false }); + const on = await buildHar({ request: baseRequest({ url, settings: { encodeUrl: true } }), shouldInterpolate: false }); expect(off.rawUrl).toBe('https://yourapp.com/#/dashboard/settings'); // Each path segment is independently encoded; the standalone `#` becomes `%23` expect(on.encodedUrl).toBe('https://yourapp.com/%23/dashboard/settings'); }); - it('Scenario 7: # directly in path (browser-address-bar style)', () => { + it('Scenario 7: # directly in path (browser-address-bar style)', async () => { // Same shape as Scenario 1 but with the # following a path segment with no // trailing slash. Behaves identically — # is data in ON, fragment in OFF. const url = 'http://localhost:6000/request-echo/hash#tag'; - const off = buildHar({ request: baseRequest({ url, settings: { encodeUrl: false } }), shouldInterpolate: false }); - const on = buildHar({ request: baseRequest({ url, settings: { encodeUrl: true } }), shouldInterpolate: false }); + const off = await buildHar({ request: baseRequest({ url, settings: { encodeUrl: false } }), shouldInterpolate: false }); + const on = await buildHar({ request: baseRequest({ url, settings: { encodeUrl: true } }), shouldInterpolate: false }); expect(off.rawUrl).toBe('http://localhost:6000/request-echo/hash#tag'); expect(on.encodedUrl).toBe('http://localhost:6000/request-echo/hash%23tag'); }); - it('Scenario 7b: pre-encoded direct path (/path/hash%23tag) — idempotent path encoding', () => { + it('Scenario 7b: pre-encoded direct path (/path/hash%23tag) — idempotent path encoding', async () => { // Mirror of 4b for the typed-in-address-bar case. Same idempotent // path-side encoding contract: `%23` survives ON mode without becoming `%2523`. const url = 'http://localhost:6000/request-echo/hash%23tag'; - const off = buildHar({ request: baseRequest({ url, settings: { encodeUrl: false } }), shouldInterpolate: false }); - const on = buildHar({ request: baseRequest({ url, settings: { encodeUrl: true } }), shouldInterpolate: false }); + const off = await buildHar({ request: baseRequest({ url, settings: { encodeUrl: false } }), shouldInterpolate: false }); + const on = await buildHar({ request: baseRequest({ url, settings: { encodeUrl: true } }), shouldInterpolate: false }); expect(off.rawUrl).toBe('http://localhost:6000/request-echo/hash%23tag'); expect(on.encodedUrl).toBe('http://localhost:6000/request-echo/hash%23tag'); }); - it('Scenario 8: OAuth-style fragment (/callback#access_token=...&token_type=Bearer)', () => { + it('Scenario 8: OAuth-style fragment (/callback#access_token=...&token_type=Bearer)', async () => { // OAuth implicit-flow callback. The entire token payload after `#` is treated // as one path segment by encodeUrl, so `#`, `=`, and `&` all get encoded. const url = 'https://myapp.com/callback#access_token=abc123&token_type=Bearer'; - const off = buildHar({ request: baseRequest({ url, settings: { encodeUrl: false } }), shouldInterpolate: false }); - const on = buildHar({ request: baseRequest({ url, settings: { encodeUrl: true } }), shouldInterpolate: false }); + const off = await buildHar({ request: baseRequest({ url, settings: { encodeUrl: false } }), shouldInterpolate: false }); + const on = await buildHar({ request: baseRequest({ url, settings: { encodeUrl: true } }), shouldInterpolate: false }); expect(off.rawUrl).toBe('https://myapp.com/callback#access_token=abc123&token_type=Bearer'); expect(on.encodedUrl).toBe('https://myapp.com/callback%23access_token%3Dabc123%26token_type%3DBearer'); diff --git a/packages/bruno-common/src/generate-code/har/index.ts b/packages/bruno-common/src/generate-code/har/index.ts index b6d0e0b07fd..71c9cacc56e 100644 --- a/packages/bruno-common/src/generate-code/har/index.ts +++ b/packages/bruno-common/src/generate-code/har/index.ts @@ -349,13 +349,13 @@ const looksLikeUrl = (url: string | undefined): boolean => * - 'wsse' → runtime-only signing */ -const authToHeaders = ( +const authToHeaders = async ( auth: BrunoAuth | undefined, variables: Record, oauth2Credentials: OAuth2CredentialRecord[] | undefined, collectionUid: string | undefined, request?: { method?: string; url?: string; headers?: BrunoKV[]; bodyText?: string } -): BrunoKV[] => { +): Promise => { if (!auth || !auth.mode || auth.mode === 'none' || auth.mode === 'inherit') return []; switch (auth.mode) { @@ -423,7 +423,7 @@ const authToHeaders = ( (request.headers || []).forEach((h) => { if (h?.enabled !== false && h?.name) requestHeaders[h.name] = String(h.value ?? ''); }); - const value = signEdgeGridRequest(get(auth, 'akamaiEdgegrid') || {}, { + const value = await signEdgeGridRequest(get(auth, 'akamaiEdgegrid') || {}, { method: request.method, url: request.url, headers: requestHeaders, @@ -584,7 +584,7 @@ const buildPostData = (body: BrunoBody | undefined): any => { // Main // --------------------------------------------------------------------------- -export function buildHar(input: BuildHarInput): BuildHarOutput { +export async function buildHar(input: BuildHarInput): Promise { const variables = input.variables || {}; const shouldInterpolate = input.shouldInterpolate ?? true; @@ -629,7 +629,7 @@ export function buildHar(input: BuildHarInput): BuildHarOutput { // Step 5 — Auth → headers. Append to request headers. Request-signing auth (EdgeGrid) must // sign the same `encodedUrl` the snippet transmits, or the signature won't cover the sent bytes. - const authHeaders = authToHeaders(working.auth, variables, input.oauth2Credentials, input.collectionUid, { + const authHeaders = await authToHeaders(working.auth, variables, input.oauth2Credentials, input.collectionUid, { method: working.method || 'GET', url: encodedUrl, headers: working.headers, diff --git a/packages/bruno-common/src/utils/edgegrid.ts b/packages/bruno-common/src/utils/edgegrid.ts new file mode 100644 index 00000000000..ee9e9ddaa46 --- /dev/null +++ b/packages/bruno-common/src/utils/edgegrid.ts @@ -0,0 +1,71 @@ +import { v4 as uuid } from 'uuid'; + +/** + * Shared EG1-HMAC-SHA256 primitives, used by both the runtime signer + * (packages/bruno-requests/src/auth/edgegrid-helper.js) and the Generate Code signer + * (packages/bruno-common/src/generate-code/har/edgegrid.ts) so the signing logic lives in one + * place. Uses the native Web Crypto API (`globalThis.crypto.subtle`) to stay browser-safe and + * dependency-free; Web Crypto is async, so the hashing helpers return Promises. Kept byte-for-byte + * compatible with Akamai's reference implementation (github.com/akamai/AkamaiOPEN-edgegrid-node). + */ + +// Web Crypto ships natively in the renderer and Node 18+; typed loosely because bruno-common's +// tsconfig omits the DOM lib. +const subtle = (globalThis as any).crypto.subtle; + +const isStrPresent = (str?: string | null): boolean => + !!str && String(str).trim() !== '' && String(str).trim() !== 'undefined'; + +const utf8 = (data: string): Uint8Array => new TextEncoder().encode(data); +const toBase64 = (buffer: ArrayBuffer): string => Buffer.from(new Uint8Array(buffer)).toString('base64'); + +// base64(HMAC-SHA256(data, key)) — key is a UTF-8 string. As the EdgeGrid signing key it is the +// base64 STRING of a prior HMAC, passed again as a UTF-8 key — matching Akamai. +export const base64HmacSha256 = async (data: string, key: string): Promise => { + const cryptoKey = await subtle.importKey('raw', utf8(key), { name: 'HMAC', hash: 'SHA-256' }, false, ['sign']); + return toBase64(await subtle.sign('HMAC', cryptoKey, utf8(data))); +}; + +// base64(SHA-256(data)) +export const base64Sha256 = async (data: string): Promise => toBase64(await subtle.digest('SHA-256', utf8(data))); + +// EdgeGrid timestamp: YYYYMMDDTHH:MM:SS+0000. `toISOString()` is always UTC (trailing `Z`) +// irrespective of the system timezone, so dropping the `.sssZ` and appending `+0000` relabels the +// same instant as UTC — it does not zero out a real local offset. +export const makeEdgeGridTimestamp = (): string => { + const [datePart, timePart] = new Date().toISOString().split('T'); + return `${datePart.replace(/-/g, '')}T${timePart.replace(/\.\d+Z$/, '')}+0000`; +}; + +// UUID v4 nonce. +export const makeEdgeGridNonce = (): string => uuid(); + +// `name:value` per signed header (lowercased name, trimmed + whitespace-collapsed value), +// tab-joined. Only headers present on the request are emitted, preserving config order. +export const canonicalizeHeaders = (headersToSign?: string, requestHeaders: Record = {}): string => { + if (!isStrPresent(headersToSign)) return ''; + const lookup: Record = {}; + Object.keys(requestHeaders || {}).forEach((name) => { + lookup[name.toLowerCase()] = requestHeaders[name]; + }); + return (headersToSign as string) + .split(',') + .map((name) => name.trim().toLowerCase()) + .filter((name) => name.length > 0) + .filter((name) => Object.prototype.hasOwnProperty.call(lookup, name)) + .map((name) => `${name}:${String(lookup[name]).trim().replace(/\s+/g, ' ')}`) + .join('\t'); +}; + +// Akamai hashes the body for POST only, over the bytes as sent, truncated to maxBodySize. +export const makeContentHash = async ( + method: string, + bodyText: string | undefined, + maxBodySize: number +): Promise => { + if (!method || method.toUpperCase() !== 'POST' || !bodyText) return ''; + let body = bodyText; + if (body.length === 0) return ''; + if (body.length > maxBodySize) body = body.substring(0, maxBodySize); + return base64Sha256(body); +}; diff --git a/packages/bruno-common/src/utils/index.ts b/packages/bruno-common/src/utils/index.ts index 99d6a7d1461..1423438535e 100644 --- a/packages/bruno-common/src/utils/index.ts +++ b/packages/bruno-common/src/utils/index.ts @@ -42,3 +42,12 @@ export { export { toDisplayString } from './string'; + +export { + makeEdgeGridTimestamp, + makeEdgeGridNonce, + canonicalizeHeaders, + base64HmacSha256, + base64Sha256, + makeContentHash +} from './edgegrid'; diff --git a/packages/bruno-filestore/src/formats/yml/common/auth.ts b/packages/bruno-filestore/src/formats/yml/common/auth.ts index f8ad1e0c880..9ea7211f78f 100644 --- a/packages/bruno-filestore/src/formats/yml/common/auth.ts +++ b/packages/bruno-filestore/src/formats/yml/common/auth.ts @@ -20,11 +20,11 @@ interface AkamaiEdgeGridAuthValues { accessToken?: string; clientToken?: string; clientSecret?: string; - nonce?: string; - timestamp?: string; - baseURL?: string; - headersToSign?: string; - maxBodySize?: number; + baseURL?: string | null; + nonce?: string | null; + timestamp?: string | null; + headersToSign?: string | null; + maxBodySize?: number | null; } const buildAwsV4Auth = (config?: BrunoAuth['awsv4']): AuthAwsV4 => { diff --git a/packages/bruno-requests/package.json b/packages/bruno-requests/package.json index c69d8bad9b0..f768b90985b 100644 --- a/packages/bruno-requests/package.json +++ b/packages/bruno-requests/package.json @@ -21,6 +21,7 @@ }, "dependencies": { "@faker-js/faker": "^9.7.0", + "@usebruno/common": "0.1.0", "@grpc/grpc-js": "^1.13.3", "@grpc/proto-loader": "^0.7.15", "@types/qs": "^6.9.18", diff --git a/packages/bruno-requests/rollup.config.js b/packages/bruno-requests/rollup.config.js index 95a91171a5b..3b6c6dffffc 100644 --- a/packages/bruno-requests/rollup.config.js +++ b/packages/bruno-requests/rollup.config.js @@ -39,6 +39,9 @@ module.exports = [ typescript({ tsconfig: './tsconfig.json' }), terser() ], - external: (id) => isBuiltin(id) || ['axios', 'qs', 'ws', 'debug', 'shell-env', 'pac-resolver', 'quickjs-emscripten'].includes(id) + external: (id) => + isBuiltin(id) + || id.startsWith('@usebruno/') + || ['axios', 'qs', 'ws', 'debug', 'shell-env', 'pac-resolver', 'quickjs-emscripten'].includes(id) } ]; diff --git a/packages/bruno-requests/src/auth/edgegrid-helper.js b/packages/bruno-requests/src/auth/edgegrid-helper.js index 171a2558f82..a246fde72e8 100644 --- a/packages/bruno-requests/src/auth/edgegrid-helper.js +++ b/packages/bruno-requests/src/auth/edgegrid-helper.js @@ -1,11 +1,19 @@ -const crypto = require('crypto'); +import { + makeEdgeGridTimestamp, + makeEdgeGridNonce, + canonicalizeHeaders, + base64HmacSha256, + makeContentHash +} from '@usebruno/common/utils'; + const { URL } = require('node:url'); /** * Akamai EdgeGrid Authentication Helper * Implements the EG1-HMAC-SHA256 scheme exactly as Akamai's official client library * (https://github.com/akamai/AkamaiOPEN-edgegrid-node) so signatures validate against - * the real Akamai gateway. + * the real Akamai gateway. The signing/crypto primitives are shared with the Generate Code + * signer via @usebruno/common/utils; they use Web Crypto and are async. * Spec: https://techdocs.akamai.com/developer/docs/authenticate-with-edgegrid */ @@ -15,105 +23,6 @@ function isStrPresent(str) { return str && str.trim() !== '' && str.trim() !== 'undefined'; } -/** - * Generate a UTC timestamp in EdgeGrid format: YYYYMMDDTHH:MM:SS+0000 - * (date part has no separators, time part keeps colons, fixed +0000 offset). - * @returns {string} - */ -function makeEdgeGridTimestamp() { - const [datePart, timePart] = new Date().toISOString().split('T'); - const date = datePart.replace(/-/g, ''); - const time = timePart.replace(/\.\d+Z$/, ''); - return `${date}T${time}+0000`; -} - -/** - * Generate a random nonce (UUID v4) - * @returns {string} - */ -function makeEdgeGridNonce() { - return crypto.randomUUID(); -} - -/** - * Base64-encoded HMAC-SHA256. Note the result is a base64 STRING; when used as the - * signing key it is passed (as a string) as the key of the next HMAC — matching Akamai. - * @param {string|Buffer} data - * @param {string} key - * @returns {string} - */ -function base64HmacSha256(data, key) { - return crypto.createHmac('sha256', key).update(data).digest('base64'); -} - -/** - * Base64-encoded SHA256 hash. - * @param {string|Buffer} data - * @returns {string} - */ -function base64Sha256(data) { - return crypto.createHash('sha256').update(data).digest('base64'); -} - -/** - * Build the canonicalized headers segment from the comma-separated list of header NAMES - * the user asked to sign, pulling the actual values off the outgoing request. - * Format per header: `name(lowercase):value(trimmed, internal whitespace collapsed)`, - * joined by a tab — matching Akamai's canonicalizeHeaders(). - * @param {string} headersToSign - comma-separated header names - * @param {Object} requestHeaders - outgoing request headers ({ name: value }) - * @returns {string} - */ -function canonicalizeHeaders(headersToSign, requestHeaders = {}) { - if (!isStrPresent(headersToSign)) { - return ''; - } - - // case-insensitive lookup of the actual request header values - const lookup = {}; - Object.keys(requestHeaders || {}).forEach((name) => { - lookup[name.toLowerCase()] = requestHeaders[name]; - }); - - return headersToSign - .split(',') - .map((name) => name.trim().toLowerCase()) - .filter((name) => name.length > 0) - // Akamai only signs headers that are actually present on the request (config order preserved); - // names not present are skipped, not emitted as empty values. - .filter((name) => Object.prototype.hasOwnProperty.call(lookup, name)) - .map((name) => `${name}:${String(lookup[name]).trim().replace(/\s+/g, ' ')}`) - .join('\t'); -} - -/** - * Compute the request body content hash. Akamai hashes the body for POST requests only, - * over the exact bytes that are sent on the wire (no re-serialization), truncated to - * maxBodySize before hashing. - * @param {Object} request - axios request config ({ method, data }) - * @param {number} maxBodySize - * @returns {string} base64 SHA256 of the (possibly truncated) body, or '' when not applicable - */ -function makeContentHash(request, maxBodySize) { - if (!request.method || request.method.toUpperCase() !== 'POST') { - return ''; - } - - let body = request.data; - if (!body) { - return ''; - } - // Hash the bytes as sent — do NOT parse/re-stringify (that would change the payload). - body = typeof body === 'string' ? body : JSON.stringify(body); - if (body.length === 0) { - return ''; - } - if (body.length > maxBodySize) { - body = body.substring(0, maxBodySize); - } - return base64Sha256(body); -} - /** * Sign an EdgeGrid request. * @param {Object} config - EdgeGrid configuration @@ -126,9 +35,9 @@ function makeContentHash(request, maxBodySize) { * @param {string} [config.headersToSign] - comma-separated header names to sign * @param {string|number} [config.maxBodySize=131072] * @param {Object} request - axios request config ({ method, url, headers, data }) - * @returns {string} Authorization header value + * @returns {Promise} Authorization header value */ -export function signEdgeGridRequest(config, request) { +export async function signEdgeGridRequest(config, request) { const { accessToken, clientToken, clientSecret, baseURL, headersToSign } = config; const maxBodySize = config.maxBodySize ? parseInt(config.maxBodySize, 10) : MAX_BODY_SIZE_DEFAULT; @@ -166,6 +75,9 @@ export function signEdgeGridRequest(config, request) { const authHeader = `EG1-HMAC-SHA256 client_token=${clientToken};access_token=${accessToken};timestamp=${timestamp};nonce=${nonce};`; + // Hash the body bytes exactly as sent — do NOT parse/re-stringify (that would change the payload). + const bodyText = typeof request.data === 'string' ? request.data : request.data ? JSON.stringify(request.data) : ''; + // data-to-sign: tab-joined, in the exact order Akamai expects. const dataToSign = [ request.method.toUpperCase(), @@ -173,14 +85,14 @@ export function signEdgeGridRequest(config, request) { parsedUrl.host, parsedUrl.pathname + parsedUrl.search, canonicalizeHeaders(headersToSign, request.headers), - makeContentHash(request, maxBodySize), + await makeContentHash(request.method, bodyText, maxBodySize), authHeader ].join('\t'); // Signing key is the base64 STRING of HMAC(timestamp, clientSecret); the signature is then // HMAC(dataToSign, signingKey) — both base64-encoded. - const signingKey = base64HmacSha256(timestamp, clientSecret); - const signature = base64HmacSha256(dataToSign, signingKey); + const signingKey = await base64HmacSha256(timestamp, clientSecret); + const signature = await base64HmacSha256(dataToSign, signingKey); return `${authHeader}signature=${signature}`; } @@ -197,18 +109,20 @@ export function addEdgeGridInterceptor(axiosInstance, request) { return; } - // Add request interceptor to sign requests - axiosInstance.interceptors.request.use((config) => { - try { - const authHeader = signEdgeGridRequest(edgeGridConfig, config); - config.headers['Authorization'] = authHeader; - return config; - } catch (error) { - console.error('EdgeGrid signing error:', error); + // Sign requests as they go out. The signer is async (Web Crypto), and axios awaits a + // Promise-returning request interceptor. + axiosInstance.interceptors.request.use( + async (config) => { + try { + config.headers['Authorization'] = await signEdgeGridRequest(edgeGridConfig, config); + return config; + } catch (error) { + console.error('EdgeGrid signing error:', error); + return Promise.reject(error); + } + }, + (error) => { return Promise.reject(error); } - }, - (error) => { - return Promise.reject(error); - }); + ); } diff --git a/packages/bruno-requests/src/auth/edgegrid-helper.spec.js b/packages/bruno-requests/src/auth/edgegrid-helper.spec.js index 0a174332108..2c2093c2e9d 100644 --- a/packages/bruno-requests/src/auth/edgegrid-helper.spec.js +++ b/packages/bruno-requests/src/auth/edgegrid-helper.spec.js @@ -46,8 +46,8 @@ describe('signEdgeGridRequest — Akamai official vectors (core)', () => { } ]; - test.each(cases)('$name', ({ config, request, expected }) => { - expect(sig(signEdgeGridRequest(config, request))).toBe(expected); + test.each(cases)('$name', async ({ config, request, expected }) => { + expect(sig(await signEdgeGridRequest(config, request))).toBe(expected); }); }); @@ -85,14 +85,14 @@ describe('signEdgeGridRequest — Akamai official vectors (headers_to_sign)', () } ]; - test.each(cases)('$name', ({ request, expected }) => { - expect(sig(signEdgeGridRequest(config, request))).toBe(expected); + test.each(cases)('$name', async ({ request, expected }) => { + expect(sig(await signEdgeGridRequest(config, request))).toBe(expected); }); }); describe('signEdgeGridRequest — body hashing rules', () => { - test('non-POST methods are NOT body-hashed (PUT with data)', () => { - const header = signEdgeGridRequest(CREDS, { + test('non-POST methods are NOT body-hashed (PUT with data)', async () => { + const header = await signEdgeGridRequest(CREDS, { method: 'PUT', url: `${HOST}/testapi/v1/t6`, data: 'PPPPPPPPPPPPPPPPPPPPPPPPPPPPPPP' @@ -101,44 +101,44 @@ describe('signEdgeGridRequest — body hashing rules', () => { expect(sig(header)).toBe('GNBWEYSEWOLtu+7dD52da2C39aX/Jchpon3K/AmBqBU='); }); - test('POST body is hashed as-sent (no JSON re-compaction)', () => { + test('POST body is hashed as-sent (no JSON re-compaction)', async () => { const pretty = '{\n "name": "bruno"\n}'; const compact = '{"name":"bruno"}'; const req = (data) => ({ method: 'POST', url: `${HOST}/x`, data }); // Different bytes on the wire ⇒ different signature (proves we hash what we send). - expect(sig(signEdgeGridRequest(CREDS, req(pretty)))).not.toBe(sig(signEdgeGridRequest(CREDS, req(compact)))); + expect(sig(await signEdgeGridRequest(CREDS, req(pretty)))).not.toBe(sig(await signEdgeGridRequest(CREDS, req(compact)))); }); - test('POST body is truncated to maxBodySize before hashing', () => { + test('POST body is truncated to maxBodySize before hashing', async () => { const config = { ...CREDS, maxBodySize: 16 }; const a = { method: 'POST', url: `${HOST}/x`, data: 'd'.repeat(16) + 'AAAAAAAA' }; const b = { method: 'POST', url: `${HOST}/x`, data: 'd'.repeat(16) + 'BBBBBBBB' }; // Bytes beyond maxBodySize are ignored ⇒ identical signature. - expect(sig(signEdgeGridRequest(config, a))).toBe(sig(signEdgeGridRequest(config, b))); + expect(sig(await signEdgeGridRequest(config, a))).toBe(sig(await signEdgeGridRequest(config, b))); }); }); describe('signEdgeGridRequest — config behaviour', () => { - test('throws when accessToken is missing', () => { - expect(() => signEdgeGridRequest({ ...CREDS, accessToken: '' }, { method: 'GET', url: `${HOST}/` })).toThrow( + test('throws when accessToken is missing', async () => { + await expect(signEdgeGridRequest({ ...CREDS, accessToken: '' }, { method: 'GET', url: `${HOST}/` })).rejects.toThrow( /accessToken is required/ ); }); - test('throws when clientToken is missing', () => { - expect(() => signEdgeGridRequest({ ...CREDS, clientToken: '' }, { method: 'GET', url: `${HOST}/` })).toThrow( + test('throws when clientToken is missing', async () => { + await expect(signEdgeGridRequest({ ...CREDS, clientToken: '' }, { method: 'GET', url: `${HOST}/` })).rejects.toThrow( /clientToken is required/ ); }); - test('throws when clientSecret is missing', () => { - expect(() => signEdgeGridRequest({ ...CREDS, clientSecret: '' }, { method: 'GET', url: `${HOST}/` })).toThrow( + test('throws when clientSecret is missing', async () => { + await expect(signEdgeGridRequest({ ...CREDS, clientSecret: '' }, { method: 'GET', url: `${HOST}/` })).rejects.toThrow( /clientSecret is required/ ); }); - test('auto-generates nonce and timestamp when not provided', () => { - const header = signEdgeGridRequest( + test('auto-generates nonce and timestamp when not provided', async () => { + const header = await signEdgeGridRequest( { clientToken: CREDS.clientToken, accessToken: CREDS.accessToken, clientSecret: CREDS.clientSecret }, { method: 'GET', url: `${HOST}/` } ); @@ -148,10 +148,10 @@ describe('signEdgeGridRequest — config behaviour', () => { expect(header).toMatch(/signature=.+$/); }); - test('baseURL overrides the host the request is signed against', () => { + test('baseURL overrides the host the request is signed against', async () => { // Signing the request URL directly vs. signing via a different baseURL host ⇒ different signature - const direct = signEdgeGridRequest(CREDS, { method: 'GET', url: `${HOST}/path` }); - const viaBase = signEdgeGridRequest( + const direct = await signEdgeGridRequest(CREDS, { method: 'GET', url: `${HOST}/path` }); + const viaBase = await signEdgeGridRequest( { ...CREDS, baseURL: 'https://other-host.luna.akamaiapis.net' }, { method: 'GET', url: `${HOST}/path` } ); @@ -168,30 +168,30 @@ describe('signEdgeGridRequest — config behaviour', () => { describe('signEdgeGridRequest — baseURL host/scheme override (httpie test_localhost equivalents)', () => { const REAL_HOST = 'https://realhost-xxxxxxxx.luna.akamaiapis.net'; - test('localhost is replaced by the baseURL host (test_localhost)', () => { - const viaBase = signEdgeGridRequest( + test('localhost is replaced by the baseURL host (test_localhost)', async () => { + const viaBase = await signEdgeGridRequest( { ...CREDS, baseURL: REAL_HOST }, { method: 'GET', url: 'https://localhost/identity-management/v3/user-profile?q=1' } ); - const direct = signEdgeGridRequest(CREDS, { + const direct = await signEdgeGridRequest(CREDS, { method: 'GET', url: `${REAL_HOST}/identity-management/v3/user-profile?q=1` }); expect(sig(viaBase)).toBe(sig(direct)); }); - test('an http request is signed against the https baseURL (test_http_to_https_conversion)', () => { - const viaBase = signEdgeGridRequest({ ...CREDS, baseURL: REAL_HOST }, { method: 'GET', url: 'http://localhost/path' }); - const direct = signEdgeGridRequest(CREDS, { method: 'GET', url: `${REAL_HOST}/path` }); + test('an http request is signed against the https baseURL (test_http_to_https_conversion)', async () => { + const viaBase = await signEdgeGridRequest({ ...CREDS, baseURL: REAL_HOST }, { method: 'GET', url: 'http://localhost/path' }); + const direct = await signEdgeGridRequest(CREDS, { method: 'GET', url: `${REAL_HOST}/path` }); expect(sig(viaBase)).toBe(sig(direct)); }); - test('scheme-less baseURL ("host:port") borrows the request scheme', () => { - const viaBase = signEdgeGridRequest( + test('scheme-less baseURL ("host:port") borrows the request scheme', async () => { + const viaBase = await signEdgeGridRequest( { ...CREDS, baseURL: 'localhost:6000' }, { method: 'GET', url: 'http://localhost:9999/path' } ); - const direct = signEdgeGridRequest(CREDS, { method: 'GET', url: 'http://localhost:6000/path' }); + const direct = await signEdgeGridRequest(CREDS, { method: 'GET', url: 'http://localhost:6000/path' }); expect(sig(viaBase)).toBe(sig(direct)); }); }); diff --git a/packages/bruno-schema-types/src/common/auth.ts b/packages/bruno-schema-types/src/common/auth.ts index e61bc89061b..7930a5f3588 100644 --- a/packages/bruno-schema-types/src/common/auth.ts +++ b/packages/bruno-schema-types/src/common/auth.ts @@ -39,12 +39,12 @@ export interface AuthApiKey { } export interface AkamaiEdgeGridAuthValues { - accessToken?: string | null; - clientToken?: string | null; - clientSecret?: string | null; + accessToken?: string; + clientToken?: string; + clientSecret?: string; + baseURL?: string | null; nonce?: string | null; timestamp?: string | null; - baseURL?: string | null; headersToSign?: string | null; maxBodySize?: number | null; } From 3d761ac55d469fc5bf0b8a13b1b7ea238878c03e Mon Sep 17 00:00:00 2001 From: shubh-bruno Date: Thu, 16 Jul 2026 14:57:23 +0530 Subject: [PATCH 06/13] chore: revert lock.json --- package-lock.json | 14 +------------- 1 file changed, 1 insertion(+), 13 deletions(-) diff --git a/package-lock.json b/package-lock.json index f5defd3af30..802b2a14483 100644 --- a/package-lock.json +++ b/package-lock.json @@ -13176,13 +13176,6 @@ "resolved": "https://registry.npmjs.org/@types/use-sync-external-store/-/use-sync-external-store-0.0.6.tgz", "integrity": "sha512-zFDAD+tlpf2r4asuHEj0XH6pY6i0g5NeAHPn+15wk3BV6JA69eERFXC1gyGThDkVa1zCyKr5jox1+2LbV/AMLg==" }, - "node_modules/@types/uuid": { - "version": "10.0.0", - "resolved": "https://registry.npmjs.org/@types/uuid/-/uuid-10.0.0.tgz", - "integrity": "sha512-7gqG38EyHgyP1S+7+xomFtL+ZNHcKv6DwNaCZmJmo1vgMugyF3TCnXVg4t1uk89mLNwnLtnY3TpOpCOyp1/xHQ==", - "dev": true, - "license": "MIT" - }, "node_modules/@types/verror": { "version": "1.10.10", "resolved": "https://registry.npmjs.org/@types/verror/-/verror-1.10.10.tgz", @@ -34634,9 +34627,6 @@ "name": "@usebruno/common", "version": "0.1.0", "license": "MIT", - "dependencies": { - "uuid": "^10.0.0" - }, "devDependencies": { "@babel/preset-env": "^7.26.9", "@babel/preset-typescript": "^7.27.0", @@ -34647,7 +34637,6 @@ "@rollup/plugin-terser": "^1.0.0", "@rollup/plugin-typescript": "^12.1.2", "@types/jest": "^29.5.14", - "@types/uuid": "^10.0.0", "babel-jest": "^29.7.0", "form-data": "4.0.4", "is-ip": "^5.0.1", @@ -36230,7 +36219,6 @@ "@grpc/grpc-js": "^1.13.3", "@grpc/proto-loader": "^0.7.15", "@types/qs": "^6.9.18", - "@usebruno/common": "0.1.0", "axios": "1.16.0", "debug": "^4.4.3", "google-protobuf": "^4.0.0", @@ -36717,4 +36705,4 @@ } } } -} +} \ No newline at end of file From a0c53af926513ddce0d7f90417d97fbb2ec625ed Mon Sep 17 00:00:00 2001 From: shubh-bruno Date: Thu, 16 Jul 2026 14:58:46 +0530 Subject: [PATCH 07/13] chore: revert diff-space --- package-lock.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/package-lock.json b/package-lock.json index 802b2a14483..13635e6626c 100644 --- a/package-lock.json +++ b/package-lock.json @@ -36705,4 +36705,4 @@ } } } -} \ No newline at end of file +} From d6dafe1eb074695ac13b9485912207d03f7574dc Mon Sep 17 00:00:00 2001 From: shubh-bruno Date: Thu, 16 Jul 2026 15:11:13 +0530 Subject: [PATCH 08/13] test: update locators --- .../akamai-edgegrid-generate-code.spec.ts | 12 +++++++++--- .../akamai-edgegrid/akamai-edgegrid-levels.spec.ts | 4 ++++ tests/auth/akamai-edgegrid/akamai-edgegrid.spec.ts | 8 ++++++-- tests/utils/page/locators.ts | 3 +++ 4 files changed, 22 insertions(+), 5 deletions(-) diff --git a/tests/auth/akamai-edgegrid/akamai-edgegrid-generate-code.spec.ts b/tests/auth/akamai-edgegrid/akamai-edgegrid-generate-code.spec.ts index af963a01134..c6005957515 100644 --- a/tests/auth/akamai-edgegrid/akamai-edgegrid-generate-code.spec.ts +++ b/tests/auth/akamai-edgegrid/akamai-edgegrid-generate-code.spec.ts @@ -1,5 +1,6 @@ import { expect, Page, test } from '../../../playwright'; import { + buildCommonLocators, closeAllCollections, closeGenerateCodeDialog, createCollection, @@ -36,6 +37,10 @@ const fillEdgeGridCredentials = async (page: Page) => { }; test.describe('Akamai EdgeGrid - Generate Code', () => { + // Configuring auth, saving, and generating a real signed snippet across several requests runs + // longer than the default 30s under parallel load. + test.describe.configure({ timeout: 60_000 }); + test.afterEach(async ({ page }) => { await closeAllCollections(page); }); @@ -59,19 +64,20 @@ test.describe('Akamai EdgeGrid - Generate Code', () => { }); test('inherited collection auth is resolved and signed in the snippet', async ({ page, createTmpDir }) => { + const { paneTabs, settingsSaveButton, auth } = buildCommonLocators(page); await createCollection(page, 'edgegrid-gencode-inherit', await createTmpDir()); // Collection settings open on creation - configure collection-level EdgeGrid auth. - await page.locator('.tab.auth').click(); + await paneTabs.collectionSettingsTab('auth').click(); await selectAuthMode(page, 'Akamai EdgeGrid'); await fillEdgeGridCredentials(page); - await page.getByRole('button', { name: 'Save' }).click(); + await settingsSaveButton().click(); await createRequest(page, 'inheriting-request', 'edgegrid-gencode-inherit', { url: REQUEST_URL }); await openRequest(page, 'edgegrid-gencode-inherit', 'inheriting-request'); await selectRequestPaneTab(page, 'Auth'); // A new request already defaults to Inherit; Generate Code reads the draft and resolves // inheritance from the collection, so no save is needed here. - await expect(page.locator('.inherit-mode-text')).toHaveText('Akamai EdgeGrid'); + await expect(auth.inheritedMode()).toHaveText('Akamai EdgeGrid'); const snippet = await getGeneratedSnippet(page); diff --git a/tests/auth/akamai-edgegrid/akamai-edgegrid-levels.spec.ts b/tests/auth/akamai-edgegrid/akamai-edgegrid-levels.spec.ts index 4ca6f771568..26035044249 100644 --- a/tests/auth/akamai-edgegrid/akamai-edgegrid-levels.spec.ts +++ b/tests/auth/akamai-edgegrid/akamai-edgegrid-levels.spec.ts @@ -75,6 +75,10 @@ const expectInheritedEdgeGridSignature = async (page, expectedNonce: string) => }; test.describe('Akamai EdgeGrid Authentication - collection, folder & inherit', () => { + // Each flow fills 8 credential fields character-by-character, switches auth modes, re-verifies + // every field, and makes real signed round-trips — more than the default 30s under parallel load. + test.describe.configure({ timeout: 60_000 }); + test.afterEach(async ({ page }) => { await closeAllCollections(page); }); diff --git a/tests/auth/akamai-edgegrid/akamai-edgegrid.spec.ts b/tests/auth/akamai-edgegrid/akamai-edgegrid.spec.ts index cac3587d884..c60ab432bfe 100644 --- a/tests/auth/akamai-edgegrid/akamai-edgegrid.spec.ts +++ b/tests/auth/akamai-edgegrid/akamai-edgegrid.spec.ts @@ -63,6 +63,10 @@ const VALUES: Record = { }; test.describe('Akamai EdgeGrid Authentication (request level)', () => { + // Each flow fills 8 credential fields character-by-character, saves, re-verifies every field, and + // makes real signed round-trips to the simulator — more than the default 30s under parallel load. + test.describe.configure({ timeout: 60_000 }); + test.afterAll(async ({ page }) => { await closeAllCollections(page); }); @@ -173,8 +177,8 @@ test.describe('Akamai EdgeGrid Authentication (request level)', () => { await selectResponsePaneTab(page, 'Timeline'); const entry = timeline.items().first(); await timeline.itemHeader(entry).click(); - await entry.getByRole('button', { name: 'Network' }).click(); - const networkLogs = entry.locator('.network-logs-container'); + await timeline.networkButton(entry).click(); + const networkLogs = timeline.networkLogs(entry); // Credentials were interpolated from the variables before signing - no unresolved tokens. await expect(networkLogs).toContainText(`access_token=${TEST_EDGEGRID.accessToken}`); diff --git a/tests/utils/page/locators.ts b/tests/utils/page/locators.ts index 31bcaad0786..073cfd42acf 100644 --- a/tests/utils/page/locators.ts +++ b/tests/utils/page/locators.ts @@ -14,6 +14,7 @@ export const buildCommonLocators = (page: Page) => ({ ai: buildAiPreferencesLocators(page), websocket: buildWebsocketCommonLocators(page), saveButton: () => page.getByTestId('save-request-button'), + settingsSaveButton: () => page.getByRole('button', { name: 'Save' }), openPreferences: () => page.getByRole('button', { name: 'Open Preferences' }), sidebar: { collectionsContainer: () => page.getByTestId('collections'), @@ -285,6 +286,8 @@ export const buildCommonLocators = (page: Page) => ({ items: () => page.getByTestId('timeline-item'), lastItem: () => page.getByTestId('timeline-item').last(), itemHeader: (item: Locator) => item.getByTestId('timeline-item-header'), + networkButton: (item: Locator) => item.getByRole('button', { name: 'Network' }), + networkLogs: (item: Locator) => item.locator('.network-logs-container'), clearButton: () => page.getByRole('button', { name: 'Clear Timeline' }) }, plusMenu: { From b1f2420cf6ced647b2a44823b4f5fa4585434cea Mon Sep 17 00:00:00 2001 From: shubh-bruno Date: Thu, 16 Jul 2026 15:34:38 +0530 Subject: [PATCH 09/13] fix: update deps --- package-lock.json | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/package-lock.json b/package-lock.json index 13635e6626c..f5defd3af30 100644 --- a/package-lock.json +++ b/package-lock.json @@ -13176,6 +13176,13 @@ "resolved": "https://registry.npmjs.org/@types/use-sync-external-store/-/use-sync-external-store-0.0.6.tgz", "integrity": "sha512-zFDAD+tlpf2r4asuHEj0XH6pY6i0g5NeAHPn+15wk3BV6JA69eERFXC1gyGThDkVa1zCyKr5jox1+2LbV/AMLg==" }, + "node_modules/@types/uuid": { + "version": "10.0.0", + "resolved": "https://registry.npmjs.org/@types/uuid/-/uuid-10.0.0.tgz", + "integrity": "sha512-7gqG38EyHgyP1S+7+xomFtL+ZNHcKv6DwNaCZmJmo1vgMugyF3TCnXVg4t1uk89mLNwnLtnY3TpOpCOyp1/xHQ==", + "dev": true, + "license": "MIT" + }, "node_modules/@types/verror": { "version": "1.10.10", "resolved": "https://registry.npmjs.org/@types/verror/-/verror-1.10.10.tgz", @@ -34627,6 +34634,9 @@ "name": "@usebruno/common", "version": "0.1.0", "license": "MIT", + "dependencies": { + "uuid": "^10.0.0" + }, "devDependencies": { "@babel/preset-env": "^7.26.9", "@babel/preset-typescript": "^7.27.0", @@ -34637,6 +34647,7 @@ "@rollup/plugin-terser": "^1.0.0", "@rollup/plugin-typescript": "^12.1.2", "@types/jest": "^29.5.14", + "@types/uuid": "^10.0.0", "babel-jest": "^29.7.0", "form-data": "4.0.4", "is-ip": "^5.0.1", @@ -36219,6 +36230,7 @@ "@grpc/grpc-js": "^1.13.3", "@grpc/proto-loader": "^0.7.15", "@types/qs": "^6.9.18", + "@usebruno/common": "0.1.0", "axios": "1.16.0", "debug": "^4.4.3", "google-protobuf": "^4.0.0", From 47c2ccb987282cedc5728457512e776943b5611e Mon Sep 17 00:00:00 2001 From: shubh-bruno Date: Thu, 16 Jul 2026 18:16:36 +0530 Subject: [PATCH 10/13] fix: resolved comments & refactor --- package-lock.json | 11 ---------- packages/bruno-common/package.json | 5 +---- .../src/generate-code/har/edgegrid.ts | 21 ++++++++----------- packages/bruno-common/src/utils/edgegrid.ts | 15 +++++++------ packages/bruno-common/src/utils/index.ts | 2 ++ .../src/auth/edgegrid-helper.js | 10 +++------ 6 files changed, 22 insertions(+), 42 deletions(-) diff --git a/package-lock.json b/package-lock.json index f5defd3af30..60f3e728b63 100644 --- a/package-lock.json +++ b/package-lock.json @@ -13176,13 +13176,6 @@ "resolved": "https://registry.npmjs.org/@types/use-sync-external-store/-/use-sync-external-store-0.0.6.tgz", "integrity": "sha512-zFDAD+tlpf2r4asuHEj0XH6pY6i0g5NeAHPn+15wk3BV6JA69eERFXC1gyGThDkVa1zCyKr5jox1+2LbV/AMLg==" }, - "node_modules/@types/uuid": { - "version": "10.0.0", - "resolved": "https://registry.npmjs.org/@types/uuid/-/uuid-10.0.0.tgz", - "integrity": "sha512-7gqG38EyHgyP1S+7+xomFtL+ZNHcKv6DwNaCZmJmo1vgMugyF3TCnXVg4t1uk89mLNwnLtnY3TpOpCOyp1/xHQ==", - "dev": true, - "license": "MIT" - }, "node_modules/@types/verror": { "version": "1.10.10", "resolved": "https://registry.npmjs.org/@types/verror/-/verror-1.10.10.tgz", @@ -34634,9 +34627,6 @@ "name": "@usebruno/common", "version": "0.1.0", "license": "MIT", - "dependencies": { - "uuid": "^10.0.0" - }, "devDependencies": { "@babel/preset-env": "^7.26.9", "@babel/preset-typescript": "^7.27.0", @@ -34647,7 +34637,6 @@ "@rollup/plugin-terser": "^1.0.0", "@rollup/plugin-typescript": "^12.1.2", "@types/jest": "^29.5.14", - "@types/uuid": "^10.0.0", "babel-jest": "^29.7.0", "form-data": "4.0.4", "is-ip": "^5.0.1", diff --git a/packages/bruno-common/package.json b/packages/bruno-common/package.json index 7237e60fab9..f3b6840243e 100644 --- a/packages/bruno-common/package.json +++ b/packages/bruno-common/package.json @@ -36,9 +36,7 @@ "watch": "rollup -c -w", "prepack": "npm run test && npm run build" }, - "dependencies": { - "uuid": "^10.0.0" - }, + "dependencies": {}, "devDependencies": { "@babel/preset-env": "^7.26.9", "@babel/preset-typescript": "^7.27.0", @@ -49,7 +47,6 @@ "@rollup/plugin-terser": "^1.0.0", "@rollup/plugin-typescript": "^12.1.2", "@types/jest": "^29.5.14", - "@types/uuid": "^10.0.0", "babel-jest": "^29.7.0", "form-data": "4.0.4", "is-ip": "^5.0.1", diff --git a/packages/bruno-common/src/generate-code/har/edgegrid.ts b/packages/bruno-common/src/generate-code/har/edgegrid.ts index 75d185e65bc..d44eda6597d 100644 --- a/packages/bruno-common/src/generate-code/har/edgegrid.ts +++ b/packages/bruno-common/src/generate-code/har/edgegrid.ts @@ -1,9 +1,11 @@ import { + MAX_BODY_SIZE_DEFAULT, makeEdgeGridTimestamp, makeEdgeGridNonce, canonicalizeHeaders, base64HmacSha256, - makeContentHash + makeContentHash, + isStrPresent } from '../../utils/edgegrid'; /** @@ -15,11 +17,6 @@ import { * Promise. Kept byte-for-byte compatible with Akamai's reference implementation. */ -const MAX_BODY_SIZE_DEFAULT = 131072; // 128 KB - -const isStrPresent = (str?: string | null): boolean => - !!str && String(str).trim() !== '' && String(str).trim() !== 'undefined'; - export interface AkamaiEdgeGridAuthValues { accessToken?: string; clientToken?: string; @@ -51,15 +48,15 @@ export const signEdgeGridRequest = async ( if (!request?.url || !request?.method) return null; const maxBodySize = config.maxBodySize ? parseInt(String(config.maxBodySize), 10) : MAX_BODY_SIZE_DEFAULT; - const nonce = isStrPresent(config.nonce) ? (config.nonce as string) : makeEdgeGridNonce(); - const timestamp = isStrPresent(config.timestamp) ? (config.timestamp as string) : makeEdgeGridTimestamp(); + const nonce = isStrPresent(config.nonce) ? config.nonce : makeEdgeGridNonce(); + const timestamp = isStrPresent(config.timestamp) ? config.timestamp : makeEdgeGridTimestamp(); let parsedUrl: URL; try { let urlToSign = request.url; if (isStrPresent(baseURL)) { const requestUrl = new URL(request.url); - const trimmed = (baseURL as string).trim(); + const trimmed = baseURL.trim(); // A scheme-less baseURL ("localhost:6000") mis-parses; borrow the request scheme. const normalized = /^[a-z][a-z0-9+.-]*:\/\//i.test(trimmed) ? trimmed : `${requestUrl.protocol}//${trimmed}`; const baseParsed = new URL(normalized); @@ -76,7 +73,7 @@ export const signEdgeGridRequest = async ( // With variables unresolved (Generate Code, interpolation off) a real signature can't be // produced — it would sign literal `{{var}}` tokens. Emit a placeholder the user replaces // once the request is signed at send time. - if (/\{\{.+?\}\}/.test(authHeader) || /\{\{.+?\}\}/.test(clientSecret as string)) { + if (/\{\{.+?\}\}/.test(authHeader) || /\{\{.+?\}\}/.test(clientSecret)) { return `${authHeader}signature=`; } @@ -85,12 +82,12 @@ export const signEdgeGridRequest = async ( parsedUrl.protocol.replace(':', ''), parsedUrl.host, parsedUrl.pathname + parsedUrl.search, - canonicalizeHeaders(headersToSign as string, request.headers), + canonicalizeHeaders(headersToSign, request.headers), await makeContentHash(request.method, request.bodyText, maxBodySize), authHeader ].join('\t'); - const signingKey = await base64HmacSha256(timestamp, clientSecret as string); + const signingKey = await base64HmacSha256(timestamp, clientSecret); const signature = await base64HmacSha256(dataToSign, signingKey); return `${authHeader}signature=${signature}`; diff --git a/packages/bruno-common/src/utils/edgegrid.ts b/packages/bruno-common/src/utils/edgegrid.ts index ee9e9ddaa46..1ced830bcb7 100644 --- a/packages/bruno-common/src/utils/edgegrid.ts +++ b/packages/bruno-common/src/utils/edgegrid.ts @@ -1,10 +1,8 @@ -import { v4 as uuid } from 'uuid'; - /** * Shared EG1-HMAC-SHA256 primitives, used by both the runtime signer * (packages/bruno-requests/src/auth/edgegrid-helper.js) and the Generate Code signer * (packages/bruno-common/src/generate-code/har/edgegrid.ts) so the signing logic lives in one - * place. Uses the native Web Crypto API (`globalThis.crypto.subtle`) to stay browser-safe and + * place. Uses the native Web Crypto API (`globalThis.crypto`) to stay browser-safe and * dependency-free; Web Crypto is async, so the hashing helpers return Promises. Kept byte-for-byte * compatible with Akamai's reference implementation (github.com/akamai/AkamaiOPEN-edgegrid-node). */ @@ -13,7 +11,9 @@ import { v4 as uuid } from 'uuid'; // tsconfig omits the DOM lib. const subtle = (globalThis as any).crypto.subtle; -const isStrPresent = (str?: string | null): boolean => +export const MAX_BODY_SIZE_DEFAULT = 131072; // 128 KB + +export const isStrPresent = (str?: string | null): str is string => !!str && String(str).trim() !== '' && String(str).trim() !== 'undefined'; const utf8 = (data: string): Uint8Array => new TextEncoder().encode(data); @@ -38,17 +38,17 @@ export const makeEdgeGridTimestamp = (): string => { }; // UUID v4 nonce. -export const makeEdgeGridNonce = (): string => uuid(); +export const makeEdgeGridNonce = (): string => (globalThis as any).crypto.randomUUID(); // `name:value` per signed header (lowercased name, trimmed + whitespace-collapsed value), // tab-joined. Only headers present on the request are emitted, preserving config order. -export const canonicalizeHeaders = (headersToSign?: string, requestHeaders: Record = {}): string => { +export const canonicalizeHeaders = (headersToSign?: string | null, requestHeaders: Record = {}): string => { if (!isStrPresent(headersToSign)) return ''; const lookup: Record = {}; Object.keys(requestHeaders || {}).forEach((name) => { lookup[name.toLowerCase()] = requestHeaders[name]; }); - return (headersToSign as string) + return headersToSign .split(',') .map((name) => name.trim().toLowerCase()) .filter((name) => name.length > 0) @@ -65,7 +65,6 @@ export const makeContentHash = async ( ): Promise => { if (!method || method.toUpperCase() !== 'POST' || !bodyText) return ''; let body = bodyText; - if (body.length === 0) return ''; if (body.length > maxBodySize) body = body.substring(0, maxBodySize); return base64Sha256(body); }; diff --git a/packages/bruno-common/src/utils/index.ts b/packages/bruno-common/src/utils/index.ts index 1423438535e..80afc3b7baa 100644 --- a/packages/bruno-common/src/utils/index.ts +++ b/packages/bruno-common/src/utils/index.ts @@ -44,6 +44,8 @@ export { } from './string'; export { + MAX_BODY_SIZE_DEFAULT, + isStrPresent, makeEdgeGridTimestamp, makeEdgeGridNonce, canonicalizeHeaders, diff --git a/packages/bruno-requests/src/auth/edgegrid-helper.js b/packages/bruno-requests/src/auth/edgegrid-helper.js index a246fde72e8..f5397c0bbf6 100644 --- a/packages/bruno-requests/src/auth/edgegrid-helper.js +++ b/packages/bruno-requests/src/auth/edgegrid-helper.js @@ -1,9 +1,11 @@ import { + MAX_BODY_SIZE_DEFAULT, makeEdgeGridTimestamp, makeEdgeGridNonce, canonicalizeHeaders, base64HmacSha256, - makeContentHash + makeContentHash, + isStrPresent } from '@usebruno/common/utils'; const { URL } = require('node:url'); @@ -17,12 +19,6 @@ const { URL } = require('node:url'); * Spec: https://techdocs.akamai.com/developer/docs/authenticate-with-edgegrid */ -const MAX_BODY_SIZE_DEFAULT = 131072; // 128 KB - -function isStrPresent(str) { - return str && str.trim() !== '' && str.trim() !== 'undefined'; -} - /** * Sign an EdgeGrid request. * @param {Object} config - EdgeGrid configuration From 491beaa71b6b471bb1305e8b7904e6289cad06ae Mon Sep 17 00:00:00 2001 From: shubh-bruno Date: Fri, 17 Jul 2026 17:15:34 +0530 Subject: [PATCH 11/13] fix: handle sensitive env data in akamai --- .../CollectionSettings/Auth/EdgeGridAuth/index.tsx | 11 ++++------- .../src/components/EnvironmentVariablesTable/index.js | 4 ++-- .../EnvironmentVariables/constants.js | 5 ++++- .../RequestPane/Auth/EdgeGridAuth/index.tsx | 11 ++++------- .../src/components/SensitiveFieldWarning/index.js | 4 ++-- 5 files changed, 16 insertions(+), 19 deletions(-) diff --git a/packages/bruno-app/src/components/CollectionSettings/Auth/EdgeGridAuth/index.tsx b/packages/bruno-app/src/components/CollectionSettings/Auth/EdgeGridAuth/index.tsx index 4a573d5700b..f213bb99b92 100644 --- a/packages/bruno-app/src/components/CollectionSettings/Auth/EdgeGridAuth/index.tsx +++ b/packages/bruno-app/src/components/CollectionSettings/Auth/EdgeGridAuth/index.tsx @@ -35,8 +35,8 @@ interface AkamaiEdgeGridAuthProps { } const FIELDS: Array<{ key: EdgeGridField; label: string; tooltip?: string; isSecret?: boolean }> = [ - { key: 'accessToken', label: 'Access Token' }, - { key: 'clientToken', label: 'Client Token' }, + { key: 'accessToken', label: 'Access Token', isSecret: true }, + { key: 'clientToken', label: 'Client Token', isSecret: true }, { key: 'clientSecret', label: 'Client Secret', isSecret: true }, { key: 'baseURL', label: 'Base URL', tooltip: 'Defaults to the request URL if not specified.' }, { @@ -77,9 +77,6 @@ const EdgeGridAuth: React.FC = ({ collection }) => { ? get(collection, 'draft.root.request.auth.akamaiEdgegrid') : get(collection, 'root.request.auth.akamaiEdgegrid')) || {}; const { isSensitive } = useDetectSensitiveField(collection); - const { showWarning: showClientSecretWarning, warningMessage: clientSecretWarningMessage } = isSensitive( - edgeGridAuth?.clientSecret - ); const handleSave = () => dispatch(saveCollectionRoot(collection.uid)); @@ -111,9 +108,9 @@ const EdgeGridAuth: React.FC = ({ collection }) => { }; const renderField = ({ key, label, tooltip, isSecret }: EdgeGridFieldConfig) => { - const showWarning = isSecret && showClientSecretWarning; const rawValue = edgeGridAuth[key]; const fieldValue = rawValue === null || rawValue === undefined ? '' : String(rawValue); + const { showWarning, warningMessage } = isSecret ? isSensitive(rawValue) : { showWarning: false, warningMessage: '' }; return (
diff --git a/packages/bruno-app/src/components/EnvironmentVariablesTable/index.js b/packages/bruno-app/src/components/EnvironmentVariablesTable/index.js index b1276f9c557..7283125ba37 100644 --- a/packages/bruno-app/src/components/EnvironmentVariablesTable/index.js +++ b/packages/bruno-app/src/components/EnvironmentVariablesTable/index.js @@ -85,9 +85,10 @@ const EnvVarValueCell = ({ ) : null} editor={(
handleRowFocus(variable.uid)} > + {renderExtraValueContent && renderExtraValueContent(variable)} - {renderExtraValueContent && renderExtraValueContent(variable)}
)} renderTypeSelector={!isLastEmptyRow diff --git a/packages/bruno-app/src/components/Environments/EnvironmentSettings/EnvironmentList/EnvironmentDetails/EnvironmentVariables/constants.js b/packages/bruno-app/src/components/Environments/EnvironmentSettings/EnvironmentList/EnvironmentDetails/EnvironmentVariables/constants.js index c7dbe0ef5a0..a72b869619e 100644 --- a/packages/bruno-app/src/components/Environments/EnvironmentSettings/EnvironmentList/EnvironmentDetails/EnvironmentVariables/constants.js +++ b/packages/bruno-app/src/components/Environments/EnvironmentSettings/EnvironmentList/EnvironmentDetails/EnvironmentVariables/constants.js @@ -5,7 +5,10 @@ const sensitiveFields = [ 'request.auth.wsse.password', 'request.auth.ntlm.password', 'request.auth.awsv4.secretAccessKey', - 'request.auth.bearer.token' + 'request.auth.bearer.token', + 'request.auth.akamaiEdgegrid.accessToken', + 'request.auth.akamaiEdgegrid.clientToken', + 'request.auth.akamaiEdgegrid.clientSecret' ]; export { sensitiveFields }; diff --git a/packages/bruno-app/src/components/RequestPane/Auth/EdgeGridAuth/index.tsx b/packages/bruno-app/src/components/RequestPane/Auth/EdgeGridAuth/index.tsx index 549ac809ce4..cf65ec51f87 100644 --- a/packages/bruno-app/src/components/RequestPane/Auth/EdgeGridAuth/index.tsx +++ b/packages/bruno-app/src/components/RequestPane/Auth/EdgeGridAuth/index.tsx @@ -39,8 +39,8 @@ interface AkamaiEdgeGridAuthProps { } const FIELDS: Array<{ key: EdgeGridField; label: string; tooltip?: string; isSecret?: boolean }> = [ - { key: 'accessToken', label: 'Access Token' }, - { key: 'clientToken', label: 'Client Token' }, + { key: 'accessToken', label: 'Access Token', isSecret: true }, + { key: 'clientToken', label: 'Client Token', isSecret: true }, { key: 'clientSecret', label: 'Client Secret', isSecret: true }, { key: 'baseURL', label: 'Base URL', tooltip: 'Defaults to the request URL if not specified.' }, { @@ -79,9 +79,6 @@ const EdgeGridAuth: React.FC = ({ item, collection, upd const edgeGridAuth: AkamaiEdgeGridAuthValues = get(request, 'auth.akamaiEdgegrid') || {}; const requestUrl = get(request, 'url', ''); const { isSensitive } = useDetectSensitiveField(collection); - const { showWarning: showClientSecretWarning, warningMessage: clientSecretWarningMessage } = isSensitive( - edgeGridAuth?.clientSecret - ); const handleRun = () => dispatch(sendRequest(item, collection.uid)); @@ -118,9 +115,9 @@ const EdgeGridAuth: React.FC = ({ item, collection, upd }; const renderField = ({ key, label, tooltip, isSecret }: EdgeGridFieldConfig) => { - const showWarning = isSecret && showClientSecretWarning; const rawValue = key === 'baseURL' ? edgeGridAuth.baseURL || requestUrl : edgeGridAuth[key]; const fieldValue = rawValue === null || rawValue === undefined ? '' : String(rawValue); + const { showWarning, warningMessage } = isSecret ? isSensitive(rawValue) : { showWarning: false, warningMessage: '' }; return (
diff --git a/packages/bruno-app/src/components/SensitiveFieldWarning/index.js b/packages/bruno-app/src/components/SensitiveFieldWarning/index.js index bf76eac6d10..bb5ca440102 100644 --- a/packages/bruno-app/src/components/SensitiveFieldWarning/index.js +++ b/packages/bruno-app/src/components/SensitiveFieldWarning/index.js @@ -8,8 +8,8 @@ const SensitiveFieldWarning = ({ fieldName, warningMessage }) => { return ( - - + + Date: Mon, 20 Jul 2026 11:25:58 +0530 Subject: [PATCH 12/13] fix: resolve comments --- .../src/generate-code/har/edgegrid.ts | 30 ++++++++++++------- 1 file changed, 19 insertions(+), 11 deletions(-) diff --git a/packages/bruno-common/src/generate-code/har/edgegrid.ts b/packages/bruno-common/src/generate-code/har/edgegrid.ts index d44eda6597d..a862716a15b 100644 --- a/packages/bruno-common/src/generate-code/har/edgegrid.ts +++ b/packages/bruno-common/src/generate-code/har/edgegrid.ts @@ -17,6 +17,10 @@ import { * Promise. Kept byte-for-byte compatible with Akamai's reference implementation. */ +// buildHar rewrites unresolved `{{var}}` URL tokens to a `bruno-var-hash-*` placeholder +// (packages/bruno-common/src/utils/template-hasher.ts); every other unresolved input stays `{{var}}`. +const UNRESOLVED_INPUT = /\{\{.+?\}\}|bruno-var-hash-/; + export interface AkamaiEdgeGridAuthValues { accessToken?: string; clientToken?: string; @@ -51,6 +55,20 @@ export const signEdgeGridRequest = async ( const nonce = isStrPresent(config.nonce) ? config.nonce : makeEdgeGridNonce(); const timestamp = isStrPresent(config.timestamp) ? config.timestamp : makeEdgeGridTimestamp(); + // The auth header (sans signature) is also the last field of the data-to-sign, per spec. + const authHeader = `EG1-HMAC-SHA256 client_token=${clientToken};access_token=${accessToken};timestamp=${timestamp};nonce=${nonce};`; + const signedHeaders = canonicalizeHeaders(headersToSign, request.headers); + + // A real signature can only be produced when every signed input is fully resolved. Generate Code + // may still carry `{{var}}` (interpolation off, or an undefined var), and buildHar rewrites + // unresolved URL vars to `bruno-var-hash-*` — signing either would cover bytes that differ from + // what's actually sent. Emit a placeholder the user replaces once the request is signed at send time. + const hasUnresolvedInput = [authHeader, clientSecret, baseURL, headersToSign, request.method, request.url, request.bodyText, signedHeaders] + .some((v) => typeof v === 'string' && UNRESOLVED_INPUT.test(v)); + if (hasUnresolvedInput) { + return `${authHeader}signature=`; + } + let parsedUrl: URL; try { let urlToSign = request.url; @@ -67,22 +85,12 @@ export const signEdgeGridRequest = async ( return null; } - // The auth header (sans signature) is also the last field of the data-to-sign, per spec. - const authHeader = `EG1-HMAC-SHA256 client_token=${clientToken};access_token=${accessToken};timestamp=${timestamp};nonce=${nonce};`; - - // With variables unresolved (Generate Code, interpolation off) a real signature can't be - // produced — it would sign literal `{{var}}` tokens. Emit a placeholder the user replaces - // once the request is signed at send time. - if (/\{\{.+?\}\}/.test(authHeader) || /\{\{.+?\}\}/.test(clientSecret)) { - return `${authHeader}signature=`; - } - const dataToSign = [ request.method.toUpperCase(), parsedUrl.protocol.replace(':', ''), parsedUrl.host, parsedUrl.pathname + parsedUrl.search, - canonicalizeHeaders(headersToSign, request.headers), + signedHeaders, await makeContentHash(request.method, request.bodyText, maxBodySize), authHeader ].join('\t'); From 8c30f474ed1e8c56d8989f4516abc808cdc584c7 Mon Sep 17 00:00:00 2001 From: shubh-bruno Date: Mon, 20 Jul 2026 12:34:29 +0530 Subject: [PATCH 13/13] chore: style change --- .../bruno-app/src/components/SensitiveFieldWarning/index.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/bruno-app/src/components/SensitiveFieldWarning/index.js b/packages/bruno-app/src/components/SensitiveFieldWarning/index.js index bb5ca440102..038ce29cd94 100644 --- a/packages/bruno-app/src/components/SensitiveFieldWarning/index.js +++ b/packages/bruno-app/src/components/SensitiveFieldWarning/index.js @@ -8,7 +8,7 @@ const SensitiveFieldWarning = ({ fieldName, warningMessage }) => { return ( - +