@keploy/capture-sdk 3.2.1 → 3.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- {"version":3,"sources":["../../contract/src/privacy.ts","../src/redact.ts","../src/page-stream.ts","../src/body-redact.ts","../package.json"],"names":["decoded","v","includes","replace","ESCAPED","e","decodeURIComponent","nameParts","raw","kind","split","map","n","toLowerCase","filter","isCredentialPart","part","PAGING_CURSORS","has","PAGE_OWN_NAMES","CREDENTIAL_NAMES","CREDENTIAL_CODE_NAMES","CARD_EXPIRY_NAMES","CREDENTIAL_SUFFIX","test","isCredentialName","parts","some","length","join","isCredentialParts","scrubRelative","value","rules","depth","hashAt","indexOf","beforeHash","slice","q","path","query","fragment","out","scrubPath","scrubPairs","scrubFragment","ownValueEnd","form","at","search","parens","squares","braces","i","c","holdsCredentialName","text","k","next","m","matchAll","whole","PAIR_SEPARATOR","pairs","_","ctx","pair","eq","bare","name","plus","decodePart","gone","before","strict","names","pieces","push","pairNames","spaced","own","rest","tail","MAX_NESTING","NESTED_QUERY","NESTED_PAIRS","inner","scrubAbsolute","startsWith","scrubNestedUrl","encodeURIComponent","segments","bases","seg","segment","semi","base","head","route","exec","AUTHORITY","spliceAbsolute","url","URL","hash","pathname","username","password","protocol","host","scheme","slashes","authority","lastIndexOf","scrubUrl","lead","trimStart","trail","trimEnd","scanEnd","start","brackets","list","end","URL_END","NEXT_URL","lastIndex","URL_TRAILER","urlEnd","normalizeKey","key","isTokenExchange","code","peer","longCode","state","EXCHANGE_GRANTS","trim","EXCHANGE_CODES","EXCHANGE_PEERS","isGeneratedState","PLAIN_WORDS","CAMEL_WORDS","isPlainState","isStateSlug","isSensitiveKey","isEmailLocalChar","isLikelyCardNumber","digits","isVisa","isMastercard","isAmex","isDiscover","isJcbDiners","sum","double","d","charCodeAt","passesLuhn","patternRanges","re","into","index","detectorRanges","extra","JWT_RE","KNOWN_TOKEN_RE","kept","floor","Math","max","EMAIL_DOMAIN","domain","emailRanges","SSN_RE","PHONE_RE","IPV4_RE","s","cardRanges","applyRanges","ranges","sort","a","b","pos","with_","REDACTED","scrubTextUrls","BODY_URL_RULES","URL_LINE","line","WHOLE_URL","URL_START_WORD","edits","spans","URL_START","groups","attr","CSS_URL_OPEN","inCssUrl","urlSpans","urlEdits","scrubEscapedUrls","ESCAPED_URL","span","plain","escape","ESCAPED_SLASH_AT","slash","holdsEncodedUrlCredential","formDecode","scrubbed","inPlace","embeddedPairRanges","onlyFlags","node","items","every","redactNode","keyHint","REDACTED_JSON","BARE_CODE_NAMES","endsWith","isBareCodeName","isSettingsValue","WORD_NAMES","isWordName","Number","isInteger","String","integerDigits","redactJsonString","redactStringText","JSON","stringify","item","entries","PAIR_NAMES","card","CARD_FIELDS","exchange","CARD_EXPIRY_BESIDE_A_CARD","EXCHANGE_REDACTED","PAIR_VALUES","redactJsonText","ws","string","run","fromCharCode","parseInt","ESCAPES","MAX_DEPTH","nest","skip","parseJsonSpans","applyEdits","parse","redactBody","body","contentType","NOT_RECORDED","isNotRecordedNote","TRUNCATED_UNPARSEABLE","cut","TRUNCATED_SUFFIX","formHeld","FORM_URL_RULES","asForm","MULTIPART","formSegment","isFormRendering","DECLARED_FORM","last","readAsForm","held","TEXT_URL_RULES","multipart","param","BOUNDARY_PARAM","boundary","delimiter","scanSpan","after","lineEnd","valueStart","headersEnd","valueEnd","headers","PART_NAME","fieldName","jsonPart","PART_FILE","redactMultipartText","UNREADABLE","formShaped","json","escaped","newDecodedText","pairsPossible","PAIR_LEAD","decodedSegments","flatMap","jsonSpans","nameEnd","segEnd","from","appendDecoded","appendUnit","jsonFormValue","spanPairRanges","found","s0","e0","lo","hi","mid","insideSpan","redactFormBody","redactStringValue","truncate","maxSize","hexByte","isNaN","capacity","Int32Array","unit","to","u","appendRaw","marks","cp","fromCodePoint","mode","EMBEDDED_NAME_IN_CODE","EMBEDDED_NAME_IN_STRING","EMBEDDED_NAME_IN_HEADER","EMBEDDED_NAME","scripts","open","close","gt","scriptRanges","r","EMBEDDED_VALUE","EMBEDDED_VALUE_IN_STRING","FORM_NAME","redacted","relayBody","native","rec","reader","say","finished","decoder","TextDecoder","source","pull","getReader","touched","one","read","then","done","reported","decode","byobRequest","respond","chunk","typedArrayTag","Reflect","get","Object","getOwnPropertyDescriptor","getPrototypeOf","Uint8Array","prototype","Symbol","toStringTag","apply","typedArrayName","TypeError","bytesOf","byteLength","stream","setTimeout","enqueue","catch","err","cutText","cancel","reason","Stream","constructor","make","type","highWaterMark","BYTE_SOURCE","redactWithin","patterns","limit","total","cutBodyNote","redactBodies","job","responseLimit","requestBody","requestType","responseBody","responseType","body_redact_exports","__export","version","module","exports","Set","f","t","TAIL_URL_RULES"],"mappings":"aAkDO,SAASA,EAAQC,GACtB,OAAOA,EAAEC,SAAS,KAAOD,EAAEE,QAAQC,EAAUC,GAAMC,mBAAmBD,IAAMJ,CAC9E,CAmPO,SAASM,EAAUC,EAAaC,GACrC,OAAOT,EAAQQ,GACZE,MAAe,QAATD,EAAiB,SAAW,WAClCE,IAAKC,GAAMA,EAAEC,cAAcV,QAAQ,YAAa,KAChDW,OAAQF,GAAY,KAANA,EACnB,CAGO,SAASG,EAAiBC,EAAcP,GAE7C,QADIQ,GAAeC,IAAIF,IACV,SAATP,GAAmBU,GAAeD,IAAIF,MAExCI,GAAiBF,IAAIF,IACrBK,GAAsBH,IAAIF,IAC1BM,GAAkBJ,IAAIF,IACtBO,GAAkBC,KAAKR,GAE3B,CAUO,SAASS,EAAiBjB,EAAaC,GAC5C,OAUK,SACLiB,EACAjB,GAEA,OACEiB,EAAMC,KAAMX,GAASD,EAAiBC,EAAMP,KAC3CiB,EAAME,OAAS,GAAKb,EAAiBW,EAAMG,KAAK,IAAKpB,EAE1D,CAlBSqB,CAAkBvB,EAAUC,EAAKC,GAAOA,EACjD,CAmNA,SAASsB,EAAcC,EAAeC,EAAiBC,GACrD,IAAMC,EAASH,EAAMI,QAAQ,KACvBC,GAA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aR,EACXM,EAAIE,YACJF,EAAIG,YACJH,EAAIL,SACJC,GAEFQ,aAAcV,EACZM,EAAII,aACJJ,EAAIK,aACJL,EAAIL,SACJM,GAGN,C,+HApGAK,EAAA,G,yDAAAC,CAAAD,EAAA,CAAAP,aAAA,IAAAA,EAAAvD,UAAA,IAAAA,EAAAgE,QAAA,IAAAA,KAAAC,OAAAC,S,EAAAJ,E,gNHwCA,IEqBIzC,EFrBE7W,EACJ,4PAkBIgB,GAAwC,IAAI2Y,IAAI,CACpD,WACA,SACA,MACA,SACA,QACA,cACA,eACA,UACA,gBACA,OACA,SACA,eACA,aACA,UACA,YACA,SACA,MACA,uBACA,aACA,aACA,MACA,MACA,MACA,aAIA,QACA,QACA,cACA,QACA,eAOA,SACA,aAEA,YACA,qBAIA,eACA,aACA,YACA,cAIA,QACA,OACA,YACA,YACA,YACA,gBAEA,MAOA,MACA,SACA,OACA,OACA,SACA,iBACA,cACA,OACA,UACA,UACA,YACA,YACA,YACA,aACA,aACA,kBACA,eACA,aACA,eACA,gBACA,kBAGA,kBACA,oBAYW1Y,GAA6C,IAAI0Y,IAAI,CAChE,aACA,iBACA,WACA,oBACA,mBACA,aACA,mBACA,cACA,YACA,UACA,UACA,UACA,WACA,gBACA,UACA,YACA,WACA,UACA,aAIIzY,GAAyC,IAAIyY,IAAI,CACrD,aACA,iBACA,iBACA,qBACA,UACA,cACA,eACA,cACA,QACA,WACA,eACA,YACA,aACA,YACA,mBACA,uBACA,WACA,UACA,cACA,aACA,kBACA,mBAaIxY,GACJ,4KASWN,GAAsC,IAAI8Y,IAAI,CACzD,YACA,gBACA,gBACA,oBACA,cACA,kBACA,YACA,YACA,gBACA,oBACA,wBACA,cACA,YACA,gBACA,gBACA,aACA,YACA,aACA,kBACA,cACA,aACA,gBAWW5Y,GAAsC,IAAI4Y,IAAI,CACzD,OACA,UACA,SACA,MACA,QA8LWhW,GAAiB,0BAsCjBqB,GAAc,EAGrBC,GAAe,6CAOfC,GAAe,mBAoTf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iL,IAAI,CAAC,MAAO,OAAQ,WAE1D3K,GAAmC,IAAI2K,IAAI,CAC/C,QACA,SACA,WACA,WAgJWtJ,GAAmB,iBA0C1BiF,GAAY,+BA+KZT,GACJ,6FAUIH,GACJ,6GAUIC,GACJ,0GAOIC,GACJ,gEAEIQ,GAAiB,yCAQjBC,GAA2B,SAwF3B7C,GAAY,+BAkDZ5B,GACJ,6EAkLIH,GAAY,sCACZU,GACJ,+DAEIU,GACJ,8EAEIG,GAAY,uDAoGZE,GAAa,oBGv6DjBsH,GAAW,QF2EPf,GAAc","sourcesContent":["// SPDX-License-Identifier: Apache-2.0\n//\n// This file alone of @keploy/contract is Apache-2.0, not the package's\n// distribution licence: @keploy/capture-sdk (Apache-2.0) inlines it into\n// its bundle, which runs in every customer's browser. packages/contract/\n// README.md carries the same carve-out, and tools/check-release-ready.mjs\n// refuses an SDK bundle that inlines a source not under a permissive\n// licence (tools/release-sources.mjs).\n\n/**\n * ONE RULE FOR A CREDENTIAL'S NAME, for every place a name is read: a\n * JSON body's key, a form's and a multipart body's field, a `name=value`\n * pair in an HTML, XML, RSC or text body, a query parameter of a request's\n * URL, of a link held in a body, of the page's own URL and of every URL\n * the DOM holds, and of a URL the replay runtime's mock-contract report\n * prints into a CI log.\n *\n * It was six rules in two packages: the SDK's body-key rule, its form\n * rule, its URL rule and its page rule, and the runtime's report list,\n * each with names the others lacked. `?jwt=` was scrubbed from a page's\n * URL and kept in a request's; `{\"email_otp\":\"482913\"}` was kept in a body\n * whose URL scrubbed `?sms_otp=`; a paging cursor was kept in a URL and\n * redacted in the response that handed it out, so a replayed page asked\n * for `?pageToken=%5BREDACTED%5D` and matched nothing; a request a replay\n * missed was printed into the customer's CI log with an `auth_token` in\n * clear (found in review). privacy-names.test.ts holds this rule's table;\n * each consumer's own test holds what it records to it.\n *\n * NO IMPORTS. @keploy/capture-sdk, whose only runtime dependency is\n * rrweb, and @keploy/replay-runtime, whose dist/test.mjs may import only\n * Node builtins, both bundle this module inline; it must pull in nothing.\n */\n\n/**\n * One code point percent-encoded as UTF-8, overlong forms and surrogates\n * excluded: exactly the escape sequences decodeURIComponent decodes, so\n * only those are handed to it and a crafted name costs no exceptions --\n * 15,000 names of `%` threw on every one, 2 s a URL once the parameters\n * were no longer capped (MEASURED).\n */\nconst ESCAPED =\n /%[0-7][\\da-f]|%(?:c[2-9a-f]|d[\\da-f])%[89ab][\\da-f]|%e0%[ab][\\da-f]%[89ab][\\da-f]|%e[1-9a-ce-f](?:%[89ab][\\da-f]){2}|%ed%[89][\\da-f]%[89ab][\\da-f]|%f0%[9ab][\\da-f](?:%[89ab][\\da-f]){2}|%f[1-3](?:%[89ab][\\da-f]){3}|%f4%8[\\da-f](?:%[89ab][\\da-f]){2}/gi;\n\n/**\n * `v` with every escape sequence that spells one code point decoded, as\n * decodeURIComponent decodes it, and every other byte as written: escape\n * by escape, not all or nothing. All or nothing, a string with one\n * malformed escape decoded none, so a text could not be decoded piece by\n * piece (found in review).\n */\nexport function decoded(v: string): string {\n return v.includes(\"%\") ? v.replace(ESCAPED, (e) => decodeURIComponent(e)) : v;\n}\n\n/**\n * The names a credential, a secret or a card's data goes by, read whole\n * (nameParts): what a JSON key, a form field and a query parameter are\n * all redacted under.\n */\nconst CREDENTIAL_NAMES: ReadonlySet<string> = new Set([\n \"password\",\n \"passwd\",\n \"pwd\",\n \"secret\",\n \"token\",\n \"accesstoken\",\n \"refreshtoken\",\n \"idtoken\",\n \"authorization\",\n \"auth\",\n \"apikey\",\n \"clientsecret\",\n \"privatekey\",\n \"session\",\n \"sessionid\",\n \"cookie\",\n \"ssn\",\n \"socialsecuritynumber\",\n \"creditcard\",\n \"cardnumber\",\n \"cvv\",\n \"cvc\",\n \"pin\",\n \"passphrase\",\n // WordPress's new-password pair, Drupal's current-password field,\n // WordPress's reset key, and the PKCE secret an OAuth\n // authorization-code exchange carries.\n \"pass1\",\n \"pass2\",\n \"currentpass\",\n \"rpkey\",\n \"codeverifier\",\n // A freshly minted secret as Keploy's api-server returns it: the\n // createUIIngestKey / createServiceAccountKey / createPersonalAccessToken\n // / createAppCIToken results carry the raw key as `rawKey` (beside a\n // `token` that is only its metadata), and a saved test-run credential\n // is an `APIKeyAuth {Key, Value}`, whose secret is the generic `Value`.\n // The SDK's dashboard-shapes.test.ts holds api-server's schema to this.\n \"rawkey\",\n \"apikeyauth\",\n // Header names a pair can carry.\n \"setcookie\",\n \"proxyauthorization\",\n // SAML's response, WordPress's confirmation key, Supabase's token hash\n // and Clerk's ticket: named here rather than by a `hash` or `ticket`\n // suffix, which would take an app's own `commitHash` or `supportTicket`.\n \"samlresponse\",\n \"confirmkey\",\n \"tokenhash\",\n \"clerkticket\",\n // The names a verification, reset or sign-in link carries its secret\n // under: a nonce, an HMAC, a login hash, a magic link, PHP's session\n // cookie and OAuth 1.0a's verifier.\n \"nonce\",\n \"hmac\",\n \"loginhash\",\n \"magiclink\",\n \"phpsessid\",\n \"oauthverifier\",\n // Azure's SAS signature.\n \"sig\",\n // The names a header carries a credential under, read here too since a\n // request's URL, a form and a body carry them as often: a session id\n // (`sid`, PHP's `sessid`), an anti-forgery token, a bearer, an\n // assertion an OAuth client or a SAML response signs, and the keys and\n // codes a vendor names by their kind (Azure's `subscription-key` is\n // accepted in a query string).\n \"sid\",\n \"sessid\",\n \"csrf\",\n \"xsrf\",\n \"bearer\",\n \"authentication\",\n \"credentials\",\n \"pass\",\n \"tokenid\",\n \"authkey\",\n \"secretkey\",\n \"accesskey\",\n \"clientkey\",\n \"signingkey\",\n \"sessionkey\",\n \"subscriptionkey\",\n \"functionskey\",\n \"factorcode\",\n \"jwtassertion\",\n \"samlassertion\",\n \"clientassertion\",\n // A cloud's temporary credentials as its SDK returns them: AWS STS's\n // `SecretAccessKey` and Alibaba Cloud's `AccessKeySecret`.\n \"secretaccesskey\",\n \"accesskeysecret\",\n]);\n\n/**\n * The names a one-time code goes by: a credential under these names and no\n * other. A bare `code` is not one (`?code=US`, a promo code), and neither\n * is a `zip_code`, a `country_code` or an `error_code`. `oobcode` is\n * Firebase's email-action link code; `linkcode` is SuperTokens' magic link\n * code, read from the page's fragment and posted as `linkCode`. `otp` and\n * `totp` end in `otp`, and CREDENTIAL_SUFFIX reads them with every other\n * name that does (`email_otp`, `sms_otp`).\n */\nexport const CREDENTIAL_CODE_NAMES: ReadonlySet<string> = new Set([\n \"invitecode\",\n \"invitationcode\",\n \"authcode\",\n \"authorizationcode\",\n \"verificationcode\",\n \"verifycode\",\n \"confirmationcode\",\n \"confirmcode\",\n \"resetcode\",\n \"mfacode\",\n \"smscode\",\n \"otpcode\",\n \"totpcode\",\n \"twofactorcode\",\n \"2facode\",\n \"logincode\",\n \"passcode\",\n \"oobcode\",\n \"linkcode\",\n]);\n\n/** A card's expiry by a name that can only be a card's (Stripe's exp_month, ...): cardholder data to PCI. */\nconst CARD_EXPIRY_NAMES: ReadonlySet<string> = new Set([\n \"cardexpiry\",\n \"cardexpiration\",\n \"cardexpirydate\",\n \"cardexpirationdate\",\n \"cardexp\",\n \"cardexpdate\",\n \"cardexpmonth\",\n \"cardexpyear\",\n \"ccexp\",\n \"ccexpiry\",\n \"ccexpiration\",\n \"ccexpdate\",\n \"ccexpmonth\",\n \"ccexpyear\",\n \"creditcardexpiry\",\n \"creditcardexpiration\",\n \"expmonth\",\n \"expyear\",\n \"expirymonth\",\n \"expiryyear\",\n \"expirationmonth\",\n \"expirationyear\",\n]);\n\n/**\n * A name that ends in a credential word: `userPassword`, `x-api-key`,\n * `authToken`, Magic's `magic_credential`, an `x_signature` (S3's\n * `X-Amz-Signature`), an `id_jwt`, an `email_otp`, a `JSESSIONID`. The\n * confirmation fields every sign-up form carries (Rails/Laravel\n * `password_confirmation`, Django `password1`/`password2`) end in a word\n * after `password`; a boolean such as `passwordlessEnabled` does not, and\n * keeps its value. A recorded curl command (api-server's LoginCurl.Curl)\n * carries its Authorization header and its form body: redacted whole.\n */\nconst CREDENTIAL_SUFFIX =\n /(?:password(?:\\d|confirm|confirmation|new|old|repeat|again|verify|retype)?|passwd|secret|token|apikey|privatekey|passphrase|signature|sessionid|jwt|otp|credential|curl)$/;\n\n/**\n * A paging cursor: a name ending in `token` that is no credential but the\n * page of results a request asks for -- a page's to request again, and\n * part of what the request is. A response's `nextPageToken` redacted made\n * a replayed page ask for `?pageToken=%5BREDACTED%5D`, which nothing\n * recorded answers (found in review). Kept under every kind of name.\n */\nexport const PAGING_CURSORS: ReadonlySet<string> = new Set([\n \"pagetoken\",\n \"nextpagetoken\",\n \"prevpagetoken\",\n \"previouspagetoken\",\n \"pagingtoken\",\n \"paginationtoken\",\n \"nexttoken\",\n \"prevtoken\",\n \"previoustoken\",\n \"continuationtoken\",\n \"nextcontinuationtoken\",\n \"cursortoken\",\n \"synctoken\",\n \"nextsynctoken\",\n \"startingtoken\",\n \"starttoken\",\n \"skiptoken\",\n \"deltatoken\",\n \"resumptiontoken\",\n \"scrolltoken\",\n \"aftertoken\",\n \"beforetoken\",\n]);\n\n/**\n * Credential names a page's own URL, and every URL its DOM holds, use as\n * an app's parameter as often -- `?auth=1`, a talk's `?session=`, a map's\n * `?pin=`, a `?sig=` -- and keep by name there, as #36's tests require:\n * the recorded page must be the page visited, and those URLs scrub a\n * value of theirs that looks generated by its shape. Every other place a\n * name is read takes them for the credentials they are.\n */\nexport const PAGE_OWN_NAMES: ReadonlySet<string> = new Set([\n \"auth\",\n \"session\",\n \"cookie\",\n \"pin\",\n \"sig\",\n]);\n\n/**\n * Where a name is read, which decides two things and nothing else:\n * - `key`: a JSON body's key, a HAR-style pair's name, a header's name.\n * Read without splitting at `.`: a dotted JSON key is a flat key\n * (`\"auth.login.title\"` in a translation bundle, `\"token.ttl\"` in a\n * config), and a credential key redacts its whole value, a flag\n * included -- `{\"auth.enabled\":true}` would become a string.\n * - `param`: a form's or a multipart body's field, a text body's\n * `name=value` pair, a query parameter of a request's URL, of a link\n * held in a body or of a URL the runtime's report prints. Read at\n * each `.` part too, as Spring's binder and `qs` with `allowDots`\n * read `user.password`.\n * - `page`: a query parameter of the page's own URL or of a URL the DOM\n * holds, read as `param` is, less PAGE_OWN_NAMES.\n */\nexport type NameKind = \"key\" | \"param\" | \"page\";\n\n/**\n * Every part a name is read under: percent-decoded escape by escape, each\n * `[...]` part (`user[password]`) and, but for a `key`, each `.` part, and\n * each part lower-cased without `-`, `_`, `$` (OData's `$skiptoken`), `+`\n * (a space in a query or a form: `api+key`) and whitespace.\n */\nexport function nameParts(raw: string, kind: NameKind): string[] {\n return decoded(raw)\n .split(kind === \"key\" ? /[[\\]]+/ : /[[\\].]+/)\n .map((n) => n.toLowerCase().replace(/[-_$+\\s]/g, \"\"))\n .filter((n) => n !== \"\");\n}\n\n/** Whether one part of a name, as nameParts reads it, is a credential's. */\nexport function isCredentialPart(part: string, kind: NameKind): boolean {\n if (PAGING_CURSORS.has(part)) return false;\n if (kind === \"page\" && PAGE_OWN_NAMES.has(part)) return false;\n return (\n CREDENTIAL_NAMES.has(part) ||\n CREDENTIAL_CODE_NAMES.has(part) ||\n CARD_EXPIRY_NAMES.has(part) ||\n CREDENTIAL_SUFFIX.test(part)\n );\n}\n\n/**\n * THE RULE: whether a name, as written, is a credential's -- any of its\n * parts (nameParts) is one (isCredentialPart), or, for a name of more\n * than one part, the parts read as one word: `session[id]` is a\n * `sessionid` and `api[key]` an `apikey`, though neither part is a\n * credential's alone (found in review: a token under `?session[id]=` was\n * recorded once brackets were read as parts).\n */\nexport function isCredentialName(raw: string, kind: NameKind): boolean {\n return isCredentialParts(nameParts(raw, kind), kind);\n}\n\n/**\n * THE RULE over a name already split (nameParts): any part is a\n * credential's, or the parts read as one word. What a reader that holds a\n * name's parts asks -- the page's own pair read and its secret collection\n * read a name per part, and `?api[key]=` taught the page-wide scrub no\n * value (found in review).\n */\nexport function isCredentialParts(\n parts: readonly string[],\n kind: NameKind,\n): boolean {\n return (\n parts.some((part) => isCredentialPart(part, kind)) ||\n (parts.length > 1 && isCredentialPart(parts.join(\"\"), kind))\n );\n}\n\n/* ------------------------------------------------------------------ */\n/* ONE URL SCRUBBER */\n/* ------------------------------------------------------------------ */\n/*\n * Every URL the SDK records, and every URL and key the replay runtime\n * prints into a CI log or attaches as evidence, is scrubbed by this\n * walker: a request's URL and every URL its request and response headers\n * carry (Location, Content-Location, Link and Refresh as a request's URL\n * is, any other by a credential's name), a URL anywhere in a request's or a\n * response's body (a JSON string that is one or holds one, an HTML, XML,\n * RSC or text body, a form's or a multipart part's value), the page's own\n * URL and every URL the DOM holds. It was five scrubbers, and only the\n * DOM's read a URL whole: a body's read a query after `?` and never a\n * fragment, a `wss:` or a custom scheme, a request's never a URL nested or\n * encoded in a value nor a path's `;jsessionid=`, and the report never a\n * fragment (found in review). What a URL is made of is read here the same\n * for every URL; what differs is passed in (UrlRules):\n *\n * - `kind`: how a name is read (isCredentialName): `param`, or `page` for\n * the page's own URL and the DOM's, which keep PAGE_OWN_NAMES.\n * - `strict`: every query and fragment-pair value replaced.\n * - `whole`: a URL the replay key reads -- a request's, and one the\n * mock-contract report prints. A pair runs from `&` to `&`, as the key\n * reads one, and a credential anywhere in it -- under a `;name=` inside\n * it, in a URL nested or encoded in its value -- replaces its whole\n * value, so the key holds `[REDACTED]`, which canonical-key.v2 matches\n * any live value against. Otherwise a `;` that a `name=` follows\n * separates pairs too, and only the credential's own value goes, a\n * nested URL scrubbed and written back encoded.\n * - `raw`: a URL a body holds, every byte the scrub does not replace\n * kept (a nested URL written back as it came).\n * - the SDK's value rules for the page's URL and the DOM's, which no\n * other URL takes: a value by its shape or a PII pattern, an OAuth\n * response's code and state, a link page's key, a page credential's\n * cut, a path's JWT or link token. A request's URL is its identity at\n * replay, and a name is what says one of its values is secret.\n */\n\n/** What a value rule is told about the pair it judges. */\nexport interface PairContext {\n /** The path the pair's query or fragment belongs to, a hash route's appended. */\n readonly path: string;\n /** Every pair of that query or fragment, as written. */\n readonly pairs: readonly string[];\n /** How many URLs the pair is nested in. */\n readonly depth: number;\n}\n\n/** How a URL is scrubbed: see the block above. */\nexport interface UrlRules {\n readonly kind: \"param\" | \"page\";\n readonly strict: boolean;\n readonly whole: boolean;\n /**\n * A nested URL written back as it came: raw when it came raw, encoded\n * when it came encoded -- a body's text, where every byte the scrub does\n * not replace is kept. Otherwise (the page's URL, the DOM's) it is\n * written back encoded.\n */\n readonly raw?: boolean;\n /**\n * A credential's own value ends at the first character ownValueEnd\n * stops at (whitespace, `,`, `;`, a quote, a `)` it does not open ...),\n * the text after it kept: a text body's line (`/api/x?token=... 200\n * OK`), a CSV row, a header's list. Otherwise -- a JSON string, a form's\n * value, every URL the page or a request holds -- it runs to the next\n * pair, a space in it the credential's own (`?password=correct horse`),\n * and fails closed (found in review). What follows it in the pair is\n * read by `tail`.\n */\n readonly spaced?: boolean;\n /**\n * In a `spaced` read, a credential's own value ends at its first\n * whitespace alone, and a pair's is replaced even when empty (a path\n * parameter's empty value is kept, as always): a form body's URLs,\n * whose values the form read then takes to the next `&`. Cut at a\n * `,`, a form value's URL was left with a tail that read took for the\n * credential's, and the whole value went (found in review).\n */\n readonly form?: boolean;\n /** The text a credential's own value leaves after it in a pair (`spaced`), read: it can hold a list's next URL. */\n readonly tail?: (text: string) => string;\n /** In a text, a `,` before a URL with a scheme and an authority ends the URL before it (NEXT_URL). */\n readonly list?: boolean;\n /** A pair's replacement value, decided before its name is read, or null. */\n readonly before?: (\n name: string,\n raw: string,\n ctx: PairContext,\n ) => string | null;\n /** Whether a pair's value goes by what it is (its shape, a PII pattern), its name aside. */\n readonly value?: (name: string, raw: string, decoded: string) => boolean;\n /** Whether a bare name (`?<token>`, no `=`) goes, by its shape. */\n readonly bare?: (raw: string) => boolean;\n /** Whether a path segment goes whole, its `;` parameters with it (a JWT). */\n readonly segment?: (segment: string) => boolean;\n /** Whether a path segment's head, its `;` parameters aside, goes (a link's token). */\n readonly head?: (\n path: string,\n base: string,\n index: number,\n bases: readonly string[],\n ) => boolean;\n}\n\n/**\n * Where a query's pair ends and the next starts, outside `whole`: at a\n * `&`, and at a `;` that a `name=` follows -- many servers read\n * `?a=1;token=...` as two pairs. A `;` inside a value (`?q=ada;lovelace`,\n * `?ids=1;2;3`) is the value's: split at every `;`, strict recorded\n * `q=[REDACTED];lovelace`, the rest of what was typed, as a bare name\n * (found in review). Split by it, a query holds its separators at odd\n * indexes. An Android intent's closing `;end` is no value's either:\n * `#Intent;S.token=...;end` lost it with the credential, and the intent\n * no longer parsed (found in review).\n */\nexport const PAIR_SEPARATOR = /(&|;(?=[^;&=#]+=|end$))/;\n\n/**\n * The names one `&` pair carries, as written: its own and each a `;`\n * inside it starts (PAIR_SEPARATOR) -- what `whole` reads a pair by.\n */\nexport function pairNames(pair: string): string[] {\n const names: string[] = [];\n const pieces = pair.split(PAIR_SEPARATOR);\n for (let i = 0; i < pieces.length; i += 2) {\n const eq = pieces[i]!.indexOf(\"=\");\n if (eq > 0) names.push(pieces[i]!.slice(0, eq));\n }\n return names;\n}\n\n/**\n * A query part decoded as a form decodes it, or as it came when an escape\n * is malformed: checked first, because a thrown URIError per pair cost a\n * 256 KB URL of `a=%&` pairs 267 ms on every full snapshot.\n */\nexport function decodePart(raw: string): string {\n const plus = raw.replace(/\\+/g, \" \");\n if (!/%/.test(plus)) return plus;\n if (/%(?![0-9A-Fa-f]{2})/.test(plus)) return raw;\n try {\n return decodeURIComponent(plus);\n } catch {\n return raw;\n }\n}\n\n/**\n * One level of nesting: a URL inside a URL is scrubbed; a URL inside that\n * which carries a query or a fragment of its own (NESTED_QUERY), or pairs\n * of its own (NESTED_PAIRS), is replaced whole, unread -- fail-closed,\n * and a crafted link cannot nest without end.\n */\nexport const MAX_NESTING = 1;\n\n/** A URL value with a query or a fragment after its path. */\nconst NESTED_QUERY = /^(?:[a-z][a-z0-9+.-]*:\\/\\/|\\/)[^?#]*[?#]./i;\n\n/**\n * A value that is no URL but holds a URL's pairs: a query after a second\n * `?` (`?a=1?token=...`), or pairs a `&` or `;` separated before they\n * were encoded (`?a=1%26token%3D...`).\n */\nconst NESTED_PAIRS = /[&;?#][^&;=?#]+=/;\n\n/**\n * A value that is itself a URL -- `?next=https://...`, `?redirect=/welcome?token=...`\n * -- or holds a URL's pairs, scrubbed one level down; null when it is\n * neither.\n */\nfunction scrubNestedUrl(\n value: string,\n rules: UrlRules,\n depth: number,\n): string | null {\n if (/^[a-z][a-z0-9+.-]*:\\/\\//i.test(value))\n return scrubAbsolute(value, rules, depth + 1);\n if (value.startsWith(\"/\")) return scrubRelative(value, rules, depth + 1);\n if (NESTED_PAIRS.test(value))\n return /[?#]/.test(value)\n ? scrubRelative(value, rules, depth + 1)\n : scrubPairs(value, rules, depth + 1);\n return null;\n}\n\n/**\n * A relative URL -- a path, `?query`, `#fragment`, or `//host/...` --\n * scrubbed as an absolute one is, without a base to parse it against:\n * its path, query and fragment found by their delimiters. Returned as it\n * came when nothing in it is scrubbed.\n */\nfunction scrubRelative(value: string, rules: UrlRules, depth: number): string {\n const hashAt = value.indexOf(\"#\");\n const beforeHash = hashAt === -1 ? value : value.slice(0, hashAt);\n const q = beforeHash.indexOf(\"?\");\n const path = q === -1 ? beforeHash : beforeHash.slice(0, q);\n const query = q === -1 ? null : beforeHash.slice(q + 1);\n const fragment = hashAt === -1 ? null : value.slice(hashAt + 1);\n const out =\n scrubPath(path, rules) +\n (query === null ? \"\" : `?${scrubPairs(query, rules, depth, path)}`) +\n (fragment === null\n ? \"\"\n : `#${scrubFragment(fragment, rules, depth, path)}`);\n return out === value ? value : out;\n}\n\n/**\n * Where a credential's own value in a text ends: at whitespace, `,`, `;`,\n * a quote, `<`, `>`, a backslash, a backtick, or a `)`, `]` or `}` it\n * does not open -- `?sig=(abc)` is one value. Ended at whitespace alone, a\n * CSV row's later columns, a `;rest` and CSS's `);color:red}` went with\n * the credential (found in review). In a form (`form`), at whitespace\n * alone.\n */\nfunction ownValueEnd(raw: string, form = false): number {\n if (form) {\n const at = raw.search(/\\s/);\n return at === -1 ? raw.length : at;\n }\n let parens = 0;\n let squares = 0;\n let braces = 0;\n for (let i = 0; i < raw.length; i++) {\n const c = raw[i]!;\n if (/[\\s,;\"'<>\\\\`]/.test(c)) return i;\n if (c === \"(\") parens++;\n else if (c === \"[\") squares++;\n else if (c === \"{\") braces++;\n else if (c === \")\" && parens-- === 0) return i;\n else if (c === \"]\" && squares-- === 0) return i;\n else if (c === \"}\" && braces-- === 0) return i;\n }\n return raw.length;\n}\n\n/** Whether a value, decoded as often as it was encoded (up to four times), names a credential under any of its pairs. */\nexport function holdsCredentialName(value: string, kind: NameKind): boolean {\n // Escape by escape (decoded): all or nothing, one malformed escape\n // (`%25zz`, a lone `%E0`) left every other escape unread and the\n // credential's name with it (found in review).\n let text = value;\n for (let k = 0; k < 4; k++) {\n const next = decoded(text);\n if (next === text) break;\n text = next;\n }\n // A pair's lead, never a path's `/`: a `/name=` segment is a path's\n // (`/dl/api_key=foo bar.txt`), which no read judges (found in review: a\n // file's name went whole).\n for (const m of text.matchAll(/(?:^|[?&;#])([^?&;#=/\\s]+)=/g))\n if (isCredentialName(m[1]!, kind)) return true;\n return false;\n}\n\n/** A query's (or a fragment's) pairs, each scrubbed; its separators kept as they came. */\nfunction scrubPairs(\n query: string,\n rules: UrlRules,\n depth = 0,\n path = \"\",\n): string {\n // Outside `whole`, a `;` separates pairs too, as many servers read one\n // (`?a=1;token=...`), where a `name=` follows it; inside a value\n // (`?q=ada;lovelace`) it is the value's (PAIR_SEPARATOR). The separators\n // are kept as they came.\n const parts = query.split(rules.whole ? /(&)/ : PAIR_SEPARATOR);\n const pairs = parts.filter((_, i) => i % 2 === 0);\n const ctx: PairContext = { path, pairs, depth };\n return pairs\n .map((pair) => {\n const eq = pair.indexOf(\"=\");\n if (eq === -1) {\n return rules.bare?.(pair) === true ? \"[REDACTED]\" : pair;\n }\n const name = pair.slice(0, eq);\n const raw = pair.slice(eq + 1);\n if (raw === \"\") return pair;\n const value = decodePart(raw);\n // Replaced whole: a value that holds a credential somewhere in it\n // (a deep URL, one encoded twice or in part) can hold it after a\n // space as well as before (found in review: it was kept in clear).\n const gone = (): string => `${name}=[REDACTED]`;\n const before = rules.before?.(name, raw, ctx) ?? null;\n if (before !== null) return `${name}=${before}`;\n if (\n rules.strict ||\n (rules.whole ? pairNames(pair) : [name]).some((n) =>\n isCredentialName(n, rules.kind),\n ) ||\n rules.value?.(name, raw, value) === true\n ) {\n if (rules.spaced !== true) return gone();\n // In a text an own value that is empty is an empty value, kept, as\n // a path parameter's is (`?sig=,1`), and what follows it is read\n // all the same (`?token=,https://b/...`, found in review); a\n // form's is replaced, as it always was.\n const own = ownValueEnd(raw, rules.form);\n const rest = raw.slice(own);\n return `${name}=${own === 0 && !rules.form ? \"\" : \"[REDACTED]\"}${rules.tail?.(rest) ?? rest}`;\n }\n if (\n depth >= MAX_NESTING &&\n (NESTED_QUERY.test(value) || NESTED_PAIRS.test(value))\n )\n // Past one level the page's URL and the DOM's replace such a value\n // unread: no key is computed from them. A request's URL, the\n // report's and a body's -- a link the page requests next -- lose\n // it only for a credential's name in it, at any depth: replaced\n // unread, a value with none changed the request's key, or the\n // link's, which then no recorded request matched (found in review).\n return rules.kind === \"page\" || holdsCredentialName(value, rules.kind)\n ? gone()\n : pair;\n const inner = scrubNestedUrl(value, rules, depth);\n if (inner !== null && inner !== value) {\n // A request's key reads the pair whole: a value redacted in part\n // is one no key matches a live one against.\n if (rules.whole) return gone();\n if (rules.raw !== true) return `${name}=${encodeURIComponent(inner)}`;\n // A body's bytes are the server's: a nested URL is written back as\n // it came -- raw, or encoded as encodeURIComponent encodes it --\n // and one encoded any other way (`/reset%3Ftoken=...`) cannot be,\n // so its value goes whole (found in review: it was re-encoded).\n if (raw === value) return `${name}=${inner}`;\n return encodeURIComponent(value) === raw\n ? `${name}=${encodeURIComponent(inner)}`\n : gone();\n }\n // A value encoded more than once -- a redirect chain's hop,\n // `?redirect=https%253A%252F%252F...%253Fjwt%253D...`, or a path whose\n // `?` is still encoded once decoded, `?next=%2Freset%253Ftoken%253D...`\n // -- holds a URL no read above sees, though the nested read found a\n // URL in it: its whole value goes when a credential's name is in it,\n // decoded as often as it was encoded (found in review: one the nested\n // read returned unchanged was kept).\n if (decoded(value) !== value && holdsCredentialName(value, rules.kind))\n return gone();\n return pair;\n })\n .map((pair, i) => (i === 0 ? \"\" : parts[2 * i - 1]) + pair)\n .join(\"\");\n}\n\n/**\n * A path: a segment the rules take whole (a JWT) is replaced, a `;name=`\n * path parameter (Java's `;jsessionid=`) has a credential's value\n * replaced, and a segment's head the rules name (a link's token) is\n * replaced. Nothing else in a\n * path is judged: slugs, digests and file names are where a flow's pages\n * come from.\n */\nfunction scrubPath(path: string, rules: UrlRules): string {\n const segments = path.split(\"/\");\n const bases = segments.map((seg) => seg.split(\";\")[0]!);\n return segments\n .map((seg, i) => {\n if (rules.segment?.(seg) === true) return \"[REDACTED]\";\n const semi = seg.indexOf(\";\");\n const base = bases[i]!;\n const head =\n rules.head?.(path, base, i, bases) === true ? \"[REDACTED]\" : base;\n if (semi === -1) return head;\n return (\n head +\n seg.slice(semi).replace(\n /;([^;=]+)=([^;]*)/g,\n // An empty value is kept, as a query's is: there is nothing to\n // redact, and `\"/x;jsessionid=\" + id` in a script is code that\n // builds one (found in review: it became `=[REDACTED]\" + id`).\n // In a text, the value is its own only (ownValueEnd).\n (m: string, n: string, v: string) => {\n const own =\n rules.spaced === true ? ownValueEnd(v, rules.form) : v.length;\n return own > 0 && isCredentialName(n, rules.kind)\n ? `;${n}=[REDACTED]${v.slice(own)}`\n : m;\n },\n )\n );\n })\n .join(\"/\");\n}\n\n/**\n * A fragment: a hash router's route keeps its path and has its own query\n * scrubbed -- `#/cb?code=...`, and `#/cb&access_token=...`, whose pairs\n * start after the route's first `&` or `;`; a fragment of pairs -- an\n * OAuth implicit grant's `#access_token=...&state=...` -- is scrubbed as a\n * query is. Anything else is read as a path, where no `name=` segment is\n * judged (`#/docs/v=2`, `#!/access_token=...` alike).\n */\nfunction scrubFragment(\n fragment: string,\n rules: UrlRules,\n depth: number,\n path = \"\",\n): string {\n // `depth` rides through, or every `#n=<url>` started the nesting count\n // again and a crafted link recursed until the stack overflowed (review).\n const q = fragment.indexOf(\"?\");\n if (q !== -1) {\n const route = fragment.slice(0, q);\n return `${scrubPath(route, rules)}?${scrubPairs(fragment.slice(q + 1), rules, depth, `${path}/${route}`)}`;\n }\n const eq = fragment.indexOf(\"=\");\n if (eq !== -1 && !fragment.slice(0, eq).includes(\"/\")) {\n return scrubPairs(fragment, rules, depth, path);\n }\n // A route whose pairs follow a `&` or a `;`: `#/cb&access_token=...`,\n // `#/cb/v=1&access_token=...` (an `=` in the route before them, found in\n // review). One with an `=` in its path and no such separator is a route\n // alone (`#/docs/v=2`), as #36's tests require.\n const route = eq === -1 ? null : /^([^&;]*)([&;])/.exec(fragment);\n if (route !== null)\n return `${scrubPath(route[1]!, rules)}${route[2]}${scrubPairs(fragment.slice(route[0].length), rules, depth, `${path}/${route[1]}`)}`;\n return scrubPath(fragment, rules);\n}\n\n/**\n * An absolute URL. The page's URL and the DOM's, with an authority\n * (`https:`, `wss:`, `myapp://`), are parsed as the browser parses them\n * and rebuilt from their parts only when something in them is scrubbed:\n * user info dropped, scheme and host kept as the parser serialises them.\n * Every other URL is spliced (spliceAbsolute). Returned as it came when\n * nothing in it is scrubbed.\n */\nfunction scrubAbsolute(raw: string, rules: UrlRules, depth: number): string {\n // A URL the page's URL rule or the DOM's reads is rebuilt as the browser\n // serialises it, as #36's tests pin. Every other URL -- a request's, one\n // a body holds, one the report prints -- keeps its bytes, and so does one\n // with no authority (`urn:`, `com.example.app:/oauth2redirect`) or one\n // the parser refuses (`https://%HOST%/x`): spliced, never returned\n // unread (found in review: each was recorded or printed as it came).\n if (rules.whole || rules.raw === true || !AUTHORITY.test(raw))\n return spliceAbsolute(raw, rules, depth);\n let url: URL;\n try {\n url = new URL(raw);\n } catch {\n return spliceAbsolute(raw, rules, depth);\n }\n const search = url.search.slice(1);\n const hash = url.hash.slice(1);\n const path = scrubPath(url.pathname, rules);\n const query = url.search\n ? scrubPairs(search, rules, depth, url.pathname)\n : \"\";\n const fragment = url.hash\n ? scrubFragment(hash, rules, depth, url.pathname)\n : \"\";\n // Nothing to scrub: the URL exactly as it came -- a trailing `?` or `#`\n // included, which a rebuild from its parts drops.\n if (\n path === url.pathname &&\n query === search &&\n fragment === hash &&\n url.username === \"\" &&\n url.password === \"\"\n ) {\n return raw;\n }\n return (\n `${url.protocol}//${url.host}` +\n path +\n (url.search ? `?${query}` : \"\") +\n (url.hash ? `#${fragment}` : \"\")\n );\n}\n\n/** A scheme a browser reads an authority after: `https:`, `https:/host`, `wss://`, `myapp://`. */\nconst AUTHORITY = /^(?:https?:|[a-z][a-z0-9+.-]*:[/\\\\]{2})/i;\n\n/**\n * An absolute URL scrubbed by its delimiters, every byte the scrub does not\n * replace kept: its scheme, the authority after it (its user info\n * dropped), then its path, query and fragment (scrubRelative).\n */\nfunction spliceAbsolute(raw: string, rules: UrlRules, depth: number): string {\n const head = /^([a-z][a-z0-9+.-]*:)([/\\\\]*)([^/\\\\?#]*)/i.exec(raw)!;\n const [whole, scheme, slashes, authority] = head as unknown as [\n string,\n string,\n string,\n string,\n ];\n const at = slashes === \"\" ? -1 : authority.lastIndexOf(\"@\");\n const out =\n scheme +\n slashes +\n authority.slice(at + 1) +\n scrubRelative(raw.slice(whole.length), rules, depth);\n return out === raw ? raw : out;\n}\n\n/**\n * THE SCRUBBER: one URL as it may be recorded or printed, by `rules`. A\n * URL with a scheme is absolute (scrubAbsolute) -- `https:`, `wss:`,\n * `myapp://`, and one with no authority (`mailto:`, `urn:`,\n * `com.example.app:/oauth2redirect?code=...`) alike -- but for a script's\n * or an inline object's (`javascript:`, `vbscript:`, `data:`, `blob:`),\n * which holds no URL's parts and is kept; anything else is a relative\n * URL, read by its delimiters. Byte for byte as it came when nothing in it\n * is a credential's.\n */\nexport function scrubUrl(value: string, rules: UrlRules): string {\n const lead = value.length - value.trimStart().length;\n const trail = value.length - value.trimEnd().length;\n const url = value.slice(lead, value.length - trail);\n let out: string;\n if (/^(?:javascript|vbscript|data|blob):/i.test(url)) return value;\n if (/^[a-z][a-z0-9+.-]*:/i.test(url)) out = scrubAbsolute(url, rules, 0);\n else out = scrubRelative(url, rules, 0);\n return out === url\n ? value\n : value.slice(0, lead) + out + value.slice(value.length - trail);\n}\n\n/**\n * Where a URL starts in a text -- an HTML, XML, RSC or text body, a JSON\n * string, a form's or a multipart part's value: a scheme with an\n * authority (`https://`, `wss://`, `myapp://`), whatever comes before it\n * (`--https://...`); any value a link's attribute holds, quoted or not\n * (`href=cb#...`); a URL any other attribute holds quoted that a path, a\n * query or a fragment starts, or a scheme as a line's start takes one (a\n * `/` after it, a `.` or `+` in its name, `localhost` and its port, a\n * scheme with no authority) (`data-next=\"/x?next=...\"`, found in review: an attribute\n * off the list kept its link) -- never another quoted value, which is a style or a script's string as often\n * (`style=\"background:url(...)\"`, whose property read as a scheme took\n * the declarations after the URL, found in review), and never an\n * unquoted `name=` in a text, which is code or a pair\n * (`x=y?1:2;token=...`); a meta refresh's `url=`\n * (`content=\"0; url=/x?...\"`, read forward from `content`); and a CSS\n * `url(`. A scheme is at most 32 characters and a name 40, and a name is\n * read from its start, so a start is read at most that far: unbounded, a\n * scheme read from each position of a run of letters cost the square of\n * the run, and so did an attribute read back over a run of spaces (2 s\n * for 64 KB, found in review), and a meta refresh's read back from each\n * `url` (17 s for 256 KB of spaces, found in review). No alternative\n * reads back further than a character, and none has two runs of spaces\n * back to back: `content=` and spaces with no quote between was read\n * once for each place one run could end (found in review).\n */\nconst URL_START =\n /[a-z][a-z0-9+.-]{0,31}:[/\\\\]{2}|(?<attr>\\bcontent\\s*=\\s*(?:[\"']\\s*)?\\d[\\d.]*\\s*[;,]\\s*url\\s*=\\s*[\"']?|\\b(?:href|src|action|formaction|poster|cite|data|background|longdesc|content|data-src|data-href|xlink:href)\\s*=\\s*[\"']?|(?<![\\w:.-])[\\w:.-]{1,40}\\s*=\\s*[\"'](?=\\.{0,2}\\/|[?#]|[a-z][a-z0-9+.-]{0,31}:\\/|[a-z][a-z0-9-]{0,30}[+.][a-z0-9+.-]{0,30}:|localhost:\\d{1,5}[/?#]|(?:mailto|tel|sms|urn|data|javascript|vbscript|blob|about|xmpp|sip|sips|magnet|intent|bitcoin|geo|market|news):)|\\burl\\(\\s*[\"']?)(?=[^\\s\"'<>])/gi;\n\n/** What ends a URL in a text: a space, a quote, a tag, a backslash, a backtick, a brace or a pipe. */\nconst URL_END = /[\\s\"'<>\\\\^`{|}]/;\n\n/** What prose puts after a URL that is no part of it. */\nconst URL_TRAILER = \".,;:!?\";\n\n/**\n * A URL with a scheme and an authority, at `lastIndex`. In a text read\n * for its list (UrlRules' `list`: what a credential's own value leaves\n * after it), a `,` before one ends the URL before it, so each URL of the\n * list is its own (`?token=...,https://b/y?next=...`). A list a query\n * holds elsewhere is the query's value (`?list=https://a,https://b&...`).\n */\nconst NEXT_URL = /[a-z][a-z0-9+.-]{0,31}:\\/\\//iy;\n\n/**\n * Where the URL in `text`'s [start, end) ends, what prose puts after it\n * set aside: a full stop, a comma, and a `)` or `]` at its end the URL\n * does not open -- `(see https://...)` -- but not one it does\n * (`?sig=(...)`, an IPv6 host's `http://[::1]`): stripped, a value's own\n * `)` was left after its marker (found in review). Read once from each\n * end, never as a regex from each position (the square of a run of full\n * stops). What the print sink reads a URL by: a `)` inside a printed key\n * (`?q=:)&token=...`) is the key's.\n */\nexport function urlEnd(text: string, start: number, end: number): number {\n let parens = 0;\n let brackets = 0;\n for (let i = start; i < end; i++) {\n const c = text[i];\n if (c === \"(\") parens++;\n else if (c === \")\") parens--;\n else if (c === \"[\") brackets++;\n else if (c === \"]\") brackets--;\n }\n while (end > start) {\n const c = text[end - 1]!;\n if (c === \")\") {\n if (parens >= 0) break;\n parens++;\n } else if (c === \"]\") {\n if (brackets >= 0) break;\n brackets++;\n } else if (!URL_TRAILER.includes(c)) break;\n end--;\n }\n return end;\n}\n\n/**\n * Where a URL the scan finds at `start` ends: at the first character that\n * ends a URL in a text (URL_END); outside a quoted attribute, also at the\n * first `)` or `]` it does not open -- CSS's\n * `url(https://...?sig=...);color:red`, prose's `(see https://...)` --\n * but not at one it does (`?sig=(...)`, `http://[::1]`); and before what\n * prose puts after it. Read to the next space and stripped at the end\n * only, a CSS declaration after the URL was the URL's, and a credential's\n * value took the `)` and the declarations with it (found in review). A\n * quoted attribute's value ends at its quote, its `)` its own\n * (`href=\"...?q=:)&next=...\"`). One pass forward, one back.\n */\nfunction scanEnd(\n text: string,\n start: number,\n brackets: boolean,\n list: boolean,\n): number {\n let end = start;\n let parens = 0;\n let squares = 0;\n for (; end < text.length; end++) {\n const c = text[end]!;\n if (URL_END.test(c)) break;\n if (list && c === \",\") {\n NEXT_URL.lastIndex = end + 1;\n if (NEXT_URL.test(text)) break;\n }\n if (!brackets) continue;\n if (c === \"(\") parens++;\n else if (c === \"[\") squares++;\n else if (c === \")\" || c === \"]\") {\n if ((c === \")\" ? parens : squares) === 0) break;\n if (c === \")\") parens--;\n else squares--;\n }\n }\n return urlEnd(text, start, end);\n}\n\n/** CSS's `url(` and its quote, at an attribute's value. */\nconst CSS_URL_OPEN = /url\\(\\s*[\"']?/iy;\n\n/** Every URL in `text`, as [start, end) spans, in order; in a text's `list`, a `,` before a URL ends the one before it (NEXT_URL). */\nexport function urlSpans(text: string, list = false): Array<[number, number]> {\n const spans: Array<[number, number]> = [];\n URL_START.lastIndex = 0;\n for (let m = URL_START.exec(text); m !== null; m = URL_START.exec(text)) {\n // A scheme's match is the URL's start; an attribute's or a `url(`'s\n // ends where the URL starts.\n let start = m.index + (m.groups?.[\"attr\"]?.length ?? 0);\n // An attribute's value that is CSS's `url(...)` holds the URL: read\n // from the attribute, the `url(` opened a `(` and the URL took its\n // `)` (`background=\"url(/x?next=...) no-repeat\"`, found in review).\n CSS_URL_OPEN.lastIndex = start;\n const inCssUrl =\n m.groups?.[\"attr\"] !== undefined && CSS_URL_OPEN.test(text);\n if (inCssUrl) start = CSS_URL_OPEN.lastIndex;\n // Read once, to the URL's end: read to the next space first and cut\n // at a `)` after, a run of CSS's `url(...);` was read to its end from\n // each `url(` (2.9 s for 64 KB, found in review). A quoted listed\n // attribute's value, but for a `url(` in it, ends at its quote alone.\n const attr = m.groups?.[\"attr\"] ?? \"\";\n let end = scanEnd(\n text,\n start,\n !/[\"']$/.test(attr) || /^url\\(/i.test(attr) || inCssUrl,\n list,\n );\n // A template literal's `${` starts code, not a value: read as one,\n // `https://x/cb?token=${t}` became `token=[REDACTED]{t}` (found in\n // review).\n if (text[end] === \"{\" && end > start && text[end - 1] === \"$\") end--;\n if (end > start) spans.push([start, end]);\n URL_START.lastIndex = Math.max(end, m.index + m[0].length, start + 1);\n }\n return spans;\n}\n\n/** Each URL in `text` scrubbed by `rules`, as [start, end, replacement] edits for those that changed. */\nexport function urlEdits(\n text: string,\n rules: UrlRules,\n): Array<[number, number, string]> {\n const edits: Array<[number, number, string]> = [];\n for (const [start, end] of urlSpans(text, rules.list === true)) {\n const url = text.slice(start, end);\n const out = scrubUrl(url, rules);\n if (out !== url) edits.push([start, end, out]);\n }\n return edits;\n}\n\n/**\n * A URL read as the replay key reads one (`whole`) under a `param`'s\n * names: what a request's URL and a URL the report prints are scrubbed\n * by, `strict` as asked.\n */\nexport function keyRules(strict: boolean): UrlRules {\n return { kind: \"param\", strict, whole: true };\n}\n\n/**\n * A BODY THE CAPTURE SDK RECORDED CUT, AND SAYS SO.\n *\n * The SDK redacts a body off the page's main thread, in a Web Worker\n * (@keploy/capture-sdk's body-worker.js). Where the page cannot run one\n * -- its CSP refuses the worker's script, the bundler did not emit it,\n * the platform has no Worker -- a body over the SDK's main-thread budget\n * (64 KiB) is not redacted whole on the page's thread: only its first\n * part is, and the rest is dropped. The same holds for a body still in\n * the worker when the page leaves, past what the page's last moment can\n * redact. That body is NOT the response the server sent, so the record\n * carries this note as its first line, naming how much of it is kept\n * (0 when nothing could be redacted in time) and how long it was, and\n * the redacted part follows it.\n *\n * Replay never serves such a body as if it were whole (mock-replay.v7\n * rules.cut): a test that reaches it cannot be proven by it.\n */\nexport function cutBodyNote(kept: number, total: number): string {\n return `[Body cut: ${kept} of ${total} characters kept, unverified]\\n`;\n}\n\n/** True for a body recorded with {@link cutBodyNote}'s first line. */\nexport function isCutBody(body: unknown): boolean {\n return (\n typeof body === \"string\" &&\n /^\\[Body cut: \\d+ of \\d+ characters kept, unverified\\]\\n/.test(body)\n );\n}\n\n/**\n * WHY THE CAPTURE SDK DID NOT CAPTURE A BODY: the reason line a body\n * recorded as {@link notCapturedBodyNote} carries, one per cause, and no\n * other. The SDK records a body only redacted, and the code it redacts\n * one with on the page's main thread is a chunk it asks for at init(),\n * beside rrweb.\n * - `left`: the page left, or the capture stopped, while that chunk was\n * still on its way. A moment after which nothing more is recorded\n * (pagehide, stop()'s bound) cannot wait for it.\n * - `code-failed`: the chunk could not load at all (a CSP that refuses\n * it, a 404 after a deploy, a module without its exports), so the page\n * has no code to redact a body with on its main thread for the rest of\n * its life (KUI_E_BODY_WORKER_UNAVAILABLE names the page's first\n * failed part, once).\n * - `early`: the page took the body's stream (`res.body`) before that\n * chunk, which holds the SDK's stream relay, had loaded (still on its\n * way, or held by the page's leave), and nothing read the body whole.\n * The page got the network's own stream at once, never waiting for the\n * chunk, so the SDK saw none of what it read: it may have read all of\n * it, or only looked.\n */\nexport const NOT_CAPTURED_WHY = {\n left: \"the page left or the capture stopped before redaction was ready\",\n \"code-failed\": \"the redaction code could not load\",\n early: \"the page took the body's stream before the redaction code had loaded\",\n} as const;\n\n/** A cause of a body recorded as {@link notCapturedBodyNote}. */\nexport type NotCapturedWhy = keyof typeof NOT_CAPTURED_WHY;\n\n/**\n * A BODY THE CAPTURE SDK DID NOT CAPTURE, AND SAYS WHY: these two lines\n * and nothing else, never the body in the clear. {@link cutBodyNote}\n * with nothing kept, then `[Body not captured: <why>]`, `<why>` being\n * {@link NOT_CAPTURED_WHY}'s line for its cause:\n *\n * [Body cut: 0 of N characters kept, unverified]\n * [Body not captured: the page left or the capture stopped before redaction was ready]\n *\n * [Body cut: 0 of N characters kept, unverified]\n * [Body not captured: the redaction code could not load]\n *\n * [Body cut: 0 of N characters kept, unverified]\n * [Body not captured: the page took the body's stream before the redaction code had loaded]\n *\n * The first line is a cut note, so replay never serves it (mock-replay.v7\n * rules.cut) and a test that reaches it is unproven, as for any cut body.\n * The second, which no other body the SDK records has after its note,\n * tells it apart from a body cut at the main thread's budget, and says\n * why (isNotCapturedBody), for a dashboard or a report.\n */\nexport function notCapturedBodyNote(\n total: number,\n why: NotCapturedWhy,\n): string {\n return `${cutBodyNote(0, total)}[Body not captured: ${NOT_CAPTURED_WHY[why]}]\\n`;\n}\n\n/**\n * True for a body recorded as {@link notCapturedBodyNote}, exactly: for\n * the cause `why` when given, else for any cause it documents. A second\n * line naming no documented cause is not one.\n */\nexport function isNotCapturedBody(\n body: unknown,\n why?: NotCapturedWhy,\n): boolean {\n const said =\n typeof body === \"string\" &&\n /^\\[Body cut: 0 of \\d+ characters kept, unverified\\]\\n\\[Body not captured: ([^\\]\\n]*)\\]\\n$/.exec(\n body,\n )?.[1];\n return said\n ? why === undefined\n ? Object.values<string>(NOT_CAPTURED_WHY).includes(said)\n : said === NOT_CAPTURED_WHY[why]\n : false;\n}\n","/* ------------------------------------------------------------------ */\n/* Structural redaction */\n/* ------------------------------------------------------------------ */\n/*\n * Replaces the regex-over-the-whole-body approach, which was a\n * correctness bug rather than a privacy nit:\n *\n * - `/\\b(?:\\d[ -]*?){13,19}\\b/g` matched every 13-digit Date.now(),\n * every snowflake id and every long numeric id.\n * - Replacing inside a serialized JSON number produced INVALID JSON:\n * {\"ts\":1699999999999} became {\"ts\":[REDACTED]}, which no longer\n * parses.\n *\n * The failure mode was especially bad because it looked like a pass: the\n * corruption also destroyed the timestamp nondeterminism it had just\n * created, so a diff of two corrupted captures could still match.\n *\n * Three rules make this deterministic and type-preserving:\n * 1. Parse first. Walk the structure, never the serialization.\n * 2. Only STRING values are scanned. A JSON number is never PII in\n * practice, and scanning numbers is what corrupted timestamps.\n * 3. Redaction is type-preserving and stable: a redacted string stays\n * a string, and the same input always produces the same output, so\n * two recordings of the same logical response stay comparable.\n */\n\nimport {\n decoded,\n holdsCredentialName,\n isCredentialName,\n nameParts,\n scrubUrl,\n urlEdits,\n type UrlRules,\n} from \"@keploy/contract/privacy\";\n\nconst REDACTED = \"[REDACTED]\";\n\n/**\n * Names that are a card's expiry only beside a card field: `expiry` on\n * a token or `expirationDate` on a cookie is a date the page needs back.\n */\nconst CARD_EXPIRY_BESIDE_A_CARD: ReadonlySet<string> = new Set([\n \"expiry\",\n \"expirydate\",\n \"expiration\",\n \"expirationdate\",\n \"expdate\",\n \"exp\",\n]);\n\n/** A field that makes the object it is in a card. */\nconst CARD_FIELDS: ReadonlySet<string> = new Set([\n \"cardnumber\",\n \"creditcard\",\n \"creditcardnumber\",\n \"ccnumber\",\n \"cardnum\",\n \"pan\",\n \"cvv\",\n \"cvc\",\n]);\n\n/** Emitted for a JSON-shaped body that cannot be parsed (usually truncated). */\nexport const TRUNCATED_UNPARSEABLE = \"[UNPARSEABLE_BODY_NOT_REDACTED]\";\n\n/**\n * The notes network.ts writes in place of a body it did not read: a\n * Blob on the XHR path or one over the cap on the fetch path, a buffer\n * over the cap or one that is not UTF-8, a response whose\n * Content-Length is over it, a stream it must not consume, a shape\n * with no name, an XHR responseType it cannot read as text.\n *\n * They are the SDK's own words, not the page's data, and they carry the\n * only record of what the body WAS and how large. They are also not\n * JSON — so under a JSON content-type they went through JSON.parse,\n * failed, and were replaced with the generic refusal below, losing the\n * kind and the size. The docs page records that as a defect: \"with no\n * record of what they were or how large\".\n *\n * Matched whole, anchored, and only for shapes with no free text in\n * them, so a page body that happened to equal one of these would skip\n * redaction — and there would be nothing in it to redact, because the\n * whole body would be that fixed string.\n */\nconst NOT_RECORDED = [\n /^\\[Blob: \\d+ bytes, truncated\\]$/,\n // The XHR path's Blob, which is named rather than read: its body has\n // to be serialised inside send(), and Blob.text() is async.\n /^\\[Blob: \\d+ bytes\\]$/,\n /^\\[Binary: \\d+ bytes\\]$/,\n /^\\[Response body too large: \\d+ bytes\\]$/,\n // A response body the page never read, nor the SDK (network.ts NOT_READ).\n /^\\[Response body not read by the page\\]$/,\n /^\\[ReadableStream\\]$/,\n /^\\[Unreadable body\\]$/,\n // `[${xhr.responseType} response]` — the XMLHttpRequestResponseType\n // enum: \"\", arraybuffer, blob, document, json, text.\n /^\\[(?:arraybuffer|blob|document|json|text|) response\\]$/,\n];\n\n/** True for a body that IS one of the SDK's own not-recorded notes. */\nexport function isNotRecordedNote(body: string): boolean {\n return NOT_RECORDED.some((re) => re.test(body));\n}\n\n/**\n * A key as the one rule reads a name (@keploy/contract's privacy.ts\n * nameParts), its parts joined: what a rule about a key's context -- a\n * card's fields, a token exchange's -- compares, so no name is read two\n * ways.\n */\nfunction normalizeKey(key: string): string {\n return nameParts(key, \"key\").join(\"\");\n}\n\n/** A plain word, or words joined by `-` or `_`: an app's filter, not an OAuth state. */\nconst PLAIN_WORDS = /^[A-Za-z]+(?:[-_][A-Za-z]+)*$/;\n/** camelCase words: an app's `state=inProgress` (#36's review). */\nconst CAMEL_WORDS = /^[A-Za-z][a-z]+(?:[A-Z][a-z]+)+$/;\n\n/**\n * Whether a state is an app's word rather than OAuth's generated value:\n * letters, or words joined by `-` or `_`, of at most 16 characters --\n * `delivered`, `California`, `in-progress` -- or longer camelCase or\n * joined words. A random run of letters past 16 is not one (review).\n */\nexport function isPlainState(state: string): boolean {\n if (!PLAIN_WORDS.test(state)) return false;\n return (\n state.length <= 16 ||\n CAMEL_WORDS.test(state) ||\n /^[A-Za-z][a-z]+(?:[-_][A-Za-z][a-z]+)+$/.test(state)\n );\n}\n\n/** The grants a token exchange redeems a code for: an authorization code's, and a device flow's (RFC 8628). */\nconst EXCHANGE_GRANTS: ReadonlySet<string> = new Set([\n \"authorization_code\",\n \"urn:ietf:params:oauth:grant-type:device_code\",\n]);\n\n/** The names, normalized, a token exchange carries its code under. */\nconst EXCHANGE_CODES: ReadonlySet<string> = new Set([\"code\", \"devicecode\"]);\n\n/** The names, normalized, an exchange's values are redacted under: its code, and the state beside it. */\nconst EXCHANGE_REDACTED: ReadonlySet<string> = new Set([\n ...EXCHANGE_CODES,\n \"state\",\n]);\n\n/** The names, normalized, an exchange's code is sent or handed out beside. */\nconst EXCHANGE_PEERS: ReadonlySet<string> = new Set([\n \"redirecturi\",\n \"clientid\",\n \"verificationuri\",\n]);\n\n/**\n * Whether a body's names and values are an OAuth token exchange's: a\n * page that finishes an OAuth flow itself (a SPA with PKCE, a backend for\n * the frontend) posts the authorization code it was handed, and `code`\n * is no credential's name anywhere else (an app's `?code=US`, a promo\n * code); a device flow's `device_code` is its code. So a code\n * (EXCHANGE_CODES) goes only beside a grant that redeems one\n * (`grant_type=authorization_code`, the device code grant), a\n * `code_verifier`, a `redirect_uri`, `client_id` or the\n * `verification_uri` a device authorization hands out with its code, or\n * -- beside a code of 10 or more -- a generated state (isGeneratedState):\n * the authorization response itself, which a page may hand its backend.\n * Names normalized.\n */\nfunction isTokenExchange(pairs: ReadonlyArray<[string, string]>): boolean {\n let code = false;\n let peer = false;\n let longCode = false;\n let state = false;\n for (const [name, value] of pairs) {\n if (name === \"granttype\" && EXCHANGE_GRANTS.has(value.trim().toLowerCase()))\n return true;\n if (name === \"codeverifier\") return true;\n if (EXCHANGE_CODES.has(name)) {\n code = true;\n if (value.length >= 10) longCode = true;\n }\n if (EXCHANGE_PEERS.has(name)) peer = true;\n if (name === \"state\" && isGeneratedState(value)) state = true;\n }\n // A generated state beside a code of 10 or more: an authorization\n // response a page hands its backend to redeem, as the URL rule reads one.\n return code && (peer || (state && longCode));\n}\n\n/**\n * An OAuth state as a provider round-trips it: 16 characters or more of a\n * token's alphabet, letters with a digit among them or with both cases\n * (`XK3JF9QZ2LMN8PRT`, `x8Kq2Lm9Np4Rt7Vw`), and no plain word or slug of\n * words and numbers (`in_progress_step2`, `pending-approval-2024`,\n * `ORDER-2024-000123`). An app's own state -- `CA`, `WA-98101`,\n * `delivered`, a timestamp -- is not one.\n */\nfunction isGeneratedState(value: string): boolean {\n return (\n value.length >= 16 &&\n /^[A-Za-z0-9_\\-.~+/=]+$/.test(value) &&\n /[A-Za-z]/.test(value) &&\n (/\\d/.test(value) || (/[a-z]/.test(value) && /[A-Z]/.test(value))) &&\n !isPlainState(value) &&\n !isStateSlug(value)\n );\n}\n\n/**\n * A slug of words and numbers, a word's digits at its end, and one part\n * letters alone: `in_progress_step2`, `ORDER-2024-000123`. With no such\n * part it is a generated token's groups (`Xk9-Pq2-Lm7-Rt4-Zw8`). No part\n * can be read two ways: where a lone capital could, `A-A-...-A1.` took\n * twice as long for each two parts more, 31 s at 30 (MEASURED).\n */\nfunction isStateSlug(value: string): boolean {\n return (\n /^(?:[A-Z]+|[A-Z]?[a-z]+)\\d*(?:[-_](?:(?:[A-Z]+|[A-Z]?[a-z]+)\\d*|\\d+))+$/.test(\n value,\n ) && /(?:^|[-_])[A-Za-z]+(?:[-_]|$)/.test(value)\n );\n}\n\n/**\n * A one-time code's names an app's settings use too: in a JSON body a\n * string or a number under them is the code, and a flag or an object is\n * the app's (`{\"totp\":{\"enabled\":true}}`), which a replay serves back.\n */\nconst BARE_CODE_NAMES: ReadonlySet<string> = new Set([\"passcode\"]);\n\n/** A value under a one-time code's settings name that holds no code itself, but is read on: an object or a list. A flag is kept under every name (redactNode). */\nfunction isSettingsValue(node: JNode): boolean {\n return node.kind === \"object\" || node.kind === \"array\";\n}\n\n/**\n * A JSON key's, a HAR-style pair's or a header's name, read by the one\n * rule (@keploy/contract's privacy.ts isCredentialName) as a `key`.\n */\nexport function isSensitiveKey(key: string): boolean {\n return isCredentialName(key, \"key\");\n}\n\n/**\n * A one-time code's name an app's settings use too: `passcode`\n * (BARE_CODE_NAMES), or a name ending in `otp` -- `otp`, `totp`, an\n * `email_otp`, an `sms_otp`: under it an object is the app's setting\n * (`{\"totp\":{\"enabled\":true}}`), and a code is the code.\n */\nfunction isBareCodeName(key: string): boolean {\n return nameParts(key, \"key\").some(\n (n) => BARE_CODE_NAMES.has(n) || n.endsWith(\"otp\"),\n );\n}\n\n/**\n * Credential names an app's data uses as often for a list, a summary or a\n * method: `{\"credentials\":[{\"id\":1,\"provider\":\"github\"}]}`,\n * `{\"authentication\":{\"providers\":[\"google\"]}}`, a test summary's\n * `{\"pass\":12,\"fail\":3}`. Under them only a string is the credential; any\n * other value is read on, its own credentials redacted by name, so a page\n * that maps over the list is served the list (found in review).\n */\nconst WORD_NAMES: ReadonlySet<string> = new Set([\n \"credentials\",\n \"authentication\",\n \"pass\",\n]);\n\n/** Whether a JSON key is one of WORD_NAMES, read as the one rule reads a key. */\nfunction isWordName(key: string): boolean {\n return nameParts(key, \"key\").some((n) => WORD_NAMES.has(n));\n}\n\n/* ------------------------------------------------------------------ */\n/* Value-level detectors — applied ONLY to strings */\n/* ------------------------------------------------------------------ */\n\n/**\n * Email addresses, found from each `@` rather than by a regex over the\n * whole text.\n *\n * The unanchored `[a-zA-Z0-9._%+-]+@...` retried the whole run from every\n * position inside it, so a long run with no `@` -- a hex digest, a base64\n * blob, a minified bundle -- cost quadratic time ON THE PAGE'S MAIN\n * THREAD: MEASURED 1.8 s for 64K characters and minutes at the 512 KB\n * body cap (review round 1). Anchoring the regex to a run's start made it\n * linear but blind to an address glued onto the previous one\n * (`ada@x.com+bob@y.org`) or ending a long `%20` run -- both of which\n * 3.0.1 caught (review round 2). So the scan starts at each `@`: the local\n * part is the last 64 local characters before it (RFC 5321's limit), not\n * reaching back into the previous match, and the domain is a bounded\n * sticky match after it. Each `@` costs at most 64 + 253 steps: linear.\n */\nconst EMAIL_DOMAIN = /[a-zA-Z0-9.-]{1,253}\\.[a-zA-Z]{2,63}/y;\n\nfunction isEmailLocalChar(code: number): boolean {\n return (\n (code >= 48 && code <= 57) || // 0-9\n (code >= 65 && code <= 90) || // A-Z\n (code >= 97 && code <= 122) || // a-z\n code === 46 || // .\n code === 95 || // _\n code === 37 || // %\n code === 43 || // +\n code === 45 // -\n );\n}\n\n/** The range of every email address in `text`, found from each `@`. */\nfunction emailRanges(text: string, into: Range[]): void {\n let kept = 0; // no match may reach back before this index\n let at = text.indexOf(\"@\");\n while (at !== -1) {\n const floor = Math.max(kept, at - 64);\n let start = at;\n while (start > floor && isEmailLocalChar(text.charCodeAt(start - 1))) {\n start--;\n }\n if (start < at) {\n EMAIL_DOMAIN.lastIndex = at + 1;\n const domain = EMAIL_DOMAIN.exec(text);\n if (domain) {\n kept = at + 1 + domain[0].length;\n into.push([start, kept]);\n at = text.indexOf(\"@\", kept);\n continue;\n }\n }\n at = text.indexOf(\"@\", at + 1);\n }\n}\n\n/**\n * A token whose provider prefix says what it is, whatever key it sits\n * under or text it is in: Keploy's own API keys (`kep_` + 43 base64url\n * characters, api-server's models.GenerateAPIKey), GitHub, GitLab, Slack,\n * Stripe, OpenAI and Anthropic, npm, webhook signing secrets, AWS access\n * key ids (long-lived and temporary) and Google API keys. Each alternative\n * is a literal prefix and a run taken whole (a longer run leaves no tail),\n * started only after a character that is not a letter or digit -- so\n * `x-kep_...` is found and `task_live_...` is not a Stripe key: linear.\n */\nconst KNOWN_TOKEN_RE =\n /(?<![A-Za-z0-9])(?:kep_[A-Za-z0-9_-]{20,}|gh[pousr]_[A-Za-z0-9]{36,}|github_pat_[A-Za-z0-9_]{22,}|glpat-[A-Za-z0-9_-]{20,}|xox[abprse]-[A-Za-z0-9-]{10,}|[sr]k_(?:live|test)_[A-Za-z0-9]{16,}|sk-(?:proj|ant)-[A-Za-z0-9_-]{20,}|npm_[A-Za-z0-9]{36,}|whsec_[A-Za-z0-9+/=]{24,}|(?:AKIA|ASIA)[0-9A-Z]{16,}|AIza[0-9A-Za-z_-]{35,})/g;\n\nconst SSN_RE = /\\b\\d{3}-\\d{2}-\\d{4}\\b/g;\n// Deliberately strict: a separator or an explicit country code is\n// required. The old \"any 7-digit run\" pattern matched order ids and is\n// what corrupted recorded URLs.\nconst PHONE_RE =\n /(?:\\+\\d{1,3}[ .-]?)?(?:\\(\\d{3}\\)[ .-]?|\\b\\d{3}[ .-])\\d{3}[ .-]\\d{4}\\b/g;\n// Starts only where the previous character is not base64url. `\\b` let a\n// match start after every `-` (a non-word character inside the alphabet),\n// so `eyJ-eyJ-...` rescanned the rest of the run from each `eyJ`:\n// MEASURED 510 ms at 64K characters on the main thread. The cost of the\n// anchor: a token glued straight onto a preceding `-` is not detected; a\n// JWT after a space, `=`, a quote or a colon -- every header, cookie,\n// query and JSON shape -- is.\nconst JWT_RE =\n /(?<![A-Za-z0-9_-])eyJ[A-Za-z0-9_-]+\\.[A-Za-z0-9_-]+\\.[A-Za-z0-9_-]+\\b/g;\n// An IP address is personal data under GDPR. Unlike the card pattern this\n// one is safe: it only ever matches inside a string value, so it cannot\n// turn a JSON number into a bare token.\n// Guarded on both sides so a build/version string is not mistaken for an\n// address: \"1.2.3.4000\" and \"10.0.0.1.5\" must survive untouched.\nconst IPV4_RE =\n /(?<![\\d.])(?:(?:25[0-5]|2[0-4]\\d|[01]?\\d\\d?)\\.){3}(?:25[0-5]|2[0-4]\\d|[01]?\\d\\d?)(?![\\d.])/g;\n\n/** Luhn check — the standard checksum every real card number satisfies. */\nfunction passesLuhn(digits: string): boolean {\n let sum = 0;\n let double = false;\n for (let i = digits.length - 1; i >= 0; i--) {\n let d = digits.charCodeAt(i) - 48;\n if (d < 0 || d > 9) return false;\n if (double) {\n d *= 2;\n if (d > 9) d -= 9;\n }\n sum += d;\n double = !double;\n }\n return sum % 10 === 0;\n}\n\n/**\n * A real card number: a known issuer prefix, a valid length for that\n * issuer, AND a passing Luhn checksum.\n *\n * All three are required on purpose. Length alone matched timestamps;\n * Luhn alone still admits ~10% of random digit runs. Together the false\n * positive rate on non-card data is negligible, and — critically — a\n * 13-digit millisecond timestamp has no valid issuer prefix.\n */\nfunction isLikelyCardNumber(digits: string): boolean {\n if (digits.length < 13 || digits.length > 19) return false;\n const isVisa =\n digits[0] === \"4\" &&\n (digits.length === 13 || digits.length === 16 || digits.length === 19);\n const isMastercard = /^(5[1-5]|2[2-7])/.test(digits) && digits.length === 16;\n const isAmex = /^3[47]/.test(digits) && digits.length === 15;\n const isDiscover = /^6(?:011|5)/.test(digits) && digits.length === 16;\n const isJcbDiners =\n /^(?:35|3[068])/.test(digits) && digits.length >= 14 && digits.length <= 19;\n if (!(isVisa || isMastercard || isAmex || isDiscover || isJcbDiners))\n return false;\n return passesLuhn(digits);\n}\n\n/** The range of every card-shaped run in `s` that is a real card number. */\nfunction cardRanges(s: string, into: Range[]): void {\n // Candidate runs of digits with optional single spaces/hyphens.\n for (const m of s.matchAll(/\\b(?:\\d[ -]?){12,18}\\d\\b/g)) {\n if (isLikelyCardNumber(m[0].replace(/[^0-9]/g, \"\"))) {\n into.push([m.index, m.index + m[0].length]);\n }\n }\n}\n\n/** Redact card-shaped runs inside a string, preserving everything else. */\nfunction redactCards(s: string): string {\n const ranges: Range[] = [];\n cardRanges(s, ranges);\n return applyRanges(s, ranges);\n}\n\n/** A half-open span of a text to redact: [start, end). */\ntype Range = [number, number] | [number, number, string];\n\n/** The range of every non-empty match of a global pattern. */\nfunction patternRanges(text: string, re: RegExp, into: Range[]): void {\n for (const m of text.matchAll(re)) {\n // An empty match hides nothing: `\\d*` matches the empty string at\n // every position, and a marker at each grew a body tenfold per pass\n // (review r7).\n if (m[0] !== \"\") into.push([m.index, m.index + m[0].length]);\n }\n}\n\n/**\n * Where every detector matches in `text`: the built-ins, then the\n * integrator's patterns (`extra`, compiled global -- see PrivacyEngine).\n *\n * EVERY DETECTOR RUNS OVER THE ORIGINAL TEXT, never over another's\n * output. The scan used to be a chain of replace() calls, each over the\n * last one's result, and both ways of letting a pattern meet a marker were\n * wrong, MEASURED: a pattern that re-scanned the markers rewrote them\n * (`/RED/` -> `[[REDACTED]ACTED]`) and grew a body tenfold per pass\n * (review r7); a pattern that ran only between markers hid only part of\n * its match -- `/Notes: .*\\/` over a phone number, a `<div class=\"notes\">`\n * pattern over an email -- and recorded the rest in clear (review r8,\n * against base 3ce8786, which redacted both). Ranges on the original text\n * have neither failure: see applyRanges.\n */\nfunction detectorRanges(\n text: string,\n extra: readonly RegExp[],\n into: Range[],\n): void {\n patternRanges(text, JWT_RE, into);\n patternRanges(text, KNOWN_TOKEN_RE, into);\n emailRanges(text, into);\n patternRanges(text, SSN_RE, into);\n patternRanges(text, PHONE_RE, into);\n patternRanges(text, IPV4_RE, into);\n cardRanges(text, into);\n for (const re of extra) patternRanges(text, re, into);\n}\n\n/**\n * `text` with every range replaced by one marker, OVERLAPPING ranges\n * merged into one: a pattern that covers a built-in's match covers it\n * whole. Ranges that only touch stay separate markers (two addresses\n * glued together are two). Nothing outside a range changes, and each\n * marker replaces at least one character -- except the one kind of empty\n * range a caller may add on purpose, a sensitive form field's empty value\n * -- so a result is at most ten times its input plus those.\n */\nfunction applyRanges(text: string, ranges: Range[]): string {\n if (ranges.length === 0) return text;\n ranges.sort((a, b) => a[0] - b[0] || b[1] - a[1]);\n let out = \"\";\n let pos = 0;\n let [start, end, with_] = ranges[0];\n for (let k = 1; k <= ranges.length; k++) {\n const next = ranges[k];\n if (next !== undefined && next[0] < end) {\n if (next[1] > end) end = next[1];\n with_ = undefined; // merged: one marker covers them all\n continue;\n }\n out += text.slice(pos, start) + (with_ ?? REDACTED);\n pos = end;\n if (next !== undefined) [start, end, with_] = next;\n }\n return out + text.slice(pos);\n}\n\n/**\n * Apply every value-level detector to one string, then every\n * caller-supplied pattern, all over the string as it came.\n *\n * `extra` is the integrator's `privacy.piiPatterns`, already compiled\n * global (see PrivacyEngine). It rides through every scan the engine\n * makes -- this function is the ONLY string scanner -- so a pattern\n * applies to a JSON string value, a text body and a header value alike.\n * It used to reach header values only, while its documentation said\n * \"matched text is replaced\".\n */\nexport function redactStringValue(\n value: string,\n extra: readonly RegExp[] = [],\n): string {\n if (!value) return value;\n const ranges: Range[] = [];\n detectorRanges(value, extra, ranges);\n return applyRanges(value, ranges);\n}\n\n/**\n * A JSON string's text: each embedded credential pair's value, by the\n * leads a string takes (EMBEDDED_NAME_IN_STRING), and each detector's\n * match replaced. A JSON string is a text -- a message, a log line, a\n * stored form -- and, read by the detectors alone, `see /cb?token=... now`\n * was recorded (found in review).\n */\nfunction redactStringText(value: string, extra: readonly RegExp[]): string {\n if (!value) return value;\n const ranges: Range[] = [];\n embeddedPairRanges(value, ranges, \"string\");\n detectorRanges(value, extra, ranges);\n return applyRanges(value, ranges);\n}\n\n/**\n * The token detectors alone -- a JWT, a provider-prefixed key -- over one\n * string: what the page's own text is read for (privacy.ts scrubDomText).\n * A credential on screen is one whatever text is around it; an email or a\n * phone number in the page's text is the page's content, which balanced\n * records.\n */\nexport function redactTokens(value: string): string {\n return value ? applyRanges(value, tokenRanges(value)) : value;\n}\n\n/**\n * What any token needs somewhere in a value to be one: a JWT's `eyJ` or a\n * provider's prefix. Every attribute and text of a page is asked, and\n * almost none holds one; this is read without the lookbehind the two\n * patterns below start every place with (MEASURED: 18 percent of a\n * snapshot of 80,000 nodes was those patterns finding nothing).\n */\nconst MAYBE_TOKEN =\n /eyJ|kep_|gh[pousr]_|github_pat_|glpat-|xox[abprse]-|[sr]k_(?:live|test)_|sk-(?:proj|ant)-|npm_|whsec_|AKIA|ASIA|AIza/;\n\n/** Where `value`'s JWTs and provider-prefixed keys lie. */\nexport function tokenRanges(value: string): Range[] {\n const ranges: Range[] = [];\n if (!MAYBE_TOKEN.test(value)) return ranges;\n patternRanges(value, JWT_RE, ranges);\n patternRanges(value, KNOWN_TOKEN_RE, ranges);\n return ranges;\n}\n\n/* ------------------------------------------------------------------ */\n/* Structural walk */\n/* ------------------------------------------------------------------ */\n\nconst MAX_DEPTH = 64;\n\n/*\n * JSON IS REDACTED IN ITS OWN TEXT. It was parsed, walked and serialised\n * again, so every byte the walk did not touch could still change: an\n * integer past 2^53 came back rounded (`9007199254740993` recorded as\n * `...992`), whitespace and escapes were normalised -- and a replay\n * serves the recording, so an unchanged app could break on its own\n * snowflake ids. Now JSON.parse only VALIDATES (what it refuses is still\n * refused), a small tokenizer finds each value's span in the text, and\n * only the spans being redacted are rewritten. Every other byte --\n * numbers, whitespace, key order, escapes -- is kept. The tokenizer is\n * the SDK's own, so every engine gives the same answer.\n */\n\n/** A JSON value and where it is in the text. */\ntype JNode =\n | {\n kind: \"object\";\n start: number;\n end: number;\n entries: { key: string; value: JNode }[];\n }\n | { kind: \"array\"; start: number; end: number; items: JNode[] }\n | { kind: \"string\"; start: number; end: number; value: string }\n | { kind: \"scalar\"; start: number; end: number }\n | { kind: \"deep\"; start: number; end: number };\n\nconst ESCAPES: Record<string, string> = {\n '\"': '\"',\n \"\\\\\": \"\\\\\",\n \"/\": \"/\",\n b: \"\\b\",\n f: \"\\f\",\n n: \"\\n\",\n r: \"\\r\",\n t: \"\\t\",\n};\n\n/**\n * The value spans of a JSON text JSON.parse has already accepted, which\n * is why nothing here re-checks the grammar. Read to MAX_DEPTH like the\n * walk below; a value deeper than that is skipped by a scan, not by\n * recursion, so a deep document cannot overflow the stack.\n */\nfunction parseJsonSpans(text: string, base: number): JNode {\n let i = 0;\n const ws = (): void => {\n while (i < text.length) {\n const c = text.charCodeAt(i);\n if (c !== 32 && c !== 9 && c !== 10 && c !== 13) break;\n i++;\n }\n };\n const string = (): string => {\n i++; // the opening quote\n let out = \"\";\n let run = i;\n while (text[i] !== '\"') {\n if (text[i] !== \"\\\\\") {\n i++;\n continue;\n }\n out += text.slice(run, i);\n const e = text[i + 1];\n if (e === \"u\") {\n out += String.fromCharCode(parseInt(text.slice(i + 2, i + 6), 16));\n i += 6;\n } else {\n out += ESCAPES[e];\n i += 2;\n }\n run = i;\n }\n out += text.slice(run, i);\n i++; // the closing quote\n return out;\n };\n // Past MAX_DEPTH: the value's extent only, read by a scan.\n const skip = (): void => {\n let nest = 0;\n do {\n const c = text[i];\n if (c === '\"') {\n i++;\n while (text[i] !== '\"') i += text[i] === \"\\\\\" ? 2 : 1;\n i++;\n } else if (c === \"{\" || c === \"[\") {\n nest++;\n i++;\n } else if (c === \"}\" || c === \"]\") {\n nest--;\n i++;\n } else if (nest === 0 && (c === \",\" || c === \":\")) {\n break;\n } else {\n i++;\n }\n } while (nest > 0 || (i < text.length && !/[\\s,\\]}]/.test(text[i])));\n };\n const value = (depth: number): JNode => {\n ws();\n const start = i;\n if (depth > MAX_DEPTH) {\n skip();\n return { kind: \"deep\", start, end: i };\n }\n const c = text[i];\n if (c === \"{\") {\n i++;\n const entries: { key: string; value: JNode }[] = [];\n ws();\n if (text[i] === \"}\") i++;\n else {\n for (;;) {\n ws();\n const key = string();\n ws();\n i++; // :\n entries.push({ key, value: value(depth + 1) });\n ws();\n if (text[i++] === \"}\") break; // else `,`\n }\n }\n return { kind: \"object\", start, end: i, entries };\n }\n if (c === \"[\") {\n i++;\n const items: JNode[] = [];\n ws();\n if (text[i] === \"]\") i++;\n else {\n for (;;) {\n items.push(value(depth + 1));\n ws();\n if (text[i++] === \"]\") break; // else `,`\n }\n }\n return { kind: \"array\", start, end: i, items };\n }\n if (c === '\"') {\n const v = string();\n return { kind: \"string\", start, end: i, value: v };\n }\n while (i < text.length && !/[\\s,\\]}]/.test(text[i])) i++;\n return { kind: \"scalar\", start, end: i };\n };\n // `base`: the depth this text sits at -- a JSON string inside a body is\n // as deep as the value that holds it, so the cap stays cumulative.\n return value(base);\n}\n\nconst REDACTED_JSON = JSON.stringify(REDACTED);\n\n/* ------------------------------------------------------------------ */\n/* URLs held in a body */\n/* ------------------------------------------------------------------ */\n\n/**\n * A URL a body holds -- a presigned S3, GCS or Azure link an API hands the\n * page, a pagination link, a redirect in a form, a link in an HTML or RSC\n * page -- scrubbed by the one URL scrubber (@keploy/contract's privacy.ts\n * scrubUrl) under a `param`'s names: a credential's value replaced, in\n * its query, its fragment, a path's `;name=` and a URL nested or encoded\n * in a value, its user info dropped, never a paging cursor (a pagination\n * link's `pageToken` is the page's to request again). A body is no replay\n * key, so its pairs are read as the DOM's are, each credential's own value\n * replaced, and a nested URL is written back as it came (`raw`). A\n * scrubbed link is not the one the server sent, so a replay that requests\n * it relies on the replay key treating a redacted value as a wildcard.\n * Every other byte is kept.\n */\nconst BODY_URL_RULES: UrlRules = {\n kind: \"param\",\n strict: false,\n whole: false,\n raw: true,\n};\n\n/**\n * A text body's URLs (an HTML, XML, RSC, CSS, text or multipart body's,\n * read raw) and a header's: BODY_URL_RULES, but a credential's own value\n * ends at the first character the contract's ownValueEnd stops at\n * (whitespace, `,`, `;`, a quote, or a bracket it does not open), the\n * text after it kept (`/api/x?token=... 200 OK`, a CSV row's later\n * columns) and read as a text's (TAIL_URL_RULES).\n */\nconst TEXT_URL_RULES: UrlRules = {\n ...BODY_URL_RULES,\n spaced: true,\n tail: (text) => scrubTextUrls(text, TAIL_URL_RULES),\n};\n\n/**\n * A form body's URLs (readAsForm): a credential's own value ends at its\n * first whitespace, as every body's did before TEXT_URL_RULES, and the\n * form read then takes each value to its `&`. Nothing after it is read\n * again (no `tail`). Read with the text's end, a raw URL's credential\n * value cut at a `,` was left a tail the form read took for the\n * credential's, and the whole value went\n * (`next=https://x/cb?token=abc,def%20ghi` became `next=[REDACTED]`), or\n * the tail was kept (found in review).\n */\nconst FORM_URL_RULES: UrlRules = {\n ...BODY_URL_RULES,\n spaced: true,\n form: true,\n};\n\n/**\n * The text a credential's own value leaves after it in a pair, read as a\n * text's URLs are, each URL of a list its own (`list`): kept unread, a\n * list's next URL kept its nested token and its user info\n * (`?token=...,https://b/y?next=%2Fcb%3Ftoken%3D...`, found in review).\n * Its own credentials' tails are left to the text pair rule, so it is\n * read once.\n */\nconst TAIL_URL_RULES: UrlRules = {\n ...BODY_URL_RULES,\n spaced: true,\n list: true,\n};\n\n/**\n * A line that starts with a URL -- a JSON string that is a link, a form's\n * value, a uri-list's or a log's line -- read whole as a URL is, what\n * follows its start its own (`?markers=red|1,2&signature=...`,\n * `?filter={\"a\":1}&token=...`): a scheme, a `/`, `./` or `../`, then a\n * query or a fragment; a relative path's segments, or none, then a `?` or\n * a `#` and a pair (`cb?jwt=...`, `#access_token=...`), which prose's\n * `Ref#123: ...` and `Q? see ...` are not -- read as a URL, a credential's\n * value took their words to the next `&` (found in review); or a path's\n * parameter (`/cart;jsessionid=...`, a `/` first and no `=` before it,\n * which a form's `a=1;password=...&b=2` is not). Its first word holds no\n * tag, quote, brace or pipe before its first `=`: a stylesheet's\n * `#a{background:url(/x?sig=...)}` and a page's `<style>a{color:#fff}`\n * are texts holding URLs, read as a URL their `)}` and `\">` went with a\n * credential's value (found in review). A scheme is one a `/` follows, one\n * whose name holds a `.` or a `+` (`com.example.app:`), `localhost` and\n * its port (`localhost:3000/`; another one-word host is CSS's\n * `grid-area:1/2` as often), or one of a list that takes no authority\n * (`mailto:`, `tel:`, `xmpp:`, `intent:`, `data:` ...): a CSS property is none,\n * and `background:url(/x?token=...);color:red` read as a URL lost its\n * `);color:red` (found in review). Anything else -- prose, markup, code --\n * is a text holding URLs, each found by the scan.\n */\nconst WHOLE_URL =\n /^(?=[^={}<>\"'\\\\^`|]*(?:=|$))(?:(?:[a-z][a-z0-9+.-]*:\\/|[a-z][a-z0-9-]*[+.][a-z0-9+.-]*:|localhost:\\d{1,5}[/?#]|(?:mailto|tel|sms|urn|data|javascript|vbscript|blob|about|xmpp|sip|sips|magnet|intent|bitcoin|geo|market|news):|\\.{0,2}\\/)[^\\s?#]*[?#]|(?:[\\w.~%-][\\w.~%/-]*)?[?#][^\\s=&#]+=|\\.{0,2}\\/[^\\s?#;=]*;)/i;\n\n/** The start a URL a line starts with is told by (WHOLE_URL): its first word. */\nconst URL_START_WORD = /^\\S*/;\n\n/**\n * Each line of a text, read whole when it starts with a URL: a raw space\n * or tab in a query is its value's (`?q=new york&api_key=...`), and a\n * credential's value ends at its first stop (ownValueEnd, scrubPairs),\n * the line's text after it kept. A URL holds no line break: a uri-list's\n * or a log's lines are each read, and none runs into the next (found in\n * review).\n */\nconst URL_LINE = /^[^\\r\\n]*/gm;\n\n/**\n * `text` -- a body, a JSON string, a form's value -- with every URL it\n * holds scrubbed (BODY_URL_RULES): each line that starts with a URL read\n * whole (WHOLE_URL), then each URL the scan finds in it.\n */\nfunction scrubTextUrls(raw: string, rules = BODY_URL_RULES): string {\n const text = raw.replace(URL_LINE, (line) =>\n WHOLE_URL.test(URL_START_WORD.exec(line)![0])\n ? scrubUrl(line, rules)\n : line,\n );\n const edits = urlEdits(text, rules);\n if (edits.length === 0) return scrubEscapedUrls(text, rules);\n let out = \"\";\n let at = 0;\n for (const [start, end, with_] of edits) {\n out += text.slice(at, start) + with_;\n at = end;\n }\n return scrubEscapedUrls(out + text.slice(at), rules);\n}\n\n/**\n * A URL a script or a JavaScript body writes with its slashes escaped, as\n * JSON and PHP's json_encode write one\n * (`\"https:\\/\\/app\\/cb#access_token=...\"`): the scan finds none, a\n * backslash ending a URL. A scheme read at most 32 characters back, as\n * URL_START's is. It ends at a parenthesis, a bracket (CSS's\n * `url(https:\\/\\/...);background-size:cover` keeps its `)` and the rest)\n * or a plain `/` that ends a regular expression (one its flags and then\n * no word follow, `/.test(`), not one inside a value\n * (`?token=abc/def`, found in review: cut there, `/def` was kept) too: escaped slashes are a regular expression's as often\n * (`/https:\\/\\/x\\/cb#access_token=([^&]+)/`), whose group read as a value\n * left the pattern unbalanced (found in review).\n */\nconst ESCAPED_URL =\n /[a-z][a-z0-9+.-]{0,31}:(?:\\\\\\/|\\\\u002[fF]){2}(?:[^\\s\"'<>\\\\^`{|}()[\\]/]|\\/(?![dgimsuvy]*(?![\\w$]))|\\\\\\/|\\\\u002[fF])*/gi;\n\n/**\n * Each URL `text` writes with its slashes escaped (ESCAPED_URL), read\n * with them unescaped by `rules`: read as written, its credential and a\n * URL nested in it (`?next=%2Fcb%3Ftoken%3D...`) were kept (found in\n * review). It ends at a plain `/` -- a regular expression's closing one,\n * `/https:\\/\\/x\\/cb;jsessionid=.../` -- and only what the read changed\n * is written back, every other byte as it came: written back with every\n * slash escaped, the pattern's closing `/` became `\\/` and the script no\n * longer parsed (found in review).\n */\nfunction scrubEscapedUrls(text: string, rules: UrlRules): string {\n if (!/:(?:\\\\\\/|\\\\u002[fF])/.test(text)) return text;\n return text.replace(ESCAPED_URL, (span) => {\n // The span unescaped, and where in the span each of its characters,\n // and its end, were written.\n let plain = \"\";\n const at: number[] = [];\n for (let i = 0; i < span.length;) {\n at.push(i);\n const escape = ESCAPED_SLASH_AT.exec(span.slice(i, i + 6));\n plain += escape === null ? span[i] : \"/\";\n i += escape === null ? 1 : escape[0].length;\n }\n at.push(span.length);\n const out = scrubUrl(plain, rules);\n if (out === plain) return span;\n // What changed lies between the longest prefix and suffix the two\n // share; only it is written anew, its slashes as the span's first.\n let head = 0;\n while (head < out.length && out[head] === plain[head]) head++;\n let tail = 0;\n while (\n tail < out.length - head &&\n tail < plain.length - head &&\n out[out.length - 1 - tail] === plain[plain.length - 1 - tail]\n )\n tail++;\n const slash = /\\\\\\/|\\\\u002[fF]/.exec(span)![0];\n return (\n span.slice(0, at[head]) +\n out.slice(head, out.length - tail).replace(/\\//g, slash) +\n span.slice(at[plain.length - tail])\n );\n });\n}\n\n/** A slash a script or a JSON text writes escaped (`\\/`, `\\u002f`), at a text's start. */\nconst ESCAPED_SLASH_AT = /^(?:\\\\\\/|\\\\u002[fF])/;\n\n/**\n * Every URL a header's value holds, scrubbed as a text body's URLs are\n * (TEXT_URL_RULES: a credential's own value replaced, ended at its first\n * stop, every other byte kept),\n * and every pair a header's leads start (EMBEDDED_NAME_IN_HEADER), as a\n * relative URL's, which the URL scan does not find, is: a `Referer`, an\n * `X-Redirect-To`, a `Content-Security-Policy`'s `report-uri` absolute or\n * relative (`/csp-report?token=...`). A header is no replay key, so no\n * pair is replaced whole for a name inside it. Only Location,\n * Content-Location, Link and Refresh were read, and a URL any other header\n * carried was recorded as it came (found in review).\n */\nexport function scrubHeaderUrls(value: string): string {\n // A credential's own value ends as a text's does (TEXT_URL_RULES): a\n // header's list is split at `,` and its parameters at `;` (RFC 9110),\n // and a value run to the next pair took a second URL and a CSP's next\n // directive with it (found in review).\n const text = scrubTextUrls(value, TEXT_URL_RULES);\n const ranges: Range[] = [];\n embeddedPairRanges(text, ranges, \"header\");\n return applyRanges(text, ranges);\n}\n\n/**\n * Whether a form value, encoded (`next=https%3A%2F%2Fx%2Fv%3Fjwt%3D...`),\n * holds a URL with a credential in it: such a value goes whole, since its\n * scrubbed URL cannot be written back encoded in place.\n */\nfunction holdsEncodedUrlCredential(raw: string): boolean {\n if (!/[%+]/.test(raw)) return false;\n const value = formDecode(raw);\n if (value === raw) return false;\n // Encoded again (`redirect=https%253A%252F%252F...%253Fjwt%253D...`): no\n // read sees its URL, and no pair search reads it in place. Decoded\n // escape by escape, as holdsCredentialName reads it: all or nothing, a\n // malformed escape beside the name (`%253DS%25zz`) kept it (found in\n // review).\n if (decoded(value) !== value && holdsCredentialName(value, \"param\"))\n return true;\n const scrubbed = scrubTextUrls(value);\n if (scrubbed === value) return false;\n // What the pair search below redacts in place, mapped back to the raw\n // bytes (`redirect=https%3A%2F%2Fx%2Fcb%3Ftoken%3D[REDACTED]`): enough\n // when it is what the URL scrub redacts.\n const inPlace: Range[] = [];\n embeddedPairRanges(value, inPlace);\n return applyRanges(value, inPlace) !== scrubbed;\n}\n\n/**\n * The digits of a JSON number written with a fraction or an exponent\n * that is still an integer (`4242424242424242.0`, `4.242424242424242e15`\n * -- a PAN either way), or null. Plain digits are read as written.\n */\nfunction integerDigits(raw: string): string | null {\n if (!/^-?\\d/.test(raw)) return null; // true, false\n const n = Number(raw);\n return Number.isInteger(n) ? String(n) : null;\n}\n\n/** A flag, or a list of flags: a value that holds no secret under any name. */\nfunction onlyFlags(text: string, node: JNode): boolean {\n if (node.kind === \"scalar\")\n return /^(?:true|false)$/.test(text.slice(node.start, node.end));\n return node.kind === \"array\" && node.items.every((n) => onlyFlags(text, n));\n}\n\n/**\n * One JSON value's redaction, as edits on the text: the decisions the\n * structural walk always made -- a sensitive key takes its whole value,\n * a card number goes even as a number, a string is scanned (and redacted\n * as JSON when it is JSON), a name/value pair goes by its name, past\n * MAX_DEPTH everything goes -- written only where they change something.\n */\nfunction redactNode(\n text: string,\n node: JNode,\n keyHint: string | null,\n depth: number,\n extra: readonly RegExp[],\n edits: Array<[number, number, string]>,\n): void {\n const replace = (with_: string): void => {\n edits.push([node.start, node.end, with_]);\n };\n // Fail CLOSED. Returning the subtree verbatim meant a `password` nested\n // past the cap was emitted in the clear.\n if (node.kind === \"deep\") return replace(REDACTED_JSON);\n // null is kept, under any key: it carries nothing, and a replay that\n // served \"[REDACTED]\" where the app recorded null hands it a string.\n if (node.kind === \"scalar\" && text.startsWith(\"null\", node.start)) return;\n // So is a flag, or a list of flags: a list's item comes here under its\n // key's name without passing the entries loop's guard below.\n if (onlyFlags(text, node)) return;\n // A sensitive key redacts its ENTIRE value, whatever shape it is, but\n // for an object or a list under a name settings use too.\n const bare = keyHint !== null && isBareCodeName(keyHint);\n if (\n keyHint !== null &&\n isSensitiveKey(keyHint) &&\n !(bare && isSettingsValue(node)) &&\n !(node.kind !== \"string\" && isWordName(keyHint))\n ) {\n return replace(REDACTED_JSON);\n }\n if (node.kind === \"scalar\") {\n // Numbers, booleans and null are never scanned -- the rule that stops\n // timestamps and ids being corrupted -- but a card number survives\n // as a JSON number, so the card test reads its digits as written.\n const raw = text.slice(node.start, node.end);\n const digits = /^\\d+$/.test(raw) ? raw : integerDigits(raw);\n if (digits !== null && isLikelyCardNumber(digits)) replace(REDACTED_JSON);\n return;\n }\n if (node.kind === \"string\") {\n const out =\n redactJsonString(node.value, depth, extra) ??\n redactStringText(scrubTextUrls(node.value), extra);\n if (out !== node.value) replace(JSON.stringify(out));\n return;\n }\n if (node.kind === \"array\") {\n for (const item of node.items) {\n redactNode(text, item, keyHint, depth + 1, extra, edits);\n }\n return;\n }\n // A name/value pair whose name is a secret's: a header list\n // (`[{name: \"Authorization\", value: ...}]`, HAR), a test report's\n // header diff (`{key: \"Authorization\", expected, actual}`). The value\n // sits under a generic name, so it goes by its sibling's.\n const pair = node.entries.some(\n ({ key, value }) =>\n PAIR_NAMES.has(key.toLowerCase()) &&\n value.kind === \"string\" &&\n isSensitiveKey(value.value),\n );\n const card = node.entries.some(({ key }) =>\n CARD_FIELDS.has(normalizeKey(key)),\n );\n const exchange = isTokenExchange(\n node.entries.map(\n ({ key, value }) =>\n [normalizeKey(key), value.kind === \"string\" ? value.value : \"\"] as [\n string,\n string,\n ],\n ),\n );\n for (const { key, value } of node.entries) {\n // A flag, or a list of flags, goes under no rule (onlyFlags): it\n // carries no secret, and replaced it became the string \"[REDACTED]\",\n // which an app reads as true -- `{\"hasSignature\":false}` replayed as a\n // signature on file (found in review). Every value a key holds is\n // read here first, a sensitive key's and a context rule's alike.\n if (onlyFlags(text, value)) continue;\n if (card && CARD_EXPIRY_BESIDE_A_CARD.has(normalizeKey(key))) {\n edits.push([value.start, value.end, REDACTED_JSON]);\n } else if (\n ((exchange && EXCHANGE_REDACTED.has(normalizeKey(key))) ||\n (bare && normalizeKey(key) === \"code\")) &&\n !(value.kind === \"scalar\" && text.startsWith(\"null\", value.start))\n ) {\n edits.push([value.start, value.end, REDACTED_JSON]);\n } else if (pair && PAIR_VALUES.has(key.toLowerCase())) {\n edits.push([value.start, value.end, REDACTED_JSON]);\n } else {\n redactNode(\n text,\n value,\n isSensitiveKey(key) ? key : null,\n depth + 1,\n extra,\n edits,\n );\n }\n }\n}\n\n/** `text` with each edit's span replaced; the text itself when there are none. */\nfunction applyEdits(\n text: string,\n edits: Array<[number, number, string]>,\n): string {\n if (edits.length === 0) return text;\n edits.sort((a, b) => a[0] - b[0]);\n let out = \"\";\n let pos = 0;\n for (const [start, end, with_] of edits) {\n out += text.slice(pos, start) + with_;\n pos = end;\n }\n return out + text.slice(pos);\n}\n\n/** A JSON text JSON.parse accepted, redacted in place. */\nfunction redactJsonText(\n text: string,\n depth: number,\n extra: readonly RegExp[],\n): string {\n const edits: Array<[number, number, string]> = [];\n redactNode(text, parseJsonSpans(text, depth), null, depth, extra, edits);\n return applyEdits(text, edits);\n}\n\n/** The field of a name/value pair that names it. */\nconst PAIR_NAMES: ReadonlySet<string> = new Set([\"key\", \"name\", \"header\"]);\n/** The fields of a name/value pair that carry the value. */\nconst PAIR_VALUES: ReadonlySet<string> = new Set([\n \"value\",\n \"values\",\n \"expected\",\n \"actual\",\n]);\n\n/**\n * A string that is itself JSON -- a test case's `header` or `body` as\n * api-server stores them, a GraphQL `variables` string -- redacted as JSON\n * and serialised again, or null when it is not JSON. Returned as it came\n * when nothing in it was redacted, so a JSON string with no secret keeps\n * every byte (its whitespace and key order included).\n */\nfunction redactJsonString(\n s: string,\n depth: number,\n extra: readonly RegExp[],\n): string | null {\n if (!/^\\s*[[{]/.test(s)) return null;\n try {\n JSON.parse(s);\n } catch {\n return null;\n }\n return redactJsonText(s, depth + 1, extra);\n}\n\n/**\n * Redact a captured body.\n *\n * JSON in, valid JSON out — always. A body that is not JSON keeps every\n * byte except what is redacted: a form's credential values and the\n * pattern matches in its other values, or, in any other text, the value\n * of an embedded credential pair and the pattern matches.\n */\nexport function redactBody(\n body: string | null | undefined,\n contentType?: string,\n extra: readonly RegExp[] = [],\n): string | null {\n if (body === null || body === undefined || body === \"\") return body ?? null;\n\n // The SDK's own note in place of a body it never read. Nothing in it\n // came from the page, and it is the only record of what the body was;\n // running it through the JSON branch below flattened it to the\n // refusal and lost the kind and the size. See isNotRecordedNote().\n if (isNotRecordedNote(body)) return body;\n\n const looksJson =\n (contentType ?? \"\").toLowerCase().includes(\"json\") || /^\\s*[[{]/.test(body);\n\n if (looksJson) {\n try {\n JSON.parse(body); // validates: what it refuses is still refused\n } catch {\n // Unparseable but JSON-shaped — almost always a truncated capture,\n // since the transport appends \"...[truncated]\" to oversized bodies.\n //\n // Falling through to the text scanner here is what let the ORIGINAL\n // bug back in: the card regex could match a bare JSON number and\n // emit {\"amount\":[REDACTED]}, which no longer parses. There is no\n // safe way to redact a fragment we cannot parse, so refuse it\n // wholesale rather than emit something corrupt.\n return TRUNCATED_UNPARSEABLE;\n }\n return redactJsonText(body, 0, extra);\n }\n\n // Every URL the body holds, raw -- an HTML, XML, RSC or text body's, a\n // multipart part's, a form value's written as it is -- scrubbed first,\n // the cut marker set aside; the passes below then read the rest. Whether\n // it is read as a form is decided once, here, on its URLs read as a\n // form's (a URL's user info can hold an `&`, and its scrub can drop one:\n // decided on the raw bytes, a form was read as text, found in review).\n // A body that is no form has its URLs read as a text's; when the form\n // read changed nothing, the text read changes nothing either.\n const cut = body.endsWith(TRUNCATED_SUFFIX);\n const raw = cut ? body.slice(0, -TRUNCATED_SUFFIX.length) : body;\n const formHeld = scrubTextUrls(raw, FORM_URL_RULES);\n const asForm = readAsForm(\n cut ? formHeld + TRUNCATED_SUFFIX : formHeld,\n contentType ?? \"\",\n );\n const held =\n asForm || formHeld === raw ? formHeld : scrubTextUrls(raw, TEXT_URL_RULES);\n const text = cut ? held + TRUNCATED_SUFFIX : held;\n\n const multipart = redactMultipartText(text, contentType ?? \"\", extra);\n if (multipart !== null) return multipart;\n // Under a multipart content-type a body is either multipart text or the\n // urlencoded rendering of a FormData's fields (see formDataText). One\n // that is neither -- its boundary not the declared one, or too long to\n // be a boundary -- has parts the form path cannot see: refused whole,\n // never recorded as it came (review r2).\n if (MULTIPART.test(contentType ?? \"\") && !asForm) {\n return UNREADABLE;\n }\n\n const form = redactFormBody(\n text,\n extra,\n asForm,\n /(?:java|ecma)script/i.test(contentType ?? \"\"),\n );\n if (form !== null) return form;\n\n return redactStringValue(text, extra);\n}\n\n/* ------------------------------------------------------------------ */\n/* Form bodies */\n/* ------------------------------------------------------------------ */\n/*\n * A CREDENTIAL IN A FORM BODY IS STILL A CREDENTIAL. Key-based redaction\n * ran on JSON alone, so `password=...` in a form post, an OAuth\n * refresh-token request (form-encoded by RFC 6749), a FormData body or an\n * XHR string body reached the server as typed -- MEASURED on 3.0.1 in\n * Chromium.\n *\n * TWO SHAPES, because a response body is served back to the page at\n * replay and must keep every byte that is not a secret:\n *\n * 1. A FORM -- every segment a pair or a bare name, no whitespace inside\n * a trimmed raw name, at least one real pair. A bare flag\n * (`remember&...`, which the WHATWG parser, Rack and PHP all accept)\n * or a trimmed name no longer takes the whole body off this path, as\n * it did in the first fix (review round 1). A value under a sensitive\n * name is replaced whole; a name is sensitive when it is, or when any\n * bracket or dot part of it is (`password[0]`, `token[value]`,\n * `user[password_confirmation]`), the way a sensitive JSON key\n * redacts its whole subtree. The body is scanned for the patterns as\n * it was sent and decoded -- an email is `ada%40example.com` on the\n * wire -- each decoded match redacting exactly the raw bytes it came\n * from.\n * 2. ANY OTHER TEXT -- HTML, an RSC payload, XML, prose: the value of an\n * embedded credential pair is replaced (see embeddedPairRanges), and the\n * whole text is scanned for the patterns.\n *\n * Everything nothing matched is kept byte for byte: nothing is ever\n * re-encoded, and every detector's ranges are merged before one marker\n * replaces each (see applyRanges).\n */\n\n/**\n * What a body cut at the cap ends with (truncate, cutText). Defined here,\n * beside the cut, so the form parser and the cut agree on one string.\n */\nexport const TRUNCATED_SUFFIX = \"...[truncated]\";\n\n/**\n * Cut a recorded body at `maxBodySize`.\n *\n * ONE RULE IN ONE PLACE. The cap was written out at six call sites and\n * missed the seventh: an XHR FormData body was assembled and recorded\n * WHOLE, however large. An upload form with a base64 field put\n * megabytes into one event — past the queue's byte accounting, and far\n * past the 32 KiB the page-unload flush can carry, so it held back\n * everything behind it there too.\n *\n * THE CAP COUNTS UTF-16 CODE UNITS, not bytes: the unit a JS string is\n * measured in, equal to bytes for ASCII and up to 2x under it for\n * multi-byte text. `maxBodySize` is a bound on what is RECORDED, not an\n * exact byte budget, and counting bytes would mean a TextEncoder pass\n * over every body the page sends. The option's docs say so.\n */\nexport function truncate(text: string, maxSize: number): string {\n return text.length > maxSize\n ? text.slice(0, maxSize) + TRUNCATED_SUFFIX\n : text;\n}\n\n/**\n * Text the SDK stopped reading before its end -- the page left, settle()\n * ended, the body failed -- marked as cut. Always under the cap: a body\n * past it has already been recorded, cut at the cap.\n */\nexport function cutText(text: string): string {\n return text + TRUNCATED_SUFFIX;\n}\n\n/**\n * A raw form field name: what a urlencoded serializer or a hand-written\n * `user[password]` leaves -- letters, digits, `%XX`, `+` and `_.-~!*'()[]`.\n * Markup, URLs and prose (`<cfg><url>https://h/x?a`) are not names, so\n * the XML body that holds one is not taken for a form (review round 2).\n * EMPTY IS A NAME: the WHATWG urlencoded parser reads `=x` as one, and\n * refusing it sent a whole form down the embedded-pair path, whose value\n * stops at `(` -- `=x&password=pa(ss` kept `(ss` (review r4, B6).\n */\nconst FORM_NAME = /^[A-Za-z0-9_.~!*'()%+[\\]-]*$/;\n\n/** A form name or value decoded, or as it came when it does not decode. */\nfunction formDecode(raw: string): string {\n if (!/[%+]/.test(raw)) return raw;\n const out = newDecodedText(raw.length);\n appendDecoded(raw, 0, raw.length, out);\n return out.parts.join(\"\");\n}\n\n/** Two hex digits at `i`, as a byte, or -1. */\nfunction hexByte(raw: string, i: number): number {\n if (i + 2 > raw.length) return -1;\n const hi = parseInt(raw[i], 16);\n const lo = parseInt(raw[i + 1], 16);\n return Number.isNaN(hi) || Number.isNaN(lo) ? -1 : hi * 16 + lo;\n}\n\n/** Decoded text, and for each of its code units the raw span it came from. */\ninterface DecodedText {\n parts: string[];\n start: Int32Array;\n end: Int32Array;\n length: number;\n}\n\n/** Room for `capacity` code units: a decoded text is never longer than its raw one. */\nfunction newDecodedText(capacity: number): DecodedText {\n return {\n parts: [],\n start: new Int32Array(capacity),\n end: new Int32Array(capacity),\n length: 0,\n };\n}\n\n/** One decoded code unit `unit`, from raw[from, to). */\nfunction appendUnit(\n out: DecodedText,\n unit: string,\n from: number,\n to: number,\n): void {\n out.parts.push(unit);\n for (let u = 0; u < unit.length; u++) {\n out.start[out.length] = from;\n out.end[out.length] = to;\n out.length++;\n }\n}\n\n/** raw[from, to) as it came, one decoded unit per raw unit. */\nfunction appendRaw(\n raw: string,\n from: number,\n to: number,\n out: DecodedText,\n): void {\n if (from >= to) return;\n out.parts.push(raw.slice(from, to));\n for (let i = from; i < to; i++) {\n out.start[out.length] = i;\n out.end[out.length] = i + 1;\n out.length++;\n }\n}\n\n/**\n * One form name or value decoded as the urlencoded parser decodes it\n * (`+` is a space, `%XX` a UTF-8 byte), appended to `out` with, for every\n * decoded code unit, the span of RAW text it came from -- so a match found\n * in the decoded text is redacted in the raw one, escapes whole, and\n * nothing outside a match is ever re-encoded (re-encoding turned each raw\n * `中` into `%E4%B8%AD`, 7.7x with no pattern at all -- review r8).\n * A part with a malformed escape or bytes that are not UTF-8 is appended\n * as it came, one unit per raw unit, without an exception:\n * decodeURIComponent threw on each, and a thrown URIError per pair cost\n * 0.4-0.8 s on a 512 KB body of them (review round 2).\n */\nfunction appendDecoded(\n raw: string,\n from: number,\n to: number,\n out: DecodedText,\n): void {\n const marks = { parts: out.parts.length, length: out.length };\n let run = from; // the start of a stretch that decodes to itself\n let i = from;\n while (i < to) {\n const c = raw.charCodeAt(i);\n if (c !== 43 && c !== 37) {\n i++; // neither `+` nor `%`\n continue;\n }\n appendRaw(raw, run, i, out);\n if (c === 43) {\n appendUnit(out, \" \", i, i + 1);\n run = ++i;\n continue;\n }\n // A UTF-8 sequence: the lead byte says how many bytes follow; each\n // must be an escaped continuation byte, and the ranges below are\n // exactly the ones decodeURIComponent accepts (no overlong forms, no\n // surrogates, nothing past U+10FFFF).\n const lead = i + 3 <= to ? hexByte(raw, i + 1) : -1;\n let n = -1;\n let lo = 0x80;\n let hi = 0xbf;\n if (lead >= 0 && lead < 0x80) n = 0;\n else if (lead >= 0xc2 && lead <= 0xdf) n = 1;\n else if (lead >= 0xe0 && lead <= 0xef) {\n n = 2;\n if (lead === 0xe0) lo = 0xa0;\n if (lead === 0xed) hi = 0x9f;\n } else if (lead >= 0xf0 && lead <= 0xf4) {\n n = 3;\n if (lead === 0xf0) lo = 0x90;\n if (lead === 0xf4) hi = 0x8f;\n }\n let cp = n <= 0 ? lead : lead & (0x3f >> n);\n for (let k = 1; k <= n && cp >= 0; k++) {\n const at = i + 3 * k;\n const b = at + 3 <= to && raw[at] === \"%\" ? hexByte(raw, at + 1) : -1;\n cp =\n b < (k === 1 ? lo : 0x80) || b > (k === 1 ? hi : 0xbf)\n ? -1\n : (cp << 6) | (b & 0x3f);\n }\n if (n < 0 || cp < 0) {\n // Not UTF-8: the whole part as it came.\n out.parts.length = marks.parts;\n out.length = marks.length;\n appendRaw(raw, from, to, out);\n return;\n }\n const end = i + 3 * (n + 1);\n appendUnit(out, String.fromCodePoint(cp), i, end);\n run = i = end;\n }\n appendRaw(raw, run, to, out);\n}\n\n/**\n * A `name=value` pair embedded in a body that is NOT a form: a query\n * string inside an HTML link (`&amp;token=`), an RSC payload or XML, or a\n * line of prose that holds one. It starts only after `?`, `&`, `;`, a\n * newline, a tag's `>` (`<p>password=...</p>`, found in review), a `#`\n * (a fragment's pair, `Location: /cb#access_token=...`, an unlisted\n * attribute's `data-url=\"/cb#access_token=...\"`, found in review), the start\n * of the body, or a space that follows no bracket and no declaration\n * (`x token=... y`, `user=bob; password=...` and `user=bob, password=...`\n * are text; `var token=`, `if (x) token=` and `{ token=` are code, whose\n * response a replay may run -- and neither in a JavaScript body nor in a\n * `<script>`'s text does a space, a tag or a `#` start a pair: a class's\n * `#token=t` is a private field), its name has no `.` (so minified\n * JS's `e&&e.token=t` is an assignment, not a pair), and its value ends\n * at the first delimiter -- so only the credential is replaced and every\n * other byte of a response that replay serves back is kept. Review round\n * 2 measured the alternative (the value running to the next `&`) deleting\n * the rest of HTML, RSC and XML bodies.\n *\n * The pattern finds a NAME and its `=`, never a value: a match that took\n * the whole pair swallowed every later `?name=` inside its value, so\n * `?next=/b?token=x` in a link, or a form's `redirect=https://x/cb?token=x`,\n * kept the token (review r1 of the port). A value is read only for a\n * sensitive name, and the search resumes after it; any other name's value\n * is searched on from its `=`. Each character is read at most once by the\n * name search and once by a value read: linear. A name's brackets close\n * (`user[password]=`): CSS's `[data-token=x]` selects, and holds no pair.\n * A name found is read by the one rule as a `param`. What is a name is\n * narrower here than in a form: letters, digits, `_`, `-`, `%` and closed\n * brackets, and no `.`, `$` or `+`, which a script's `;e.token=t`,\n * `$token=` and `token+=1` hold -- a JavaScript body or a `<script>`\n * rewritten to `e.token=[REDACTED]` throws when a replay serves it.\n */\nconst EMBEDDED_NAME =\n /(^|[?&;\\n>#]|(?<!\\b(?:var|let|const)|[(){}])[ \\t\\r\\f\\v])([\\w%-]*(?:\\[[\\w%-]*\\][\\w%-]*)*)=/g;\n/**\n * The leads a pair takes in a body that is JavaScript: a start, `?`, `&`,\n * `;`, a newline, or a `#` after a path's character\n * (`\"/cb#access_token=...\"`, found in review) -- its spaces and tags\n * separate code, not pairs, and a `#` after a `.`, a brace, a space or\n * the keyword `static` or `accessor` (`static#token=null`, minified,\n * found in review), or the star and slash that close a block comment\n * (`class A{/**`, `/#token=null}`, found in review), is a private field.\n */\nconst EMBEDDED_NAME_IN_CODE =\n /(^|[?&;\\n]|(?<=[\\w/%~-])(?<!\\*\\/|(?:^|[^\\w$/%~.-])(?:static|accessor))#)([\\w%-]*(?:\\[[\\w%-]*\\][\\w%-]*)*)=/g;\n/**\n * The leads a pair takes in a JSON string, whose content-type says\n * nothing of what it holds -- a message, a stored form, a link, or code,\n * SQL or Markdown: its start, a query's `?` and `&`, and a fragment's `#`\n * after a path (`/cb#access_token=`), never a `;`, a space, a newline or\n * a `#` after a bracket or a dot. Read with a text body's leads, a\n * string's `let a=1;token=getToken()`, `SET password=?` and a class's\n * `#token=null` lost their code (found in review).\n */\nconst EMBEDDED_NAME_IN_STRING =\n /(^|[?&]|(?<=[\\w/%~-])(?<!\\*\\/|(?:^|[^\\w$/%~.-])(?:static|accessor))#)([\\w%-]*(?:\\[[\\w%-]*\\][\\w%-]*)*)=/g;\n/**\n * The leads a pair takes in a header's value (one Location, Content-Location,\n * Link and Refresh are not): a header's parameters are separated by `;`,\n * `,` and spaces (`a=1, token=...`, `0; url=/next?a=1;sig=...`), and\n * hold no code (found in review: each was kept).\n */\nconst EMBEDDED_NAME_IN_HEADER =\n /(^|[?&;,\\s]|(?<=[\\w/%~-])#)([\\w%-]*(?:\\[[\\w%-]*\\][\\w%-]*)*)=/g;\n/** A pair's value: to its first space, quote, backtick, tag, bracket, backslash, `&`, `;`, comma, or a template literal's `${` (code, not a value: `` `/api?token=abc${t}` `` lost its `$`, found in review). */\nconst EMBEDDED_VALUE = /(?:[^\\s&\"'`<>\\\\,;(){}[\\]$]|\\$(?!\\{))+/y;\n/**\n * A JSON string's pair's value: to the next `&` or the string's end. A\n * credential's value there fails closed: ended at a space,\n * `password=correct horse battery staple` kept the words after its first\n * (found in review), and ended at a line break, a PEM key's lines after\n * its first would be kept.\n */\nconst EMBEDDED_VALUE_IN_STRING = /[^&]+/y;\n\n/** Which leads a pair takes: a text body's, a JavaScript body's, a JSON string's, or a header's. */\ntype PairMode = \"text\" | \"code\" | \"string\" | \"header\";\n\n/** The value range of every embedded credential pair in `body`, by `mode`'s leads (EMBEDDED_NAME, EMBEDDED_NAME_IN_CODE, EMBEDDED_NAME_IN_STRING, EMBEDDED_NAME_IN_HEADER) and its value's end (EMBEDDED_VALUE_IN_STRING in a JSON string, EMBEDDED_VALUE elsewhere). */\nfunction embeddedPairRanges(\n body: string,\n into: Range[],\n mode: PairMode = \"text\",\n): void {\n const names =\n mode === \"code\"\n ? EMBEDDED_NAME_IN_CODE\n : mode === \"string\"\n ? EMBEDDED_NAME_IN_STRING\n : mode === \"header\"\n ? EMBEDDED_NAME_IN_HEADER\n : EMBEDDED_NAME;\n // A <script>'s text is code, as a JavaScript body is: a space or a tag\n // there leads no pair (`<script>let a = 1; token=t</script>`).\n const scripts =\n mode !== \"text\" || !/<script/i.test(body) ? [] : scriptRanges(body);\n let r = 0;\n names.lastIndex = 0;\n for (let m = names.exec(body); m !== null; m = names.exec(body)) {\n if (!isCredentialName(m[2], \"param\")) continue;\n // In a <script>, a `#` leads a pair only after a path's character, as\n // in a string (`location.replace(\"/cb#access_token=...\")`, found in\n // review), never after a `.`, a brace, a space, a comment's `*/`,\n // `static` or `accessor` (a private field).\n if (\n scripts.length > 0 &&\n (/^[ \\t\\r\\f\\v>]$/.test(m[1]) ||\n (m[1] === \"#\" &&\n (!/[\\w/%~-]/.test(body[m.index - 1] ?? \"\") ||\n body.startsWith(\"*/\", m.index - 2) ||\n /(?:^|[^\\w$/%~.-])(?:static|accessor)$/.test(\n body.slice(Math.max(0, m.index - 9), m.index),\n ))))\n ) {\n while (r < scripts.length && scripts[r][1] <= m.index) r++;\n if (r < scripts.length && scripts[r][0] <= m.index) continue;\n }\n const valueStart = m.index + m[0].length;\n EMBEDDED_VALUE.lastIndex = valueStart;\n let value = EMBEDDED_VALUE.exec(body);\n if (value === null) continue;\n // A JSON string's value runs on to the next `&` or the string's end,\n // where EMBEDDED_VALUE starts one: one that starts at a space, a\n // quote, a backtick, a bracket, `<`, `>`, `,`, `;` or a backslash is\n // code's, kept (`fetch('/api?token='+t)`, `x='?token='`, found in\n // review), and so is a marker a URL scrub before this one wrote\n // (`?token=[REDACTED]\">link</a>`): the bytes after it are the text's.\n if (mode === \"string\") {\n EMBEDDED_VALUE_IN_STRING.lastIndex = valueStart;\n value = EMBEDDED_VALUE_IN_STRING.exec(body) ?? value;\n }\n const valueEnd = valueStart + value[0].length;\n into.push([valueStart, valueEnd]);\n names.lastIndex = valueEnd;\n }\n}\n\n/**\n * The text of each `<script>` in `body`, to its end tag or the body's\n * end. An open tag is found, then its `>`, each once: a pattern that took\n * the tag whole read to the body's end from every `<script` with no `>`\n * after it, seconds on a 512 KB response (MEASURED in review). With no\n * `>` left, no tag can open.\n */\nfunction scriptRanges(body: string): Range[] {\n const out: Range[] = [];\n const open = /<script\\b/gi;\n const close = /<\\/script\\s*>/gi;\n for (let m = open.exec(body); m !== null; m = open.exec(body)) {\n const gt = body.indexOf(\">\", m.index);\n if (gt === -1) break;\n close.lastIndex = gt + 1;\n const end = close.exec(body);\n const to = end === null ? body.length : end.index;\n out.push([gt + 1, to]);\n open.lastIndex = to;\n }\n return out;\n}\n\n/** A character an embedded pair can follow, as sent or once decoded. */\nconst PAIR_LEAD = /[?;\\n]|%(?:3[FfBb]|26|0[Aa])/;\n\n/**\n * One segment of a form: a pair or a bare name, its trimmed raw name a\n * form name and its value free of raw whitespace (an encoded value\n * carries none; one that does is prose or markup, kept byte for byte on\n * the other path). An empty segment -- a trailing or doubled `&` -- has\n * the empty name, which FORM_NAME accepts.\n */\nfunction formSegment(seg: string): boolean {\n const eq = seg.indexOf(\"=\");\n const name = (eq === -1 ? seg : seg.slice(0, eq)).trim();\n return FORM_NAME.test(name) && (eq === -1 || !/\\s/.test(seg.slice(eq + 1)));\n}\n\n/**\n * The embedded credential pairs inside one form segment, text[from, to).\n *\n * Per segment, and only a segment that holds a character a pair can\n * follow (`?`, `;`, `&` once decoded, a newline): a search over the whole\n * form found every pair of the form itself again and re-checked each name\n * the segment loop had just checked, which doubled the cost of a form of\n * many fields on the page's main thread (512 KB of `a=b&`: 18 -> 35 ms\n * quiet, over a second under load). The check is a walk over the segment\n * alone, so it stays linear. A segment's start counts as a line start.\n */\nfunction spanPairRanges(\n text: string,\n from: number,\n to: number,\n into: Range[],\n): void {\n let lead = false;\n for (let i = from; i < to && !lead; i++) {\n const c = text.charCodeAt(i);\n lead = c === 63 || c === 59 || c === 38 || c === 10; // ? ; & \\n\n }\n if (!lead) return;\n const found: Range[] = [];\n embeddedPairRanges(text.slice(from, to), found);\n for (const [s0, e0] of found) into.push([from + s0, from + e0]);\n}\n\n/**\n * A content-type under which the page itself says the body is a form.\n * multipart is here because network.ts records a FormData -- passed\n * directly or inside a Request -- as the urlencoded pairs of its fields\n * (see formDataText). Multipart TEXT, as a page writes it by hand, is\n * parsed before this is consulted (see redactMultipartText).\n */\nconst DECLARED_FORM =\n /^\\s*(?:application\\/x-www-form-urlencoded|multipart\\/form-data)\\s*(?:;|$)/i;\n\n/**\n * Whether a body is read as a form (redactFormBody), `body` its bytes with\n * its URLs read as a form's and the cut marker, if any, on. The page says\n * so for one it declares x-www-form-urlencoded: it is one whatever its\n * bytes look like, and every\n * value runs to the next `&` -- a hand-built `password=correct horse\n * battery staple` recorded `password=[REDACTED] horse battery staple`\n * while the raw spaces sent it down the embedded-pair path, whose value\n * stops at the first space (review round 3). Under multipart a body that\n * is no multipart text is a FormData's rendering (see formDataText).\n * Otherwise it is one shaped as a form throughout: every segment a pair or\n * a bare name (no whitespace inside a trimmed name), and at least one\n * pair. A cut tail is exempt from the shape test -- the cut may have taken\n * its `=` or split a value -- and may be that pair, so `password=abc(def`\n * cut at the cap keeps its whole value redacted. A cut segment of HTML or\n * a log line taken for a form this way loses nothing: the form path\n * searches every segment for embedded credential pairs as the text path\n * does.\n */\nfunction readAsForm(body: string, contentType: string): boolean {\n if (MULTIPART.test(contentType)) return isFormRendering(body);\n if (DECLARED_FORM.test(contentType)) return true;\n const cut = body.endsWith(TRUNCATED_SUFFIX);\n const text = cut ? body.slice(0, -TRUNCATED_SUFFIX.length) : body;\n const segments = text.split(\"&\");\n const last = segments.length - 1;\n return (\n segments.some((seg) => seg.includes(\"=\")) &&\n segments.every((seg, i) => (cut && i === last) || formSegment(seg))\n );\n}\n\n/** The body redacted as a form, or null when nothing in it applied; `formShaped` is readAsForm's answer. */\nfunction redactFormBody(\n body: string,\n extra: readonly RegExp[],\n formShaped: boolean,\n code = false,\n): string | null {\n // A cut body ends mid-pair: its last segment may have lost its `=`.\n const cut = body.endsWith(TRUNCATED_SUFFIX);\n const text = cut ? body.slice(0, -TRUNCATED_SUFFIX.length) : body;\n const segments = text.split(\"&\");\n if (!formShaped) {\n // Only a body that holds a credential pair takes this path; any other\n // text is the caller's plain scan. The cut marker is the SDK's, not the\n // body's: it is set aside, or a value read up to it took its dots.\n const ranges: Range[] = [];\n embeddedPairRanges(text, ranges, code ? \"code\" : \"text\");\n if (ranges.length === 0) return null;\n detectorRanges(text, extra, ranges);\n return applyRanges(text, ranges) + (cut ? TRUNCATED_SUFFIX : \"\");\n }\n\n // ONE pass of every detector over the body as it came, and one over it\n // decoded, each name and value decoded with a map back to its raw\n // bytes; the `&` and `=` between them stay themselves. No built-in can\n // match across an `&` or an `=` (none of them admits either), so a\n // whole-body scan finds exactly what a scan per name and value found --\n // at one pass instead of six per pair, which cost 100-300x base on a\n // form of many fields (review r8). The integrator's patterns see the\n // whole body too, so one may span `name=value` (`member_id=\\d+`) or\n // several fields (review round 5, H2), as base's scan of the whole body\n // allowed, and one written against the decoded value (`dob=01/02/1990`\n // in a FormData, recorded as `dob=01%2F02%2F1990`) matches it (review\n // r6, B2). PII in the NAME half of a pair is found the same way (review\n // round 4).\n const ranges: Range[] = [];\n detectorRanges(text, extra, ranges);\n // With no `%` and no `+` anywhere, the decoded form IS the form as sent,\n // and a second scan of it would find exactly the same ranges.\n const escaped = /[%+]/.test(text);\n const decoded = newDecodedText(escaped ? text.length : 0);\n // An embedded pair follows `?`, `;` or a newline, raw or escaped, or an\n // `&` that only decoding produces. A form with none of them -- most\n // forms -- skips the pair search below: one pass instead of one per\n // segment.\n const pairsPossible = PAIR_LEAD.test(text);\n // Where each segment sits in the decoded text, for the pair search below.\n const decodedSegments: number[] = [];\n // An OAuth token exchange's `code` (isTokenExchange).\n const exchange = isTokenExchange(\n segments.flatMap((seg) => {\n const eq = seg.indexOf(\"=\");\n return eq === -1\n ? []\n : [\n [\n normalizeKey(formDecode(seg.slice(0, eq))),\n formDecode(seg.slice(eq + 1)),\n ] as [string, string],\n ];\n }),\n );\n // Raw JSON values redacted in their own text, and the scratch result.\n const jsonSpans: Range[] = [];\n let json: Range | null;\n let at = 0;\n for (const seg of segments) {\n const eq = seg.indexOf(\"=\");\n const nameEnd = eq === -1 ? at + seg.length : at + eq;\n const segEnd = at + seg.length;\n const from = decoded.length;\n if (escaped) appendDecoded(text, at, nameEnd, decoded);\n if (eq !== -1 && escaped) {\n appendUnit(decoded, \"=\", nameEnd, nameEnd + 1);\n appendDecoded(text, nameEnd + 1, segEnd, decoded);\n }\n // A sensitive name redacts its value wherever the pair sits, an\n // empty one included.\n if (\n eq !== -1 &&\n (isCredentialName(seg.slice(0, eq), \"param\") ||\n (exchange &&\n EXCHANGE_REDACTED.has(normalizeKey(formDecode(seg.slice(0, eq))))))\n ) {\n ranges.push([nameEnd + 1, segEnd]);\n } else if (\n eq !== -1 &&\n holdsEncodedUrlCredential(text.slice(nameEnd + 1, segEnd))\n ) {\n // A URL a value holds encoded, with a credential in it\n // (holdsEncodedUrlCredential): the value goes whole.\n ranges.push([nameEnd + 1, segEnd]);\n } else if (\n eq !== -1 &&\n (json = jsonFormValue(text, nameEnd + 1, segEnd, extra)) !== null\n ) {\n // A value that is JSON with something in it to redact -- a GraphQL\n // multipart upload's `operations` carries the variables. Written as\n // it came, it is redacted in its own text; URL-encoded, it goes\n // whole, since a redaction inside it cannot be written back without\n // re-encoding the rest.\n if (json.length === 3) jsonSpans.push(json);\n else ranges.push(json);\n } else if (pairsPossible) {\n // A credential pair INSIDE any other segment -- a redirect URL's\n // `?token=` in a value, a `cb?pwd=` in a name -- is found as in any\n // other text, raw here and decoded below.\n spanPairRanges(text, at, segEnd, ranges);\n if (escaped) decodedSegments.push(from, decoded.length);\n }\n at += seg.length;\n if (at < text.length) {\n if (escaped) appendUnit(decoded, \"&\", at, at + 1);\n at++;\n }\n }\n if (escaped) {\n const found: Range[] = [];\n const plain = decoded.parts.join(\"\");\n detectorRanges(plain, extra, found);\n // `redirect=https%3A%2F%2Fx%2Fcb%3Ftoken%3Dabc` holds `?token=abc`\n // only once decoded.\n for (let k = 0; k < decodedSegments.length; k += 2) {\n spanPairRanges(plain, decodedSegments[k], decodedSegments[k + 1], found);\n }\n for (const [s0, e0] of found) {\n ranges.push([decoded.start[s0], decoded.end[e0 - 1]]);\n }\n }\n // A raw JSON value's own redaction already scanned it: a detector's\n // range inside it would merge with it into a bare marker.\n // jsonSpans are in text order and disjoint (one per segment): each\n // range is looked up by binary search, not against every span -- a\n // form of 40,000 JSON fields was quadratic (review).\n const kept = ranges.filter(([a, b]) => !insideSpan(jsonSpans, a, b));\n return (\n applyRanges(text, [...kept, ...jsonSpans]) + (cut ? TRUNCATED_SUFFIX : \"\")\n );\n}\n\n/* ------------------------------------------------------------------ */\n/* Multipart text */\n/* ------------------------------------------------------------------ */\n\nconst MULTIPART = /^\\s*multipart\\/form-data\\s*(?:;|$)/i;\nconst BOUNDARY_PARAM =\n /;\\s*boundary\\s*=\\s*(?:\"([^\"\\r\\n]{1,200})\"|([^\\s;\"]{1,200}))/i;\n/** A part's field name in its Content-Disposition header. */\nconst PART_NAME =\n /^content-disposition\\s*:[^\\n]*?;\\s*name\\s*=\\s*(?:\"([^\"\\r\\n]*)\"|([^\\s;]+))/im;\n/** A part that carries a file: its bytes are never recorded. */\nconst PART_FILE = /^content-disposition\\s*:[^\\n]*?;\\s*filename\\*?\\s*=/im;\n\n/**\n * A multipart body written out as TEXT -- by hand, as a string passed to\n * fetch or XMLHttpRequest, or served as a response -- redacted part by\n * part, or null when the body is not one.\n *\n * Without this such a body took the form path, which knows `&` and `=`\n * and not parts: a `name=\"password\"` part's value was recorded in clear,\n * and a `&password=` inside another part's text redacted everything after\n * it, the closing boundary included (review r1 of the port, M2).\n *\n * The boundary is the content-type's, or -- when the page declared none\n * -- the body's own first line. Each part's value is replaced whole when\n * its name is sensitive (as a form field's is: `password`, `user[token]`)\n * or when the part is a file; every other value, and every header block,\n * is scanned like any other text. Every other byte is kept. A body cut at\n * the cap keeps what it has: its last part runs to the cut.\n */\nfunction redactMultipartText(\n body: string,\n contentType: string,\n extra: readonly RegExp[],\n): string | null {\n if (!MULTIPART.test(contentType)) return null;\n const cut = body.endsWith(TRUNCATED_SUFFIX);\n const text = cut ? body.slice(0, -TRUNCATED_SUFFIX.length) : body;\n const param = BOUNDARY_PARAM.exec(contentType);\n const boundary =\n param !== null\n ? (param[1] ?? param[2])\n : (/^--([^\\r\\n]{1,200})\\r?\\n/.exec(text)?.[1] ?? null);\n if (boundary === null) return null;\n const delimiter = \"--\" + boundary;\n let at = text.startsWith(delimiter) ? 0 : text.indexOf(\"\\n\" + delimiter);\n // Not multipart text: a FormData rendering (pairs) or anything else.\n if (at === -1) return null;\n if (at > 0) at += 1;\n const ranges: Range[] = [];\n scanSpan(text, 0, at, extra, ranges); // a preamble\n for (;;) {\n const after = at + delimiter.length;\n // A close delimiter ends the body only when no delimiter follows it:\n // `--X--` written inside a value must not leave the parts after it\n // to the pattern scan alone (review r2).\n if (\n text.startsWith(\"--\", after) &&\n text.indexOf(\"\\n\" + delimiter, after) === -1\n ) {\n scanSpan(text, after + 2, text.length, extra, ranges); // an epilogue\n break;\n }\n const lineEnd = text.indexOf(\"\\n\", after);\n if (lineEnd === -1) break; // cut inside a delimiter line\n // Headers run to the first empty line.\n let line = lineEnd + 1;\n let valueStart = -1;\n while (line < text.length) {\n const end = text.indexOf(\"\\n\", line);\n if (end === -1) break;\n if (end === line || (end === line + 1 && text[line] === \"\\r\")) {\n valueStart = end + 1;\n break;\n }\n line = end + 1;\n }\n const headersEnd = valueStart === -1 ? text.length : valueStart;\n scanSpan(text, lineEnd + 1, headersEnd, extra, ranges);\n if (valueStart === -1) break; // cut inside a header block\n const next = text.indexOf(\"\\n\" + delimiter, valueStart);\n let valueEnd = next === -1 ? text.length : next;\n if (next !== -1 && valueEnd > valueStart && text[valueEnd - 1] === \"\\r\") {\n valueEnd--;\n }\n const headers = text.slice(lineEnd + 1, headersEnd);\n const name = PART_NAME.exec(headers);\n const fieldName = name === null ? \"\" : (name[1] ?? name[2]);\n const jsonPart =\n PART_FILE.test(headers) || isCredentialName(fieldName, \"param\")\n ? null\n : redactJsonString(text.slice(valueStart, valueEnd), 0, extra);\n if (PART_FILE.test(headers) || isCredentialName(fieldName, \"param\")) {\n ranges.push([valueStart, valueEnd]);\n } else if (\n jsonPart !== null &&\n jsonPart !== text.slice(valueStart, valueEnd)\n ) {\n // A JSON part with something in it to redact (a GraphQL upload's\n // `operations`), redacted in its own text.\n ranges.push([valueStart, valueEnd, jsonPart]);\n } else {\n scanSpan(text, valueStart, valueEnd, extra, ranges);\n }\n if (next === -1) break;\n at = next + 1;\n }\n return applyRanges(text, ranges) + (cut ? TRUNCATED_SUFFIX : \"\");\n}\n\n/** The fail-closed note: a body nothing here can read safely. */\nconst UNREADABLE = \"[Unreadable body]\";\n\n/**\n * True for a body shaped as a FormData's urlencoded rendering, whole or\n * cut: every `&`-segment a form segment. The cut marker holds no `=`, `&`\n * or whitespace, and its dots, brackets and letters are name characters,\n * so it never makes a segment pass that would fail without it, and a\n * rendering cut anywhere, inside a name or a value, still passes. The\n * last segment of a cut body was once let through unread, and a cut body\n * with no `&` is one segment and the last: a multipart body under another\n * boundary than the declared one, cut at the cap, passed for a rendering\n * and went down the form path, which cannot see its parts.\n */\nfunction isFormRendering(body: string): boolean {\n return body.split(\"&\").every(formSegment);\n}\n\n/** True when [a, b) lies inside one of `spans`, which are sorted and disjoint. */\nfunction insideSpan(spans: Range[], a: number, b: number): boolean {\n let lo = 0;\n let hi = spans.length - 1;\n while (lo <= hi) {\n const mid = (lo + hi) >> 1;\n const [c, d] = spans[mid];\n if (a < c) hi = mid - 1;\n else if (a >= d) lo = mid + 1;\n else return b <= d;\n }\n return false;\n}\n\n/**\n * A form value that is JSON with something in it to redact, as the range\n * to write, or null. Written as it came (no `%`, no `+`), its own\n * redaction is the replacement, every other byte kept; URL-encoded, the\n * whole value goes.\n */\nfunction jsonFormValue(\n text: string,\n start: number,\n end: number,\n extra: readonly RegExp[],\n): Range | null {\n const raw = text.slice(start, end);\n if (!/^(?:%7B|%5B|[[{])/i.test(raw)) return null;\n if (/[%+]/.test(raw)) {\n const decoded = formDecode(raw);\n const redacted = redactJsonString(decoded, 0, extra);\n return redacted === null || redacted === decoded ? null : [start, end];\n }\n const redacted = redactJsonString(raw, 0, extra);\n return redacted === null || redacted === raw ? null : [start, end, redacted];\n}\n\n/** text[from, to) scanned like any other text, its ranges shifted back. */\nfunction scanSpan(\n text: string,\n from: number,\n to: number,\n extra: readonly RegExp[],\n into: Range[],\n): void {\n if (from >= to) return;\n const span = text.slice(from, to);\n const found: Range[] = [];\n detectorRanges(span, extra, found);\n embeddedPairRanges(span, found);\n for (const [s0, e0] of found) into.push([from + s0, from + e0]);\n}\n\n/** Exposed for tests and diagnostics. */\nexport const __internals = {\n isSensitiveKey,\n isLikelyCardNumber,\n passesLuhn,\n redactCards,\n};\n","/* ------------------------------------------------------------------ */\n/* @keploy/capture-sdk - the page's stream of its body, a lazy chunk */\n/* ------------------------------------------------------------------ */\n\n/*\n * THE RELAY OF A BODY THE PAGE READS THROUGH `res.body` (network.ts\n * relayResponse says why it is a relay): a byte stream that takes the\n * network's reader at the page's first read and reads the network once\n * per page read, recording what the page reads. Only pages that stream a\n * body (SSE, NDJSON, LLM tokens, RSC) run it, so it is not in the main\n * bundle (founder, 2026-11-11: lazy-load what only some pages use): it is\n * part of the body code's chunk (body-redact.ts exports it), which the\n * capture asks for at init. Until that chunk has arrived -- or while the\n * page's leave holds its load -- the page gets the network's own stream\n * at once, never a wait (network.ts; coordinator ruling C4, 2026-11-16,\n * from the founder's \"the SDK never slows the frontend\" and \"losing\n * capture fails closed\"). Taking it records nothing (C7: a page may only\n * look, then read whole); a body nothing reads whole is recorded as not\n * captured. Whole reads (text(), json(), ...) need none of this and are\n * recorded in the main bundle.\n */\n\nimport { cutText, truncate } from \"./redact\";\n\n/**\n * One exchange's recording, as network.ts's relayResponse keeps it: its\n * whole reads and the page's stream both read into it, and the first to\n * report is the recording.\n */\nexport interface Recording {\n /** A read of the body began: a whole read of any member, or the page's own stream. */\n touched: boolean;\n /** The body is recorded: nothing reads into it any more. */\n reported: boolean;\n /** The stream path's text so far, while it records (cut where it is at a leave). */\n text: string;\n /** Record `value`, if nothing has yet. */\n say: (value: string | null) => void;\n /** Record `value`, if nothing has yet, and end the relay. */\n end: (value: string | null) => void;\n /** End the relay: its event may go (network.ts emit). */\n finished: () => void;\n}\n\n/**\n * A body chunk as the platform takes one: a Uint8Array (from any realm),\n * else a TypeError -- what `text()` and the other readers answer for a\n * page-built body that enqueues anything else, without the SDK too.\n */\nfunction bytesOf(value: unknown): Uint8Array {\n // The platform's own TypedArray tag getter: it reads the object's real\n // type (any realm, subclasses included) and runs no code of the page's,\n // where its Symbol.toStringTag could be faked or throw.\n if (typedArrayName(value) === \"Uint8Array\") return value as Uint8Array;\n throw new TypeError(\"a response body chunk is not a Uint8Array\");\n}\n\n/**\n * `%TypedArray%.prototype[Symbol.toStringTag]`'s getter, looked up at the\n * first chunk (the worker, which bundles this chunk's module, never runs it).\n */\nlet typedArrayTag: unknown;\n/** A typed array's name, else undefined. */\nfunction typedArrayName(value: unknown): unknown {\n typedArrayTag ??= Reflect.get(\n Object.getOwnPropertyDescriptor(\n Object.getPrototypeOf(Uint8Array.prototype) as object,\n Symbol.toStringTag,\n ) ?? {},\n \"get\",\n );\n return typeof typedArrayTag === \"function\"\n ? Reflect.apply(typedArrayTag, value, [])\n : undefined;\n}\n\n/** The underlying-source type of a byte stream. */\nconst BYTE_SOURCE = \"bytes\";\n\n/** What the relay calls on its page stream's controller, default or byte. */\ninterface PageController {\n enqueue(chunk: Uint8Array): void;\n close(): void;\n error(reason?: unknown): void;\n readonly byobRequest?: { respond(bytesWritten: number): void } | null;\n}\n\n/**\n * The page's stream of `native`, its own Response's network body, read\n * into `rec` up to `maxSize` UTF-16 units (network.ts relayResponse).\n */\nexport function relayBody(\n native: ReadableStream<Uint8Array>,\n maxSize: number,\n rec: Recording,\n): ReadableStream<Uint8Array> {\n const { end, say, finished } = rec;\n const decoder = new TextDecoder();\n let reader: ReadableStreamDefaultReader<Uint8Array> | undefined;\n const source = {\n pull(c: PageController) {\n if (!reader) {\n reader = native.getReader();\n rec.touched = true;\n }\n // Until a chunk is handed over or the body ends: a pull that settles\n // with neither is not called again (Streams: pullAgain), and the\n // page's read would wait for ever.\n const one = (): Promise<void> =>\n reader!.read().then((next) => {\n if (next.done) {\n if (!rec.reported)\n end(truncate(rec.text + decoder.decode(), maxSize));\n finished();\n c.close();\n // A BYOB read waiting at the end is answered with no bytes.\n c.byobRequest?.respond(0);\n return;\n }\n const chunk = bytesOf(next.value);\n // An empty chunk (a page-built body may enqueue one) is nothing\n // to hand over: a byte stream refuses it.\n if (!chunk.byteLength) return one();\n // Decoded only while it records: not once it is reported (past\n // the cap, read whole through a clone, or not read at `hidden`).\n if (!rec.reported) {\n rec.text += decoder.decode(chunk, { stream: true });\n if (rec.text.length > maxSize) {\n say(truncate(rec.text, maxSize));\n rec.text = \"\";\n // A body still arriving a second after its cap is a\n // stream, or one the page is not reading: its event is\n // masked then (emit), not held to its end.\n setTimeout(finished, 1_000);\n }\n }\n // A byte stream's enqueue() transfers (detaches) the chunk's\n // buffer, which the body's source may still hold -- a pooled\n // buffer, or a constant chunk a page-built body enqueues again\n // and again. The page is handed a copy, made by the\n // constructor, not by the chunk's own slice(): a Buffer\n // polyfill's slice() is a view onto the same memory.\n c.enqueue(new Uint8Array(chunk));\n });\n return one().catch((err: unknown) => {\n // The body failed, or a chunk is not bytes (a page-built body):\n // what had arrived is recorded cut and marked, the network is\n // let go, and the page's read rejects with the reason, as the\n // platform's own read would. Firefox and WebKit abort a\n // document's fetches when it navigates, BEFORE pagehide\n // (MEASURED): this is where a page that leaves mid-body is cut\n // there.\n end(cutText(rec.text));\n void reader!.cancel(err).catch(() => {});\n throw err;\n });\n },\n cancel(reason: unknown) {\n // What the page read, as it read it (nothing, before any read):\n // never a marker. (Past the cap, or read whole through a clone, it\n // is reported already.)\n end(rec.text);\n return (reader ?? native).cancel(reason);\n },\n };\n const Stream = (Object.getPrototypeOf(native) as ReadableStream)\n .constructor as typeof ReadableStream;\n // A BYTE stream, as the network's body is (Fetch spec), so a page's\n // `getReader({ mode: \"byob\" })` works as it does without the SDK; a\n // platform without byte streams gets a default one. A high-water mark\n // of 0: nothing is pulled until the page reads.\n const make = (type?: string): ReadableStream<Uint8Array> =>\n new Stream(\n { ...source, type } as unknown as UnderlyingDefaultSource<Uint8Array>,\n { highWaterMark: 0 },\n );\n try {\n return make(BYTE_SOURCE);\n } catch {\n return make();\n }\n}\n","/* ------------------------------------------------------------------ */\n/* @keploy/capture-sdk - body redaction, off the main bundle */\n/* ------------------------------------------------------------------ */\n\n/*\n * THE BODY HALF OF PrivacyEngine.maskNetworkData, IN ONE PLACE, SHIPPED\n * TWICE AND NEVER IN THE MAIN BUNDLE. MEASURED (uic-sdk-perf MEASURE.md,\n * SDK 81f32f0960): redacting a 512 KB JSON body takes 42-58 ms of the\n * page's main thread, 150 ms on a phone-speed CPU, and fifty 64 KB\n * responses froze a page for 257-299 ms. So this code runs in a Web\n * Worker, dist/body-worker.js (body-worker.ts), and the main thread\n * only posts a body and reads its answer (body-jobs.ts).\n *\n * The same module is also the chunk dist/body-redact.{mjs,js}, loaded by\n * the package's own name as the GraphQL term's chunk is: the main thread\n * runs it only where it must -- a page whose CSP or bundler gives it no\n * worker, under the main-thread budget, and a body still in the worker\n * when the page leaves. Both are built from THIS file and redact.ts with\n * the one shared rule (@keploy/contract/privacy), so a body comes out the\n * same bytes either way (body-worker-parity.test.ts runs the redaction\n * corpora and the seeded fuzzers through both).\n */\n\nimport { cutBodyNote } from \"@keploy/contract/privacy\";\nimport { redactBody, TRUNCATED_SUFFIX } from \"./redact\";\n/** The version this chunk was built as: the SDK refuses one of another (module-of.ts ownChunk). */\nexport { version } from \"../package.json\";\n/**\n * The page's stream of a body it reads through `res.body` (page-stream.ts):\n * in this chunk, not the main bundle, as only pages that stream a body run\n * it. The worker, which bundles this module for redactBodies, leaves it out.\n */\nexport { relayBody } from \"./page-stream\";\n\n/** One exchange's bodies, as the main thread hands them over. */\nexport interface BodyJob {\n requestBody: string | null;\n responseBody: string | null;\n /** The request's and the response's content-type, if any. */\n requestType?: string;\n responseType?: string;\n /** The integrator's piiPatterns, compiled global (structured-cloned into the worker). */\n patterns: RegExp[];\n}\n\n/** The two bodies as recorded. */\nexport interface BodyOut {\n requestBody: string | null;\n responseBody: string | null;\n}\n\n/**\n * `body` as recorded when at most `limit` UTF-16 units of it may be\n * redacted: whole when it fits; otherwise its first `limit` units,\n * redacted as any body cut at a cap is (`...[truncated]`), under\n * cutBodyNote's first line, which says it is not the whole body. A\n * `limit` of 0 keeps nothing of it but the note.\n */\nfunction redactWithin(\n body: string | null,\n type: string | undefined,\n patterns: readonly RegExp[],\n limit: number,\n): string | null {\n if (body === null || body.length <= limit) {\n return redactBody(body, type, patterns);\n }\n return (\n cutBodyNote(limit, body.length) +\n (limit > 0\n ? (redactBody(body.slice(0, limit) + TRUNCATED_SUFFIX, type, patterns) ??\n \"\")\n : \"\")\n );\n}\n\n/**\n * Both bodies of `job`, redacted. The worker passes no limits and redacts\n * them whole; the main thread passes its budget (body-jobs.ts): `limit`\n * UTF-16 units of the request body, and `responseLimit` of the response's.\n */\nexport function redactBodies(\n job: BodyJob,\n limit = Infinity,\n responseLimit = limit,\n): BodyOut {\n return {\n requestBody: redactWithin(\n job.requestBody,\n job.requestType,\n job.patterns,\n limit,\n ),\n responseBody: redactWithin(\n job.responseBody,\n job.responseType,\n job.patterns,\n responseLimit,\n ),\n };\n}\n","{\n \"name\": \"@keploy/capture-sdk\",\n \"version\": \"3.2.1\",\n \"description\": \"Lightweight SDK to capture UI flows from real users - DOM recording, network interception, PII masking\",\n \"homepage\": \"https://keploy.io/docs/running-keploy/ui-capture/\",\n \"main\": \"dist/index.js\",\n \"module\": \"dist/index.bundler.mjs\",\n \"unpkg\": \"dist/index.mjs\",\n \"jsdelivr\": \"dist/index.mjs\",\n \"types\": \"dist/index.d.ts\",\n \"exports\": {\n \".\": {\n \"types\": \"./dist/index.d.ts\",\n \"import\": \"./dist/index.mjs\",\n \"require\": \"./dist/index.js\"\n },\n \"./request-term\": {\n \"types\": \"./dist/request-term.d.ts\",\n \"import\": \"./dist/request-term.mjs\",\n \"require\": \"./dist/request-term.js\"\n },\n \"./strict-attributes\": {\n \"types\": \"./dist/strict-attributes.d.ts\",\n \"import\": \"./dist/strict-attributes.mjs\",\n \"require\": \"./dist/strict-attributes.js\"\n },\n \"./body-redact\": {\n \"types\": \"./dist/body-redact.d.ts\",\n \"import\": \"./dist/body-redact.mjs\",\n \"require\": \"./dist/body-redact.js\"\n },\n \"./body-worker-start\": {\n \"types\": \"./dist/body-worker-start.d.ts\",\n \"import\": \"./dist/body-worker-start.mjs\",\n \"require\": \"./dist/body-worker-start.js\"\n },\n \"./package.json\": \"./package.json\"\n },\n \"files\": [\n \"dist\",\n \"request-term/package.json\",\n \"strict-attributes/package.json\",\n \"body-redact/package.json\",\n \"body-worker-start/package.json\",\n \"LICENSE\",\n \"README.md\"\n ],\n \"scripts\": {\n \"build\": \"node scripts/build-main.mjs && node scripts/build-worker.mjs && tsc -p tsconfig.build.json\",\n \"dev\": \"node scripts/build-main.mjs --watch\",\n \"test\": \"vitest run\",\n \"clean\": \"rm -rf dist\",\n \"typecheck\": \"tsc --noEmit\",\n \"prepublishOnly\": \"pnpm run clean && turbo run build --filter=@keploy/capture-sdk --force && node ../../tools/check-release-size.mjs\"\n },\n \"dependencies\": {\n \"rrweb\": \"^2.1.6\"\n },\n \"devDependencies\": {\n \"@keploy/contract\": \"workspace:*\",\n \"@types/node\": \"~24.13.5\",\n \"jsdom\": \"^30.1.0\",\n \"terser\": \"5.51.2\",\n \"tsup\": \"^8.3.0\",\n \"typescript\": \"^7.0.2\",\n \"vitest\": \"^5.0.1\"\n },\n \"peerDependencies\": {},\n \"keywords\": [\n \"keploy\",\n \"ui-testing\",\n \"session-recording\",\n \"e2e\",\n \"capture\"\n ],\n \"browser\": {\n \"./dist/body-worker-unbundled.mjs\": \"./dist/body-worker-none.mjs\"\n },\n \"alias\": {\n \"@keploy/capture-sdk/body-worker-start\": \"./dist/body-worker-start.mjs\"\n },\n \"license\": \"Apache-2.0\",\n \"publishConfig\": {\n \"access\": \"public\"\n }\n}\n"]}
1
+ {"version":3,"sources":["../../contract/src/privacy.ts","../src/redact.ts","../src/page-stream.ts","../src/body-redact.ts","../package.json"],"names":["decoded","v","includes","replace","ESCAPED","e","decodeURIComponent","nameParts","raw","kind","split","map","n","toLowerCase","filter","isCredentialPart","part","PAGING_CURSORS","has","PAGE_OWN_NAMES","CREDENTIAL_NAMES","CREDENTIAL_CODE_NAMES","CARD_EXPIRY_NAMES","CREDENTIAL_SUFFIX","test","isCredentialName","parts","some","length","join","isCredentialParts","scrubRelative","value","rules","depth","hashAt","indexOf","beforeHash","slice","q","path","query","fragment","out","scrubPath","scrubPairs","scrubFragment","ownValueEnd","form","at","search","parens","squares","braces","i","c","holdsCredentialName","text","k","next","m","matchAll","whole","PAIR_SEPARATOR","pairs","_","ctx","pair","eq","bare","name","plus","decodePart","gone","before","strict","names","pieces","push","pairNames","spaced","own","rest","tail","MAX_NESTING","NESTED_QUERY","NESTED_PAIRS","inner","scrubAbsolute","startsWith","scrubNestedUrl","encodeURIComponent","segments","bases","seg","segment","semi","base","head","route","exec","AUTHORITY","spliceAbsolute","url","URL","hash","pathname","username","password","protocol","host","scheme","slashes","authority","lastIndexOf","scrubUrl","lead","trimStart","trail","trimEnd","scanEnd","start","brackets","list","end","URL_END","NEXT_URL","lastIndex","URL_TRAILER","urlEnd","normalizeKey","key","isTokenExchange","code","peer","longCode","state","EXCHANGE_GRANTS","trim","EXCHANGE_CODES","EXCHANGE_PEERS","isGeneratedState","PLAIN_WORDS","CAMEL_WORDS","isPlainState","isStateSlug","isSensitiveKey","isEmailLocalChar","isLikelyCardNumber","digits","isVisa","isMastercard","isAmex","isDiscover","isJcbDiners","sum","double","d","charCodeAt","passesLuhn","patternRanges","re","into","index","detectorRanges","extra","JWT_RE","KNOWN_TOKEN_RE","kept","floor","Math","max","EMAIL_DOMAIN","domain","emailRanges","SSN_RE","PHONE_RE","IPV4_RE","s","cardRanges","applyRanges","ranges","sort","a","b","pos","with_","REDACTED","scrubTextUrls","BODY_URL_RULES","URL_LINE","line","WHOLE_URL","URL_START_WORD","edits","spans","URL_START","groups","attr","CSS_URL_OPEN","inCssUrl","urlSpans","urlEdits","scrubEscapedUrls","ESCAPED_URL","span","plain","escape","ESCAPED_SLASH_AT","slash","holdsEncodedUrlCredential","formDecode","scrubbed","inPlace","embeddedPairRanges","onlyFlags","node","items","every","redactNode","keyHint","REDACTED_JSON","BARE_CODE_NAMES","endsWith","isBareCodeName","isSettingsValue","WORD_NAMES","isWordName","Number","isInteger","String","integerDigits","redactJsonString","redactStringText","JSON","stringify","item","entries","PAIR_NAMES","card","CARD_FIELDS","exchange","CARD_EXPIRY_BESIDE_A_CARD","EXCHANGE_REDACTED","PAIR_VALUES","redactJsonText","ws","string","run","fromCharCode","parseInt","ESCAPES","MAX_DEPTH","nest","skip","parseJsonSpans","applyEdits","parse","redactBody","body","contentType","NOT_RECORDED","isNotRecordedNote","TRUNCATED_UNPARSEABLE","cut","TRUNCATED_SUFFIX","formHeld","FORM_URL_RULES","asForm","MULTIPART","formSegment","isFormRendering","DECLARED_FORM","last","readAsForm","held","TEXT_URL_RULES","multipart","param","BOUNDARY_PARAM","boundary","delimiter","scanSpan","after","lineEnd","valueStart","headersEnd","valueEnd","headers","PART_NAME","fieldName","jsonPart","PART_FILE","redactMultipartText","UNREADABLE","formShaped","json","escaped","newDecodedText","pairsPossible","PAIR_LEAD","decodedSegments","flatMap","jsonSpans","nameEnd","segEnd","from","appendDecoded","appendUnit","jsonFormValue","spanPairRanges","found","s0","e0","lo","hi","mid","insideSpan","redactFormBody","redactStringValue","truncate","maxSize","hexByte","isNaN","capacity","Int32Array","unit","to","u","appendRaw","marks","cp","fromCodePoint","mode","EMBEDDED_NAME_IN_CODE","EMBEDDED_NAME_IN_STRING","EMBEDDED_NAME_IN_HEADER","EMBEDDED_NAME","scripts","open","close","gt","scriptRanges","r","EMBEDDED_VALUE","EMBEDDED_VALUE_IN_STRING","FORM_NAME","redacted","relayBody","native","rec","reader","say","finished","decoder","TextDecoder","source","pull","getReader","touched","one","read","then","done","reported","decode","byobRequest","respond","chunk","typedArrayTag","Reflect","get","Object","getOwnPropertyDescriptor","getPrototypeOf","Uint8Array","prototype","Symbol","toStringTag","apply","typedArrayName","TypeError","bytesOf","byteLength","stream","setTimeout","enqueue","catch","err","cutText","cancel","reason","Stream","constructor","make","type","highWaterMark","BYTE_SOURCE","redactWithin","patterns","limit","total","cutBodyNote","redactBodies","job","responseLimit","requestBody","requestType","responseBody","responseType","body_redact_exports","__export","version","module","exports","Set","f","t","TAIL_URL_RULES"],"mappings":"aAkDO,SAASA,EAAQC,GACtB,OAAOA,EAAEC,SAAS,KAAOD,EAAEE,QAAQC,EAAUC,GAAMC,mBAAmBD,IAAMJ,CAC9E,CAmPO,SAASM,EAAUC,EAAaC,GACrC,OAAOT,EAAQQ,GACZE,MAAe,QAATD,EAAiB,SAAW,WAClCE,IAAKC,GAAMA,EAAEC,cAAcV,QAAQ,YAAa,KAChDW,OAAQF,GAAY,KAANA,EACnB,CAGO,SAASG,EAAiBC,EAAcP,GAE7C,QADIQ,GAAeC,IAAIF,IACV,SAATP,GAAmBU,GAAeD,IAAIF,MAExCI,GAAiBF,IAAIF,IACrBK,GAAsBH,IAAIF,IAC1BM,GAAkBJ,IAAIF,IACtBO,GAAkBC,KAAKR,GAE3B,CAUO,SAASS,EAAiBjB,EAAaC,GAC5C,OAUK,SACLiB,EACAjB,GAEA,OACEiB,EAAMC,KAAMX,GAASD,EAAiBC,EAAMP,KAC3CiB,EAAME,OAAS,GAAKb,EAAiBW,EAAMG,KAAK,IAAKpB,EAE1D,CAlBSqB,CAAkBvB,EAAUC,EAAKC,GAAOA,EACjD,CAmNA,SAASsB,EAAcC,EAAeC,EAAiBC,GACrD,IAAMC,EAASH,EAAMI,QAAQ,KACvBC,GAAwB,IAAXF,EAAgBH,EAAQA,EAAMM,MAAM,EAAGH,GACpDI,EAAIF,EAAWD,QAAQ,KACvBI,GAAa,IAAND,EAAWF,EAAaA,EAAWC,MAAM,EAAGC,GACnDE,GAAc,IAANF,EAAW,KAAOF,EAAWC,MAAMC,EAAI,GAC/CG,GAAsB,IAAXP,EAAgB,KAAOH,EAAMM,MAAMH,EAAS,GACvDQ,EACJC,EAAUJ,EAAMP,IACL,OAAVQ,EAAiB,GAAK,IAAII,EAAWJ,EAAOR,EAAOC,EAAOM,OAC7C,OAAbE,EACG,GACA,IAAII,EAAc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ACA,SACA,eACA,aACA,UACA,YACA,SACA,MACA,uBACA,aACA,aACA,MACA,MACA,MACA,aAIA,QACA,QACA,cACA,QACA,eAOA,SACA,aAEA,YACA,qBAIA,eACA,aACA,YACA,cAIA,QACA,OACA,YACA,YACA,YACA,gBAEA,MAOA,MACA,SACA,OACA,OACA,SACA,iBACA,cACA,OACA,UACA,UACA,YACA,YACA,YACA,aACA,aACA,kBACA,eACA,aACA,eACA,gBACA,kBAGA,kBACA,oBAYW1Y,GAA6C,IAAI0Y,IAAI,CAChE,aACA,iBACA,WACA,oBACA,mBACA,aACA,mBACA,cACA,YACA,UACA,UACA,UACA,WACA,gBACA,UACA,YACA,WACA,UACA,aAIIzY,GAAyC,IAAIyY,IAAI,CACrD,aACA,iBACA,iBACA,qBACA,UACA,cACA,eACA,cACA,QACA,WACA,eACA,YACA,aACA,YACA,mBACA,uBACA,WACA,UACA,cACA,aACA,kBACA,mBAaIxY,GACJ,4KASWN,GAAsC,IAAI8Y,IAAI,CACzD,YACA,gBACA,gBACA,oBACA,cACA,kBACA,YACA,YACA,gBACA,oBACA,wBACA,cACA,YACA,gBACA,gBACA,aACA,YACA,aACA,kBACA,cACA,aACA,gBAWW5Y,GAAsC,IAAI4Y,IAAI,CACzD,OACA,UACA,SACA,MACA,QA8LWhW,GAAiB,0BAsCjBqB,GAAc,EAGrBC,GAAe,6CAOfC,GAAe,mBAoTfe,GAAY,2CAwEZ+F,GACJ,mgBAGIvE,GAAU,kBAGVG,GAAc,SASdF,GAAW,gCA6EXyE,GAAe,kBCh7BfZ,GAAW,aAMXuD,GAAiD,IAAI6K,IAAI,CAC7D,SACA,aACA,aACA,iBACA,UACA,QAII/K,GAAmC,IAAI+K,IAAI,CAC/C,aACA,aACA,mBACA,WACA,UACA,MACA,MACA,QAIWxJ,GAAwB,kCAqB/BF,GAAe,CACnB,mCAGA,wBACA,0BACA,2CAEA,2CACA,uBACA,wBAGA,2DAmBIvH,GAAc,gCAEdC,GAAc,mCAkBdN,GAA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-License-Identifier: Apache-2.0\n//\n// This file alone of @keploy/contract is Apache-2.0, not the package's\n// distribution licence: @keploy/capture-sdk (Apache-2.0) inlines it into\n// its bundle, which runs in every customer's browser. packages/contract/\n// README.md carries the same carve-out, and tools/check-release-ready.mjs\n// refuses an SDK bundle that inlines a source not under a permissive\n// licence (tools/release-sources.mjs).\n\n/**\n * ONE RULE FOR A CREDENTIAL'S NAME, for every place a name is read: a\n * JSON body's key, a form's and a multipart body's field, a `name=value`\n * pair in an HTML, XML, RSC or text body, a query parameter of a request's\n * URL, of a link held in a body, of the page's own URL and of every URL\n * the DOM holds, and of a URL the replay runtime's mock-contract report\n * prints into a CI log.\n *\n * It was six rules in two packages: the SDK's body-key rule, its form\n * rule, its URL rule and its page rule, and the runtime's report list,\n * each with names the others lacked. `?jwt=` was scrubbed from a page's\n * URL and kept in a request's; `{\"email_otp\":\"482913\"}` was kept in a body\n * whose URL scrubbed `?sms_otp=`; a paging cursor was kept in a URL and\n * redacted in the response that handed it out, so a replayed page asked\n * for `?pageToken=%5BREDACTED%5D` and matched nothing; a request a replay\n * missed was printed into the customer's CI log with an `auth_token` in\n * clear (found in review). privacy-names.test.ts holds this rule's table;\n * each consumer's own test holds what it records to it.\n *\n * NO IMPORTS. @keploy/capture-sdk, whose only runtime dependency is\n * rrweb, and @keploy/replay-runtime, whose dist/test.mjs may import only\n * Node builtins, both bundle this module inline; it must pull in nothing.\n */\n\n/**\n * One code point percent-encoded as UTF-8, overlong forms and surrogates\n * excluded: exactly the escape sequences decodeURIComponent decodes, so\n * only those are handed to it and a crafted name costs no exceptions --\n * 15,000 names of `%` threw on every one, 2 s a URL once the parameters\n * were no longer capped (MEASURED).\n */\nconst ESCAPED =\n /%[0-7][\\da-f]|%(?:c[2-9a-f]|d[\\da-f])%[89ab][\\da-f]|%e0%[ab][\\da-f]%[89ab][\\da-f]|%e[1-9a-ce-f](?:%[89ab][\\da-f]){2}|%ed%[89][\\da-f]%[89ab][\\da-f]|%f0%[9ab][\\da-f](?:%[89ab][\\da-f]){2}|%f[1-3](?:%[89ab][\\da-f]){3}|%f4%8[\\da-f](?:%[89ab][\\da-f]){2}/gi;\n\n/**\n * `v` with every escape sequence that spells one code point decoded, as\n * decodeURIComponent decodes it, and every other byte as written: escape\n * by escape, not all or nothing. All or nothing, a string with one\n * malformed escape decoded none, so a text could not be decoded piece by\n * piece (found in review).\n */\nexport function decoded(v: string): string {\n return v.includes(\"%\") ? v.replace(ESCAPED, (e) => decodeURIComponent(e)) : v;\n}\n\n/**\n * The names a credential, a secret or a card's data goes by, read whole\n * (nameParts): what a JSON key, a form field and a query parameter are\n * all redacted under.\n */\nconst CREDENTIAL_NAMES: ReadonlySet<string> = new Set([\n \"password\",\n \"passwd\",\n \"pwd\",\n \"secret\",\n \"token\",\n \"accesstoken\",\n \"refreshtoken\",\n \"idtoken\",\n \"authorization\",\n \"auth\",\n \"apikey\",\n \"clientsecret\",\n \"privatekey\",\n \"session\",\n \"sessionid\",\n \"cookie\",\n \"ssn\",\n \"socialsecuritynumber\",\n \"creditcard\",\n \"cardnumber\",\n \"cvv\",\n \"cvc\",\n \"pin\",\n \"passphrase\",\n // WordPress's new-password pair, Drupal's current-password field,\n // WordPress's reset key, and the PKCE secret an OAuth\n // authorization-code exchange carries.\n \"pass1\",\n \"pass2\",\n \"currentpass\",\n \"rpkey\",\n \"codeverifier\",\n // A freshly minted secret as Keploy's api-server returns it: the\n // createUIIngestKey / createServiceAccountKey / createPersonalAccessToken\n // / createAppCIToken results carry the raw key as `rawKey` (beside a\n // `token` that is only its metadata), and a saved test-run credential\n // is an `APIKeyAuth {Key, Value}`, whose secret is the generic `Value`.\n // The SDK's dashboard-shapes.test.ts holds api-server's schema to this.\n \"rawkey\",\n \"apikeyauth\",\n // Header names a pair can carry.\n \"setcookie\",\n \"proxyauthorization\",\n // SAML's response, WordPress's confirmation key, Supabase's token hash\n // and Clerk's ticket: named here rather than by a `hash` or `ticket`\n // suffix, which would take an app's own `commitHash` or `supportTicket`.\n \"samlresponse\",\n \"confirmkey\",\n \"tokenhash\",\n \"clerkticket\",\n // The names a verification, reset or sign-in link carries its secret\n // under: a nonce, an HMAC, a login hash, a magic link, PHP's session\n // cookie and OAuth 1.0a's verifier.\n \"nonce\",\n \"hmac\",\n \"loginhash\",\n \"magiclink\",\n \"phpsessid\",\n \"oauthverifier\",\n // Azure's SAS signature.\n \"sig\",\n // The names a header carries a credential under, read here too since a\n // request's URL, a form and a body carry them as often: a session id\n // (`sid`, PHP's `sessid`), an anti-forgery token, a bearer, an\n // assertion an OAuth client or a SAML response signs, and the keys and\n // codes a vendor names by their kind (Azure's `subscription-key` is\n // accepted in a query string).\n \"sid\",\n \"sessid\",\n \"csrf\",\n \"xsrf\",\n \"bearer\",\n \"authentication\",\n \"credentials\",\n \"pass\",\n \"tokenid\",\n \"authkey\",\n \"secretkey\",\n \"accesskey\",\n \"clientkey\",\n \"signingkey\",\n \"sessionkey\",\n \"subscriptionkey\",\n \"functionskey\",\n \"factorcode\",\n \"jwtassertion\",\n \"samlassertion\",\n \"clientassertion\",\n // A cloud's temporary credentials as its SDK returns them: AWS STS's\n // `SecretAccessKey` and Alibaba Cloud's `AccessKeySecret`.\n \"secretaccesskey\",\n \"accesskeysecret\",\n]);\n\n/**\n * The names a one-time code goes by: a credential under these names and no\n * other. A bare `code` is not one (`?code=US`, a promo code), and neither\n * is a `zip_code`, a `country_code` or an `error_code`. `oobcode` is\n * Firebase's email-action link code; `linkcode` is SuperTokens' magic link\n * code, read from the page's fragment and posted as `linkCode`. `otp` and\n * `totp` end in `otp`, and CREDENTIAL_SUFFIX reads them with every other\n * name that does (`email_otp`, `sms_otp`).\n */\nexport const CREDENTIAL_CODE_NAMES: ReadonlySet<string> = new Set([\n \"invitecode\",\n \"invitationcode\",\n \"authcode\",\n \"authorizationcode\",\n \"verificationcode\",\n \"verifycode\",\n \"confirmationcode\",\n \"confirmcode\",\n \"resetcode\",\n \"mfacode\",\n \"smscode\",\n \"otpcode\",\n \"totpcode\",\n \"twofactorcode\",\n \"2facode\",\n \"logincode\",\n \"passcode\",\n \"oobcode\",\n \"linkcode\",\n]);\n\n/** A card's expiry by a name that can only be a card's (Stripe's exp_month, ...): cardholder data to PCI. */\nconst CARD_EXPIRY_NAMES: ReadonlySet<string> = new Set([\n \"cardexpiry\",\n \"cardexpiration\",\n \"cardexpirydate\",\n \"cardexpirationdate\",\n \"cardexp\",\n \"cardexpdate\",\n \"cardexpmonth\",\n \"cardexpyear\",\n \"ccexp\",\n \"ccexpiry\",\n \"ccexpiration\",\n \"ccexpdate\",\n \"ccexpmonth\",\n \"ccexpyear\",\n \"creditcardexpiry\",\n \"creditcardexpiration\",\n \"expmonth\",\n \"expyear\",\n \"expirymonth\",\n \"expiryyear\",\n \"expirationmonth\",\n \"expirationyear\",\n]);\n\n/**\n * A name that ends in a credential word: `userPassword`, `x-api-key`,\n * `authToken`, Magic's `magic_credential`, an `x_signature` (S3's\n * `X-Amz-Signature`), an `id_jwt`, an `email_otp`, a `JSESSIONID`. The\n * confirmation fields every sign-up form carries (Rails/Laravel\n * `password_confirmation`, Django `password1`/`password2`) end in a word\n * after `password`; a boolean such as `passwordlessEnabled` does not, and\n * keeps its value. A recorded curl command (api-server's LoginCurl.Curl)\n * carries its Authorization header and its form body: redacted whole.\n */\nconst CREDENTIAL_SUFFIX =\n /(?:password(?:\\d|confirm|confirmation|new|old|repeat|again|verify|retype)?|passwd|secret|token|apikey|privatekey|passphrase|signature|sessionid|jwt|otp|credential|curl)$/;\n\n/**\n * A paging cursor: a name ending in `token` that is no credential but the\n * page of results a request asks for -- a page's to request again, and\n * part of what the request is. A response's `nextPageToken` redacted made\n * a replayed page ask for `?pageToken=%5BREDACTED%5D`, which nothing\n * recorded answers (found in review). Kept under every kind of name.\n */\nexport const PAGING_CURSORS: ReadonlySet<string> = new Set([\n \"pagetoken\",\n \"nextpagetoken\",\n \"prevpagetoken\",\n \"previouspagetoken\",\n \"pagingtoken\",\n \"paginationtoken\",\n \"nexttoken\",\n \"prevtoken\",\n \"previoustoken\",\n \"continuationtoken\",\n \"nextcontinuationtoken\",\n \"cursortoken\",\n \"synctoken\",\n \"nextsynctoken\",\n \"startingtoken\",\n \"starttoken\",\n \"skiptoken\",\n \"deltatoken\",\n \"resumptiontoken\",\n \"scrolltoken\",\n \"aftertoken\",\n \"beforetoken\",\n]);\n\n/**\n * Credential names a page's own URL, and every URL its DOM holds, use as\n * an app's parameter as often -- `?auth=1`, a talk's `?session=`, a map's\n * `?pin=`, a `?sig=` -- and keep by name there, as #36's tests require:\n * the recorded page must be the page visited, and those URLs scrub a\n * value of theirs that looks generated by its shape. Every other place a\n * name is read takes them for the credentials they are.\n */\nexport const PAGE_OWN_NAMES: ReadonlySet<string> = new Set([\n \"auth\",\n \"session\",\n \"cookie\",\n \"pin\",\n \"sig\",\n]);\n\n/**\n * Where a name is read, which decides two things and nothing else:\n * - `key`: a JSON body's key, a HAR-style pair's name, a header's name.\n * Read without splitting at `.`: a dotted JSON key is a flat key\n * (`\"auth.login.title\"` in a translation bundle, `\"token.ttl\"` in a\n * config), and a credential key redacts its whole value, a flag\n * included -- `{\"auth.enabled\":true}` would become a string.\n * - `param`: a form's or a multipart body's field, a text body's\n * `name=value` pair, a query parameter of a request's URL, of a link\n * held in a body or of a URL the runtime's report prints. Read at\n * each `.` part too, as Spring's binder and `qs` with `allowDots`\n * read `user.password`.\n * - `page`: a query parameter of the page's own URL or of a URL the DOM\n * holds, read as `param` is, less PAGE_OWN_NAMES.\n */\nexport type NameKind = \"key\" | \"param\" | \"page\";\n\n/**\n * Every part a name is read under: percent-decoded escape by escape, each\n * `[...]` part (`user[password]`) and, but for a `key`, each `.` part, and\n * each part lower-cased without `-`, `_`, `$` (OData's `$skiptoken`), `+`\n * (a space in a query or a form: `api+key`) and whitespace.\n */\nexport function nameParts(raw: string, kind: NameKind): string[] {\n return decoded(raw)\n .split(kind === \"key\" ? /[[\\]]+/ : /[[\\].]+/)\n .map((n) => n.toLowerCase().replace(/[-_$+\\s]/g, \"\"))\n .filter((n) => n !== \"\");\n}\n\n/** Whether one part of a name, as nameParts reads it, is a credential's. */\nexport function isCredentialPart(part: string, kind: NameKind): boolean {\n if (PAGING_CURSORS.has(part)) return false;\n if (kind === \"page\" && PAGE_OWN_NAMES.has(part)) return false;\n return (\n CREDENTIAL_NAMES.has(part) ||\n CREDENTIAL_CODE_NAMES.has(part) ||\n CARD_EXPIRY_NAMES.has(part) ||\n CREDENTIAL_SUFFIX.test(part)\n );\n}\n\n/**\n * THE RULE: whether a name, as written, is a credential's -- any of its\n * parts (nameParts) is one (isCredentialPart), or, for a name of more\n * than one part, the parts read as one word: `session[id]` is a\n * `sessionid` and `api[key]` an `apikey`, though neither part is a\n * credential's alone (found in review: a token under `?session[id]=` was\n * recorded once brackets were read as parts).\n */\nexport function isCredentialName(raw: string, kind: NameKind): boolean {\n return isCredentialParts(nameParts(raw, kind), kind);\n}\n\n/**\n * THE RULE over a name already split (nameParts): any part is a\n * credential's, or the parts read as one word. What a reader that holds a\n * name's parts asks -- the page's own pair read and its secret collection\n * read a name per part, and `?api[key]=` taught the page-wide scrub no\n * value (found in review).\n */\nexport function isCredentialParts(\n parts: readonly string[],\n kind: NameKind,\n): boolean {\n return (\n parts.some((part) => isCredentialPart(part, kind)) ||\n (parts.length > 1 && isCredentialPart(parts.join(\"\"), kind))\n );\n}\n\n/* ------------------------------------------------------------------ */\n/* ONE URL SCRUBBER */\n/* ------------------------------------------------------------------ */\n/*\n * Every URL the SDK records, and every URL and key the replay runtime\n * prints into a CI log or attaches as evidence, is scrubbed by this\n * walker: a request's URL and every URL its request and response headers\n * carry (Location, Content-Location, Link and Refresh as a request's URL\n * is, any other by a credential's name), a URL anywhere in a request's or a\n * response's body (a JSON string that is one or holds one, an HTML, XML,\n * RSC or text body, a form's or a multipart part's value), the page's own\n * URL and every URL the DOM holds. It was five scrubbers, and only the\n * DOM's read a URL whole: a body's read a query after `?` and never a\n * fragment, a `wss:` or a custom scheme, a request's never a URL nested or\n * encoded in a value nor a path's `;jsessionid=`, and the report never a\n * fragment (found in review). What a URL is made of is read here the same\n * for every URL; what differs is passed in (UrlRules):\n *\n * - `kind`: how a name is read (isCredentialName): `param`, or `page` for\n * the page's own URL and the DOM's, which keep PAGE_OWN_NAMES.\n * - `strict`: every query and fragment-pair value replaced.\n * - `whole`: a URL the replay key reads -- a request's, and one the\n * mock-contract report prints. A pair runs from `&` to `&`, as the key\n * reads one, and a credential anywhere in it -- under a `;name=` inside\n * it, in a URL nested or encoded in its value -- replaces its whole\n * value, so the key holds `[REDACTED]`, which canonical-key.v2 matches\n * any live value against. Otherwise a `;` that a `name=` follows\n * separates pairs too, and only the credential's own value goes, a\n * nested URL scrubbed and written back encoded.\n * - `raw`: a URL a body holds, every byte the scrub does not replace\n * kept (a nested URL written back as it came).\n * - the SDK's value rules for the page's URL and the DOM's, which no\n * other URL takes: a value by its shape or a PII pattern, an OAuth\n * response's code and state, a link page's key, a page credential's\n * cut, a path's JWT or link token. A request's URL is its identity at\n * replay, and a name is what says one of its values is secret.\n */\n\n/** What a value rule is told about the pair it judges. */\nexport interface PairContext {\n /** The path the pair's query or fragment belongs to, a hash route's appended. */\n readonly path: string;\n /** Every pair of that query or fragment, as written. */\n readonly pairs: readonly string[];\n /** How many URLs the pair is nested in. */\n readonly depth: number;\n}\n\n/** How a URL is scrubbed: see the block above. */\nexport interface UrlRules {\n readonly kind: \"param\" | \"page\";\n readonly strict: boolean;\n readonly whole: boolean;\n /**\n * A nested URL written back as it came: raw when it came raw, encoded\n * when it came encoded -- a body's text, where every byte the scrub does\n * not replace is kept. Otherwise (the page's URL, the DOM's) it is\n * written back encoded.\n */\n readonly raw?: boolean;\n /**\n * A credential's own value ends at the first character ownValueEnd\n * stops at (whitespace, `,`, `;`, a quote, a `)` it does not open ...),\n * the text after it kept: a text body's line (`/api/x?token=... 200\n * OK`), a CSV row, a header's list. Otherwise -- a JSON string, a form's\n * value, every URL the page or a request holds -- it runs to the next\n * pair, a space in it the credential's own (`?password=correct horse`),\n * and fails closed (found in review). What follows it in the pair is\n * read by `tail`.\n */\n readonly spaced?: boolean;\n /**\n * In a `spaced` read, a credential's own value ends at its first\n * whitespace alone, and a pair's is replaced even when empty (a path\n * parameter's empty value is kept, as always): a form body's URLs,\n * whose values the form read then takes to the next `&`. Cut at a\n * `,`, a form value's URL was left with a tail that read took for the\n * credential's, and the whole value went (found in review).\n */\n readonly form?: boolean;\n /** The text a credential's own value leaves after it in a pair (`spaced`), read: it can hold a list's next URL. */\n readonly tail?: (text: string) => string;\n /** In a text, a `,` before a URL with a scheme and an authority ends the URL before it (NEXT_URL). */\n readonly list?: boolean;\n /** A pair's replacement value, decided before its name is read, or null. */\n readonly before?: (\n name: string,\n raw: string,\n ctx: PairContext,\n ) => string | null;\n /** Whether a pair's value goes by what it is (its shape, a PII pattern), its name aside. */\n readonly value?: (name: string, raw: string, decoded: string) => boolean;\n /** Whether a bare name (`?<token>`, no `=`) goes, by its shape. */\n readonly bare?: (raw: string) => boolean;\n /** Whether a path segment goes whole, its `;` parameters with it (a JWT). */\n readonly segment?: (segment: string) => boolean;\n /** Whether a path segment's head, its `;` parameters aside, goes (a link's token). */\n readonly head?: (\n path: string,\n base: string,\n index: number,\n bases: readonly string[],\n ) => boolean;\n}\n\n/**\n * Where a query's pair ends and the next starts, outside `whole`: at a\n * `&`, and at a `;` that a `name=` follows -- many servers read\n * `?a=1;token=...` as two pairs. A `;` inside a value (`?q=ada;lovelace`,\n * `?ids=1;2;3`) is the value's: split at every `;`, strict recorded\n * `q=[REDACTED];lovelace`, the rest of what was typed, as a bare name\n * (found in review). Split by it, a query holds its separators at odd\n * indexes. An Android intent's closing `;end` is no value's either:\n * `#Intent;S.token=...;end` lost it with the credential, and the intent\n * no longer parsed (found in review).\n */\nexport const PAIR_SEPARATOR = /(&|;(?=[^;&=#]+=|end$))/;\n\n/**\n * The names one `&` pair carries, as written: its own and each a `;`\n * inside it starts (PAIR_SEPARATOR) -- what `whole` reads a pair by.\n */\nexport function pairNames(pair: string): string[] {\n const names: string[] = [];\n const pieces = pair.split(PAIR_SEPARATOR);\n for (let i = 0; i < pieces.length; i += 2) {\n const eq = pieces[i]!.indexOf(\"=\");\n if (eq > 0) names.push(pieces[i]!.slice(0, eq));\n }\n return names;\n}\n\n/**\n * A query part decoded as a form decodes it, or as it came when an escape\n * is malformed: checked first, because a thrown URIError per pair cost a\n * 256 KB URL of `a=%&` pairs 267 ms on every full snapshot.\n */\nexport function decodePart(raw: string): string {\n const plus = raw.replace(/\\+/g, \" \");\n if (!/%/.test(plus)) return plus;\n if (/%(?![0-9A-Fa-f]{2})/.test(plus)) return raw;\n try {\n return decodeURIComponent(plus);\n } catch {\n return raw;\n }\n}\n\n/**\n * One level of nesting: a URL inside a URL is scrubbed; a URL inside that\n * which carries a query or a fragment of its own (NESTED_QUERY), or pairs\n * of its own (NESTED_PAIRS), is replaced whole, unread -- fail-closed,\n * and a crafted link cannot nest without end.\n */\nexport const MAX_NESTING = 1;\n\n/** A URL value with a query or a fragment after its path. */\nconst NESTED_QUERY = /^(?:[a-z][a-z0-9+.-]*:\\/\\/|\\/)[^?#]*[?#]./i;\n\n/**\n * A value that is no URL but holds a URL's pairs: a query after a second\n * `?` (`?a=1?token=...`), or pairs a `&` or `;` separated before they\n * were encoded (`?a=1%26token%3D...`).\n */\nconst NESTED_PAIRS = /[&;?#][^&;=?#]+=/;\n\n/**\n * A value that is itself a URL -- `?next=https://...`, `?redirect=/welcome?token=...`\n * -- or holds a URL's pairs, scrubbed one level down; null when it is\n * neither.\n */\nfunction scrubNestedUrl(\n value: string,\n rules: UrlRules,\n depth: number,\n): string | null {\n if (/^[a-z][a-z0-9+.-]*:\\/\\//i.test(value))\n return scrubAbsolute(value, rules, depth + 1);\n if (value.startsWith(\"/\")) return scrubRelative(value, rules, depth + 1);\n if (NESTED_PAIRS.test(value))\n return /[?#]/.test(value)\n ? scrubRelative(value, rules, depth + 1)\n : scrubPairs(value, rules, depth + 1);\n return null;\n}\n\n/**\n * A relative URL -- a path, `?query`, `#fragment`, or `//host/...` --\n * scrubbed as an absolute one is, without a base to parse it against:\n * its path, query and fragment found by their delimiters. Returned as it\n * came when nothing in it is scrubbed.\n */\nfunction scrubRelative(value: string, rules: UrlRules, depth: number): string {\n const hashAt = value.indexOf(\"#\");\n const beforeHash = hashAt === -1 ? value : value.slice(0, hashAt);\n const q = beforeHash.indexOf(\"?\");\n const path = q === -1 ? beforeHash : beforeHash.slice(0, q);\n const query = q === -1 ? null : beforeHash.slice(q + 1);\n const fragment = hashAt === -1 ? null : value.slice(hashAt + 1);\n const out =\n scrubPath(path, rules) +\n (query === null ? \"\" : `?${scrubPairs(query, rules, depth, path)}`) +\n (fragment === null\n ? \"\"\n : `#${scrubFragment(fragment, rules, depth, path)}`);\n return out === value ? value : out;\n}\n\n/**\n * Where a credential's own value in a text ends: at whitespace, `,`, `;`,\n * a quote, `<`, `>`, a backslash, a backtick, or a `)`, `]` or `}` it\n * does not open -- `?sig=(abc)` is one value. Ended at whitespace alone, a\n * CSV row's later columns, a `;rest` and CSS's `);color:red}` went with\n * the credential (found in review). In a form (`form`), at whitespace\n * alone.\n */\nfunction ownValueEnd(raw: string, form = false): number {\n if (form) {\n const at = raw.search(/\\s/);\n return at === -1 ? raw.length : at;\n }\n let parens = 0;\n let squares = 0;\n let braces = 0;\n for (let i = 0; i < raw.length; i++) {\n const c = raw[i]!;\n if (/[\\s,;\"'<>\\\\`]/.test(c)) return i;\n if (c === \"(\") parens++;\n else if (c === \"[\") squares++;\n else if (c === \"{\") braces++;\n else if (c === \")\" && parens-- === 0) return i;\n else if (c === \"]\" && squares-- === 0) return i;\n else if (c === \"}\" && braces-- === 0) return i;\n }\n return raw.length;\n}\n\n/** Whether a value, decoded as often as it was encoded (up to four times), names a credential under any of its pairs. */\nexport function holdsCredentialName(value: string, kind: NameKind): boolean {\n // Escape by escape (decoded): all or nothing, one malformed escape\n // (`%25zz`, a lone `%E0`) left every other escape unread and the\n // credential's name with it (found in review).\n let text = value;\n for (let k = 0; k < 4; k++) {\n const next = decoded(text);\n if (next === text) break;\n text = next;\n }\n // A pair's lead, never a path's `/`: a `/name=` segment is a path's\n // (`/dl/api_key=foo bar.txt`), which no read judges (found in review: a\n // file's name went whole).\n for (const m of text.matchAll(/(?:^|[?&;#])([^?&;#=/\\s]+)=/g))\n if (isCredentialName(m[1]!, kind)) return true;\n return false;\n}\n\n/** A query's (or a fragment's) pairs, each scrubbed; its separators kept as they came. */\nfunction scrubPairs(\n query: string,\n rules: UrlRules,\n depth = 0,\n path = \"\",\n): string {\n // Outside `whole`, a `;` separates pairs too, as many servers read one\n // (`?a=1;token=...`), where a `name=` follows it; inside a value\n // (`?q=ada;lovelace`) it is the value's (PAIR_SEPARATOR). The separators\n // are kept as they came.\n const parts = query.split(rules.whole ? /(&)/ : PAIR_SEPARATOR);\n const pairs = parts.filter((_, i) => i % 2 === 0);\n const ctx: PairContext = { path, pairs, depth };\n return pairs\n .map((pair) => {\n const eq = pair.indexOf(\"=\");\n if (eq === -1) {\n return rules.bare?.(pair) === true ? \"[REDACTED]\" : pair;\n }\n const name = pair.slice(0, eq);\n const raw = pair.slice(eq + 1);\n if (raw === \"\") return pair;\n const value = decodePart(raw);\n // Replaced whole: a value that holds a credential somewhere in it\n // (a deep URL, one encoded twice or in part) can hold it after a\n // space as well as before (found in review: it was kept in clear).\n const gone = (): string => `${name}=[REDACTED]`;\n const before = rules.before?.(name, raw, ctx) ?? null;\n if (before !== null) return `${name}=${before}`;\n if (\n rules.strict ||\n (rules.whole ? pairNames(pair) : [name]).some((n) =>\n isCredentialName(n, rules.kind),\n ) ||\n rules.value?.(name, raw, value) === true\n ) {\n if (rules.spaced !== true) return gone();\n // In a text an own value that is empty is an empty value, kept, as\n // a path parameter's is (`?sig=,1`), and what follows it is read\n // all the same (`?token=,https://b/...`, found in review); a\n // form's is replaced, as it always was.\n const own = ownValueEnd(raw, rules.form);\n const rest = raw.slice(own);\n return `${name}=${own === 0 && !rules.form ? \"\" : \"[REDACTED]\"}${rules.tail?.(rest) ?? rest}`;\n }\n if (\n depth >= MAX_NESTING &&\n (NESTED_QUERY.test(value) || NESTED_PAIRS.test(value))\n )\n // Past one level the page's URL and the DOM's replace such a value\n // unread: no key is computed from them. A request's URL, the\n // report's and a body's -- a link the page requests next -- lose\n // it only for a credential's name in it, at any depth: replaced\n // unread, a value with none changed the request's key, or the\n // link's, which then no recorded request matched (found in review).\n return rules.kind === \"page\" || holdsCredentialName(value, rules.kind)\n ? gone()\n : pair;\n const inner = scrubNestedUrl(value, rules, depth);\n if (inner !== null && inner !== value) {\n // A request's key reads the pair whole: a value redacted in part\n // is one no key matches a live one against.\n if (rules.whole) return gone();\n if (rules.raw !== true) return `${name}=${encodeURIComponent(inner)}`;\n // A body's bytes are the server's: a nested URL is written back as\n // it came -- raw, or encoded as encodeURIComponent encodes it --\n // and one encoded any other way (`/reset%3Ftoken=...`) cannot be,\n // so its value goes whole (found in review: it was re-encoded).\n if (raw === value) return `${name}=${inner}`;\n return encodeURIComponent(value) === raw\n ? `${name}=${encodeURIComponent(inner)}`\n : gone();\n }\n // A value encoded more than once -- a redirect chain's hop,\n // `?redirect=https%253A%252F%252F...%253Fjwt%253D...`, or a path whose\n // `?` is still encoded once decoded, `?next=%2Freset%253Ftoken%253D...`\n // -- holds a URL no read above sees, though the nested read found a\n // URL in it: its whole value goes when a credential's name is in it,\n // decoded as often as it was encoded (found in review: one the nested\n // read returned unchanged was kept).\n if (decoded(value) !== value && holdsCredentialName(value, rules.kind))\n return gone();\n return pair;\n })\n .map((pair, i) => (i === 0 ? \"\" : parts[2 * i - 1]) + pair)\n .join(\"\");\n}\n\n/**\n * A path: a segment the rules take whole (a JWT) is replaced, a `;name=`\n * path parameter (Java's `;jsessionid=`) has a credential's value\n * replaced, and a segment's head the rules name (a link's token) is\n * replaced. Nothing else in a\n * path is judged: slugs, digests and file names are where a flow's pages\n * come from.\n */\nfunction scrubPath(path: string, rules: UrlRules): string {\n const segments = path.split(\"/\");\n const bases = segments.map((seg) => seg.split(\";\")[0]!);\n return segments\n .map((seg, i) => {\n if (rules.segment?.(seg) === true) return \"[REDACTED]\";\n const semi = seg.indexOf(\";\");\n const base = bases[i]!;\n const head =\n rules.head?.(path, base, i, bases) === true ? \"[REDACTED]\" : base;\n if (semi === -1) return head;\n return (\n head +\n seg.slice(semi).replace(\n /;([^;=]+)=([^;]*)/g,\n // An empty value is kept, as a query's is: there is nothing to\n // redact, and `\"/x;jsessionid=\" + id` in a script is code that\n // builds one (found in review: it became `=[REDACTED]\" + id`).\n // In a text, the value is its own only (ownValueEnd).\n (m: string, n: string, v: string) => {\n const own =\n rules.spaced === true ? ownValueEnd(v, rules.form) : v.length;\n return own > 0 && isCredentialName(n, rules.kind)\n ? `;${n}=[REDACTED]${v.slice(own)}`\n : m;\n },\n )\n );\n })\n .join(\"/\");\n}\n\n/**\n * A fragment: a hash router's route keeps its path and has its own query\n * scrubbed -- `#/cb?code=...`, and `#/cb&access_token=...`, whose pairs\n * start after the route's first `&` or `;`; a fragment of pairs -- an\n * OAuth implicit grant's `#access_token=...&state=...` -- is scrubbed as a\n * query is. Anything else is read as a path, where no `name=` segment is\n * judged (`#/docs/v=2`, `#!/access_token=...` alike).\n */\nfunction scrubFragment(\n fragment: string,\n rules: UrlRules,\n depth: number,\n path = \"\",\n): string {\n // `depth` rides through, or every `#n=<url>` started the nesting count\n // again and a crafted link recursed until the stack overflowed (review).\n const q = fragment.indexOf(\"?\");\n if (q !== -1) {\n const route = fragment.slice(0, q);\n return `${scrubPath(route, rules)}?${scrubPairs(fragment.slice(q + 1), rules, depth, `${path}/${route}`)}`;\n }\n const eq = fragment.indexOf(\"=\");\n if (eq !== -1 && !fragment.slice(0, eq).includes(\"/\")) {\n return scrubPairs(fragment, rules, depth, path);\n }\n // A route whose pairs follow a `&` or a `;`: `#/cb&access_token=...`,\n // `#/cb/v=1&access_token=...` (an `=` in the route before them, found in\n // review). One with an `=` in its path and no such separator is a route\n // alone (`#/docs/v=2`), as #36's tests require.\n const route = eq === -1 ? null : /^([^&;]*)([&;])/.exec(fragment);\n if (route !== null)\n return `${scrubPath(route[1]!, rules)}${route[2]}${scrubPairs(fragment.slice(route[0].length), rules, depth, `${path}/${route[1]}`)}`;\n return scrubPath(fragment, rules);\n}\n\n/**\n * An absolute URL. The page's URL and the DOM's, with an authority\n * (`https:`, `wss:`, `myapp://`), are parsed as the browser parses them\n * and rebuilt from their parts only when something in them is scrubbed:\n * user info dropped, scheme and host kept as the parser serialises them.\n * Every other URL is spliced (spliceAbsolute). Returned as it came when\n * nothing in it is scrubbed.\n */\nfunction scrubAbsolute(raw: string, rules: UrlRules, depth: number): string {\n // A URL the page's URL rule or the DOM's reads is rebuilt as the browser\n // serialises it, as #36's tests pin. Every other URL -- a request's, one\n // a body holds, one the report prints -- keeps its bytes, and so does one\n // with no authority (`urn:`, `com.example.app:/oauth2redirect`) or one\n // the parser refuses (`https://%HOST%/x`): spliced, never returned\n // unread (found in review: each was recorded or printed as it came).\n if (rules.whole || rules.raw === true || !AUTHORITY.test(raw))\n return spliceAbsolute(raw, rules, depth);\n let url: URL;\n try {\n url = new URL(raw);\n } catch {\n return spliceAbsolute(raw, rules, depth);\n }\n const search = url.search.slice(1);\n const hash = url.hash.slice(1);\n const path = scrubPath(url.pathname, rules);\n const query = url.search\n ? scrubPairs(search, rules, depth, url.pathname)\n : \"\";\n const fragment = url.hash\n ? scrubFragment(hash, rules, depth, url.pathname)\n : \"\";\n // Nothing to scrub: the URL exactly as it came -- a trailing `?` or `#`\n // included, which a rebuild from its parts drops.\n if (\n path === url.pathname &&\n query === search &&\n fragment === hash &&\n url.username === \"\" &&\n url.password === \"\"\n ) {\n return raw;\n }\n return (\n `${url.protocol}//${url.host}` +\n path +\n (url.search ? `?${query}` : \"\") +\n (url.hash ? `#${fragment}` : \"\")\n );\n}\n\n/** A scheme a browser reads an authority after: `https:`, `https:/host`, `wss://`, `myapp://`. */\nconst AUTHORITY = /^(?:https?:|[a-z][a-z0-9+.-]*:[/\\\\]{2})/i;\n\n/**\n * An absolute URL scrubbed by its delimiters, every byte the scrub does not\n * replace kept: its scheme, the authority after it (its user info\n * dropped), then its path, query and fragment (scrubRelative).\n */\nfunction spliceAbsolute(raw: string, rules: UrlRules, depth: number): string {\n const head = /^([a-z][a-z0-9+.-]*:)([/\\\\]*)([^/\\\\?#]*)/i.exec(raw)!;\n const [whole, scheme, slashes, authority] = head as unknown as [\n string,\n string,\n string,\n string,\n ];\n const at = slashes === \"\" ? -1 : authority.lastIndexOf(\"@\");\n const out =\n scheme +\n slashes +\n authority.slice(at + 1) +\n scrubRelative(raw.slice(whole.length), rules, depth);\n return out === raw ? raw : out;\n}\n\n/**\n * THE SCRUBBER: one URL as it may be recorded or printed, by `rules`. A\n * URL with a scheme is absolute (scrubAbsolute) -- `https:`, `wss:`,\n * `myapp://`, and one with no authority (`mailto:`, `urn:`,\n * `com.example.app:/oauth2redirect?code=...`) alike -- but for a script's\n * or an inline object's (`javascript:`, `vbscript:`, `data:`, `blob:`),\n * which holds no URL's parts and is kept; anything else is a relative\n * URL, read by its delimiters. Byte for byte as it came when nothing in it\n * is a credential's.\n */\nexport function scrubUrl(value: string, rules: UrlRules): string {\n const lead = value.length - value.trimStart().length;\n const trail = value.length - value.trimEnd().length;\n const url = value.slice(lead, value.length - trail);\n let out: string;\n if (/^(?:javascript|vbscript|data|blob):/i.test(url)) return value;\n if (/^[a-z][a-z0-9+.-]*:/i.test(url)) out = scrubAbsolute(url, rules, 0);\n else out = scrubRelative(url, rules, 0);\n return out === url\n ? value\n : value.slice(0, lead) + out + value.slice(value.length - trail);\n}\n\n/**\n * Where a URL starts in a text -- an HTML, XML, RSC or text body, a JSON\n * string, a form's or a multipart part's value: a scheme with an\n * authority (`https://`, `wss://`, `myapp://`), whatever comes before it\n * (`--https://...`); any value a link's attribute holds, quoted or not\n * (`href=cb#...`); a URL any other attribute holds quoted that a path, a\n * query or a fragment starts, or a scheme as a line's start takes one (a\n * `/` after it, a `.` or `+` in its name, `localhost` and its port, a\n * scheme with no authority) (`data-next=\"/x?next=...\"`, found in review: an attribute\n * off the list kept its link) -- never another quoted value, which is a style or a script's string as often\n * (`style=\"background:url(...)\"`, whose property read as a scheme took\n * the declarations after the URL, found in review), and never an\n * unquoted `name=` in a text, which is code or a pair\n * (`x=y?1:2;token=...`); a meta refresh's `url=`\n * (`content=\"0; url=/x?...\"`, read forward from `content`); and a CSS\n * `url(`. A scheme is at most 32 characters and a name 40, and a name is\n * read from its start, so a start is read at most that far: unbounded, a\n * scheme read from each position of a run of letters cost the square of\n * the run, and so did an attribute read back over a run of spaces (2 s\n * for 64 KB, found in review), and a meta refresh's read back from each\n * `url` (17 s for 256 KB of spaces, found in review). No alternative\n * reads back further than a character, and none has two runs of spaces\n * back to back: `content=` and spaces with no quote between was read\n * once for each place one run could end (found in review).\n */\nconst URL_START =\n /[a-z][a-z0-9+.-]{0,31}:[/\\\\]{2}|(?<attr>\\bcontent\\s*=\\s*(?:[\"']\\s*)?\\d[\\d.]*\\s*[;,]\\s*url\\s*=\\s*[\"']?|\\b(?:href|src|action|formaction|poster|cite|data|background|longdesc|content|data-src|data-href|xlink:href)\\s*=\\s*[\"']?|(?<![\\w:.-])[\\w:.-]{1,40}\\s*=\\s*[\"'](?=\\.{0,2}\\/|[?#]|[a-z][a-z0-9+.-]{0,31}:\\/|[a-z][a-z0-9-]{0,30}[+.][a-z0-9+.-]{0,30}:|localhost:\\d{1,5}[/?#]|(?:mailto|tel|sms|urn|data|javascript|vbscript|blob|about|xmpp|sip|sips|magnet|intent|bitcoin|geo|market|news):)|\\burl\\(\\s*[\"']?)(?=[^\\s\"'<>])/gi;\n\n/** What ends a URL in a text: a space, a quote, a tag, a backslash, a backtick, a brace or a pipe. */\nconst URL_END = /[\\s\"'<>\\\\^`{|}]/;\n\n/** What prose puts after a URL that is no part of it. */\nconst URL_TRAILER = \".,;:!?\";\n\n/**\n * A URL with a scheme and an authority, at `lastIndex`. In a text read\n * for its list (UrlRules' `list`: what a credential's own value leaves\n * after it), a `,` before one ends the URL before it, so each URL of the\n * list is its own (`?token=...,https://b/y?next=...`). A list a query\n * holds elsewhere is the query's value (`?list=https://a,https://b&...`).\n */\nconst NEXT_URL = /[a-z][a-z0-9+.-]{0,31}:\\/\\//iy;\n\n/**\n * Where the URL in `text`'s [start, end) ends, what prose puts after it\n * set aside: a full stop, a comma, and a `)` or `]` at its end the URL\n * does not open -- `(see https://...)` -- but not one it does\n * (`?sig=(...)`, an IPv6 host's `http://[::1]`): stripped, a value's own\n * `)` was left after its marker (found in review). Read once from each\n * end, never as a regex from each position (the square of a run of full\n * stops). What the print sink reads a URL by: a `)` inside a printed key\n * (`?q=:)&token=...`) is the key's.\n */\nexport function urlEnd(text: string, start: number, end: number): number {\n let parens = 0;\n let brackets = 0;\n for (let i = start; i < end; i++) {\n const c = text[i];\n if (c === \"(\") parens++;\n else if (c === \")\") parens--;\n else if (c === \"[\") brackets++;\n else if (c === \"]\") brackets--;\n }\n while (end > start) {\n const c = text[end - 1]!;\n if (c === \")\") {\n if (parens >= 0) break;\n parens++;\n } else if (c === \"]\") {\n if (brackets >= 0) break;\n brackets++;\n } else if (!URL_TRAILER.includes(c)) break;\n end--;\n }\n return end;\n}\n\n/**\n * Where a URL the scan finds at `start` ends: at the first character that\n * ends a URL in a text (URL_END); outside a quoted attribute, also at the\n * first `)` or `]` it does not open -- CSS's\n * `url(https://...?sig=...);color:red`, prose's `(see https://...)` --\n * but not at one it does (`?sig=(...)`, `http://[::1]`); and before what\n * prose puts after it. Read to the next space and stripped at the end\n * only, a CSS declaration after the URL was the URL's, and a credential's\n * value took the `)` and the declarations with it (found in review). A\n * quoted attribute's value ends at its quote, its `)` its own\n * (`href=\"...?q=:)&next=...\"`). One pass forward, one back.\n */\nfunction scanEnd(\n text: string,\n start: number,\n brackets: boolean,\n list: boolean,\n): number {\n let end = start;\n let parens = 0;\n let squares = 0;\n for (; end < text.length; end++) {\n const c = text[end]!;\n if (URL_END.test(c)) break;\n if (list && c === \",\") {\n NEXT_URL.lastIndex = end + 1;\n if (NEXT_URL.test(text)) break;\n }\n if (!brackets) continue;\n if (c === \"(\") parens++;\n else if (c === \"[\") squares++;\n else if (c === \")\" || c === \"]\") {\n if ((c === \")\" ? parens : squares) === 0) break;\n if (c === \")\") parens--;\n else squares--;\n }\n }\n return urlEnd(text, start, end);\n}\n\n/** CSS's `url(` and its quote, at an attribute's value. */\nconst CSS_URL_OPEN = /url\\(\\s*[\"']?/iy;\n\n/** Every URL in `text`, as [start, end) spans, in order; in a text's `list`, a `,` before a URL ends the one before it (NEXT_URL). */\nexport function urlSpans(text: string, list = false): Array<[number, number]> {\n const spans: Array<[number, number]> = [];\n URL_START.lastIndex = 0;\n for (let m = URL_START.exec(text); m !== null; m = URL_START.exec(text)) {\n // A scheme's match is the URL's start; an attribute's or a `url(`'s\n // ends where the URL starts.\n let start = m.index + (m.groups?.[\"attr\"]?.length ?? 0);\n // An attribute's value that is CSS's `url(...)` holds the URL: read\n // from the attribute, the `url(` opened a `(` and the URL took its\n // `)` (`background=\"url(/x?next=...) no-repeat\"`, found in review).\n CSS_URL_OPEN.lastIndex = start;\n const inCssUrl =\n m.groups?.[\"attr\"] !== undefined && CSS_URL_OPEN.test(text);\n if (inCssUrl) start = CSS_URL_OPEN.lastIndex;\n // Read once, to the URL's end: read to the next space first and cut\n // at a `)` after, a run of CSS's `url(...);` was read to its end from\n // each `url(` (2.9 s for 64 KB, found in review). A quoted listed\n // attribute's value, but for a `url(` in it, ends at its quote alone.\n const attr = m.groups?.[\"attr\"] ?? \"\";\n let end = scanEnd(\n text,\n start,\n !/[\"']$/.test(attr) || /^url\\(/i.test(attr) || inCssUrl,\n list,\n );\n // A template literal's `${` starts code, not a value: read as one,\n // `https://x/cb?token=${t}` became `token=[REDACTED]{t}` (found in\n // review).\n if (text[end] === \"{\" && end > start && text[end - 1] === \"$\") end--;\n if (end > start) spans.push([start, end]);\n URL_START.lastIndex = Math.max(end, m.index + m[0].length, start + 1);\n }\n return spans;\n}\n\n/** Each URL in `text` scrubbed by `rules`, as [start, end, replacement] edits for those that changed. */\nexport function urlEdits(\n text: string,\n rules: UrlRules,\n): Array<[number, number, string]> {\n const edits: Array<[number, number, string]> = [];\n for (const [start, end] of urlSpans(text, rules.list === true)) {\n const url = text.slice(start, end);\n const out = scrubUrl(url, rules);\n if (out !== url) edits.push([start, end, out]);\n }\n return edits;\n}\n\n/**\n * A URL read as the replay key reads one (`whole`) under a `param`'s\n * names: what a request's URL and a URL the report prints are scrubbed\n * by, `strict` as asked.\n */\nexport function keyRules(strict: boolean): UrlRules {\n return { kind: \"param\", strict, whole: true };\n}\n\n/**\n * A BODY THE CAPTURE SDK RECORDED CUT, AND SAYS SO.\n *\n * The SDK redacts a body off the page's main thread, in a Web Worker\n * (@keploy/capture-sdk's body-worker.js). Where the page cannot run one\n * -- its CSP refuses the worker's script, the bundler did not emit it,\n * the platform has no Worker -- a body over the SDK's main-thread budget\n * (64 KiB) is not redacted whole on the page's thread: only its first\n * part is, and the rest is dropped. The same holds for a body still in\n * the worker when the page leaves, past what the page's last moment can\n * redact. That body is NOT the response the server sent, so the record\n * carries this note as its first line, naming how much of it is kept\n * (0 when nothing could be redacted in time) and how long it was, and\n * the redacted part follows it.\n *\n * Replay never serves such a body as if it were whole (mock-replay.v7\n * rules.cut): a test that reaches it cannot be proven by it.\n */\nexport function cutBodyNote(kept: number, total: number): string {\n return `[Body cut: ${kept} of ${total} characters kept, unverified]\\n`;\n}\n\n/** True for a body recorded with {@link cutBodyNote}'s first line. */\nexport function isCutBody(body: unknown): boolean {\n return (\n typeof body === \"string\" &&\n /^\\[Body cut: \\d+ of \\d+ characters kept, unverified\\]\\n/.test(body)\n );\n}\n\n/**\n * WHY THE CAPTURE SDK DID NOT CAPTURE A BODY: the reason line a body\n * recorded as {@link notCapturedBodyNote} carries, one per cause, and no\n * other. The SDK records a body only redacted, and the code it redacts\n * one with on the page's main thread is a chunk it asks for at init(),\n * beside rrweb.\n * - `left`: the page left, or the capture stopped, while that chunk was\n * still on its way. A moment after which nothing more is recorded\n * (pagehide, stop()'s bound) cannot wait for it.\n * - `code-failed`: the chunk could not load at all (a CSP that refuses\n * it, a 404 after a deploy, a module without its exports), so the page\n * has no code to redact a body with on its main thread for the rest of\n * its life (KUI_E_BODY_WORKER_UNAVAILABLE names the page's first\n * failed part, once).\n * - `early`: the page took the body's stream (`res.body`) before that\n * chunk, which holds the SDK's stream relay, had loaded (still on its\n * way, or held by the page's leave), and nothing read the body whole.\n * The page got the network's own stream at once, never waiting for the\n * chunk, so the SDK saw none of what it read: it may have read all of\n * it, or only looked.\n */\nexport const NOT_CAPTURED_WHY = {\n left: \"the page left or the capture stopped before redaction was ready\",\n \"code-failed\": \"the redaction code could not load\",\n early: \"the page took the body's stream before the redaction code had loaded\",\n} as const;\n\n/** A cause of a body recorded as {@link notCapturedBodyNote}. */\nexport type NotCapturedWhy = keyof typeof NOT_CAPTURED_WHY;\n\n/**\n * A BODY THE CAPTURE SDK DID NOT CAPTURE, AND SAYS WHY: these two lines\n * and nothing else, never the body in the clear. {@link cutBodyNote}\n * with nothing kept, then `[Body not captured: <why>]`, `<why>` being\n * {@link NOT_CAPTURED_WHY}'s line for its cause:\n *\n * [Body cut: 0 of N characters kept, unverified]\n * [Body not captured: the page left or the capture stopped before redaction was ready]\n *\n * [Body cut: 0 of N characters kept, unverified]\n * [Body not captured: the redaction code could not load]\n *\n * [Body cut: 0 of N characters kept, unverified]\n * [Body not captured: the page took the body's stream before the redaction code had loaded]\n *\n * The first line is a cut note, so replay never serves it (mock-replay.v7\n * rules.cut) and a test that reaches it is unproven, as for any cut body.\n * The second, which no other body the SDK records has after its note,\n * tells it apart from a body cut at the main thread's budget, and says\n * why (isNotCapturedBody), for a dashboard or a report.\n */\nexport function notCapturedBodyNote(\n total: number,\n why: NotCapturedWhy,\n): string {\n return `${cutBodyNote(0, total)}[Body not captured: ${NOT_CAPTURED_WHY[why]}]\\n`;\n}\n\n/**\n * True for a body recorded as {@link notCapturedBodyNote}, exactly: for\n * the cause `why` when given, else for any cause it documents. A second\n * line naming no documented cause is not one.\n */\nexport function isNotCapturedBody(\n body: unknown,\n why?: NotCapturedWhy,\n): boolean {\n const said =\n typeof body === \"string\" &&\n /^\\[Body cut: 0 of \\d+ characters kept, unverified\\]\\n\\[Body not captured: ([^\\]\\n]*)\\]\\n$/.exec(\n body,\n )?.[1];\n return said\n ? why === undefined\n ? Object.values<string>(NOT_CAPTURED_WHY).includes(said)\n : said === NOT_CAPTURED_WHY[why]\n : false;\n}\n","/* ------------------------------------------------------------------ */\n/* Structural redaction */\n/* ------------------------------------------------------------------ */\n/*\n * Replaces the regex-over-the-whole-body approach, which was a\n * correctness bug rather than a privacy nit:\n *\n * - `/\\b(?:\\d[ -]*?){13,19}\\b/g` matched every 13-digit Date.now(),\n * every snowflake id and every long numeric id.\n * - Replacing inside a serialized JSON number produced INVALID JSON:\n * {\"ts\":1699999999999} became {\"ts\":[REDACTED]}, which no longer\n * parses.\n *\n * The failure mode was especially bad because it looked like a pass: the\n * corruption also destroyed the timestamp nondeterminism it had just\n * created, so a diff of two corrupted captures could still match.\n *\n * Three rules make this deterministic and type-preserving:\n * 1. Parse first. Walk the structure, never the serialization.\n * 2. Only STRING values are scanned. A JSON number is never PII in\n * practice, and scanning numbers is what corrupted timestamps.\n * 3. Redaction is type-preserving and stable: a redacted string stays\n * a string, and the same input always produces the same output, so\n * two recordings of the same logical response stay comparable.\n */\n\nimport {\n decoded,\n holdsCredentialName,\n isCredentialName,\n nameParts,\n scrubUrl,\n urlEdits,\n type UrlRules,\n} from \"@keploy/contract/privacy\";\n\nconst REDACTED = \"[REDACTED]\";\n\n/**\n * Names that are a card's expiry only beside a card field: `expiry` on\n * a token or `expirationDate` on a cookie is a date the page needs back.\n */\nconst CARD_EXPIRY_BESIDE_A_CARD: ReadonlySet<string> = new Set([\n \"expiry\",\n \"expirydate\",\n \"expiration\",\n \"expirationdate\",\n \"expdate\",\n \"exp\",\n]);\n\n/** A field that makes the object it is in a card. */\nconst CARD_FIELDS: ReadonlySet<string> = new Set([\n \"cardnumber\",\n \"creditcard\",\n \"creditcardnumber\",\n \"ccnumber\",\n \"cardnum\",\n \"pan\",\n \"cvv\",\n \"cvc\",\n]);\n\n/** Emitted for a JSON-shaped body that cannot be parsed (usually truncated). */\nexport const TRUNCATED_UNPARSEABLE = \"[UNPARSEABLE_BODY_NOT_REDACTED]\";\n\n/**\n * The notes network.ts writes in place of a body it did not read: a\n * Blob on the XHR path or one over the cap on the fetch path, a buffer\n * over the cap or one that is not UTF-8, a response whose\n * Content-Length is over it, a stream it must not consume, a shape\n * with no name, an XHR responseType it cannot read as text.\n *\n * They are the SDK's own words, not the page's data, and they carry the\n * only record of what the body WAS and how large. They are also not\n * JSON — so under a JSON content-type they went through JSON.parse,\n * failed, and were replaced with the generic refusal below, losing the\n * kind and the size. The docs page records that as a defect: \"with no\n * record of what they were or how large\".\n *\n * Matched whole, anchored, and only for shapes with no free text in\n * them, so a page body that happened to equal one of these would skip\n * redaction — and there would be nothing in it to redact, because the\n * whole body would be that fixed string.\n */\nconst NOT_RECORDED = [\n /^\\[Blob: \\d+ bytes, truncated\\]$/,\n // The XHR path's Blob, which is named rather than read: its body has\n // to be serialised inside send(), and Blob.text() is async.\n /^\\[Blob: \\d+ bytes\\]$/,\n /^\\[Binary: \\d+ bytes\\]$/,\n /^\\[Response body too large: \\d+ bytes\\]$/,\n // A response body the page never read, nor the SDK (network.ts NOT_READ).\n /^\\[Response body not read by the page\\]$/,\n /^\\[ReadableStream\\]$/,\n /^\\[Unreadable body\\]$/,\n // `[${xhr.responseType} response]` — the XMLHttpRequestResponseType\n // enum: \"\", arraybuffer, blob, document, json, text.\n /^\\[(?:arraybuffer|blob|document|json|text|) response\\]$/,\n];\n\n/** True for a body that IS one of the SDK's own not-recorded notes. */\nexport function isNotRecordedNote(body: string): boolean {\n return NOT_RECORDED.some((re) => re.test(body));\n}\n\n/**\n * A key as the one rule reads a name (@keploy/contract's privacy.ts\n * nameParts), its parts joined: what a rule about a key's context -- a\n * card's fields, a token exchange's -- compares, so no name is read two\n * ways.\n */\nfunction normalizeKey(key: string): string {\n return nameParts(key, \"key\").join(\"\");\n}\n\n/** A plain word, or words joined by `-` or `_`: an app's filter, not an OAuth state. */\nconst PLAIN_WORDS = /^[A-Za-z]+(?:[-_][A-Za-z]+)*$/;\n/** camelCase words: an app's `state=inProgress` (#36's review). */\nconst CAMEL_WORDS = /^[A-Za-z][a-z]+(?:[A-Z][a-z]+)+$/;\n\n/**\n * Whether a state is an app's word rather than OAuth's generated value:\n * letters, or words joined by `-` or `_`, of at most 16 characters --\n * `delivered`, `California`, `in-progress` -- or longer camelCase or\n * joined words. A random run of letters past 16 is not one (review).\n */\nexport function isPlainState(state: string): boolean {\n if (!PLAIN_WORDS.test(state)) return false;\n return (\n state.length <= 16 ||\n CAMEL_WORDS.test(state) ||\n /^[A-Za-z][a-z]+(?:[-_][A-Za-z][a-z]+)+$/.test(state)\n );\n}\n\n/** The grants a token exchange redeems a code for: an authorization code's, and a device flow's (RFC 8628). */\nconst EXCHANGE_GRANTS: ReadonlySet<string> = new Set([\n \"authorization_code\",\n \"urn:ietf:params:oauth:grant-type:device_code\",\n]);\n\n/** The names, normalized, a token exchange carries its code under. */\nconst EXCHANGE_CODES: ReadonlySet<string> = new Set([\"code\", \"devicecode\"]);\n\n/** The names, normalized, an exchange's values are redacted under: its code, and the state beside it. */\nconst EXCHANGE_REDACTED: ReadonlySet<string> = new Set([\n ...EXCHANGE_CODES,\n \"state\",\n]);\n\n/** The names, normalized, an exchange's code is sent or handed out beside. */\nconst EXCHANGE_PEERS: ReadonlySet<string> = new Set([\n \"redirecturi\",\n \"clientid\",\n \"verificationuri\",\n]);\n\n/**\n * Whether a body's names and values are an OAuth token exchange's: a\n * page that finishes an OAuth flow itself (a SPA with PKCE, a backend for\n * the frontend) posts the authorization code it was handed, and `code`\n * is no credential's name anywhere else (an app's `?code=US`, a promo\n * code); a device flow's `device_code` is its code. So a code\n * (EXCHANGE_CODES) goes only beside a grant that redeems one\n * (`grant_type=authorization_code`, the device code grant), a\n * `code_verifier`, a `redirect_uri`, `client_id` or the\n * `verification_uri` a device authorization hands out with its code, or\n * -- beside a code of 10 or more -- a generated state (isGeneratedState):\n * the authorization response itself, which a page may hand its backend.\n * Names normalized.\n */\nfunction isTokenExchange(pairs: ReadonlyArray<[string, string]>): boolean {\n let code = false;\n let peer = false;\n let longCode = false;\n let state = false;\n for (const [name, value] of pairs) {\n if (name === \"granttype\" && EXCHANGE_GRANTS.has(value.trim().toLowerCase()))\n return true;\n if (name === \"codeverifier\") return true;\n if (EXCHANGE_CODES.has(name)) {\n code = true;\n if (value.length >= 10) longCode = true;\n }\n if (EXCHANGE_PEERS.has(name)) peer = true;\n if (name === \"state\" && isGeneratedState(value)) state = true;\n }\n // A generated state beside a code of 10 or more: an authorization\n // response a page hands its backend to redeem, as the URL rule reads one.\n return code && (peer || (state && longCode));\n}\n\n/**\n * An OAuth state as a provider round-trips it: 16 characters or more of a\n * token's alphabet, letters with a digit among them or with both cases\n * (`XK3JF9QZ2LMN8PRT`, `x8Kq2Lm9Np4Rt7Vw`), and no plain word or slug of\n * words and numbers (`in_progress_step2`, `pending-approval-2024`,\n * `ORDER-2024-000123`). An app's own state -- `CA`, `WA-98101`,\n * `delivered`, a timestamp -- is not one.\n */\nfunction isGeneratedState(value: string): boolean {\n return (\n value.length >= 16 &&\n /^[A-Za-z0-9_\\-.~+/=]+$/.test(value) &&\n /[A-Za-z]/.test(value) &&\n (/\\d/.test(value) || (/[a-z]/.test(value) && /[A-Z]/.test(value))) &&\n !isPlainState(value) &&\n !isStateSlug(value)\n );\n}\n\n/**\n * A slug of words and numbers, a word's digits at its end, and one part\n * letters alone: `in_progress_step2`, `ORDER-2024-000123`. With no such\n * part it is a generated token's groups (`Xk9-Pq2-Lm7-Rt4-Zw8`). No part\n * can be read two ways: where a lone capital could, `A-A-...-A1.` took\n * twice as long for each two parts more, 31 s at 30 (MEASURED).\n */\nfunction isStateSlug(value: string): boolean {\n return (\n /^(?:[A-Z]+|[A-Z]?[a-z]+)\\d*(?:[-_](?:(?:[A-Z]+|[A-Z]?[a-z]+)\\d*|\\d+))+$/.test(\n value,\n ) && /(?:^|[-_])[A-Za-z]+(?:[-_]|$)/.test(value)\n );\n}\n\n/**\n * A one-time code's names an app's settings use too: in a JSON body a\n * string or a number under them is the code, and a flag or an object is\n * the app's (`{\"totp\":{\"enabled\":true}}`), which a replay serves back.\n */\nconst BARE_CODE_NAMES: ReadonlySet<string> = new Set([\"passcode\"]);\n\n/** A value under a one-time code's settings name that holds no code itself, but is read on: an object or a list. A flag is kept under every name (redactNode). */\nfunction isSettingsValue(node: JNode): boolean {\n return node.kind === \"object\" || node.kind === \"array\";\n}\n\n/**\n * A JSON key's, a HAR-style pair's or a header's name, read by the one\n * rule (@keploy/contract's privacy.ts isCredentialName) as a `key`.\n */\nexport function isSensitiveKey(key: string): boolean {\n return isCredentialName(key, \"key\");\n}\n\n/**\n * A one-time code's name an app's settings use too: `passcode`\n * (BARE_CODE_NAMES), or a name ending in `otp` -- `otp`, `totp`, an\n * `email_otp`, an `sms_otp`: under it an object is the app's setting\n * (`{\"totp\":{\"enabled\":true}}`), and a code is the code.\n */\nfunction isBareCodeName(key: string): boolean {\n return nameParts(key, \"key\").some(\n (n) => BARE_CODE_NAMES.has(n) || n.endsWith(\"otp\"),\n );\n}\n\n/**\n * Credential names an app's data uses as often for a list, a summary or a\n * method: `{\"credentials\":[{\"id\":1,\"provider\":\"github\"}]}`,\n * `{\"authentication\":{\"providers\":[\"google\"]}}`, a test summary's\n * `{\"pass\":12,\"fail\":3}`. Under them only a string is the credential; any\n * other value is read on, its own credentials redacted by name, so a page\n * that maps over the list is served the list (found in review).\n */\nconst WORD_NAMES: ReadonlySet<string> = new Set([\n \"credentials\",\n \"authentication\",\n \"pass\",\n]);\n\n/** Whether a JSON key is one of WORD_NAMES, read as the one rule reads a key. */\nfunction isWordName(key: string): boolean {\n return nameParts(key, \"key\").some((n) => WORD_NAMES.has(n));\n}\n\n/* ------------------------------------------------------------------ */\n/* Value-level detectors — applied ONLY to strings */\n/* ------------------------------------------------------------------ */\n\n/**\n * Email addresses, found from each `@` rather than by a regex over the\n * whole text.\n *\n * The unanchored `[a-zA-Z0-9._%+-]+@...` retried the whole run from every\n * position inside it, so a long run with no `@` -- a hex digest, a base64\n * blob, a minified bundle -- cost quadratic time ON THE PAGE'S MAIN\n * THREAD: MEASURED 1.8 s for 64K characters and minutes at the 512 KB\n * body cap (review round 1). Anchoring the regex to a run's start made it\n * linear but blind to an address glued onto the previous one\n * (`ada@x.com+bob@y.org`) or ending a long `%20` run -- both of which\n * 3.0.1 caught (review round 2). So the scan starts at each `@`: the local\n * part is the last 64 local characters before it (RFC 5321's limit), not\n * reaching back into the previous match, and the domain is a bounded\n * sticky match after it. Each `@` costs at most 64 + 253 steps: linear.\n */\nconst EMAIL_DOMAIN = /[a-zA-Z0-9.-]{1,253}\\.[a-zA-Z]{2,63}/y;\n\nfunction isEmailLocalChar(code: number): boolean {\n return (\n (code >= 48 && code <= 57) || // 0-9\n (code >= 65 && code <= 90) || // A-Z\n (code >= 97 && code <= 122) || // a-z\n code === 46 || // .\n code === 95 || // _\n code === 37 || // %\n code === 43 || // +\n code === 45 // -\n );\n}\n\n/** The range of every email address in `text`, found from each `@`. */\nfunction emailRanges(text: string, into: Range[]): void {\n let kept = 0; // no match may reach back before this index\n let at = text.indexOf(\"@\");\n while (at !== -1) {\n const floor = Math.max(kept, at - 64);\n let start = at;\n while (start > floor && isEmailLocalChar(text.charCodeAt(start - 1))) {\n start--;\n }\n if (start < at) {\n EMAIL_DOMAIN.lastIndex = at + 1;\n const domain = EMAIL_DOMAIN.exec(text);\n if (domain) {\n kept = at + 1 + domain[0].length;\n into.push([start, kept]);\n at = text.indexOf(\"@\", kept);\n continue;\n }\n }\n at = text.indexOf(\"@\", at + 1);\n }\n}\n\n/**\n * A token whose provider prefix says what it is, whatever key it sits\n * under or text it is in: Keploy's own API keys (`kep_` + 43 base64url\n * characters, api-server's models.GenerateAPIKey), GitHub, GitLab, Slack,\n * Stripe, OpenAI and Anthropic, npm, webhook signing secrets, AWS access\n * key ids (long-lived and temporary) and Google API keys. Each alternative\n * is a literal prefix and a run taken whole (a longer run leaves no tail),\n * started only after a character that is not a letter or digit -- so\n * `x-kep_...` is found and `task_live_...` is not a Stripe key: linear.\n */\nconst KNOWN_TOKEN_RE =\n /(?<![A-Za-z0-9])(?:kep_[A-Za-z0-9_-]{20,}|gh[pousr]_[A-Za-z0-9]{36,}|github_pat_[A-Za-z0-9_]{22,}|glpat-[A-Za-z0-9_-]{20,}|xox[abprse]-[A-Za-z0-9-]{10,}|[sr]k_(?:live|test)_[A-Za-z0-9]{16,}|sk-(?:proj|ant)-[A-Za-z0-9_-]{20,}|npm_[A-Za-z0-9]{36,}|whsec_[A-Za-z0-9+/=]{24,}|(?:AKIA|ASIA)[0-9A-Z]{16,}|AIza[0-9A-Za-z_-]{35,})/g;\n\nconst SSN_RE = /\\b\\d{3}-\\d{2}-\\d{4}\\b/g;\n// Deliberately strict: a separator or an explicit country code is\n// required. The old \"any 7-digit run\" pattern matched order ids and is\n// what corrupted recorded URLs.\nconst PHONE_RE =\n /(?:\\+\\d{1,3}[ .-]?)?(?:\\(\\d{3}\\)[ .-]?|\\b\\d{3}[ .-])\\d{3}[ .-]\\d{4}\\b/g;\n// Starts only where the previous character is not base64url. `\\b` let a\n// match start after every `-` (a non-word character inside the alphabet),\n// so `eyJ-eyJ-...` rescanned the rest of the run from each `eyJ`:\n// MEASURED 510 ms at 64K characters on the main thread. The cost of the\n// anchor: a token glued straight onto a preceding `-` is not detected; a\n// JWT after a space, `=`, a quote or a colon -- every header, cookie,\n// query and JSON shape -- is.\nconst JWT_RE =\n /(?<![A-Za-z0-9_-])eyJ[A-Za-z0-9_-]+\\.[A-Za-z0-9_-]+\\.[A-Za-z0-9_-]+\\b/g;\n// An IP address is personal data under GDPR. Unlike the card pattern this\n// one is safe: it only ever matches inside a string value, so it cannot\n// turn a JSON number into a bare token.\n// Guarded on both sides so a build/version string is not mistaken for an\n// address: \"1.2.3.4000\" and \"10.0.0.1.5\" must survive untouched.\nconst IPV4_RE =\n /(?<![\\d.])(?:(?:25[0-5]|2[0-4]\\d|[01]?\\d\\d?)\\.){3}(?:25[0-5]|2[0-4]\\d|[01]?\\d\\d?)(?![\\d.])/g;\n\n/** Luhn check — the standard checksum every real card number satisfies. */\nfunction passesLuhn(digits: string): boolean {\n let sum = 0;\n let double = false;\n for (let i = digits.length - 1; i >= 0; i--) {\n let d = digits.charCodeAt(i) - 48;\n if (d < 0 || d > 9) return false;\n if (double) {\n d *= 2;\n if (d > 9) d -= 9;\n }\n sum += d;\n double = !double;\n }\n return sum % 10 === 0;\n}\n\n/**\n * A real card number: a known issuer prefix, a valid length for that\n * issuer, AND a passing Luhn checksum.\n *\n * All three are required on purpose. Length alone matched timestamps;\n * Luhn alone still admits ~10% of random digit runs. Together the false\n * positive rate on non-card data is negligible, and — critically — a\n * 13-digit millisecond timestamp has no valid issuer prefix.\n */\nfunction isLikelyCardNumber(digits: string): boolean {\n if (digits.length < 13 || digits.length > 19) return false;\n const isVisa =\n digits[0] === \"4\" &&\n (digits.length === 13 || digits.length === 16 || digits.length === 19);\n const isMastercard = /^(5[1-5]|2[2-7])/.test(digits) && digits.length === 16;\n const isAmex = /^3[47]/.test(digits) && digits.length === 15;\n const isDiscover = /^6(?:011|5)/.test(digits) && digits.length === 16;\n const isJcbDiners =\n /^(?:35|3[068])/.test(digits) && digits.length >= 14 && digits.length <= 19;\n if (!(isVisa || isMastercard || isAmex || isDiscover || isJcbDiners))\n return false;\n return passesLuhn(digits);\n}\n\n/** The range of every card-shaped run in `s` that is a real card number. */\nfunction cardRanges(s: string, into: Range[]): void {\n // Candidate runs of digits with optional single spaces/hyphens.\n for (const m of s.matchAll(/\\b(?:\\d[ -]?){12,18}\\d\\b/g)) {\n if (isLikelyCardNumber(m[0].replace(/[^0-9]/g, \"\"))) {\n into.push([m.index, m.index + m[0].length]);\n }\n }\n}\n\n/** Redact card-shaped runs inside a string, preserving everything else. */\nfunction redactCards(s: string): string {\n const ranges: Range[] = [];\n cardRanges(s, ranges);\n return applyRanges(s, ranges);\n}\n\n/** A half-open span of a text to redact: [start, end). */\ntype Range = [number, number] | [number, number, string];\n\n/** The range of every non-empty match of a global pattern. */\nfunction patternRanges(text: string, re: RegExp, into: Range[]): void {\n for (const m of text.matchAll(re)) {\n // An empty match hides nothing: `\\d*` matches the empty string at\n // every position, and a marker at each grew a body tenfold per pass\n // (review r7).\n if (m[0] !== \"\") into.push([m.index, m.index + m[0].length]);\n }\n}\n\n/**\n * Where every detector matches in `text`: the built-ins, then the\n * integrator's patterns (`extra`, compiled global -- see PrivacyEngine).\n *\n * EVERY DETECTOR RUNS OVER THE ORIGINAL TEXT, never over another's\n * output. The scan used to be a chain of replace() calls, each over the\n * last one's result, and both ways of letting a pattern meet a marker were\n * wrong, MEASURED: a pattern that re-scanned the markers rewrote them\n * (`/RED/` -> `[[REDACTED]ACTED]`) and grew a body tenfold per pass\n * (review r7); a pattern that ran only between markers hid only part of\n * its match -- `/Notes: .*\\/` over a phone number, a `<div class=\"notes\">`\n * pattern over an email -- and recorded the rest in clear (review r8,\n * against base 3ce8786, which redacted both). Ranges on the original text\n * have neither failure: see applyRanges.\n */\nfunction detectorRanges(\n text: string,\n extra: readonly RegExp[],\n into: Range[],\n): void {\n patternRanges(text, JWT_RE, into);\n patternRanges(text, KNOWN_TOKEN_RE, into);\n emailRanges(text, into);\n patternRanges(text, SSN_RE, into);\n patternRanges(text, PHONE_RE, into);\n patternRanges(text, IPV4_RE, into);\n cardRanges(text, into);\n for (const re of extra) patternRanges(text, re, into);\n}\n\n/**\n * `text` with every range replaced by one marker, OVERLAPPING ranges\n * merged into one: a pattern that covers a built-in's match covers it\n * whole. Ranges that only touch stay separate markers (two addresses\n * glued together are two). Nothing outside a range changes, and each\n * marker replaces at least one character -- except the one kind of empty\n * range a caller may add on purpose, a sensitive form field's empty value\n * -- so a result is at most ten times its input plus those.\n */\nfunction applyRanges(text: string, ranges: Range[]): string {\n if (ranges.length === 0) return text;\n ranges.sort((a, b) => a[0] - b[0] || b[1] - a[1]);\n let out = \"\";\n let pos = 0;\n let [start, end, with_] = ranges[0];\n for (let k = 1; k <= ranges.length; k++) {\n const next = ranges[k];\n if (next !== undefined && next[0] < end) {\n if (next[1] > end) end = next[1];\n with_ = undefined; // merged: one marker covers them all\n continue;\n }\n out += text.slice(pos, start) + (with_ ?? REDACTED);\n pos = end;\n if (next !== undefined) [start, end, with_] = next;\n }\n return out + text.slice(pos);\n}\n\n/**\n * Apply every value-level detector to one string, then every\n * caller-supplied pattern, all over the string as it came.\n *\n * `extra` is the integrator's `privacy.piiPatterns`, already compiled\n * global (see PrivacyEngine). It rides through every scan the engine\n * makes -- this function is the ONLY string scanner -- so a pattern\n * applies to a JSON string value, a text body and a header value alike.\n * It used to reach header values only, while its documentation said\n * \"matched text is replaced\".\n */\nexport function redactStringValue(\n value: string,\n extra: readonly RegExp[] = [],\n): string {\n if (!value) return value;\n const ranges: Range[] = [];\n detectorRanges(value, extra, ranges);\n return applyRanges(value, ranges);\n}\n\n/**\n * A JSON string's text: each embedded credential pair's value, by the\n * leads a string takes (EMBEDDED_NAME_IN_STRING), and each detector's\n * match replaced. A JSON string is a text -- a message, a log line, a\n * stored form -- and, read by the detectors alone, `see /cb?token=... now`\n * was recorded (found in review).\n */\nfunction redactStringText(value: string, extra: readonly RegExp[]): string {\n if (!value) return value;\n const ranges: Range[] = [];\n embeddedPairRanges(value, ranges, \"string\");\n detectorRanges(value, extra, ranges);\n return applyRanges(value, ranges);\n}\n\n/**\n * The token detectors alone -- a JWT, a provider-prefixed key -- over one\n * string: what the page's own text is read for (privacy.ts scrubDomText).\n * A credential on screen is one whatever text is around it; an email or a\n * phone number in the page's text is the page's content, which balanced\n * records.\n */\nexport function redactTokens(value: string): string {\n return value ? applyRanges(value, tokenRanges(value)) : value;\n}\n\n/**\n * What any token needs somewhere in a value to be one: a JWT's `eyJ` or a\n * provider's prefix. Every attribute and text of a page is asked, and\n * almost none holds one; this is read without the lookbehind the two\n * patterns below start every place with (MEASURED: 18 percent of a\n * snapshot of 80,000 nodes was those patterns finding nothing).\n */\nconst MAYBE_TOKEN =\n /eyJ|kep_|gh[pousr]_|github_pat_|glpat-|xox[abprse]-|[sr]k_(?:live|test)_|sk-(?:proj|ant)-|npm_|whsec_|AKIA|ASIA|AIza/;\n\n/** Where `value`'s JWTs and provider-prefixed keys lie. */\nexport function tokenRanges(value: string): Range[] {\n const ranges: Range[] = [];\n if (!MAYBE_TOKEN.test(value)) return ranges;\n patternRanges(value, JWT_RE, ranges);\n patternRanges(value, KNOWN_TOKEN_RE, ranges);\n return ranges;\n}\n\n/* ------------------------------------------------------------------ */\n/* Structural walk */\n/* ------------------------------------------------------------------ */\n\nconst MAX_DEPTH = 64;\n\n/*\n * JSON IS REDACTED IN ITS OWN TEXT. It was parsed, walked and serialised\n * again, so every byte the walk did not touch could still change: an\n * integer past 2^53 came back rounded (`9007199254740993` recorded as\n * `...992`), whitespace and escapes were normalised -- and a replay\n * serves the recording, so an unchanged app could break on its own\n * snowflake ids. Now JSON.parse only VALIDATES (what it refuses is still\n * refused), a small tokenizer finds each value's span in the text, and\n * only the spans being redacted are rewritten. Every other byte --\n * numbers, whitespace, key order, escapes -- is kept. The tokenizer is\n * the SDK's own, so every engine gives the same answer.\n */\n\n/** A JSON value and where it is in the text. */\ntype JNode =\n | {\n kind: \"object\";\n start: number;\n end: number;\n entries: { key: string; value: JNode }[];\n }\n | { kind: \"array\"; start: number; end: number; items: JNode[] }\n | { kind: \"string\"; start: number; end: number; value: string }\n | { kind: \"scalar\"; start: number; end: number }\n | { kind: \"deep\"; start: number; end: number };\n\nconst ESCAPES: Record<string, string> = {\n '\"': '\"',\n \"\\\\\": \"\\\\\",\n \"/\": \"/\",\n b: \"\\b\",\n f: \"\\f\",\n n: \"\\n\",\n r: \"\\r\",\n t: \"\\t\",\n};\n\n/**\n * The value spans of a JSON text JSON.parse has already accepted, which\n * is why nothing here re-checks the grammar. Read to MAX_DEPTH like the\n * walk below; a value deeper than that is skipped by a scan, not by\n * recursion, so a deep document cannot overflow the stack.\n */\nfunction parseJsonSpans(text: string, base: number): JNode {\n let i = 0;\n const ws = (): void => {\n while (i < text.length) {\n const c = text.charCodeAt(i);\n if (c !== 32 && c !== 9 && c !== 10 && c !== 13) break;\n i++;\n }\n };\n const string = (): string => {\n i++; // the opening quote\n let out = \"\";\n let run = i;\n while (text[i] !== '\"') {\n if (text[i] !== \"\\\\\") {\n i++;\n continue;\n }\n out += text.slice(run, i);\n const e = text[i + 1];\n if (e === \"u\") {\n out += String.fromCharCode(parseInt(text.slice(i + 2, i + 6), 16));\n i += 6;\n } else {\n out += ESCAPES[e];\n i += 2;\n }\n run = i;\n }\n out += text.slice(run, i);\n i++; // the closing quote\n return out;\n };\n // Past MAX_DEPTH: the value's extent only, read by a scan.\n const skip = (): void => {\n let nest = 0;\n do {\n const c = text[i];\n if (c === '\"') {\n i++;\n while (text[i] !== '\"') i += text[i] === \"\\\\\" ? 2 : 1;\n i++;\n } else if (c === \"{\" || c === \"[\") {\n nest++;\n i++;\n } else if (c === \"}\" || c === \"]\") {\n nest--;\n i++;\n } else if (nest === 0 && (c === \",\" || c === \":\")) {\n break;\n } else {\n i++;\n }\n } while (nest > 0 || (i < text.length && !/[\\s,\\]}]/.test(text[i])));\n };\n const value = (depth: number): JNode => {\n ws();\n const start = i;\n if (depth > MAX_DEPTH) {\n skip();\n return { kind: \"deep\", start, end: i };\n }\n const c = text[i];\n if (c === \"{\") {\n i++;\n const entries: { key: string; value: JNode }[] = [];\n ws();\n if (text[i] === \"}\") i++;\n else {\n for (;;) {\n ws();\n const key = string();\n ws();\n i++; // :\n entries.push({ key, value: value(depth + 1) });\n ws();\n if (text[i++] === \"}\") break; // else `,`\n }\n }\n return { kind: \"object\", start, end: i, entries };\n }\n if (c === \"[\") {\n i++;\n const items: JNode[] = [];\n ws();\n if (text[i] === \"]\") i++;\n else {\n for (;;) {\n items.push(value(depth + 1));\n ws();\n if (text[i++] === \"]\") break; // else `,`\n }\n }\n return { kind: \"array\", start, end: i, items };\n }\n if (c === '\"') {\n const v = string();\n return { kind: \"string\", start, end: i, value: v };\n }\n while (i < text.length && !/[\\s,\\]}]/.test(text[i])) i++;\n return { kind: \"scalar\", start, end: i };\n };\n // `base`: the depth this text sits at -- a JSON string inside a body is\n // as deep as the value that holds it, so the cap stays cumulative.\n return value(base);\n}\n\nconst REDACTED_JSON = JSON.stringify(REDACTED);\n\n/* ------------------------------------------------------------------ */\n/* URLs held in a body */\n/* ------------------------------------------------------------------ */\n\n/**\n * A URL a body holds -- a presigned S3, GCS or Azure link an API hands the\n * page, a pagination link, a redirect in a form, a link in an HTML or RSC\n * page -- scrubbed by the one URL scrubber (@keploy/contract's privacy.ts\n * scrubUrl) under a `param`'s names: a credential's value replaced, in\n * its query, its fragment, a path's `;name=` and a URL nested or encoded\n * in a value, its user info dropped, never a paging cursor (a pagination\n * link's `pageToken` is the page's to request again). A body is no replay\n * key, so its pairs are read as the DOM's are, each credential's own value\n * replaced, and a nested URL is written back as it came (`raw`). A\n * scrubbed link is not the one the server sent, so a replay that requests\n * it relies on the replay key treating a redacted value as a wildcard.\n * Every other byte is kept.\n */\nconst BODY_URL_RULES: UrlRules = {\n kind: \"param\",\n strict: false,\n whole: false,\n raw: true,\n};\n\n/**\n * A text body's URLs (an HTML, XML, RSC, CSS, text or multipart body's,\n * read raw) and a header's: BODY_URL_RULES, but a credential's own value\n * ends at the first character the contract's ownValueEnd stops at\n * (whitespace, `,`, `;`, a quote, or a bracket it does not open), the\n * text after it kept (`/api/x?token=... 200 OK`, a CSV row's later\n * columns) and read as a text's (TAIL_URL_RULES).\n */\nconst TEXT_URL_RULES: UrlRules = {\n ...BODY_URL_RULES,\n spaced: true,\n tail: (text) => scrubTextUrls(text, TAIL_URL_RULES),\n};\n\n/**\n * A form body's URLs (readAsForm): a credential's own value ends at its\n * first whitespace, as every body's did before TEXT_URL_RULES, and the\n * form read then takes each value to its `&`. Nothing after it is read\n * again (no `tail`). Read with the text's end, a raw URL's credential\n * value cut at a `,` was left a tail the form read took for the\n * credential's, and the whole value went\n * (`next=https://x/cb?token=abc,def%20ghi` became `next=[REDACTED]`), or\n * the tail was kept (found in review).\n */\nconst FORM_URL_RULES: UrlRules = {\n ...BODY_URL_RULES,\n spaced: true,\n form: true,\n};\n\n/**\n * The text a credential's own value leaves after it in a pair, read as a\n * text's URLs are, each URL of a list its own (`list`): kept unread, a\n * list's next URL kept its nested token and its user info\n * (`?token=...,https://b/y?next=%2Fcb%3Ftoken%3D...`, found in review).\n * Its own credentials' tails are left to the text pair rule, so it is\n * read once.\n */\nconst TAIL_URL_RULES: UrlRules = {\n ...BODY_URL_RULES,\n spaced: true,\n list: true,\n};\n\n/**\n * A line that starts with a URL -- a JSON string that is a link, a form's\n * value, a uri-list's or a log's line -- read whole as a URL is, what\n * follows its start its own (`?markers=red|1,2&signature=...`,\n * `?filter={\"a\":1}&token=...`): a scheme, a `/`, `./` or `../`, then a\n * query or a fragment; a relative path's segments, or none, then a `?` or\n * a `#` and a pair (`cb?jwt=...`, `#access_token=...`), which prose's\n * `Ref#123: ...` and `Q? see ...` are not -- read as a URL, a credential's\n * value took their words to the next `&` (found in review); or a path's\n * parameter (`/cart;jsessionid=...`, a `/` first and no `=` before it,\n * which a form's `a=1;password=...&b=2` is not). Its first word holds no\n * tag, quote, brace or pipe before its first `=`: a stylesheet's\n * `#a{background:url(/x?sig=...)}` and a page's `<style>a{color:#fff}`\n * are texts holding URLs, read as a URL their `)}` and `\">` went with a\n * credential's value (found in review). A scheme is one a `/` follows, one\n * whose name holds a `.` or a `+` (`com.example.app:`), `localhost` and\n * its port (`localhost:3000/`; another one-word host is CSS's\n * `grid-area:1/2` as often), or one of a list that takes no authority\n * (`mailto:`, `tel:`, `xmpp:`, `intent:`, `data:` ...): a CSS property is none,\n * and `background:url(/x?token=...);color:red` read as a URL lost its\n * `);color:red` (found in review). Anything else -- prose, markup, code --\n * is a text holding URLs, each found by the scan.\n */\nconst WHOLE_URL =\n /^(?=[^={}<>\"'\\\\^`|]*(?:=|$))(?:(?:[a-z][a-z0-9+.-]*:\\/|[a-z][a-z0-9-]*[+.][a-z0-9+.-]*:|localhost:\\d{1,5}[/?#]|(?:mailto|tel|sms|urn|data|javascript|vbscript|blob|about|xmpp|sip|sips|magnet|intent|bitcoin|geo|market|news):|\\.{0,2}\\/)[^\\s?#]*[?#]|(?:[\\w.~%-][\\w.~%/-]*)?[?#][^\\s=&#]+=|\\.{0,2}\\/[^\\s?#;=]*;)/i;\n\n/** The start a URL a line starts with is told by (WHOLE_URL): its first word. */\nconst URL_START_WORD = /^\\S*/;\n\n/**\n * Each line of a text, read whole when it starts with a URL: a raw space\n * or tab in a query is its value's (`?q=new york&api_key=...`), and a\n * credential's value ends at its first stop (ownValueEnd, scrubPairs),\n * the line's text after it kept. A URL holds no line break: a uri-list's\n * or a log's lines are each read, and none runs into the next (found in\n * review).\n */\nconst URL_LINE = /^[^\\r\\n]*/gm;\n\n/**\n * `text` -- a body, a JSON string, a form's value -- with every URL it\n * holds scrubbed (BODY_URL_RULES): each line that starts with a URL read\n * whole (WHOLE_URL), then each URL the scan finds in it.\n */\nfunction scrubTextUrls(raw: string, rules = BODY_URL_RULES): string {\n const text = raw.replace(URL_LINE, (line) =>\n WHOLE_URL.test(URL_START_WORD.exec(line)![0])\n ? scrubUrl(line, rules)\n : line,\n );\n const edits = urlEdits(text, rules);\n if (edits.length === 0) return scrubEscapedUrls(text, rules);\n let out = \"\";\n let at = 0;\n for (const [start, end, with_] of edits) {\n out += text.slice(at, start) + with_;\n at = end;\n }\n return scrubEscapedUrls(out + text.slice(at), rules);\n}\n\n/**\n * A URL a script or a JavaScript body writes with its slashes escaped, as\n * JSON and PHP's json_encode write one\n * (`\"https:\\/\\/app\\/cb#access_token=...\"`): the scan finds none, a\n * backslash ending a URL. A scheme read at most 32 characters back, as\n * URL_START's is. It ends at a parenthesis, a bracket (CSS's\n * `url(https:\\/\\/...);background-size:cover` keeps its `)` and the rest)\n * or a plain `/` that ends a regular expression (one its flags and then\n * no word follow, `/.test(`), not one inside a value\n * (`?token=abc/def`, found in review: cut there, `/def` was kept) too: escaped slashes are a regular expression's as often\n * (`/https:\\/\\/x\\/cb#access_token=([^&]+)/`), whose group read as a value\n * left the pattern unbalanced (found in review).\n */\nconst ESCAPED_URL =\n /[a-z][a-z0-9+.-]{0,31}:(?:\\\\\\/|\\\\u002[fF]){2}(?:[^\\s\"'<>\\\\^`{|}()[\\]/]|\\/(?![dgimsuvy]*(?![\\w$]))|\\\\\\/|\\\\u002[fF])*/gi;\n\n/**\n * Each URL `text` writes with its slashes escaped (ESCAPED_URL), read\n * with them unescaped by `rules`: read as written, its credential and a\n * URL nested in it (`?next=%2Fcb%3Ftoken%3D...`) were kept (found in\n * review). It ends at a plain `/` -- a regular expression's closing one,\n * `/https:\\/\\/x\\/cb;jsessionid=.../` -- and only what the read changed\n * is written back, every other byte as it came: written back with every\n * slash escaped, the pattern's closing `/` became `\\/` and the script no\n * longer parsed (found in review).\n */\nfunction scrubEscapedUrls(text: string, rules: UrlRules): string {\n if (!/:(?:\\\\\\/|\\\\u002[fF])/.test(text)) return text;\n return text.replace(ESCAPED_URL, (span) => {\n // The span unescaped, and where in the span each of its characters,\n // and its end, were written.\n let plain = \"\";\n const at: number[] = [];\n for (let i = 0; i < span.length;) {\n at.push(i);\n const escape = ESCAPED_SLASH_AT.exec(span.slice(i, i + 6));\n plain += escape === null ? span[i] : \"/\";\n i += escape === null ? 1 : escape[0].length;\n }\n at.push(span.length);\n const out = scrubUrl(plain, rules);\n if (out === plain) return span;\n // What changed lies between the longest prefix and suffix the two\n // share; only it is written anew, its slashes as the span's first.\n let head = 0;\n while (head < out.length && out[head] === plain[head]) head++;\n let tail = 0;\n while (\n tail < out.length - head &&\n tail < plain.length - head &&\n out[out.length - 1 - tail] === plain[plain.length - 1 - tail]\n )\n tail++;\n const slash = /\\\\\\/|\\\\u002[fF]/.exec(span)![0];\n return (\n span.slice(0, at[head]) +\n out.slice(head, out.length - tail).replace(/\\//g, slash) +\n span.slice(at[plain.length - tail])\n );\n });\n}\n\n/** A slash a script or a JSON text writes escaped (`\\/`, `\\u002f`), at a text's start. */\nconst ESCAPED_SLASH_AT = /^(?:\\\\\\/|\\\\u002[fF])/;\n\n/**\n * Every URL a header's value holds, scrubbed as a text body's URLs are\n * (TEXT_URL_RULES: a credential's own value replaced, ended at its first\n * stop, every other byte kept),\n * and every pair a header's leads start (EMBEDDED_NAME_IN_HEADER), as a\n * relative URL's, which the URL scan does not find, is: a `Referer`, an\n * `X-Redirect-To`, a `Content-Security-Policy`'s `report-uri` absolute or\n * relative (`/csp-report?token=...`). A header is no replay key, so no\n * pair is replaced whole for a name inside it. Only Location,\n * Content-Location, Link and Refresh were read, and a URL any other header\n * carried was recorded as it came (found in review).\n */\nexport function scrubHeaderUrls(value: string): string {\n // A credential's own value ends as a text's does (TEXT_URL_RULES): a\n // header's list is split at `,` and its parameters at `;` (RFC 9110),\n // and a value run to the next pair took a second URL and a CSP's next\n // directive with it (found in review).\n const text = scrubTextUrls(value, TEXT_URL_RULES);\n const ranges: Range[] = [];\n embeddedPairRanges(text, ranges, \"header\");\n return applyRanges(text, ranges);\n}\n\n/**\n * Whether a form value, encoded (`next=https%3A%2F%2Fx%2Fv%3Fjwt%3D...`),\n * holds a URL with a credential in it: such a value goes whole, since its\n * scrubbed URL cannot be written back encoded in place.\n */\nfunction holdsEncodedUrlCredential(raw: string): boolean {\n if (!/[%+]/.test(raw)) return false;\n const value = formDecode(raw);\n if (value === raw) return false;\n // Encoded again (`redirect=https%253A%252F%252F...%253Fjwt%253D...`): no\n // read sees its URL, and no pair search reads it in place. Decoded\n // escape by escape, as holdsCredentialName reads it: all or nothing, a\n // malformed escape beside the name (`%253DS%25zz`) kept it (found in\n // review).\n if (decoded(value) !== value && holdsCredentialName(value, \"param\"))\n return true;\n const scrubbed = scrubTextUrls(value);\n if (scrubbed === value) return false;\n // What the pair search below redacts in place, mapped back to the raw\n // bytes (`redirect=https%3A%2F%2Fx%2Fcb%3Ftoken%3D[REDACTED]`): enough\n // when it is what the URL scrub redacts.\n const inPlace: Range[] = [];\n embeddedPairRanges(value, inPlace);\n return applyRanges(value, inPlace) !== scrubbed;\n}\n\n/**\n * The digits of a JSON number written with a fraction or an exponent\n * that is still an integer (`4242424242424242.0`, `4.242424242424242e15`\n * -- a PAN either way), or null. Plain digits are read as written.\n */\nfunction integerDigits(raw: string): string | null {\n if (!/^-?\\d/.test(raw)) return null; // true, false\n const n = Number(raw);\n return Number.isInteger(n) ? String(n) : null;\n}\n\n/** A flag, or a list of flags: a value that holds no secret under any name. */\nfunction onlyFlags(text: string, node: JNode): boolean {\n if (node.kind === \"scalar\")\n return /^(?:true|false)$/.test(text.slice(node.start, node.end));\n return node.kind === \"array\" && node.items.every((n) => onlyFlags(text, n));\n}\n\n/**\n * One JSON value's redaction, as edits on the text: the decisions the\n * structural walk always made -- a sensitive key takes its whole value,\n * a card number goes even as a number, a string is scanned (and redacted\n * as JSON when it is JSON), a name/value pair goes by its name, past\n * MAX_DEPTH everything goes -- written only where they change something.\n */\nfunction redactNode(\n text: string,\n node: JNode,\n keyHint: string | null,\n depth: number,\n extra: readonly RegExp[],\n edits: Array<[number, number, string]>,\n): void {\n const replace = (with_: string): void => {\n edits.push([node.start, node.end, with_]);\n };\n // Fail CLOSED. Returning the subtree verbatim meant a `password` nested\n // past the cap was emitted in the clear.\n if (node.kind === \"deep\") return replace(REDACTED_JSON);\n // null is kept, under any key: it carries nothing, and a replay that\n // served \"[REDACTED]\" where the app recorded null hands it a string.\n if (node.kind === \"scalar\" && text.startsWith(\"null\", node.start)) return;\n // So is a flag, or a list of flags: a list's item comes here under its\n // key's name without passing the entries loop's guard below.\n if (onlyFlags(text, node)) return;\n // A sensitive key redacts its ENTIRE value, whatever shape it is, but\n // for an object or a list under a name settings use too.\n const bare = keyHint !== null && isBareCodeName(keyHint);\n if (\n keyHint !== null &&\n isSensitiveKey(keyHint) &&\n !(bare && isSettingsValue(node)) &&\n !(node.kind !== \"string\" && isWordName(keyHint))\n ) {\n return replace(REDACTED_JSON);\n }\n if (node.kind === \"scalar\") {\n // Numbers, booleans and null are never scanned -- the rule that stops\n // timestamps and ids being corrupted -- but a card number survives\n // as a JSON number, so the card test reads its digits as written.\n const raw = text.slice(node.start, node.end);\n const digits = /^\\d+$/.test(raw) ? raw : integerDigits(raw);\n if (digits !== null && isLikelyCardNumber(digits)) replace(REDACTED_JSON);\n return;\n }\n if (node.kind === \"string\") {\n const out =\n redactJsonString(node.value, depth, extra) ??\n redactStringText(scrubTextUrls(node.value), extra);\n if (out !== node.value) replace(JSON.stringify(out));\n return;\n }\n if (node.kind === \"array\") {\n for (const item of node.items) {\n redactNode(text, item, keyHint, depth + 1, extra, edits);\n }\n return;\n }\n // A name/value pair whose name is a secret's: a header list\n // (`[{name: \"Authorization\", value: ...}]`, HAR), a test report's\n // header diff (`{key: \"Authorization\", expected, actual}`). The value\n // sits under a generic name, so it goes by its sibling's.\n const pair = node.entries.some(\n ({ key, value }) =>\n PAIR_NAMES.has(key.toLowerCase()) &&\n value.kind === \"string\" &&\n isSensitiveKey(value.value),\n );\n const card = node.entries.some(({ key }) =>\n CARD_FIELDS.has(normalizeKey(key)),\n );\n const exchange = isTokenExchange(\n node.entries.map(\n ({ key, value }) =>\n [normalizeKey(key), value.kind === \"string\" ? value.value : \"\"] as [\n string,\n string,\n ],\n ),\n );\n for (const { key, value } of node.entries) {\n // A flag, or a list of flags, goes under no rule (onlyFlags): it\n // carries no secret, and replaced it became the string \"[REDACTED]\",\n // which an app reads as true -- `{\"hasSignature\":false}` replayed as a\n // signature on file (found in review). Every value a key holds is\n // read here first, a sensitive key's and a context rule's alike.\n if (onlyFlags(text, value)) continue;\n if (card && CARD_EXPIRY_BESIDE_A_CARD.has(normalizeKey(key))) {\n edits.push([value.start, value.end, REDACTED_JSON]);\n } else if (\n ((exchange && EXCHANGE_REDACTED.has(normalizeKey(key))) ||\n (bare && normalizeKey(key) === \"code\")) &&\n !(value.kind === \"scalar\" && text.startsWith(\"null\", value.start))\n ) {\n edits.push([value.start, value.end, REDACTED_JSON]);\n } else if (pair && PAIR_VALUES.has(key.toLowerCase())) {\n edits.push([value.start, value.end, REDACTED_JSON]);\n } else {\n redactNode(\n text,\n value,\n isSensitiveKey(key) ? key : null,\n depth + 1,\n extra,\n edits,\n );\n }\n }\n}\n\n/** `text` with each edit's span replaced; the text itself when there are none. */\nfunction applyEdits(\n text: string,\n edits: Array<[number, number, string]>,\n): string {\n if (edits.length === 0) return text;\n edits.sort((a, b) => a[0] - b[0]);\n let out = \"\";\n let pos = 0;\n for (const [start, end, with_] of edits) {\n out += text.slice(pos, start) + with_;\n pos = end;\n }\n return out + text.slice(pos);\n}\n\n/** A JSON text JSON.parse accepted, redacted in place. */\nfunction redactJsonText(\n text: string,\n depth: number,\n extra: readonly RegExp[],\n): string {\n const edits: Array<[number, number, string]> = [];\n redactNode(text, parseJsonSpans(text, depth), null, depth, extra, edits);\n return applyEdits(text, edits);\n}\n\n/** The field of a name/value pair that names it. */\nconst PAIR_NAMES: ReadonlySet<string> = new Set([\"key\", \"name\", \"header\"]);\n/** The fields of a name/value pair that carry the value. */\nconst PAIR_VALUES: ReadonlySet<string> = new Set([\n \"value\",\n \"values\",\n \"expected\",\n \"actual\",\n]);\n\n/**\n * A string that is itself JSON -- a test case's `header` or `body` as\n * api-server stores them, a GraphQL `variables` string -- redacted as JSON\n * and serialised again, or null when it is not JSON. Returned as it came\n * when nothing in it was redacted, so a JSON string with no secret keeps\n * every byte (its whitespace and key order included).\n */\nfunction redactJsonString(\n s: string,\n depth: number,\n extra: readonly RegExp[],\n): string | null {\n if (!/^\\s*[[{]/.test(s)) return null;\n try {\n JSON.parse(s);\n } catch {\n return null;\n }\n return redactJsonText(s, depth + 1, extra);\n}\n\n/**\n * Redact a captured body.\n *\n * JSON in, valid JSON out — always. A body that is not JSON keeps every\n * byte except what is redacted: a form's credential values and the\n * pattern matches in its other values, or, in any other text, the value\n * of an embedded credential pair and the pattern matches.\n */\nexport function redactBody(\n body: string | null | undefined,\n contentType?: string,\n extra: readonly RegExp[] = [],\n): string | null {\n if (body === null || body === undefined || body === \"\") return body ?? null;\n\n // The SDK's own note in place of a body it never read. Nothing in it\n // came from the page, and it is the only record of what the body was;\n // running it through the JSON branch below flattened it to the\n // refusal and lost the kind and the size. See isNotRecordedNote().\n if (isNotRecordedNote(body)) return body;\n\n const looksJson =\n (contentType ?? \"\").toLowerCase().includes(\"json\") || /^\\s*[[{]/.test(body);\n\n if (looksJson) {\n try {\n JSON.parse(body); // validates: what it refuses is still refused\n } catch {\n // Unparseable but JSON-shaped — almost always a truncated capture,\n // since the transport appends \"...[truncated]\" to oversized bodies.\n //\n // Falling through to the text scanner here is what let the ORIGINAL\n // bug back in: the card regex could match a bare JSON number and\n // emit {\"amount\":[REDACTED]}, which no longer parses. There is no\n // safe way to redact a fragment we cannot parse, so refuse it\n // wholesale rather than emit something corrupt.\n return TRUNCATED_UNPARSEABLE;\n }\n return redactJsonText(body, 0, extra);\n }\n\n // Every URL the body holds, raw -- an HTML, XML, RSC or text body's, a\n // multipart part's, a form value's written as it is -- scrubbed first,\n // the cut marker set aside; the passes below then read the rest. Whether\n // it is read as a form is decided once, here, on its URLs read as a\n // form's (a URL's user info can hold an `&`, and its scrub can drop one:\n // decided on the raw bytes, a form was read as text, found in review).\n // A body that is no form has its URLs read as a text's; when the form\n // read changed nothing, the text read changes nothing either.\n const cut = body.endsWith(TRUNCATED_SUFFIX);\n const raw = cut ? body.slice(0, -TRUNCATED_SUFFIX.length) : body;\n const formHeld = scrubTextUrls(raw, FORM_URL_RULES);\n const asForm = readAsForm(\n cut ? formHeld + TRUNCATED_SUFFIX : formHeld,\n contentType ?? \"\",\n );\n const held =\n asForm || formHeld === raw ? formHeld : scrubTextUrls(raw, TEXT_URL_RULES);\n const text = cut ? held + TRUNCATED_SUFFIX : held;\n\n const multipart = redactMultipartText(text, contentType ?? \"\", extra);\n if (multipart !== null) return multipart;\n // Under a multipart content-type a body is either multipart text or the\n // urlencoded rendering of a FormData's fields (see formDataText). One\n // that is neither -- its boundary not the declared one, or too long to\n // be a boundary -- has parts the form path cannot see: refused whole,\n // never recorded as it came (review r2).\n if (MULTIPART.test(contentType ?? \"\") && !asForm) {\n return UNREADABLE;\n }\n\n const form = redactFormBody(\n text,\n extra,\n asForm,\n /(?:java|ecma)script/i.test(contentType ?? \"\"),\n );\n if (form !== null) return form;\n\n return redactStringValue(text, extra);\n}\n\n/* ------------------------------------------------------------------ */\n/* Form bodies */\n/* ------------------------------------------------------------------ */\n/*\n * A CREDENTIAL IN A FORM BODY IS STILL A CREDENTIAL. Key-based redaction\n * ran on JSON alone, so `password=...` in a form post, an OAuth\n * refresh-token request (form-encoded by RFC 6749), a FormData body or an\n * XHR string body reached the server as typed -- MEASURED on 3.0.1 in\n * Chromium.\n *\n * TWO SHAPES, because a response body is served back to the page at\n * replay and must keep every byte that is not a secret:\n *\n * 1. A FORM -- every segment a pair or a bare name, no whitespace inside\n * a trimmed raw name, at least one real pair. A bare flag\n * (`remember&...`, which the WHATWG parser, Rack and PHP all accept)\n * or a trimmed name no longer takes the whole body off this path, as\n * it did in the first fix (review round 1). A value under a sensitive\n * name is replaced whole; a name is sensitive when it is, or when any\n * bracket or dot part of it is (`password[0]`, `token[value]`,\n * `user[password_confirmation]`), the way a sensitive JSON key\n * redacts its whole subtree. The body is scanned for the patterns as\n * it was sent and decoded -- an email is `ada%40example.com` on the\n * wire -- each decoded match redacting exactly the raw bytes it came\n * from.\n * 2. ANY OTHER TEXT -- HTML, an RSC payload, XML, prose: the value of an\n * embedded credential pair is replaced (see embeddedPairRanges), and the\n * whole text is scanned for the patterns.\n *\n * Everything nothing matched is kept byte for byte: nothing is ever\n * re-encoded, and every detector's ranges are merged before one marker\n * replaces each (see applyRanges).\n */\n\n/**\n * What a body cut at the cap ends with (truncate, cutText). Defined here,\n * beside the cut, so the form parser and the cut agree on one string.\n */\nexport const TRUNCATED_SUFFIX = \"...[truncated]\";\n\n/**\n * Cut a recorded body at `maxBodySize`.\n *\n * ONE RULE IN ONE PLACE. The cap was written out at six call sites and\n * missed the seventh: an XHR FormData body was assembled and recorded\n * WHOLE, however large. An upload form with a base64 field put\n * megabytes into one event — past the queue's byte accounting, and far\n * past the 32 KiB the page-unload flush can carry, so it held back\n * everything behind it there too.\n *\n * THE CAP COUNTS UTF-16 CODE UNITS, not bytes: the unit a JS string is\n * measured in, equal to bytes for ASCII and up to 2x under it for\n * multi-byte text. `maxBodySize` is a bound on what is RECORDED, not an\n * exact byte budget, and counting bytes would mean a TextEncoder pass\n * over every body the page sends. The option's docs say so.\n */\nexport function truncate(text: string, maxSize: number): string {\n return text.length > maxSize\n ? text.slice(0, maxSize) + TRUNCATED_SUFFIX\n : text;\n}\n\n/**\n * Text the SDK stopped reading before its end -- the page left, settle()\n * ended, the body failed -- marked as cut. Always under the cap: a body\n * past it has already been recorded, cut at the cap.\n */\nexport function cutText(text: string): string {\n return text + TRUNCATED_SUFFIX;\n}\n\n/**\n * A raw form field name: what a urlencoded serializer or a hand-written\n * `user[password]` leaves -- letters, digits, `%XX`, `+` and `_.-~!*'()[]`.\n * Markup, URLs and prose (`<cfg><url>https://h/x?a`) are not names, so\n * the XML body that holds one is not taken for a form (review round 2).\n * EMPTY IS A NAME: the WHATWG urlencoded parser reads `=x` as one, and\n * refusing it sent a whole form down the embedded-pair path, whose value\n * stops at `(` -- `=x&password=pa(ss` kept `(ss` (review r4, B6).\n */\nconst FORM_NAME = /^[A-Za-z0-9_.~!*'()%+[\\]-]*$/;\n\n/** A form name or value decoded, or as it came when it does not decode. */\nfunction formDecode(raw: string): string {\n if (!/[%+]/.test(raw)) return raw;\n const out = newDecodedText(raw.length);\n appendDecoded(raw, 0, raw.length, out);\n return out.parts.join(\"\");\n}\n\n/** Two hex digits at `i`, as a byte, or -1. */\nfunction hexByte(raw: string, i: number): number {\n if (i + 2 > raw.length) return -1;\n const hi = parseInt(raw[i], 16);\n const lo = parseInt(raw[i + 1], 16);\n return Number.isNaN(hi) || Number.isNaN(lo) ? -1 : hi * 16 + lo;\n}\n\n/** Decoded text, and for each of its code units the raw span it came from. */\ninterface DecodedText {\n parts: string[];\n start: Int32Array;\n end: Int32Array;\n length: number;\n}\n\n/** Room for `capacity` code units: a decoded text is never longer than its raw one. */\nfunction newDecodedText(capacity: number): DecodedText {\n return {\n parts: [],\n start: new Int32Array(capacity),\n end: new Int32Array(capacity),\n length: 0,\n };\n}\n\n/** One decoded code unit `unit`, from raw[from, to). */\nfunction appendUnit(\n out: DecodedText,\n unit: string,\n from: number,\n to: number,\n): void {\n out.parts.push(unit);\n for (let u = 0; u < unit.length; u++) {\n out.start[out.length] = from;\n out.end[out.length] = to;\n out.length++;\n }\n}\n\n/** raw[from, to) as it came, one decoded unit per raw unit. */\nfunction appendRaw(\n raw: string,\n from: number,\n to: number,\n out: DecodedText,\n): void {\n if (from >= to) return;\n out.parts.push(raw.slice(from, to));\n for (let i = from; i < to; i++) {\n out.start[out.length] = i;\n out.end[out.length] = i + 1;\n out.length++;\n }\n}\n\n/**\n * One form name or value decoded as the urlencoded parser decodes it\n * (`+` is a space, `%XX` a UTF-8 byte), appended to `out` with, for every\n * decoded code unit, the span of RAW text it came from -- so a match found\n * in the decoded text is redacted in the raw one, escapes whole, and\n * nothing outside a match is ever re-encoded (re-encoding turned each raw\n * `中` into `%E4%B8%AD`, 7.7x with no pattern at all -- review r8).\n * A part with a malformed escape or bytes that are not UTF-8 is appended\n * as it came, one unit per raw unit, without an exception:\n * decodeURIComponent threw on each, and a thrown URIError per pair cost\n * 0.4-0.8 s on a 512 KB body of them (review round 2).\n */\nfunction appendDecoded(\n raw: string,\n from: number,\n to: number,\n out: DecodedText,\n): void {\n const marks = { parts: out.parts.length, length: out.length };\n let run = from; // the start of a stretch that decodes to itself\n let i = from;\n while (i < to) {\n const c = raw.charCodeAt(i);\n if (c !== 43 && c !== 37) {\n i++; // neither `+` nor `%`\n continue;\n }\n appendRaw(raw, run, i, out);\n if (c === 43) {\n appendUnit(out, \" \", i, i + 1);\n run = ++i;\n continue;\n }\n // A UTF-8 sequence: the lead byte says how many bytes follow; each\n // must be an escaped continuation byte, and the ranges below are\n // exactly the ones decodeURIComponent accepts (no overlong forms, no\n // surrogates, nothing past U+10FFFF).\n const lead = i + 3 <= to ? hexByte(raw, i + 1) : -1;\n let n = -1;\n let lo = 0x80;\n let hi = 0xbf;\n if (lead >= 0 && lead < 0x80) n = 0;\n else if (lead >= 0xc2 && lead <= 0xdf) n = 1;\n else if (lead >= 0xe0 && lead <= 0xef) {\n n = 2;\n if (lead === 0xe0) lo = 0xa0;\n if (lead === 0xed) hi = 0x9f;\n } else if (lead >= 0xf0 && lead <= 0xf4) {\n n = 3;\n if (lead === 0xf0) lo = 0x90;\n if (lead === 0xf4) hi = 0x8f;\n }\n let cp = n <= 0 ? lead : lead & (0x3f >> n);\n for (let k = 1; k <= n && cp >= 0; k++) {\n const at = i + 3 * k;\n const b = at + 3 <= to && raw[at] === \"%\" ? hexByte(raw, at + 1) : -1;\n cp =\n b < (k === 1 ? lo : 0x80) || b > (k === 1 ? hi : 0xbf)\n ? -1\n : (cp << 6) | (b & 0x3f);\n }\n if (n < 0 || cp < 0) {\n // Not UTF-8: the whole part as it came.\n out.parts.length = marks.parts;\n out.length = marks.length;\n appendRaw(raw, from, to, out);\n return;\n }\n const end = i + 3 * (n + 1);\n appendUnit(out, String.fromCodePoint(cp), i, end);\n run = i = end;\n }\n appendRaw(raw, run, to, out);\n}\n\n/**\n * A `name=value` pair embedded in a body that is NOT a form: a query\n * string inside an HTML link (`&amp;token=`), an RSC payload or XML, or a\n * line of prose that holds one. It starts only after `?`, `&`, `;`, a\n * newline, a tag's `>` (`<p>password=...</p>`, found in review), a `#`\n * (a fragment's pair, `Location: /cb#access_token=...`, an unlisted\n * attribute's `data-url=\"/cb#access_token=...\"`, found in review), the start\n * of the body, or a space that follows no bracket and no declaration\n * (`x token=... y`, `user=bob; password=...` and `user=bob, password=...`\n * are text; `var token=`, `if (x) token=` and `{ token=` are code, whose\n * response a replay may run -- and neither in a JavaScript body nor in a\n * `<script>`'s text does a space, a tag or a `#` start a pair: a class's\n * `#token=t` is a private field), its name has no `.` (so minified\n * JS's `e&&e.token=t` is an assignment, not a pair), and its value ends\n * at the first delimiter -- so only the credential is replaced and every\n * other byte of a response that replay serves back is kept. Review round\n * 2 measured the alternative (the value running to the next `&`) deleting\n * the rest of HTML, RSC and XML bodies.\n *\n * The pattern finds a NAME and its `=`, never a value: a match that took\n * the whole pair swallowed every later `?name=` inside its value, so\n * `?next=/b?token=x` in a link, or a form's `redirect=https://x/cb?token=x`,\n * kept the token (review r1 of the port). A value is read only for a\n * sensitive name, and the search resumes after it; any other name's value\n * is searched on from its `=`. Each character is read at most once by the\n * name search and once by a value read: linear. A name's brackets close\n * (`user[password]=`): CSS's `[data-token=x]` selects, and holds no pair.\n * A name found is read by the one rule as a `param`. What is a name is\n * narrower here than in a form: letters, digits, `_`, `-`, `%` and closed\n * brackets, and no `.`, `$` or `+`, which a script's `;e.token=t`,\n * `$token=` and `token+=1` hold -- a JavaScript body or a `<script>`\n * rewritten to `e.token=[REDACTED]` throws when a replay serves it.\n */\nconst EMBEDDED_NAME =\n /(^|[?&;\\n>#]|(?<!\\b(?:var|let|const)|[(){}])[ \\t\\r\\f\\v])([\\w%-]*(?:\\[[\\w%-]*\\][\\w%-]*)*)=/g;\n/**\n * The leads a pair takes in a body that is JavaScript: a start, `?`, `&`,\n * `;`, a newline, or a `#` after a path's character\n * (`\"/cb#access_token=...\"`, found in review) -- its spaces and tags\n * separate code, not pairs, and a `#` after a `.`, a brace, a space or\n * the keyword `static` or `accessor` (`static#token=null`, minified,\n * found in review), or the star and slash that close a block comment\n * (`class A{/**`, `/#token=null}`, found in review), is a private field.\n */\nconst EMBEDDED_NAME_IN_CODE =\n /(^|[?&;\\n]|(?<=[\\w/%~-])(?<!\\*\\/|(?:^|[^\\w$/%~.-])(?:static|accessor))#)([\\w%-]*(?:\\[[\\w%-]*\\][\\w%-]*)*)=/g;\n/**\n * The leads a pair takes in a JSON string, whose content-type says\n * nothing of what it holds -- a message, a stored form, a link, or code,\n * SQL or Markdown: its start, a query's `?` and `&`, and a fragment's `#`\n * after a path (`/cb#access_token=`), never a `;`, a space, a newline or\n * a `#` after a bracket or a dot. Read with a text body's leads, a\n * string's `let a=1;token=getToken()`, `SET password=?` and a class's\n * `#token=null` lost their code (found in review).\n */\nconst EMBEDDED_NAME_IN_STRING =\n /(^|[?&]|(?<=[\\w/%~-])(?<!\\*\\/|(?:^|[^\\w$/%~.-])(?:static|accessor))#)([\\w%-]*(?:\\[[\\w%-]*\\][\\w%-]*)*)=/g;\n/**\n * The leads a pair takes in a header's value (one Location, Content-Location,\n * Link and Refresh are not): a header's parameters are separated by `;`,\n * `,` and spaces (`a=1, token=...`, `0; url=/next?a=1;sig=...`), and\n * hold no code (found in review: each was kept).\n */\nconst EMBEDDED_NAME_IN_HEADER =\n /(^|[?&;,\\s]|(?<=[\\w/%~-])#)([\\w%-]*(?:\\[[\\w%-]*\\][\\w%-]*)*)=/g;\n/** A pair's value: to its first space, quote, backtick, tag, bracket, backslash, `&`, `;`, comma, or a template literal's `${` (code, not a value: `` `/api?token=abc${t}` `` lost its `$`, found in review). */\nconst EMBEDDED_VALUE = /(?:[^\\s&\"'`<>\\\\,;(){}[\\]$]|\\$(?!\\{))+/y;\n/**\n * A JSON string's pair's value: to the next `&` or the string's end. A\n * credential's value there fails closed: ended at a space,\n * `password=correct horse battery staple` kept the words after its first\n * (found in review), and ended at a line break, a PEM key's lines after\n * its first would be kept.\n */\nconst EMBEDDED_VALUE_IN_STRING = /[^&]+/y;\n\n/** Which leads a pair takes: a text body's, a JavaScript body's, a JSON string's, or a header's. */\ntype PairMode = \"text\" | \"code\" | \"string\" | \"header\";\n\n/** The value range of every embedded credential pair in `body`, by `mode`'s leads (EMBEDDED_NAME, EMBEDDED_NAME_IN_CODE, EMBEDDED_NAME_IN_STRING, EMBEDDED_NAME_IN_HEADER) and its value's end (EMBEDDED_VALUE_IN_STRING in a JSON string, EMBEDDED_VALUE elsewhere). */\nfunction embeddedPairRanges(\n body: string,\n into: Range[],\n mode: PairMode = \"text\",\n): void {\n const names =\n mode === \"code\"\n ? EMBEDDED_NAME_IN_CODE\n : mode === \"string\"\n ? EMBEDDED_NAME_IN_STRING\n : mode === \"header\"\n ? EMBEDDED_NAME_IN_HEADER\n : EMBEDDED_NAME;\n // A <script>'s text is code, as a JavaScript body is: a space or a tag\n // there leads no pair (`<script>let a = 1; token=t</script>`).\n const scripts =\n mode !== \"text\" || !/<script/i.test(body) ? [] : scriptRanges(body);\n let r = 0;\n names.lastIndex = 0;\n for (let m = names.exec(body); m !== null; m = names.exec(body)) {\n if (!isCredentialName(m[2], \"param\")) continue;\n // In a <script>, a `#` leads a pair only after a path's character, as\n // in a string (`location.replace(\"/cb#access_token=...\")`, found in\n // review), never after a `.`, a brace, a space, a comment's `*/`,\n // `static` or `accessor` (a private field).\n if (\n scripts.length > 0 &&\n (/^[ \\t\\r\\f\\v>]$/.test(m[1]) ||\n (m[1] === \"#\" &&\n (!/[\\w/%~-]/.test(body[m.index - 1] ?? \"\") ||\n body.startsWith(\"*/\", m.index - 2) ||\n /(?:^|[^\\w$/%~.-])(?:static|accessor)$/.test(\n body.slice(Math.max(0, m.index - 9), m.index),\n ))))\n ) {\n while (r < scripts.length && scripts[r][1] <= m.index) r++;\n if (r < scripts.length && scripts[r][0] <= m.index) continue;\n }\n const valueStart = m.index + m[0].length;\n EMBEDDED_VALUE.lastIndex = valueStart;\n let value = EMBEDDED_VALUE.exec(body);\n if (value === null) continue;\n // A JSON string's value runs on to the next `&` or the string's end,\n // where EMBEDDED_VALUE starts one: one that starts at a space, a\n // quote, a backtick, a bracket, `<`, `>`, `,`, `;` or a backslash is\n // code's, kept (`fetch('/api?token='+t)`, `x='?token='`, found in\n // review), and so is a marker a URL scrub before this one wrote\n // (`?token=[REDACTED]\">link</a>`): the bytes after it are the text's.\n if (mode === \"string\") {\n EMBEDDED_VALUE_IN_STRING.lastIndex = valueStart;\n value = EMBEDDED_VALUE_IN_STRING.exec(body) ?? value;\n }\n const valueEnd = valueStart + value[0].length;\n into.push([valueStart, valueEnd]);\n names.lastIndex = valueEnd;\n }\n}\n\n/**\n * The text of each `<script>` in `body`, to its end tag or the body's\n * end. An open tag is found, then its `>`, each once: a pattern that took\n * the tag whole read to the body's end from every `<script` with no `>`\n * after it, seconds on a 512 KB response (MEASURED in review). With no\n * `>` left, no tag can open.\n */\nfunction scriptRanges(body: string): Range[] {\n const out: Range[] = [];\n const open = /<script\\b/gi;\n const close = /<\\/script\\s*>/gi;\n for (let m = open.exec(body); m !== null; m = open.exec(body)) {\n const gt = body.indexOf(\">\", m.index);\n if (gt === -1) break;\n close.lastIndex = gt + 1;\n const end = close.exec(body);\n const to = end === null ? body.length : end.index;\n out.push([gt + 1, to]);\n open.lastIndex = to;\n }\n return out;\n}\n\n/** A character an embedded pair can follow, as sent or once decoded. */\nconst PAIR_LEAD = /[?;\\n]|%(?:3[FfBb]|26|0[Aa])/;\n\n/**\n * One segment of a form: a pair or a bare name, its trimmed raw name a\n * form name and its value free of raw whitespace (an encoded value\n * carries none; one that does is prose or markup, kept byte for byte on\n * the other path). An empty segment -- a trailing or doubled `&` -- has\n * the empty name, which FORM_NAME accepts.\n */\nfunction formSegment(seg: string): boolean {\n const eq = seg.indexOf(\"=\");\n const name = (eq === -1 ? seg : seg.slice(0, eq)).trim();\n return FORM_NAME.test(name) && (eq === -1 || !/\\s/.test(seg.slice(eq + 1)));\n}\n\n/**\n * The embedded credential pairs inside one form segment, text[from, to).\n *\n * Per segment, and only a segment that holds a character a pair can\n * follow (`?`, `;`, `&` once decoded, a newline): a search over the whole\n * form found every pair of the form itself again and re-checked each name\n * the segment loop had just checked, which doubled the cost of a form of\n * many fields on the page's main thread (512 KB of `a=b&`: 18 -> 35 ms\n * quiet, over a second under load). The check is a walk over the segment\n * alone, so it stays linear. A segment's start counts as a line start.\n */\nfunction spanPairRanges(\n text: string,\n from: number,\n to: number,\n into: Range[],\n): void {\n let lead = false;\n for (let i = from; i < to && !lead; i++) {\n const c = text.charCodeAt(i);\n lead = c === 63 || c === 59 || c === 38 || c === 10; // ? ; & \\n\n }\n if (!lead) return;\n const found: Range[] = [];\n embeddedPairRanges(text.slice(from, to), found);\n for (const [s0, e0] of found) into.push([from + s0, from + e0]);\n}\n\n/**\n * A content-type under which the page itself says the body is a form.\n * multipart is here because network.ts records a FormData -- passed\n * directly or inside a Request -- as the urlencoded pairs of its fields\n * (see formDataText). Multipart TEXT, as a page writes it by hand, is\n * parsed before this is consulted (see redactMultipartText).\n */\nconst DECLARED_FORM =\n /^\\s*(?:application\\/x-www-form-urlencoded|multipart\\/form-data)\\s*(?:;|$)/i;\n\n/**\n * Whether a body is read as a form (redactFormBody), `body` its bytes with\n * its URLs read as a form's and the cut marker, if any, on. The page says\n * so for one it declares x-www-form-urlencoded: it is one whatever its\n * bytes look like, and every\n * value runs to the next `&` -- a hand-built `password=correct horse\n * battery staple` recorded `password=[REDACTED] horse battery staple`\n * while the raw spaces sent it down the embedded-pair path, whose value\n * stops at the first space (review round 3). Under multipart a body that\n * is no multipart text is a FormData's rendering (see formDataText).\n * Otherwise it is one shaped as a form throughout: every segment a pair or\n * a bare name (no whitespace inside a trimmed name), and at least one\n * pair. A cut tail is exempt from the shape test -- the cut may have taken\n * its `=` or split a value -- and may be that pair, so `password=abc(def`\n * cut at the cap keeps its whole value redacted. A cut segment of HTML or\n * a log line taken for a form this way loses nothing: the form path\n * searches every segment for embedded credential pairs as the text path\n * does.\n */\nfunction readAsForm(body: string, contentType: string): boolean {\n if (MULTIPART.test(contentType)) return isFormRendering(body);\n if (DECLARED_FORM.test(contentType)) return true;\n const cut = body.endsWith(TRUNCATED_SUFFIX);\n const text = cut ? body.slice(0, -TRUNCATED_SUFFIX.length) : body;\n const segments = text.split(\"&\");\n const last = segments.length - 1;\n return (\n segments.some((seg) => seg.includes(\"=\")) &&\n segments.every((seg, i) => (cut && i === last) || formSegment(seg))\n );\n}\n\n/** The body redacted as a form, or null when nothing in it applied; `formShaped` is readAsForm's answer. */\nfunction redactFormBody(\n body: string,\n extra: readonly RegExp[],\n formShaped: boolean,\n code = false,\n): string | null {\n // A cut body ends mid-pair: its last segment may have lost its `=`.\n const cut = body.endsWith(TRUNCATED_SUFFIX);\n const text = cut ? body.slice(0, -TRUNCATED_SUFFIX.length) : body;\n const segments = text.split(\"&\");\n if (!formShaped) {\n // Only a body that holds a credential pair takes this path; any other\n // text is the caller's plain scan. The cut marker is the SDK's, not the\n // body's: it is set aside, or a value read up to it took its dots.\n const ranges: Range[] = [];\n embeddedPairRanges(text, ranges, code ? \"code\" : \"text\");\n if (ranges.length === 0) return null;\n detectorRanges(text, extra, ranges);\n return applyRanges(text, ranges) + (cut ? TRUNCATED_SUFFIX : \"\");\n }\n\n // ONE pass of every detector over the body as it came, and one over it\n // decoded, each name and value decoded with a map back to its raw\n // bytes; the `&` and `=` between them stay themselves. No built-in can\n // match across an `&` or an `=` (none of them admits either), so a\n // whole-body scan finds exactly what a scan per name and value found --\n // at one pass instead of six per pair, which cost 100-300x base on a\n // form of many fields (review r8). The integrator's patterns see the\n // whole body too, so one may span `name=value` (`member_id=\\d+`) or\n // several fields (review round 5, H2), as base's scan of the whole body\n // allowed, and one written against the decoded value (`dob=01/02/1990`\n // in a FormData, recorded as `dob=01%2F02%2F1990`) matches it (review\n // r6, B2). PII in the NAME half of a pair is found the same way (review\n // round 4).\n const ranges: Range[] = [];\n detectorRanges(text, extra, ranges);\n // With no `%` and no `+` anywhere, the decoded form IS the form as sent,\n // and a second scan of it would find exactly the same ranges.\n const escaped = /[%+]/.test(text);\n const decoded = newDecodedText(escaped ? text.length : 0);\n // An embedded pair follows `?`, `;` or a newline, raw or escaped, or an\n // `&` that only decoding produces. A form with none of them -- most\n // forms -- skips the pair search below: one pass instead of one per\n // segment.\n const pairsPossible = PAIR_LEAD.test(text);\n // Where each segment sits in the decoded text, for the pair search below.\n const decodedSegments: number[] = [];\n // An OAuth token exchange's `code` (isTokenExchange).\n const exchange = isTokenExchange(\n segments.flatMap((seg) => {\n const eq = seg.indexOf(\"=\");\n return eq === -1\n ? []\n : [\n [\n normalizeKey(formDecode(seg.slice(0, eq))),\n formDecode(seg.slice(eq + 1)),\n ] as [string, string],\n ];\n }),\n );\n // Raw JSON values redacted in their own text, and the scratch result.\n const jsonSpans: Range[] = [];\n let json: Range | null;\n let at = 0;\n for (const seg of segments) {\n const eq = seg.indexOf(\"=\");\n const nameEnd = eq === -1 ? at + seg.length : at + eq;\n const segEnd = at + seg.length;\n const from = decoded.length;\n if (escaped) appendDecoded(text, at, nameEnd, decoded);\n if (eq !== -1 && escaped) {\n appendUnit(decoded, \"=\", nameEnd, nameEnd + 1);\n appendDecoded(text, nameEnd + 1, segEnd, decoded);\n }\n // A sensitive name redacts its value wherever the pair sits, an\n // empty one included.\n if (\n eq !== -1 &&\n (isCredentialName(seg.slice(0, eq), \"param\") ||\n (exchange &&\n EXCHANGE_REDACTED.has(normalizeKey(formDecode(seg.slice(0, eq))))))\n ) {\n ranges.push([nameEnd + 1, segEnd]);\n } else if (\n eq !== -1 &&\n holdsEncodedUrlCredential(text.slice(nameEnd + 1, segEnd))\n ) {\n // A URL a value holds encoded, with a credential in it\n // (holdsEncodedUrlCredential): the value goes whole.\n ranges.push([nameEnd + 1, segEnd]);\n } else if (\n eq !== -1 &&\n (json = jsonFormValue(text, nameEnd + 1, segEnd, extra)) !== null\n ) {\n // A value that is JSON with something in it to redact -- a GraphQL\n // multipart upload's `operations` carries the variables. Written as\n // it came, it is redacted in its own text; URL-encoded, it goes\n // whole, since a redaction inside it cannot be written back without\n // re-encoding the rest.\n if (json.length === 3) jsonSpans.push(json);\n else ranges.push(json);\n } else if (pairsPossible) {\n // A credential pair INSIDE any other segment -- a redirect URL's\n // `?token=` in a value, a `cb?pwd=` in a name -- is found as in any\n // other text, raw here and decoded below.\n spanPairRanges(text, at, segEnd, ranges);\n if (escaped) decodedSegments.push(from, decoded.length);\n }\n at += seg.length;\n if (at < text.length) {\n if (escaped) appendUnit(decoded, \"&\", at, at + 1);\n at++;\n }\n }\n if (escaped) {\n const found: Range[] = [];\n const plain = decoded.parts.join(\"\");\n detectorRanges(plain, extra, found);\n // `redirect=https%3A%2F%2Fx%2Fcb%3Ftoken%3Dabc` holds `?token=abc`\n // only once decoded.\n for (let k = 0; k < decodedSegments.length; k += 2) {\n spanPairRanges(plain, decodedSegments[k], decodedSegments[k + 1], found);\n }\n for (const [s0, e0] of found) {\n ranges.push([decoded.start[s0], decoded.end[e0 - 1]]);\n }\n }\n // A raw JSON value's own redaction already scanned it: a detector's\n // range inside it would merge with it into a bare marker.\n // jsonSpans are in text order and disjoint (one per segment): each\n // range is looked up by binary search, not against every span -- a\n // form of 40,000 JSON fields was quadratic (review).\n const kept = ranges.filter(([a, b]) => !insideSpan(jsonSpans, a, b));\n return (\n applyRanges(text, [...kept, ...jsonSpans]) + (cut ? TRUNCATED_SUFFIX : \"\")\n );\n}\n\n/* ------------------------------------------------------------------ */\n/* Multipart text */\n/* ------------------------------------------------------------------ */\n\nconst MULTIPART = /^\\s*multipart\\/form-data\\s*(?:;|$)/i;\nconst BOUNDARY_PARAM =\n /;\\s*boundary\\s*=\\s*(?:\"([^\"\\r\\n]{1,200})\"|([^\\s;\"]{1,200}))/i;\n/** A part's field name in its Content-Disposition header. */\nconst PART_NAME =\n /^content-disposition\\s*:[^\\n]*?;\\s*name\\s*=\\s*(?:\"([^\"\\r\\n]*)\"|([^\\s;]+))/im;\n/** A part that carries a file: its bytes are never recorded. */\nconst PART_FILE = /^content-disposition\\s*:[^\\n]*?;\\s*filename\\*?\\s*=/im;\n\n/**\n * A multipart body written out as TEXT -- by hand, as a string passed to\n * fetch or XMLHttpRequest, or served as a response -- redacted part by\n * part, or null when the body is not one.\n *\n * Without this such a body took the form path, which knows `&` and `=`\n * and not parts: a `name=\"password\"` part's value was recorded in clear,\n * and a `&password=` inside another part's text redacted everything after\n * it, the closing boundary included (review r1 of the port, M2).\n *\n * The boundary is the content-type's, or -- when the page declared none\n * -- the body's own first line. Each part's value is replaced whole when\n * its name is sensitive (as a form field's is: `password`, `user[token]`)\n * or when the part is a file; every other value, and every header block,\n * is scanned like any other text. Every other byte is kept. A body cut at\n * the cap keeps what it has: its last part runs to the cut.\n */\nfunction redactMultipartText(\n body: string,\n contentType: string,\n extra: readonly RegExp[],\n): string | null {\n if (!MULTIPART.test(contentType)) return null;\n const cut = body.endsWith(TRUNCATED_SUFFIX);\n const text = cut ? body.slice(0, -TRUNCATED_SUFFIX.length) : body;\n const param = BOUNDARY_PARAM.exec(contentType);\n const boundary =\n param !== null\n ? (param[1] ?? param[2])\n : (/^--([^\\r\\n]{1,200})\\r?\\n/.exec(text)?.[1] ?? null);\n if (boundary === null) return null;\n const delimiter = \"--\" + boundary;\n let at = text.startsWith(delimiter) ? 0 : text.indexOf(\"\\n\" + delimiter);\n // Not multipart text: a FormData rendering (pairs) or anything else.\n if (at === -1) return null;\n if (at > 0) at += 1;\n const ranges: Range[] = [];\n scanSpan(text, 0, at, extra, ranges); // a preamble\n for (;;) {\n const after = at + delimiter.length;\n // A close delimiter ends the body only when no delimiter follows it:\n // `--X--` written inside a value must not leave the parts after it\n // to the pattern scan alone (review r2).\n if (\n text.startsWith(\"--\", after) &&\n text.indexOf(\"\\n\" + delimiter, after) === -1\n ) {\n scanSpan(text, after + 2, text.length, extra, ranges); // an epilogue\n break;\n }\n const lineEnd = text.indexOf(\"\\n\", after);\n if (lineEnd === -1) break; // cut inside a delimiter line\n // Headers run to the first empty line.\n let line = lineEnd + 1;\n let valueStart = -1;\n while (line < text.length) {\n const end = text.indexOf(\"\\n\", line);\n if (end === -1) break;\n if (end === line || (end === line + 1 && text[line] === \"\\r\")) {\n valueStart = end + 1;\n break;\n }\n line = end + 1;\n }\n const headersEnd = valueStart === -1 ? text.length : valueStart;\n scanSpan(text, lineEnd + 1, headersEnd, extra, ranges);\n if (valueStart === -1) break; // cut inside a header block\n const next = text.indexOf(\"\\n\" + delimiter, valueStart);\n let valueEnd = next === -1 ? text.length : next;\n if (next !== -1 && valueEnd > valueStart && text[valueEnd - 1] === \"\\r\") {\n valueEnd--;\n }\n const headers = text.slice(lineEnd + 1, headersEnd);\n const name = PART_NAME.exec(headers);\n const fieldName = name === null ? \"\" : (name[1] ?? name[2]);\n const jsonPart =\n PART_FILE.test(headers) || isCredentialName(fieldName, \"param\")\n ? null\n : redactJsonString(text.slice(valueStart, valueEnd), 0, extra);\n if (PART_FILE.test(headers) || isCredentialName(fieldName, \"param\")) {\n ranges.push([valueStart, valueEnd]);\n } else if (\n jsonPart !== null &&\n jsonPart !== text.slice(valueStart, valueEnd)\n ) {\n // A JSON part with something in it to redact (a GraphQL upload's\n // `operations`), redacted in its own text.\n ranges.push([valueStart, valueEnd, jsonPart]);\n } else {\n scanSpan(text, valueStart, valueEnd, extra, ranges);\n }\n if (next === -1) break;\n at = next + 1;\n }\n return applyRanges(text, ranges) + (cut ? TRUNCATED_SUFFIX : \"\");\n}\n\n/** The fail-closed note: a body nothing here can read safely. */\nconst UNREADABLE = \"[Unreadable body]\";\n\n/**\n * True for a body shaped as a FormData's urlencoded rendering, whole or\n * cut: every `&`-segment a form segment. The cut marker holds no `=`, `&`\n * or whitespace, and its dots, brackets and letters are name characters,\n * so it never makes a segment pass that would fail without it, and a\n * rendering cut anywhere, inside a name or a value, still passes. The\n * last segment of a cut body was once let through unread, and a cut body\n * with no `&` is one segment and the last: a multipart body under another\n * boundary than the declared one, cut at the cap, passed for a rendering\n * and went down the form path, which cannot see its parts.\n */\nfunction isFormRendering(body: string): boolean {\n return body.split(\"&\").every(formSegment);\n}\n\n/** True when [a, b) lies inside one of `spans`, which are sorted and disjoint. */\nfunction insideSpan(spans: Range[], a: number, b: number): boolean {\n let lo = 0;\n let hi = spans.length - 1;\n while (lo <= hi) {\n const mid = (lo + hi) >> 1;\n const [c, d] = spans[mid];\n if (a < c) hi = mid - 1;\n else if (a >= d) lo = mid + 1;\n else return b <= d;\n }\n return false;\n}\n\n/**\n * A form value that is JSON with something in it to redact, as the range\n * to write, or null. Written as it came (no `%`, no `+`), its own\n * redaction is the replacement, every other byte kept; URL-encoded, the\n * whole value goes.\n */\nfunction jsonFormValue(\n text: string,\n start: number,\n end: number,\n extra: readonly RegExp[],\n): Range | null {\n const raw = text.slice(start, end);\n if (!/^(?:%7B|%5B|[[{])/i.test(raw)) return null;\n if (/[%+]/.test(raw)) {\n const decoded = formDecode(raw);\n const redacted = redactJsonString(decoded, 0, extra);\n return redacted === null || redacted === decoded ? null : [start, end];\n }\n const redacted = redactJsonString(raw, 0, extra);\n return redacted === null || redacted === raw ? null : [start, end, redacted];\n}\n\n/** text[from, to) scanned like any other text, its ranges shifted back. */\nfunction scanSpan(\n text: string,\n from: number,\n to: number,\n extra: readonly RegExp[],\n into: Range[],\n): void {\n if (from >= to) return;\n const span = text.slice(from, to);\n const found: Range[] = [];\n detectorRanges(span, extra, found);\n embeddedPairRanges(span, found);\n for (const [s0, e0] of found) into.push([from + s0, from + e0]);\n}\n\n/** Exposed for tests and diagnostics. */\nexport const __internals = {\n isSensitiveKey,\n isLikelyCardNumber,\n passesLuhn,\n redactCards,\n};\n","/* ------------------------------------------------------------------ */\n/* @keploy/capture-sdk - the page's stream of its body, a lazy chunk */\n/* ------------------------------------------------------------------ */\n\n/*\n * THE RELAY OF A BODY THE PAGE READS THROUGH `res.body` (network.ts\n * relayResponse says why it is a relay): a byte stream that takes the\n * network's reader at the page's first read and reads the network once\n * per page read, recording what the page reads. Only pages that stream a\n * body (SSE, NDJSON, LLM tokens, RSC) run it, so it is not in the main\n * bundle (founder, 2026-11-11: lazy-load what only some pages use): it is\n * part of the body code's chunk (body-redact.ts exports it), which the\n * capture asks for at init. Until that chunk has arrived -- or while the\n * page's leave holds its load -- the page gets the network's own stream\n * at once, never a wait (network.ts; coordinator ruling C4, 2026-11-16,\n * from the founder's \"the SDK never slows the frontend\" and \"losing\n * capture fails closed\"). Taking it records nothing (C7: a page may only\n * look, then read whole); a body nothing reads whole is recorded as not\n * captured. Whole reads (text(), json(), ...) need none of this and are\n * recorded in the main bundle.\n */\n\nimport { cutText, truncate } from \"./redact\";\n\n/**\n * One exchange's recording, as network.ts's relayResponse keeps it: its\n * whole reads and the page's stream both read into it, and the first to\n * report is the recording.\n */\nexport interface Recording {\n /** A read of the body began: a whole read of any member, or the page's own stream. */\n touched: boolean;\n /** The body is recorded: nothing reads into it any more. */\n reported: boolean;\n /** The stream path's text so far, while it records (cut where it is at a leave). */\n text: string;\n /** Record `value`, if nothing has yet. */\n say: (value: string | null) => void;\n /** Record `value`, if nothing has yet, and end the relay. */\n end: (value: string | null) => void;\n /** End the relay: its event may go (network.ts emit). */\n finished: () => void;\n}\n\n/**\n * A body chunk as the platform takes one: a Uint8Array (from any realm),\n * else a TypeError -- what `text()` and the other readers answer for a\n * page-built body that enqueues anything else, without the SDK too.\n */\nfunction bytesOf(value: unknown): Uint8Array {\n // The platform's own TypedArray tag getter: it reads the object's real\n // type (any realm, subclasses included) and runs no code of the page's,\n // where its Symbol.toStringTag could be faked or throw.\n if (typedArrayName(value) === \"Uint8Array\") return value as Uint8Array;\n throw new TypeError(\"a response body chunk is not a Uint8Array\");\n}\n\n/**\n * `%TypedArray%.prototype[Symbol.toStringTag]`'s getter, looked up at the\n * first chunk (the worker, which bundles this chunk's module, never runs it).\n */\nlet typedArrayTag: unknown;\n/** A typed array's name, else undefined. */\nfunction typedArrayName(value: unknown): unknown {\n typedArrayTag ??= Reflect.get(\n Object.getOwnPropertyDescriptor(\n Object.getPrototypeOf(Uint8Array.prototype) as object,\n Symbol.toStringTag,\n ) ?? {},\n \"get\",\n );\n return typeof typedArrayTag === \"function\"\n ? Reflect.apply(typedArrayTag, value, [])\n : undefined;\n}\n\n/** The underlying-source type of a byte stream. */\nconst BYTE_SOURCE = \"bytes\";\n\n/** What the relay calls on its page stream's controller, default or byte. */\ninterface PageController {\n enqueue(chunk: Uint8Array): void;\n close(): void;\n error(reason?: unknown): void;\n readonly byobRequest?: { respond(bytesWritten: number): void } | null;\n}\n\n/**\n * The page's stream of `native`, its own Response's network body, read\n * into `rec` up to `maxSize` UTF-16 units (network.ts relayResponse).\n */\nexport function relayBody(\n native: ReadableStream<Uint8Array>,\n maxSize: number,\n rec: Recording,\n): ReadableStream<Uint8Array> {\n const { end, say, finished } = rec;\n const decoder = new TextDecoder();\n let reader: ReadableStreamDefaultReader<Uint8Array> | undefined;\n const source = {\n pull(c: PageController) {\n if (!reader) {\n reader = native.getReader();\n rec.touched = true;\n }\n // Until a chunk is handed over or the body ends: a pull that settles\n // with neither is not called again (Streams: pullAgain), and the\n // page's read would wait for ever.\n const one = (): Promise<void> =>\n reader!.read().then((next) => {\n if (next.done) {\n if (!rec.reported)\n end(truncate(rec.text + decoder.decode(), maxSize));\n finished();\n c.close();\n // A BYOB read waiting at the end is answered with no bytes.\n c.byobRequest?.respond(0);\n return;\n }\n const chunk = bytesOf(next.value);\n // An empty chunk (a page-built body may enqueue one) is nothing\n // to hand over: a byte stream refuses it.\n if (!chunk.byteLength) return one();\n // Decoded only while it records: not once it is reported (past\n // the cap, read whole through a clone, or not read at `hidden`).\n if (!rec.reported) {\n rec.text += decoder.decode(chunk, { stream: true });\n if (rec.text.length > maxSize) {\n say(truncate(rec.text, maxSize));\n rec.text = \"\";\n // A body still arriving a second after its cap is a\n // stream, or one the page is not reading: its event is\n // masked then (emit), not held to its end.\n setTimeout(finished, 1_000);\n }\n }\n // A byte stream's enqueue() transfers (detaches) the chunk's\n // buffer, which the body's source may still hold -- a pooled\n // buffer, or a constant chunk a page-built body enqueues again\n // and again. The page is handed a copy, made by the\n // constructor, not by the chunk's own slice(): a Buffer\n // polyfill's slice() is a view onto the same memory.\n c.enqueue(new Uint8Array(chunk));\n });\n return one().catch((err: unknown) => {\n // The body failed, or a chunk is not bytes (a page-built body):\n // what had arrived is recorded cut and marked, the network is\n // let go, and the page's read rejects with the reason, as the\n // platform's own read would. Firefox and WebKit abort a\n // document's fetches when it navigates, BEFORE pagehide\n // (MEASURED): this is where a page that leaves mid-body is cut\n // there.\n end(cutText(rec.text));\n void reader!.cancel(err).catch(() => {});\n throw err;\n });\n },\n cancel(reason: unknown) {\n // What the page read, as it read it (nothing, before any read):\n // never a marker. (Past the cap, or read whole through a clone, it\n // is reported already.)\n end(rec.text);\n return (reader ?? native).cancel(reason);\n },\n };\n const Stream = (Object.getPrototypeOf(native) as ReadableStream)\n .constructor as typeof ReadableStream;\n // A BYTE stream, as the network's body is (Fetch spec), so a page's\n // `getReader({ mode: \"byob\" })` works as it does without the SDK; a\n // platform without byte streams gets a default one. A high-water mark\n // of 0: nothing is pulled until the page reads.\n const make = (type?: string): ReadableStream<Uint8Array> =>\n new Stream(\n { ...source, type } as unknown as UnderlyingDefaultSource<Uint8Array>,\n { highWaterMark: 0 },\n );\n try {\n return make(BYTE_SOURCE);\n } catch {\n return make();\n }\n}\n","/* ------------------------------------------------------------------ */\n/* @keploy/capture-sdk - body redaction, off the main bundle */\n/* ------------------------------------------------------------------ */\n\n/*\n * THE BODY HALF OF PrivacyEngine.maskNetworkData, IN ONE PLACE, SHIPPED\n * TWICE AND NEVER IN THE MAIN BUNDLE. MEASURED (uic-sdk-perf MEASURE.md,\n * SDK 81f32f0960): redacting a 512 KB JSON body takes 42-58 ms of the\n * page's main thread, 150 ms on a phone-speed CPU, and fifty 64 KB\n * responses froze a page for 257-299 ms. So this code runs in a Web\n * Worker, dist/body-worker.js (body-worker.ts), and the main thread\n * only posts a body and reads its answer (body-jobs.ts).\n *\n * The same module is also the chunk dist/body-redact.{mjs,js}, loaded by\n * the package's own name as the GraphQL term's chunk is: the main thread\n * runs it only where it must -- a page whose CSP or bundler gives it no\n * worker, under the main-thread budget, and a body still in the worker\n * when the page leaves. Both are built from THIS file and redact.ts with\n * the one shared rule (@keploy/contract/privacy), so a body comes out the\n * same bytes either way (body-worker-parity.test.ts runs the redaction\n * corpora and the seeded fuzzers through both).\n */\n\nimport { cutBodyNote } from \"@keploy/contract/privacy\";\nimport { redactBody, TRUNCATED_SUFFIX } from \"./redact\";\n/** The version this chunk was built as: the SDK refuses one of another (module-of.ts ownChunk). */\nexport { version } from \"../package.json\";\n/**\n * The page's stream of a body it reads through `res.body` (page-stream.ts):\n * in this chunk, not the main bundle, as only pages that stream a body run\n * it. The worker, which bundles this module for redactBodies, leaves it out.\n */\nexport { relayBody } from \"./page-stream\";\n\n/** One exchange's bodies, as the main thread hands them over. */\nexport interface BodyJob {\n requestBody: string | null;\n responseBody: string | null;\n /** The request's and the response's content-type, if any. */\n requestType?: string;\n responseType?: string;\n /** The integrator's piiPatterns, compiled global (structured-cloned into the worker). */\n patterns: RegExp[];\n}\n\n/** The two bodies as recorded. */\nexport interface BodyOut {\n requestBody: string | null;\n responseBody: string | null;\n}\n\n/**\n * `body` as recorded when at most `limit` UTF-16 units of it may be\n * redacted: whole when it fits; otherwise its first `limit` units,\n * redacted as any body cut at a cap is (`...[truncated]`), under\n * cutBodyNote's first line, which says it is not the whole body. A\n * `limit` of 0 keeps nothing of it but the note.\n */\nfunction redactWithin(\n body: string | null,\n type: string | undefined,\n patterns: readonly RegExp[],\n limit: number,\n): string | null {\n if (body === null || body.length <= limit) {\n return redactBody(body, type, patterns);\n }\n return (\n cutBodyNote(limit, body.length) +\n (limit > 0\n ? (redactBody(body.slice(0, limit) + TRUNCATED_SUFFIX, type, patterns) ??\n \"\")\n : \"\")\n );\n}\n\n/**\n * Both bodies of `job`, redacted. The worker passes no limits and redacts\n * them whole; the main thread passes its budget (body-jobs.ts): `limit`\n * UTF-16 units of the request body, and `responseLimit` of the response's.\n */\nexport function redactBodies(\n job: BodyJob,\n limit = Infinity,\n responseLimit = limit,\n): BodyOut {\n return {\n requestBody: redactWithin(\n job.requestBody,\n job.requestType,\n job.patterns,\n limit,\n ),\n responseBody: redactWithin(\n job.responseBody,\n job.responseType,\n job.patterns,\n responseLimit,\n ),\n };\n}\n","{\n \"name\": \"@keploy/capture-sdk\",\n \"version\": \"3.3.0\",\n \"description\": \"Lightweight SDK to capture UI flows from real users - DOM recording, network interception, PII masking\",\n \"homepage\": \"https://keploy.io/docs/running-keploy/ui-capture/\",\n \"main\": \"dist/index.js\",\n \"module\": \"dist/index.bundler.mjs\",\n \"unpkg\": \"dist/index.mjs\",\n \"jsdelivr\": \"dist/index.mjs\",\n \"types\": \"dist/index.d.ts\",\n \"exports\": {\n \".\": {\n \"types\": \"./dist/index.d.ts\",\n \"import\": \"./dist/index.mjs\",\n \"require\": \"./dist/index.js\"\n },\n \"./request-term\": {\n \"types\": \"./dist/request-term.d.ts\",\n \"import\": \"./dist/request-term.mjs\",\n \"require\": \"./dist/request-term.js\"\n },\n \"./strict-attributes\": {\n \"types\": \"./dist/strict-attributes.d.ts\",\n \"import\": \"./dist/strict-attributes.mjs\",\n \"require\": \"./dist/strict-attributes.js\"\n },\n \"./body-redact\": {\n \"types\": \"./dist/body-redact.d.ts\",\n \"import\": \"./dist/body-redact.mjs\",\n \"require\": \"./dist/body-redact.js\"\n },\n \"./body-worker-start\": {\n \"types\": \"./dist/body-worker-start.d.ts\",\n \"import\": \"./dist/body-worker-start.mjs\",\n \"require\": \"./dist/body-worker-start.js\"\n },\n \"./package.json\": \"./package.json\"\n },\n \"files\": [\n \"dist\",\n \"request-term/package.json\",\n \"strict-attributes/package.json\",\n \"body-redact/package.json\",\n \"body-worker-start/package.json\",\n \"LICENSE\",\n \"README.md\"\n ],\n \"scripts\": {\n \"build\": \"node scripts/build-main.mjs && node scripts/build-worker.mjs && tsc -p tsconfig.build.json\",\n \"dev\": \"node scripts/build-main.mjs --watch\",\n \"test\": \"vitest run\",\n \"clean\": \"rm -rf dist\",\n \"typecheck\": \"tsc --noEmit\",\n \"prepublishOnly\": \"pnpm run clean && turbo run build --filter=@keploy/capture-sdk --force && node ../../tools/check-release-size.mjs\"\n },\n \"dependencies\": {\n \"rrweb\": \"^2.2.2\"\n },\n \"devDependencies\": {\n \"@keploy/contract\": \"workspace:*\",\n \"@types/node\": \"~24.13.5\",\n \"jsdom\": \"^30.1.0\",\n \"terser\": \"5.51.2\",\n \"tsup\": \"^8.3.0\",\n \"typescript\": \"^7.0.2\",\n \"vitest\": \"^5.0.1\"\n },\n \"peerDependencies\": {},\n \"keywords\": [\n \"keploy\",\n \"ui-testing\",\n \"session-recording\",\n \"e2e\",\n \"capture\"\n ],\n \"browser\": {\n \"./dist/body-worker-unbundled.mjs\": \"./dist/body-worker-none.mjs\"\n },\n \"alias\": {\n \"@keploy/capture-sdk/body-worker-start\": \"./dist/body-worker-start.mjs\"\n },\n \"license\": \"Apache-2.0\",\n \"publishConfig\": {\n \"access\": \"public\"\n }\n}\n"]}