Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 | 3x 3x 17x 17x 17x 16x 16x 16x 8x 8x 8x 63x 6x 87x 87x 6x 57x 57x 8x 9x 6x 655x 339x 316x 278x 155x 553x 155x 155x 123x 155x 155x 155x 9x 9x 9x 155x 5x 5x 9x 9x 9x 155x 6x 369x 9x 1087x 541x 10x 10x 10x 10x 10x 10x 541x 546x 136x 94x 452x 200x 807x 6x 6x 6x 6x 5x 5x 3x 4x 2x 2x 2x 2x 1x 1x 1x 1x 1x 2x 2x 2x 4x 2x 2x 2x 2x 2x 1x 1x 2x 1x 2x 1x 1x 1x 4x 4x 4x 4x 4x 3x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 12x 12x 323x 1x 33x 33x 33x 33x 318x 32x | import type { HarEntry } from "../types/har";
import { replaceProtectedBody, replaceProtectedTokens } from "./resolvedValues";
export type ProtectedTokenMode = "encrypt" | "tokenize";
export interface ProtectedToken {
token: string;
mode: ProtectedTokenMode;
keyId: string;
payload: Uint8Array;
}
export interface ProtectedOccurrence extends ProtectedToken {
path: string;
request: boolean;
}
export interface BatchDecryptProgress {
completed: number;
total: number;
failures: number;
}
export interface BatchDecryptResult {
values: Map<string, string>;
failures: number;
}
export type ActiveProtectionKeys = ReadonlyMap<string, string>;
export interface BatchVerifyProgress {
completed: number;
total: number;
matches: number;
}
const TOKEN_RE = /REC-(ENC|TOK)-v1\.([A-Za-z0-9_-]+)\.([A-Za-z0-9_-]+)/g;
const MAX_TOKEN_CHARS = 24 << 20;
export function parseProtectedToken(token: string): ProtectedToken {
Iif (token.length > MAX_TOKEN_CHARS) throw new Error("Protected token exceeds the Inspector safety limit.");
const match = /^(REC-(ENC|TOK)-v1)\.([A-Za-z0-9_-]+)\.([A-Za-z0-9_-]+)$/.exec(token);
if (!match) throw new Error("Unsupported or malformed protected token.");
const keyId = new TextDecoder("utf-8", { fatal: true }).decode(base64UrlBytes(match[3]));
Iif (!keyId) throw new Error("Protected token has an empty key ID.");
return {
token,
mode: match[2] === "ENC" ? "encrypt" : "tokenize",
keyId,
payload: base64UrlBytes(match[4]),
};
}
export function protectedOccurrences(entry: HarEntry): ProtectedOccurrence[] {
const occurrences: ProtectedOccurrence[] = [];
const seen = new Set<string>();
for (const [key, value] of Object.entries(entry)) {
if (key === "_recorder" && value && typeof value === "object") {
for (const [extensionKey, extensionValue] of Object.entries(value)) {
const request = extensionKey === "network" || extensionKey === "expect100" || extensionKey.startsWith("request");
walk(extensionValue, `_recorder.${extensionKey}`, request, occurrences, seen);
}
continue;
}
const request = key === "request";
walk(value, key, request, occurrences, seen);
}
return occurrences;
}
/** Return an in-memory view with decrypted tokens substituted in every string.
* The parsed HAR and its nested objects are never mutated. */
export function withResolvedValues<T>(value: T, resolvedValues: ReadonlyMap<string, string>): T {
if (resolvedValues.size === 0) return value;
return replaceResolved(value, resolvedValues) as T;
}
function replaceResolved(value: unknown, resolvedValues: ReadonlyMap<string, string>): unknown {
if (typeof value === "string") {
return replaceProtectedTokens(value, resolvedValues);
}
if (Array.isArray(value)) return value.map((item) => replaceResolved(item, resolvedValues));
if (value && typeof value === "object") {
const resolved = Object.fromEntries(
Object.entries(value).map(([key, child]) => [key, replaceResolved(child, resolvedValues)]),
);
resolveEntryBodies(value as Record<string, unknown>, resolved, resolvedValues);
return resolved;
}
return value;
}
function resolveEntryBodies(
source: Record<string, unknown>,
resolved: Record<string, unknown>,
resolvedValues: ReadonlyMap<string, string>,
): void {
const request = objectValue(source["request"]);
const response = objectValue(source["response"]);
if (!request || !response) return;
const resolvedRequest = objectValue(resolved["request"]);
const postData = objectValue(request["postData"]);
const resolvedPostData = objectValue(resolvedRequest?.["postData"]);
if (postData && resolvedPostData && typeof postData["text"] === "string") {
const extension = objectValue(source["_recorder"]);
resolvedPostData["text"] = extension?.["requestBodyEncoding"] === "base64"
? postData["text"]
: replaceProtectedBody(postData["text"], stringValue(postData["mimeType"]), resolvedValues);
}
const resolvedResponse = objectValue(resolved["response"]);
const content = objectValue(response["content"]);
const resolvedContent = objectValue(resolvedResponse?.["content"]);
if (content && resolvedContent && typeof content["text"] === "string") {
resolvedContent["text"] = content["encoding"] === "base64"
? content["text"]
: replaceProtectedBody(content["text"], stringValue(content["mimeType"]), resolvedValues);
}
}
function objectValue(value: unknown): Record<string, unknown> | undefined {
return value && typeof value === "object" && !Array.isArray(value)
? value as Record<string, unknown>
: undefined;
}
function stringValue(value: unknown): string | undefined {
return typeof value === "string" ? value : undefined;
}
function walk(
value: unknown,
path: string,
request: boolean,
out: ProtectedOccurrence[],
seen: Set<string>,
): void {
if (typeof value === "string") {
for (const match of value.matchAll(TOKEN_RE)) {
const token = match[0];
const identity = `${path}\0${token}`;
Iif (seen.has(identity)) continue;
seen.add(identity);
try {
out.push({ ...parseProtectedToken(token), path, request });
} catch {
// Rendering untrusted HAR input must remain best-effort.
}
}
return;
}
if (Array.isArray(value)) {
value.forEach((item, index) => walk(item, `${path}[${index}]`, request, out, seen));
return;
}
if (value && typeof value === "object") {
for (const [key, child] of Object.entries(value as Record<string, unknown>)) {
walk(child, `${path}.${key}`, request, out, seen);
}
}
}
export async function decryptProtectedToken(token: ProtectedToken, keyText: string): Promise<string> {
Iif (token.mode !== "encrypt") throw new Error("This token is not encrypted.");
const keyBytes = decodeKey(keyText);
Iif (keyBytes.length !== 32) throw new Error("AES-256-GCM keys must contain exactly 32 bytes.");
if (token.payload.length < 12 + 16) throw new Error("Encrypted token payload is too short.");
const key = await crypto.subtle.importKey("raw", arrayBuffer(keyBytes), { name: "AES-GCM" }, false, ["decrypt"]);
const plain = await crypto.subtle.decrypt({
name: "AES-GCM",
iv: arrayBuffer(token.payload.slice(0, 12)),
additionalData: arrayBuffer(new TextEncoder().encode(token.keyId)),
tagLength: 128,
}, key, arrayBuffer(token.payload.slice(12)));
return new TextDecoder("utf-8", { fatal: true }).decode(plain);
}
/** Decrypt unique tokens in bounded batches. The first value validates the
* key, avoiding thousands of identical failures when the key is wrong. */
export async function decryptProtectedTokens(
tokens: readonly ProtectedToken[],
keyText: string,
onProgress?: (progress: BatchDecryptProgress) => void,
): Promise<BatchDecryptResult> {
const unique = [...new Map(tokens.filter((token) => token.mode === "encrypt").map((token) => [token.token, token])).values()];
const values = new Map<string, string>();
Iif (unique.length === 0) return { values, failures: 0 };
let first: string;
try {
first = await decryptProtectedToken(unique[0], keyText);
} catch {
throw new Error("The first value could not be decrypted; the key may be wrong or the token may be damaged.");
}
values.set(unique[0].token, first);
let completed = 1;
let failures = 0;
onProgress?.({ completed, total: unique.length, failures });
const batchSize = 64;
for (let offset = 1; offset < unique.length; offset += batchSize) {
const batch = unique.slice(offset, offset + batchSize);
const results = await Promise.allSettled(batch.map((token) => decryptProtectedToken(token, keyText)));
results.forEach((result, index) => {
if (result.status === "fulfilled") values.set(batch[index].token, result.value);
else failures += 1;
});
completed += batch.length;
onProgress?.({ completed, total: unique.length, failures });
await new Promise<void>((resolve) => setTimeout(resolve, 0));
}
return { values, failures };
}
/** Resolve encrypted values in one newly arrived live entry with keys already
* validated by an explicit user decrypt operation. Failures are isolated per
* token so one damaged value does not prevent other values from resolving. */
export async function decryptLiveEntry(
entry: HarEntry,
activeKeys: ActiveProtectionKeys,
): Promise<BatchDecryptResult> {
const unique = [...new Map(protectedOccurrences(entry)
.filter((token) => token.mode === "encrypt" && activeKeys.has(`${token.mode}:${token.keyId}`))
.map((token) => [token.token, token])).values()];
const values = new Map<string, string>();
let failures = 0;
const batchSize = 64;
for (let offset = 0; offset < unique.length; offset += batchSize) {
const batch = unique.slice(offset, offset + batchSize);
const results = await Promise.allSettled(batch.map((token) =>
decryptProtectedToken(token, activeKeys.get(`${token.mode}:${token.keyId}`) ?? "")));
results.forEach((result, index) => {
if (result.status === "fulfilled") values.set(batch[index].token, result.value);
else failures += 1;
});
await new Promise<void>((resolve) => setTimeout(resolve, 0));
}
return { values, failures };
}
export async function verifyProtectedToken(
token: ProtectedToken,
candidate: string,
keyText: string,
): Promise<boolean> {
Iif (token.mode !== "tokenize") throw new Error("This token is not tokenized.");
const keyBytes = decodeKey(keyText);
Iif (keyBytes.length < 32) throw new Error("HMAC keys must contain at least 32 bytes.");
const key = await crypto.subtle.importKey("raw", arrayBuffer(keyBytes), { name: "HMAC", hash: "SHA-256" }, false, ["verify"]);
return crypto.subtle.verify("HMAC", key, arrayBuffer(token.payload), arrayBuffer(new TextEncoder().encode(candidate)));
}
/** Verify unique tokenized values in bounded batches and retain only matches. */
export async function verifyProtectedTokens(
tokens: readonly ProtectedToken[],
candidate: string,
keyText: string,
onProgress?: (progress: BatchVerifyProgress) => void,
): Promise<Map<string, string>> {
const unique = [...new Map(tokens.filter((token) => token.mode === "tokenize").map((token) => [token.token, token])).values()];
const values = new Map<string, string>();
const batchSize = 64;
let completed = 0;
for (let offset = 0; offset < unique.length; offset += batchSize) {
const batch = unique.slice(offset, offset + batchSize);
const results = await Promise.all(batch.map((token) => verifyProtectedToken(token, candidate, keyText)));
results.forEach((matches, index) => {
if (matches) values.set(batch[index].token, candidate);
});
completed += batch.length;
onProgress?.({ completed, total: unique.length, matches: values.size });
await new Promise<void>((resolve) => setTimeout(resolve, 0));
}
return values;
}
/** Accept hex, standard base64, or unpadded base64url without persisting it. */
export function decodeKey(text: string): Uint8Array {
const compact = text.trim();
if (/^(?:[0-9a-fA-F]{2})+$/.test(compact)) {
return Uint8Array.from(compact.match(/.{2}/g) ?? [], (part) => Number.parseInt(part, 16));
}
return base64UrlBytes(compact.replaceAll("+", "-").replaceAll("/", "_").replace(/=+$/, ""));
}
function base64UrlBytes(value: string): Uint8Array {
Iif (!/^[A-Za-z0-9_-]*$/.test(value)) throw new Error("Invalid base64url data.");
const padded = value.replaceAll("-", "+").replaceAll("_", "/") + "=".repeat((4 - value.length % 4) % 4);
let binary: string;
try {
binary = atob(padded);
} catch {
throw new Error("Invalid base64url data.");
}
return Uint8Array.from(binary, (char) => char.charCodeAt(0));
}
function arrayBuffer(value: Uint8Array): ArrayBuffer {
return value.slice().buffer as ArrayBuffer;
}
|