diff --git a/scripts/verify/architecture-guards.mjs b/scripts/verify/architecture-guards.mjs index dcb2e2df7b..b53deb9771 100644 --- a/scripts/verify/architecture-guards.mjs +++ b/scripts/verify/architecture-guards.mjs @@ -212,7 +212,7 @@ check( ], ); -// "Non-null object other than an array" has one owner: src/domain/isRecord.ts. +// "Non-null object other than an array" has one owner: src/kernel/isRecord.ts. // A local predicate with that body, under any name, is a copy. The listed files // still hold one and may only be removed from the list; a listed file that no // longer matches fails so the list shrinks with the code. @@ -230,7 +230,7 @@ const RECORD_PREDICATE_COPIES = [ "src/pcap/PcapOutput.ts", ]; const mismatchedRecordCopies = files.filter(({ path, content }) => { - if (path === "src/domain/isRecord.ts") return false; + if (path === "src/kernel/isRecord.ts") return false; const { named, bodies } = recordPredicateCounts(content); return ( named !== 0 || bodies !== (RECORD_PREDICATE_COPIES.includes(path) ? 1 : 0) @@ -559,6 +559,24 @@ checkCounted( ["src/kernel/sha256Hex.ts"], ); +// The isRecord predicate written inline in a condition is a copy of +// src/kernel/isRecord.ts. Bodies of the named copies in RECORD_PREDICATE_COPIES +// are counted by that list, not here. +const inlineRecordCheck = + /typeof\s+([A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*)*)\s*===\s*["']object["']\s*&&\s*\1\s*!==\s*null\s*&&\s*!Array\.isArray\(\s*\1\s*\)/gu; +checkCounted( + "inline non-array record check (use isRecord from src/kernel/isRecord)", + "inline-record-check", + files, + (content) => + Math.max( + 0, + (content.match(inlineRecordCheck)?.length ?? 0) - + recordPredicateCounts(content).bodies, + ), + ["src/kernel/isRecord.ts"], +); + // Strict UTF-8 decoding has one owner, src/domain/strictUtf8.ts, which makes // each site state its byte-order-mark policy. A local fatal decoder silently // strips a leading BOM unless it remembers ignoreBOM. The pattern matches the diff --git a/scripts/verify/baselines/inline-sha256-hex.json b/scripts/verify/baselines/inline-sha256-hex.json deleted file mode 100644 index ae2c398ea7..0000000000 --- a/scripts/verify/baselines/inline-sha256-hex.json +++ /dev/null @@ -1,71 +0,0 @@ -{ - "src/adb/AdbProvider.ts": 1, - "src/android/AndroidJniLibraries.ts": 2, - "src/apkSignature/apkCertificateFacts.ts": 1, - "src/application/GuidanceAccess.ts": 1, - "src/application/LinuxHopperPublisher.ts": 2, - "src/application/PublishWebScripts.ts": 1, - "src/application/ReferenceSourceImportEntries.ts": 1, - "src/application/SetupRecoveryBackup.ts": 1, - "src/application/ValidateSelectedWebScript.ts": 1, - "src/application/WebScriptExportService.ts": 1, - "src/application/WebSourceLocationService.ts": 1, - "src/application/decompileDirectory/exportTree.ts": 2, - "src/application/desktop/DesktopBuildWitness.ts": 1, - "src/application/desktop/DesktopBuildWitnessRecord.ts": 1, - "src/application/desktop/DesktopExportFiles.ts": 1, - "src/application/desktop/DesktopExportWithheld.ts": 1, - "src/application/desktop/DesktopRetainedContent.ts": 1, - "src/application/environment/environmentBundleWrite.ts": 1, - "src/application/javascript/JavaScriptArtifactAnalysis.ts": 1, - "src/application/javascript/JavaScriptArtifactGraphFindings.ts": 1, - "src/artifacts/DesktopFileInspection.ts": 1, - "src/artifacts/apple/InterfaceBuilderAnalysis.ts": 1, - "src/artifacts/apple/KeyedArchiveReader.ts": 1, - "src/artifacts/javascript/JavaScriptArtifactFiles.ts": 1, - "src/artifacts/nodeSea/NodeSeaLocation.ts": 1, - "src/browser/CdpCaptureStorageFingerprints.ts": 1, - "src/browser/CdpWebMcpDiscovery.ts": 1, - "src/browser/PlaywrightElectronActiveProvider.ts": 1, - "src/browser/PlaywrightScenarioArtifacts.ts": 2, - "src/browser/WebSourceMapFetcher.ts": 1, - "src/browser/history/HarCapture.ts": 1, - "src/browser/history/SazProjection.ts": 1, - "src/browser/history/protobuf/ProtobufCapture.ts": 1, - "src/browser/network/PlaywrightNetworkContent.ts": 1, - "src/cutter/CutterBridgeSource.ts": 1, - "src/desktop/AgentEnvComputer.ts": 1, - "src/desktop/BuildComputerController.ts": 1, - "src/desktop/DesktopContentStore.ts": 1, - "src/desktop/GpgvKeyCheck.ts": 1, - "src/dotnet/ManagedSnapshot.ts": 1, - "src/erlang/BeamParser.ts": 1, - "src/evm/EvmoleInterfaceProvider.ts": 1, - "src/evm/EvmoleInterfaceWorker.ts": 1, - "src/firmware/FirmwarePublication.ts": 1, - "src/frida/FridaInstrumentationManager.ts": 3, - "src/ghidra/GhidraAnalysisSeeds.ts": 1, - "src/ghidra/GhidraCheckpoint.ts": 1, - "src/ghidra/GhidraExecutableHeader.ts": 1, - "src/ghidra/GhidraInstallationProperties.ts": 1, - "src/ghidra/GhidraLoadImageValues.ts": 1, - "src/ghidra/extensions/GhidraExtensions.ts": 2, - "src/gpu/GpuSource.ts": 1, - "src/inspector/V8InspectorCaptureProjection.ts": 1, - "src/javascript/analysis/JavaScriptAnalysisWorker.ts": 2, - "src/javascript/analysis/JavaScriptAnalysisWorkerServer.ts": 2, - "src/javascript/recovery/RecoveryFiles.ts": 1, - "src/javascript/sourceMaps/TraceSourceMap.ts": 2, - "src/kuna/KunaProjectCache.ts": 1, - "src/kuna/KunaProjectExport.ts": 1, - "src/kuna/KunaReferenceFiles.ts": 1, - "src/main/deferredRuntime.ts": 1, - "src/native/AppleDispatchMetadata.ts": 1, - "src/native/elf/ElfNoteParser.ts": 1, - "src/native/elf/KernelModuleParser.ts": 1, - "src/native/pe/PeCertificateParser.ts": 1, - "src/native/windows/WindowsShortcutParser.ts": 1, - "src/python/PythonPycParser.ts": 1, - "src/v8/V8CodeCacheParser.ts": 1, - "src/wasm/WabtArtifactProvider.ts": 1 -} diff --git a/scripts/verify/managed/manifest-parser.mjs b/scripts/verify/managed/manifest-parser.mjs index 2628cffdcc..cc590e2991 100644 --- a/scripts/verify/managed/manifest-parser.mjs +++ b/scripts/verify/managed/manifest-parser.mjs @@ -1,4 +1,4 @@ -import { isRecord } from "#dist/domain/isRecord.js"; +import { isRecord } from "#dist/kernel/isRecord.js"; /** @typedef {ReturnType} ManagedAppManifest */ /** @typedef {ManagedAppManifest["methods"][number]} ManagedAppManifestMethod */ diff --git a/src/adb/AdbProvider.ts b/src/adb/AdbProvider.ts index 1276969853..bc9c89a506 100644 --- a/src/adb/AdbProvider.ts +++ b/src/adb/AdbProvider.ts @@ -12,7 +12,6 @@ import { adbInputFileError, } from "./AdbFilesystemAdmission.js"; import { analysisClientFailureForOperation } from "../providers/AnalysisClientFailure.js"; -import { createHash } from "node:crypto"; import { constants as fsConstants } from "node:fs"; import { access, @@ -161,6 +160,7 @@ import { type AdbCommandContext, } from "./AdbDeviceOperations.js"; import { errorMessage } from "../kernel/errorMessage.js"; +import { sha256Hex } from "../kernel/sha256Hex.js"; const SHELL_TIMEOUT_MS = 30_000; const PACKAGE_LIST_TIMEOUT_MS = 60_000; @@ -3052,9 +3052,7 @@ export class AdbProvider { ), ); } - const sha256 = createHash("sha256") - .update(captured.value.stdout) - .digest("hex"); + const sha256 = sha256Hex(captured.value.stdout); const completed = createAnalysisExecution( { client, diff --git a/src/android/AndroidJniLibraries.ts b/src/android/AndroidJniLibraries.ts index 1eafb9f410..a318a2f35c 100644 --- a/src/android/AndroidJniLibraries.ts +++ b/src/android/AndroidJniLibraries.ts @@ -1,4 +1,3 @@ -import { createHash } from "node:crypto"; import { ArtifactReaderFailure, type ArtifactResourceScope, @@ -24,6 +23,7 @@ import { ProviderCleanupError } from "../domain/providerCleanupError.js"; import { analysisErrorWithCleanupFailure } from "../domain/analysisErrorCleanup.js"; import { analysisClientFailureForOperation } from "../providers/AnalysisClientFailure.js"; import { errorMessage } from "../kernel/errorMessage.js"; +import { sha256Hex } from "../kernel/sha256Hex.js"; import { invariantViolation } from "../domain/internalInvariant.js"; /** Bounds cover the live library buffer, completed scan work and retained JSON separately. */ @@ -116,9 +116,7 @@ export const readAndroidJniLibraries = async (input: { break; } const identity = { - library_id: `jni_library_${createHash("sha256") - .update(JSON.stringify([input.apkSha256, entry.adapterKey])) - .digest("hex")}`, + library_id: `jni_library_${sha256Hex(JSON.stringify([input.apkSha256, entry.adapterKey]))}`, source_index, source_key: entry.adapterKey, path: entry.path, @@ -191,7 +189,7 @@ export const readAndroidJniLibraries = async (input: { { integrityCheck: "declared-size" }, ); throwIfJadxInterrupted(input.signal); - const sha256 = createHash("sha256").update(bytes).digest("hex"); + const sha256 = sha256Hex(bytes); inProgress = { ...identity, sha256, diff --git a/src/apkSignature/apkCertificateFacts.ts b/src/apkSignature/apkCertificateFacts.ts index d4cedbc1ac..3736eb15f3 100644 --- a/src/apkSignature/apkCertificateFacts.ts +++ b/src/apkSignature/apkCertificateFacts.ts @@ -3,17 +3,14 @@ * v3/v3.1, lineage nodes and source stamps): identity is SHA-256 over the raw * embedded DER, and the readable X.509 facts come from the platform parser. */ -import { createHash, X509Certificate } from "node:crypto"; +import { X509Certificate } from "node:crypto"; import type { ApkSignatureResult } from "../domain/apkSignature/apkSignatureReport.js"; +import { sha256Hex } from "../kernel/sha256Hex.js"; export type Certificate = ApkSignatureResult["schemes"]["v2"]["signers"][number]["certificate"]; -/** SHA-256 over the raw embedded DER — exactly what apksig/apksigner hash. */ -const derFingerprint = (der: Uint8Array): string => - createHash("sha256").update(der).digest("hex"); - /** Each fact is read independently so one unsupported field does not hide the rest. */ const attempt = (read: () => T): T | null => { try { @@ -34,7 +31,7 @@ export const certificateFacts = (der: Uint8Array): NonNullable => { return parsed.raw.equals(Buffer.from(der)) ? parsed : null; }); return { - sha256_fingerprint: derFingerprint(der), + sha256_fingerprint: sha256Hex(der), subject: cert?.subject ?? null, issuer: cert?.issuer ?? null, serial_number: cert?.serialNumber ?? null, diff --git a/src/application/ClientConfigurationFiles.ts b/src/application/ClientConfigurationFiles.ts index dc7632735f..b9a614a4f2 100644 --- a/src/application/ClientConfigurationFiles.ts +++ b/src/application/ClientConfigurationFiles.ts @@ -16,7 +16,7 @@ import type { ArtifactResourceScope } from "../resources/index.js"; import type { ConfigurationError } from "../domain/configurationErrors.js"; import { mergeEnvironmentOverrides } from "../process/snapshotEnvironment.js"; import { PRODUCT_IDENTITY } from "../identity.js"; -import { isRecord } from "../domain/isRecord.js"; +import { isRecord } from "../kernel/isRecord.js"; import { errorMessage } from "../kernel/errorMessage.js"; /** diff --git a/src/application/DirectAnalysisCleanup.ts b/src/application/DirectAnalysisCleanup.ts index b8ac2646b4..9f6c71c58e 100644 --- a/src/application/DirectAnalysisCleanup.ts +++ b/src/application/DirectAnalysisCleanup.ts @@ -21,6 +21,7 @@ import { } from "../domain/analysisErrorCleanup.js"; import { withEvidenceCallerInputPath } from "../domain/evidence.js"; import { recognizeEvidence } from "../domain/evidenceValidation.js"; +import { isRecord } from "../kernel/isRecord.js"; /** * Project a one-shot failure for its invocation, which has released its @@ -38,11 +39,7 @@ export const projectDirectAnalysisFailure = ( ): ReturnType => { const projection = projectInvocationFailure(error); const partial = projection.details?.partial_observation; - const wrapped = - typeof partial === "object" && - partial !== null && - !Array.isArray(partial) && - partial.kind === "unretained-evidence"; + const wrapped = isRecord(partial) && partial.kind === "unretained-evidence"; // Only authenticated Evidence gains the request path; a record that fails // authentication is projected as the owner reported it, never as absent. const observation = recognizeEvidence(wrapped ? partial.evidence : partial); diff --git a/src/application/DshCordisPatch.ts b/src/application/DshCordisPatch.ts index b56afc52a0..a987d965c2 100644 --- a/src/application/DshCordisPatch.ts +++ b/src/application/DshCordisPatch.ts @@ -6,16 +6,14 @@ import { err, ok, type Result } from "../domain/result.js"; import type { ClientConfigurationDocument } from "./ClientConfigurationDocument.js"; import { CordisExpression, DshCordisYaml } from "./DshCordisYaml.js"; import { mergeEnvironmentOverrides } from "../process/snapshotEnvironment.js"; +import { isRecord } from "../kernel/isRecord.js"; export const DSH_ENTRY_ID = "rea-mcp"; export const DSH_CLIENT_PACKAGE = "@deepseek-ai/dsh-mcp-client"; const LAUNCHER_KEYS = new Set(["serverName", "transport", "command", "args"]); const SELECTOR_KEYS = new Set(["id", "name"]); const isPatchRecord = (value: unknown): value is Record => - typeof value === "object" && - value !== null && - !Array.isArray(value) && - !(value instanceof CordisExpression); + isRecord(value) && !(value instanceof CordisExpression); interface PatchOperation { readonly source: unknown; diff --git a/src/application/GuidanceAccess.ts b/src/application/GuidanceAccess.ts index ec58614653..6eaf42c9c0 100644 --- a/src/application/GuidanceAccess.ts +++ b/src/application/GuidanceAccess.ts @@ -1,5 +1,4 @@ import { boundedList, type BoundedList } from "../domain/boundedList.js"; -import { createHash } from "node:crypto"; import { fileURLToPath } from "node:url"; import type { z } from "zod"; import { @@ -30,14 +29,12 @@ import { parseGuidanceSections, type GuideSection, } from "./GuidanceSections.js"; +import { sha256Hex } from "../kernel/sha256Hex.js"; const SKILL_ROOT = `../../skills/${PRODUCT_IDENTITY.skillName}/`; const SOURCE = "installed_rea_guidance" as const; const MAX_GUIDE_FILE_BYTES = 1_048_576; const MAX_GUIDE_BUNDLE_BYTES = 4_194_304; -const sha256 = (value: string | Uint8Array): string => - createHash("sha256").update(value).digest("hex"); - interface GuidanceBundle { readonly digest: string; readonly sections: readonly GuideSection[]; @@ -115,9 +112,9 @@ const readBundle = async ( "Installed REA guidance is missing or unreadable; no complete bundle could be indexed.", }; } - const digest = sha256( + const digest = sha256Hex( [...files] - .map(([path, content]) => `${path}\0${sha256(content)}\n`) + .map(([path, content]) => `${path}\0${sha256Hex(content)}\n`) .join(""), ); const sections = parseGuidanceSections(files); @@ -195,7 +192,7 @@ const sectionLocator = ( bundle: bundle.digest, guide: section.guide, ordinal: section.ordinal, - section: sha256(section.content), + section: sha256Hex(section.content), }); return `rea-guide-v1.${Buffer.from(identity).toString("base64url")}`; }; @@ -297,7 +294,7 @@ const searchGuidanceInScope = async ( message: "Invalid guidance continuation token", }, ]); - const queryDigest = sha256(parsed.data.query); + const queryDigest = sha256Hex(parsed.data.query); if (cursor !== undefined && cursor.query !== queryDigest) return invalidInput("search_guidance", input, [ { @@ -626,7 +623,7 @@ const readGuidanceSectionInScope = async ( (candidate) => candidate.guide === identity.guide && candidate.ordinal === identity.ordinal && - sha256(candidate.content) === identity.section, + sha256Hex(candidate.content) === identity.section, ); if (section === undefined) return ok( diff --git a/src/application/HermesConfigurationYaml.ts b/src/application/HermesConfigurationYaml.ts index a91a41db91..e565e5532b 100644 --- a/src/application/HermesConfigurationYaml.ts +++ b/src/application/HermesConfigurationYaml.ts @@ -26,6 +26,7 @@ import { retainYamlScalarSource, yamlNumericValuesEqual, } from "./YamlConfigurationSource.js"; +import { isRecord } from "../kernel/isRecord.js"; const SOURCE_SCALAR_TAGS = new Set([ "tag:yaml.org,2002:int", @@ -434,9 +435,7 @@ export const editHermesConfigurationYaml = ( ? "absent" : projectedYamlValue(document, path); if ( - typeof value === "object" && - value !== null && - !Array.isArray(value) && + isRecord(value) && inheritedRegistration !== "absent" && typeof inheritedRegistration.value === "object" && inheritedRegistration.value !== null && diff --git a/src/application/LinuxHopperPublisher.ts b/src/application/LinuxHopperPublisher.ts index 007c25edf5..ce383c78b6 100644 --- a/src/application/LinuxHopperPublisher.ts +++ b/src/application/LinuxHopperPublisher.ts @@ -1,4 +1,4 @@ -import { createHash, randomUUID } from "node:crypto"; +import { randomUUID } from "node:crypto"; import { copyFile, lstat, mkdir, rename, writeFile } from "node:fs/promises"; import { join } from "node:path"; import { appendCallerPath } from "../filesystem/callerPath.js"; @@ -53,6 +53,7 @@ import { } from "./HopperReleaseFeed.js"; import { withRegularFile } from "../process/RegularFileRead.js"; import { decodeStrictUtf8 } from "../domain/strictUtf8.js"; +import { sha256Hex } from "../kernel/sha256Hex.js"; /** Metadata/key inspection budget, independent of the compressed package budget. */ const RELEASE_METADATA_BYTES = 1024 * 1024; @@ -197,20 +198,18 @@ export class LinuxHopperPublisher { }); publicKey = decodeUtf8(response.value); } - const packageSha256 = createHash("sha256").update(bytes).digest("hex"); + const packageSha256 = sha256Hex(bytes); // Every read still validates file identity, byte bounds and selected metadata. // Reuse only proof of the exact signed bytes/key/signature/payload interpretation. - const proofKey = createHash("sha256") - .update( - JSON.stringify([ - family, - packageSha256, - publicKey, - release.signature, - release.main_exe_hash, - ]), - ) - .digest("hex"); + const proofKey = sha256Hex( + JSON.stringify([ + family, + packageSha256, + publicKey, + release.signature, + release.main_exe_hash, + ]), + ); signal?.throwIfAborted(); const existingProof = packageProofs.get(proofKey); if (existingProof !== undefined) diff --git a/src/application/PublishWebScripts.ts b/src/application/PublishWebScripts.ts index f6a160e406..400bc6cee6 100644 --- a/src/application/PublishWebScripts.ts +++ b/src/application/PublishWebScripts.ts @@ -1,4 +1,3 @@ -import { createHash } from "node:crypto"; import { join } from "node:path"; import { Readable } from "node:stream"; @@ -31,6 +30,7 @@ import { } from "../domain/webScriptExportPlan.js"; import { WebScriptExportError } from "../domain/webScriptExportError.js"; import type { SelectedScriptCapture } from "../domain/webScriptCaptureAdapters.js"; +import { sha256Hex } from "../kernel/sha256Hex.js"; const LIMITATIONS = [ "Only script bytes retained in this capture are exported. Sources are not refetched or executed, and a response or Debugger source does not prove execution.", @@ -112,7 +112,7 @@ export const publishWebScripts = async ( ], }); const bytes = Buffer.from(`${JSON.stringify(manifest, null, 2)}\n`); - const digest = createHash("sha256").update(bytes).digest("hex"); + const digest = sha256Hex(bytes); result = webScriptExportResultSchema.parse({ ...manifest, manifest: { diff --git a/src/application/ReferenceSourceImportEntries.ts b/src/application/ReferenceSourceImportEntries.ts index ddcd179f5f..a7cd80e55e 100644 --- a/src/application/ReferenceSourceImportEntries.ts +++ b/src/application/ReferenceSourceImportEntries.ts @@ -1,6 +1,5 @@ import type { JavaScriptMemberMutationAllowance } from "../domain/javascript/javascriptSemanticWorkAllowance.js"; import { err, ok, type Result } from "../domain/result.js"; -import { createHash } from "node:crypto"; import { posix } from "node:path"; import type { JavaScriptPackageType } from "../domain/javascript/javascriptSourceParser.js"; @@ -28,6 +27,7 @@ import type { import { typescriptEmittedSourceCandidates } from "./TypeScriptEmittedSourceCandidates.js"; import { appendAll } from "../domain/appendAll.js"; import { decodeStrictUtf8 } from "../domain/strictUtf8.js"; +import { sha256Hex } from "../kernel/sha256Hex.js"; export interface ParsedReferenceSourceEntries { readonly entries: HistoricalSourceGraphInput["entries"]; @@ -57,9 +57,6 @@ const entryRecoveryGuidance = ( return "This file could not be read. Check its permissions, then try again."; }; -const hashBytes = (bytes: Uint8Array): string => - createHash("sha256").update(bytes).digest("hex"); - const failedEntry = ( entry: Extract, ): HistoricalSourceGraphInput["entries"][number] => { @@ -563,7 +560,7 @@ const appendFile = ( output.entries.push({ path: entry.path, kind: "file", - sha256: hashBytes(entry.bytes), + sha256: sha256Hex(entry.bytes), size: entry.size, language, classifications: classifyReferenceSourcePath(entry.path), diff --git a/src/application/SetupClientConfiguration.ts b/src/application/SetupClientConfiguration.ts index 47db19e6e7..32c19c99fd 100644 --- a/src/application/SetupClientConfiguration.ts +++ b/src/application/SetupClientConfiguration.ts @@ -85,6 +85,7 @@ import { type SetupClient, } from "./SupportedClients.js"; import { errorMessage } from "../kernel/errorMessage.js"; +import { isRecord } from "../kernel/isRecord.js"; export class ClientConfigurationCleanupRollbackFailure extends RegularFileCleanupFailure { constructor( @@ -1138,9 +1139,7 @@ const registrationOwnershipBlocker = ( const inheritsLauncher = effective !== undefined && effective !== parsed && - typeof fragment === "object" && - fragment !== null && - !Array.isArray(fragment) && + isRecord(fragment) && !Object.hasOwn(fragment, "command"); if (Object.hasOwn(parsed.servers, name) && !inheritsLauncher) entries.push({ value: parsed.servers[name], paths: [client.configPath] }); diff --git a/src/application/SetupRecoveryBackup.ts b/src/application/SetupRecoveryBackup.ts index db4e679711..f8fa449027 100644 --- a/src/application/SetupRecoveryBackup.ts +++ b/src/application/SetupRecoveryBackup.ts @@ -1,4 +1,3 @@ -import { createHash } from "node:crypto"; import { constants as fsConstants } from "node:fs"; import { copyFile } from "node:fs/promises"; import { err, ok, type Result } from "../domain/result.js"; @@ -6,6 +5,7 @@ import { RegularFileCleanupFailure } from "../filesystem/OwnedRegularFile.js"; import { readRegularFile } from "../process/RegularFileRead.js"; import type { ArtifactResourceScope } from "../resources/index.js"; import { errorMessage } from "../kernel/errorMessage.js"; +import { sha256Hex } from "../kernel/sha256Hex.js"; export interface RecoveryBackupSelection { readonly backupPath: string; @@ -52,7 +52,7 @@ export const selectCurrentRecoveryBackup = async ( if (firstBackup.equals(expected)) return ok({ backupPath: firstBackupPath, present: true }); - const digest = createHash("sha256").update(expected).digest("hex"); + const digest = sha256Hex(expected); const recoveryPath = `${firstBackupPath}.${digest}.recovery`; let recovery: Buffer | undefined; try { diff --git a/src/application/ValidateSelectedWebScript.ts b/src/application/ValidateSelectedWebScript.ts index e16ce43c82..82d18f6715 100644 --- a/src/application/ValidateSelectedWebScript.ts +++ b/src/application/ValidateSelectedWebScript.ts @@ -1,4 +1,3 @@ -import { createHash } from "node:crypto"; import type { AnalysisError } from "../domain/analysisErrorBase.js"; import { AnalysisOutputError } from "../domain/analysisErrorCore.js"; import { err, ok, type Result } from "../domain/result.js"; @@ -7,6 +6,7 @@ import type { SelectedWebScriptInput, } from "../domain/webScriptArtifacts.js"; import type { ExportedWebScript } from "../domain/webScriptExport.js"; +import { sha256Hex } from "../kernel/sha256Hex.js"; /** Bind actual source text to the selected manifest entry before analysis. */ export const validateSelectedWebScript = ( @@ -21,8 +21,7 @@ export const validateSelectedWebScript = ( selected.content.sha256 !== data.sourceFile.sha256 || selected.content.bytes !== data.sourceFile.bytes || Buffer.byteLength(data.source) !== data.sourceFile.bytes || - createHash("sha256").update(data.source, "utf8").digest("hex") !== - data.sourceFile.sha256 || + sha256Hex(data.source) !== data.sourceFile.sha256 || data.manifestFile.path !== input.manifest_path ) return err( diff --git a/src/application/WebScriptExportService.ts b/src/application/WebScriptExportService.ts index 7dc7bf692b..c3fe4b3ec8 100644 --- a/src/application/WebScriptExportService.ts +++ b/src/application/WebScriptExportService.ts @@ -1,5 +1,4 @@ import { decodeStrictUtf8 } from "../domain/strictUtf8.js"; -import { createHash } from "node:crypto"; import { z } from "zod"; @@ -50,6 +49,7 @@ import { regularFileCancellation, } from "../filesystem/OwnedRegularFile.js"; import { errorMessage } from "../kernel/errorMessage.js"; +import { sha256Hex } from "../kernel/sha256Hex.js"; const OPERATION = "export_web_scripts"; @@ -100,7 +100,7 @@ export const exportWebScriptsValidated = async ( const { bytes, loaded } = prepared.value; if (options.signal?.aborted) return err(cancelledBy(OPERATION, options.signal)); - const sha256 = createHash("sha256").update(bytes).digest("hex"); + const sha256 = sha256Hex(bytes); const result = await publishWebScripts(input, loaded, sha256, { resources, ...(options.signal === undefined ? {} : { signal: options.signal }), diff --git a/src/application/WebSourceLocationService.ts b/src/application/WebSourceLocationService.ts index c82028851f..0d0b94e3a2 100644 --- a/src/application/WebSourceLocationService.ts +++ b/src/application/WebSourceLocationService.ts @@ -4,7 +4,6 @@ import { } from "../domain/sourceMapLimits.js"; import { WEB_SOURCE_LOCATION_PROVIDER } from "../domain/webTraceProviders.js"; import { closeOwnedWebResources } from "./closeOwnedWebResources.js"; -import { createHash } from "node:crypto"; import { z } from "zod"; import { primaryAnalysisError, @@ -42,6 +41,7 @@ import type { } from "../ports/WebSourceLocationPorts.js"; import { completeProviderEvidence } from "./ProviderOperationExecution.js"; import { parseAnalysisInput } from "./AnalysisInput.js"; +import { sha256Hex } from "../kernel/sha256Hex.js"; const OPERATION = "trace_web_source_location"; const artifactsSchema = selectedWebScriptArtifactsSchema.extend({ @@ -293,7 +293,7 @@ const verifyPairing = ( map.file.path !== input.source_map.path || map.url !== input.source_map.url || Buffer.byteLength(map.text) !== map.file.bytes || - createHash("sha256").update(map.text).digest("hex") !== map.file.sha256 || + sha256Hex(map.text) !== map.file.sha256 || map.file.bytes > selectedSourceMapLimits(input.source_map_limits).mapBytes ) return invalidOutput( diff --git a/src/application/analysisView/evidenceFileSource.ts b/src/application/analysisView/evidenceFileSource.ts index 0a9b4ec7eb..0930782dbd 100644 --- a/src/application/analysisView/evidenceFileSource.ts +++ b/src/application/analysisView/evidenceFileSource.ts @@ -19,6 +19,7 @@ import { isUnsupportedEvidenceFormat } from "../../domain/evidenceFormat.js"; import { EvidenceFileError } from "../../domain/evidenceErrors.js"; import { projectInputIssuesBounded } from "../../domain/inputIssueProjection.js"; import { readJsonFile } from "../JsonFiles.js"; +import { isRecord } from "../../kernel/isRecord.js"; /** The request cancellation and the scope retaining descriptors whose close failed. */ export interface EvidenceFileReadOptions { @@ -167,12 +168,7 @@ export const readEvidenceFileSource = async ( if (!loaded.ok) return loaded; if (signal?.aborted) return err(cancelledBy(operation, signal)); const value = loaded.value; - if ( - typeof value === "object" && - value !== null && - !Array.isArray(value) && - Object.hasOwn(value, "records") - ) { + if (isRecord(value) && Object.hasOwn(value, "records")) { const bundle = authenticateEvidenceBundleValue(value, path, { operation, immutable: true, diff --git a/src/application/decompileDirectory/exportTree.ts b/src/application/decompileDirectory/exportTree.ts index 37c4d17582..d476e0ce96 100644 --- a/src/application/decompileDirectory/exportTree.ts +++ b/src/application/decompileDirectory/exportTree.ts @@ -1,5 +1,5 @@ import { decodeStrictUtf8 } from "../../domain/strictUtf8.js"; -import { createHash, randomUUID } from "node:crypto"; +import { randomUUID } from "node:crypto"; import { constants } from "node:fs"; import { chmod, @@ -48,6 +48,7 @@ import type { RetainedResourceScope } from "../../ports/AnalysisProvider.js"; import { ExportResources } from "./exportResources.js"; import { decompileInputError } from "./inputError.js"; import { compareProcedureAddresses } from "./selection.js"; +import { sha256Hex } from "../../kernel/sha256Hex.js"; export interface ExportIdentity { readonly targetSha256: string | null; @@ -436,7 +437,7 @@ const commitFunctionFile = async ( if (!isDecompileFunctionRelativePath(relativePath)) return { status: "io" }; const finalPath = join(root, relativePath); if (!isPathWithinRoot(root, finalPath)) return { status: "io" }; - const digest = sha256(bytes); + const digest = sha256Hex(bytes); const linked = await resources.publish(bytes, finalPath, "link").then( () => true, (cause: unknown) => cause, @@ -907,7 +908,7 @@ const allocateFunctionPath = ( const directory = DECOMPILE_DIRECTORY_FUNCTIONS_DIRECTORY; const plain = `${directory}/${base}.c`; if (!used.has(portablePathKey(plain))) return plain; - const suffix = createHash("sha256").update(address).digest("hex").slice(0, 8); + const suffix = sha256Hex(address).slice(0, 8); let candidate = `${directory}/${base}-${suffix}.c`; let discriminator = 0; // Terminates: `used` is finite. @@ -1115,9 +1116,6 @@ export const exportOutputFailure = ( return error; }; -export const sha256 = (bytes: Buffer): string => - createHash("sha256").update(bytes).digest("hex"); - const isFileHandle = (value: unknown): value is FileHandle => typeof value === "object" && value !== null && diff --git a/src/application/desktop/DesktopApplicationExport.ts b/src/application/desktop/DesktopApplicationExport.ts index 4852ac233f..2e69d448f6 100644 --- a/src/application/desktop/DesktopApplicationExport.ts +++ b/src/application/desktop/DesktopApplicationExport.ts @@ -79,7 +79,7 @@ import { type TaskSummary, } from "./DesktopTaskExport.js"; import { taskReads } from "./DesktopExportReaders.js"; -import { isRecord } from "../../domain/isRecord.js"; +import { isRecord } from "../../kernel/isRecord.js"; const OPERATION = "export_desktop_application"; /** Largest seed file the export copies; the state view reads only 64 MiB. */ diff --git a/src/application/desktop/DesktopApplicationState.ts b/src/application/desktop/DesktopApplicationState.ts index 0f30fdf896..9325ded9db 100644 --- a/src/application/desktop/DesktopApplicationState.ts +++ b/src/application/desktop/DesktopApplicationState.ts @@ -71,6 +71,7 @@ import { DESKTOP_PROVIDER, desktopOperationFailure, } from "./DesktopCaptureRefusals.js"; +import { isRecord } from "../../kernel/isRecord.js"; const OPERATION = "inspect_desktop_application_state"; @@ -435,9 +436,7 @@ const hasDconfGroups = (version: Version): boolean => { const view = version.view; return ( version.format === "dconf" && - typeof view === "object" && - view !== null && - !Array.isArray(view) && + isRecord(view) && typeof view.groups === "object" && view.groups !== null && Object.keys(view.groups).length > 0 diff --git a/src/application/desktop/DesktopBuildWitness.ts b/src/application/desktop/DesktopBuildWitness.ts index d4168bdb8e..737ae03a7d 100644 --- a/src/application/desktop/DesktopBuildWitness.ts +++ b/src/application/desktop/DesktopBuildWitness.ts @@ -1,4 +1,4 @@ -import { createHash, randomUUID } from "node:crypto"; +import { randomUUID } from "node:crypto"; import { z } from "zod"; @@ -55,6 +55,7 @@ import { type WitnessRecord, } from "./DesktopBuildWitnessRecord.js"; import { errorMessage } from "../../kernel/errorMessage.js"; +import { sha256Hex } from "../../kernel/sha256Hex.js"; const CHECK = "check_build_task"; const FRESH = @@ -100,8 +101,7 @@ const refused = (userMessage: string, remediationAction: string) => conformsToInputContract: true, }); -const taskDigest = (task: DesktopTask) => - createHash("sha256").update(JSON.stringify(task)).digest("hex"); +const taskDigest = (task: DesktopTask) => sha256Hex(JSON.stringify(task)); /** A retry cannot redirect an ended witness to another folder. */ const recordDirectoryRefusal = ( diff --git a/src/application/desktop/DesktopBuildWitnessRecord.ts b/src/application/desktop/DesktopBuildWitnessRecord.ts index d0b255026e..9aca7d0ca6 100644 --- a/src/application/desktop/DesktopBuildWitnessRecord.ts +++ b/src/application/desktop/DesktopBuildWitnessRecord.ts @@ -1,5 +1,4 @@ import { unknownTarget } from "../../domain/targetIdentity.js"; -import { createHash } from "node:crypto"; import { join } from "node:path"; import { Readable } from "node:stream"; @@ -33,6 +32,7 @@ import { desktopOutputFailure, } from "./DesktopOutputTree.js"; import { errorMessage } from "../../kernel/errorMessage.js"; +import { sha256Hex } from "../../kernel/sha256Hex.js"; const CHECK = "check_build_task"; const RECORD = "witness.json"; @@ -83,9 +83,6 @@ export interface EndedWitness { readonly stages: WitnessStageRecord[]; } -const sha256 = (bytes: Buffer) => - createHash("sha256").update(bytes).digest("hex"); - /** A recording fetch that can resume after the manifest is known. */ type RecordingFetch = | { @@ -129,7 +126,7 @@ const fetchRecording = async ( segment.path.split("/").at(-1) ?? segment.path, ), bytes: segment.bytes.length, - sha256: sha256(segment.bytes), + sha256: sha256Hex(segment.bytes), })), }, }; @@ -161,7 +158,7 @@ const writeRecordFolder = async ( await tree.write( file.path, Readable.from([file.bytes]), - { bytes: file.bytes.length, sha256: sha256(file.bytes) }, + { bytes: file.bytes.length, sha256: sha256Hex(file.bytes) }, signal, ); }, diff --git a/src/application/desktop/DesktopExportFiles.ts b/src/application/desktop/DesktopExportFiles.ts index 7451d4f0a1..1f9e87e6ed 100644 --- a/src/application/desktop/DesktopExportFiles.ts +++ b/src/application/desktop/DesktopExportFiles.ts @@ -4,7 +4,6 @@ import { desktopViewFileLimitMessage, type DesktopViewPolicy, } from "../../domain/desktop/desktopViewPolicy.js"; -import { createHash } from "node:crypto"; import { Readable } from "node:stream"; import type { SafeOutputTree } from "../../resources/index.js"; @@ -31,6 +30,7 @@ import { err } from "../../domain/result.js"; import { refuse } from "./DesktopExportInstall.js"; import type { RetainedContent } from "./DesktopRetainedContent.js"; import { readZipView } from "./DesktopZipView.js"; +import { sha256Hex } from "../../kernel/sha256Hex.js"; /** A file the export writes from bytes it made. */ export interface GeneratedFile { @@ -215,8 +215,7 @@ export const writeFiles = async ( Readable.from([bytes]), { bytes: bytes.length, - sha256: - shipped.sha256 ?? createHash("sha256").update(bytes).digest("hex"), + sha256: shipped.sha256 ?? sha256Hex(bytes), }, signal, ); diff --git a/src/application/desktop/DesktopExportWithheld.ts b/src/application/desktop/DesktopExportWithheld.ts index dcb8215a20..c888696d58 100644 --- a/src/application/desktop/DesktopExportWithheld.ts +++ b/src/application/desktop/DesktopExportWithheld.ts @@ -34,6 +34,8 @@ import { withRetainedContent, type RetainedContent, } from "./DesktopRetainedContent.js"; +import { sha256Hex } from "../../kernel/sha256Hex.js"; +import { isRecord } from "../../kernel/isRecord.js"; const OPERATION = "export_desktop_application"; /** Largest retained file read back, as the export reads seeds. */ @@ -187,15 +189,12 @@ const dconfKeys = ( version: DesktopStatePath["versions"][number] | undefined, ): ReadonlyMap => { const view = version?.present === true ? version.view : null; - const groups = - typeof view === "object" && view !== null && !Array.isArray(view) - ? view.groups - : undefined; + const groups = isRecord(view) ? view.groups : undefined; if (typeof groups !== "object" || groups === null || Array.isArray(groups)) return new Map(); return new Map( Object.entries(groups).flatMap(([group, keys]) => - typeof keys === "object" && keys !== null && !Array.isArray(keys) + isRecord(keys) ? Object.entries(keys).map( ([key, value]) => [`${group}/${key}`, JSON.stringify(value)] as const, @@ -280,7 +279,7 @@ const writeWithheldCopy = ( Readable.from([bytes]), { bytes: bytes.length, - sha256: createHash("sha256").update(bytes).digest("hex"), + sha256: sha256Hex(bytes), }, signal, ); diff --git a/src/application/desktop/DesktopRetainedContent.ts b/src/application/desktop/DesktopRetainedContent.ts index c5c6552945..78b506d5b4 100644 --- a/src/application/desktop/DesktopRetainedContent.ts +++ b/src/application/desktop/DesktopRetainedContent.ts @@ -1,5 +1,4 @@ import { DESKTOP_VIEW_DEFAULTS } from "../../domain/desktop/desktopViewPolicy.js"; -import { createHash } from "node:crypto"; import { join } from "node:path"; import { @@ -21,6 +20,7 @@ import { RegularFileCapacityError, readStableFileBytes, } from "../../filesystem/readStableFileBytes.js"; +import { sha256Hex } from "../../kernel/sha256Hex.js"; const MIB = 1024 * 1024; @@ -94,7 +94,7 @@ export class RetainedContent { else if (cause instanceof Error) return err("is missing or unreadable"); else throw cause; } - return createHash("sha256").update(bytes).digest("hex") === sha256 + return sha256Hex(bytes) === sha256 ? ok(bytes) : err("does not match its digest"); } diff --git a/src/application/environment/environmentBundleWrite.ts b/src/application/environment/environmentBundleWrite.ts index cd7242c5fa..f8f75d39a0 100644 --- a/src/application/environment/environmentBundleWrite.ts +++ b/src/application/environment/environmentBundleWrite.ts @@ -34,6 +34,7 @@ import type { WrittenBundleFile, } from "./environmentExport.js"; import { errorMessage } from "../../kernel/errorMessage.js"; +import { sha256Hex } from "../../kernel/sha256Hex.js"; /** * A host failure on one file the bundle writer was reading or writing. @@ -95,7 +96,7 @@ const writeBytes = async ( const written = await writingBundleFile(directory, relative, () => tree.write(relative, Readable.from([bytes]), { bytes: bytes.length, - sha256: createHash("sha256").update(bytes).digest("hex"), + sha256: sha256Hex(bytes), }), ); return { path: written.relativePath, bytes: written.bytesWritten }; diff --git a/src/application/environment/environmentCompareDiff.ts b/src/application/environment/environmentCompareDiff.ts index eb093c21f2..6a34eabdf8 100644 --- a/src/application/environment/environmentCompareDiff.ts +++ b/src/application/environment/environmentCompareDiff.ts @@ -24,7 +24,7 @@ import { translateValue, type IdMap, } from "./environmentCompareIds.js"; -import { isRecord } from "../../domain/isRecord.js"; +import { isRecord } from "../../kernel/isRecord.js"; export const DIFFERENCE_CATEGORIES = [ "status", diff --git a/src/application/environment/environmentCompareIds.ts b/src/application/environment/environmentCompareIds.ts index cb086f0be7..46fad00475 100644 --- a/src/application/environment/environmentCompareIds.ts +++ b/src/application/environment/environmentCompareIds.ts @@ -4,7 +4,7 @@ import type { BodyAddress } from "../../domain/analysisView/environmentStateWrit import { isUuid } from "../../domain/analysisView/environmentStateWriteValues.js"; import type { JsonValue } from "../../domain/jsonValue.js"; import type { ProbeToolCall } from "./environmentCompareMatch.js"; -import { isRecord } from "../../domain/isRecord.js"; +import { isRecord } from "../../kernel/isRecord.js"; /** Field names that hold an identifier: `id`, `uuid`, `guid`, or names ending in `id` or `_id`. */ export const ID_FIELD = /^(id|uuid|guid)$|(_id|Id|ID|_uuid|Uuid)$/u; diff --git a/src/application/environment/environmentStateFormAnswer.test.ts b/src/application/environment/environmentStateFormAnswer.test.ts index 97374407cd..2ae24d0983 100644 --- a/src/application/environment/environmentStateFormAnswer.test.ts +++ b/src/application/environment/environmentStateFormAnswer.test.ts @@ -14,14 +14,11 @@ import { } from "../../../tests/fixtures/environmentStateFormWrites.js"; import { servedFrom } from "../../../tests/fixtures/environmentStateServing.js"; import type { JsonValue } from "../../domain/jsonValue.js"; +import { isRecord } from "../../kernel/isRecord.js"; const field = (body: JsonValue | undefined, name: string): JsonValue[] => { if (!Array.isArray(body)) throw new Error("Expected a list body"); - return body.map((item) => - typeof item === "object" && item !== null && !Array.isArray(item) - ? (item[name] ?? null) - : null, - ); + return body.map((item) => (isRecord(item) ? (item[name] ?? null) : null)); }; describe("served creates and updates modelled on form recordings", () => { diff --git a/src/application/environment/environmentStateLaterReadsAnswer.test.ts b/src/application/environment/environmentStateLaterReadsAnswer.test.ts index 2df9af718f..cfb0f19f68 100644 --- a/src/application/environment/environmentStateLaterReadsAnswer.test.ts +++ b/src/application/environment/environmentStateLaterReadsAnswer.test.ts @@ -13,17 +13,14 @@ import { } from "../../../tests/fixtures/environmentStateLaterReads.js"; import { servedFrom } from "../../../tests/fixtures/environmentStateServing.js"; import type { JsonValue } from "../../domain/jsonValue.js"; +import { isRecord } from "../../kernel/isRecord.js"; const names = (body: JsonValue | undefined): JsonValue[] => { if (typeof body !== "object" || body === null || Array.isArray(body)) throw new Error("Expected an object body"); const list = body["list"]; if (!Array.isArray(list)) throw new Error("Expected a list"); - return list.map((item) => - typeof item === "object" && item !== null && !Array.isArray(item) - ? (item["name"] ?? null) - : null, - ); + return list.map((item) => (isRecord(item) ? (item["name"] ?? null) : null)); }; describe("served writes modelled on later reads", () => { diff --git a/src/application/javascript/JavaScriptArtifactAnalysis.ts b/src/application/javascript/JavaScriptArtifactAnalysis.ts index 195be47611..c21647b73f 100644 --- a/src/application/javascript/JavaScriptArtifactAnalysis.ts +++ b/src/application/javascript/JavaScriptArtifactAnalysis.ts @@ -1,5 +1,4 @@ import { boundedList } from "../../domain/boundedList.js"; -import { createHash } from "node:crypto"; import { posix } from "node:path"; import { setImmediate } from "node:timers/promises"; @@ -57,6 +56,7 @@ import { cancelledBy, carriedReason, } from "../../domain/analysisErrorCore.js"; +import { sha256Hex } from "../../kernel/sha256Hex.js"; interface MutableArtifactAnalysis { readonly jsonDocuments: JavaScriptJsonDocuments; @@ -700,7 +700,7 @@ const collectSourceMapOriginals = ( declaration_index: declarationIndex++, reference, content, - content_sha256: content === null ? null : sha256(content), + content_sha256: content === null ? null : sha256Hex(content), section_path, }); } @@ -786,6 +786,3 @@ const findingCount = (analysis: JavaScriptStaticAnalysis): number => const optionalString = (value: unknown): string | null => typeof value === "string" && value.length > 0 ? value : null; - -const sha256 = (value: string): string => - createHash("sha256").update(value).digest("hex"); diff --git a/src/application/javascript/JavaScriptArtifactGraphFindings.ts b/src/application/javascript/JavaScriptArtifactGraphFindings.ts index 8c67d204bd..8534e20595 100644 --- a/src/application/javascript/JavaScriptArtifactGraphFindings.ts +++ b/src/application/javascript/JavaScriptArtifactGraphFindings.ts @@ -1,4 +1,3 @@ -import { createHash } from "node:crypto"; import { posix } from "node:path"; import { compactStringIdentityKey } from "../../domain/compactStringIdentity.js"; @@ -38,6 +37,7 @@ import { isJsonModuleTarget, isNativeAddonModuleTarget, } from "../../domain/javascript/javascriptModuleResolutionMode.js"; +import { sha256Hex } from "../../kernel/sha256Hex.js"; type StaticReference = JavaScriptStaticAnalysis["references"][number]; type StaticEndpoint = JavaScriptStaticAnalysis["endpoints"][number]; @@ -666,9 +666,7 @@ const addSourceMapEdge = ( context: JavaScriptArtifactGraphContext, input: FindingInput, ): void => { - const declaredUrlSha256 = createHash("sha256") - .update(input.value.declared_url) - .digest("hex"); + const declaredUrlSha256 = sha256Hex(input.value.declared_url); const resolution = resolveArtifactPathByContext({ declaredPath: input.value.declared_url, sourcePath: input.file.path, diff --git a/src/application/javascript/JavaScriptArtifactPathResolution.ts b/src/application/javascript/JavaScriptArtifactPathResolution.ts index 773f7e1b0c..539cb5a9dc 100644 --- a/src/application/javascript/JavaScriptArtifactPathResolution.ts +++ b/src/application/javascript/JavaScriptArtifactPathResolution.ts @@ -36,6 +36,7 @@ import { selectPackageSubpathPattern } from "../../domain/javascript/javascriptP import type { JavaScriptModuleResolutionMode } from "../../domain/javascript/javascriptModuleResolutionMode.js"; import type { JsonValue } from "../../domain/jsonValue.js"; import { err, ok, type Result } from "../../domain/result.js"; +import { isRecord } from "../../kernel/isRecord.js"; type ArtifactPathResolutionContext = | "package-entrypoint" @@ -1502,10 +1503,7 @@ const readPackageMetadata = ( ? exports : undefined, // Import maps must be non-array objects; other shapes are not a map. - imports: - typeof imports === "object" && imports !== null && !Array.isArray(imports) - ? imports - : undefined, + imports: isRecord(imports) ? imports : undefined, main: input.moduleKind !== undefined && typeof main !== "string" ? undefined @@ -1851,7 +1849,7 @@ const selectPackageExport = ( let target = value; let pattern: string | undefined; let declared: string[] = []; - if (typeof value === "object" && value !== null && !Array.isArray(value)) { + if (isRecord(value)) { const keys = Object.keys(value); const hasSubpaths = keys.some((key) => key.startsWith(".")); if (hasSubpaths && keys.some((key) => !key.startsWith("."))) diff --git a/src/artifacts/DesktopFileInspection.ts b/src/artifacts/DesktopFileInspection.ts index 51fa186836..921587aff0 100644 --- a/src/artifacts/DesktopFileInspection.ts +++ b/src/artifacts/DesktopFileInspection.ts @@ -6,7 +6,6 @@ import { } from "../domain/godotPckFormat.js"; import { observeEmbeddedGodotPck } from "./GodotPckLocation.js"; import type { FileHandle } from "node:fs/promises"; -import { createHash } from "node:crypto"; import { setImmediate } from "node:timers/promises"; import type { DesktopFile, DesktopFact } from "../domain/desktopApplication.js"; import { jsonValueByteLength } from "../domain/jsonValueByteLength.js"; @@ -27,6 +26,7 @@ import { hasUnityFsHeader, readUnityFsHeaderFacts, } from "../domain/unityfsFormat.js"; +import { sha256Hex } from "../kernel/sha256Hex.js"; export interface DesktopReadBudget { bytes: number; @@ -129,7 +129,7 @@ export const inspectDesktopFile = async ( row.ranges.push({ offset, bytes, - sha256: createHash("sha256").update(result).digest("hex"), + sha256: sha256Hex(result), }); return result; }; diff --git a/src/artifacts/apple/InterfaceBuilderAnalysis.ts b/src/artifacts/apple/InterfaceBuilderAnalysis.ts index e88ae85948..975717176c 100644 --- a/src/artifacts/apple/InterfaceBuilderAnalysis.ts +++ b/src/artifacts/apple/InterfaceBuilderAnalysis.ts @@ -1,4 +1,3 @@ -import { createHash } from "node:crypto"; import { isHostLimitFailure, ParseFailureError, @@ -72,6 +71,7 @@ import { hasNibArchiveSignature, } from "../../domain/apple/appleArchiveFormat.js"; import { strictUtf8Decoder } from "../../domain/strictUtf8.js"; +import { sha256Hex } from "../../kernel/sha256Hex.js"; const MAX_AGGREGATE_INPUT_BYTES = 32 * 1024 * 1024; const MAX_AGGREGATE_DECODE_BYTES = 256 * 1024 * 1024; @@ -265,7 +265,7 @@ const decodeInterfaceBuilderBundle = async ( unknownScalars.set(entry.path, unknownScalarCount); if (repeatedKeys !== undefined && repeatedKeys.replaced > 0) duplicateKeys.set(entry.path, repeatedKeys); - const documentHash = createHash("sha256").update(bytes).digest("hex"); + const documentHash = sha256Hex(bytes); documents.push({ relativePath: entry.path, archiveSha256: documentHash, diff --git a/src/artifacts/apple/KeyedArchiveReader.ts b/src/artifacts/apple/KeyedArchiveReader.ts index 8ef2748b7c..8856a7cde8 100644 --- a/src/artifacts/apple/KeyedArchiveReader.ts +++ b/src/artifacts/apple/KeyedArchiveReader.ts @@ -14,7 +14,6 @@ import { DirectoryArtifactEntryAccessDenied, translateArtifactFailure, } from "../../resources/index.js"; -import { createHash } from "node:crypto"; import { decodeLimit, isHostLimitFailure, @@ -64,6 +63,7 @@ import { } from "../../domain/apple/appleArchiveFormat.js"; import { estimateBinaryPlistExpansion } from "../../domain/apple/propertyListDecodeBudget.js"; import { errorMessage } from "../../kernel/errorMessage.js"; +import { sha256Hex } from "../../kernel/sha256Hex.js"; const MAX_BYTES = 64 * 1024 * 1024; /** Decoded representation budget, the same 8:1 ratio Interface Builder uses. */ @@ -424,7 +424,7 @@ const readSelectedKeyedArchive = async ( const bytes = Buffer.concat(chunks, size); return decodeSelectedArchive(bytes, { targetSha256: input.targetSha256, - archiveSha256: createHash("sha256").update(bytes).digest("hex"), + archiveSha256: sha256Hex(bytes), resourceRoot: input.resourceRoot, parameters: selected, platform: input.platform, diff --git a/src/artifacts/apple/NibArchive.ts b/src/artifacts/apple/NibArchive.ts index 00570bc166..dfecf3d1ab 100644 --- a/src/artifacts/apple/NibArchive.ts +++ b/src/artifacts/apple/NibArchive.ts @@ -11,6 +11,7 @@ import { interfaceBuilderDecodeBudgetExceeded, } from "./InterfaceBuilderDecodeBudget.js"; import { strictUtf8Decoder } from "../../domain/strictUtf8.js"; +import { isRecord } from "../../kernel/isRecord.js"; const DEFAULT_DECODE_BUDGET_BYTES = 128 * 1024 * 1024; @@ -147,9 +148,7 @@ export const decodeNibArchive = ( ); for (const { value } of values.values()) { if ( - typeof value === "object" && - value !== null && - !Array.isArray(value) && + isRecord(value) && typeof value.$nib_object_ref === "number" && value.$nib_object_ref >= objectCount ) diff --git a/src/artifacts/javascript/JavaScriptArtifactFiles.ts b/src/artifacts/javascript/JavaScriptArtifactFiles.ts index 304fe49b34..a6b087ce8f 100644 --- a/src/artifacts/javascript/JavaScriptArtifactFiles.ts +++ b/src/artifacts/javascript/JavaScriptArtifactFiles.ts @@ -1,5 +1,4 @@ import type { AsarHeaderAdmission } from "../../config/asarHeaderAdmission.js"; -import { createHash } from "node:crypto"; import { isAbsolute } from "node:path"; import type { Readable } from "node:stream"; @@ -29,6 +28,7 @@ import type { JavaScriptArtifactFileSet, } from "../../domain/javascript/javascriptArtifactFiles.js"; import { strictUtf8Decoder } from "../../domain/strictUtf8.js"; +import { sha256Hex } from "../../kernel/sha256Hex.js"; interface ExpectedFile { readonly path: string; @@ -381,7 +381,7 @@ const readText = async ( await input.reader.open(input.entry, context.signal), context.signal, ); - const digest = createHash("sha256").update(bytes).digest("hex"); + const digest = sha256Hex(bytes); if (digest !== input.expected.sha256 || bytes.length !== input.expected.bytes) throw new ArtifactReaderFailure( "integrity", diff --git a/src/artifacts/nodeSea/NodeSeaLocation.ts b/src/artifacts/nodeSea/NodeSeaLocation.ts index 06dfcfaa15..826de2cb04 100644 --- a/src/artifacts/nodeSea/NodeSeaLocation.ts +++ b/src/artifacts/nodeSea/NodeSeaLocation.ts @@ -8,7 +8,6 @@ import { readMachoSectionHeader } from "../../domain/apple/machoSectionHeader.js import { readElfSectionHeader } from "../../domain/elfSectionHeader.js"; import { readElfProgramHeader } from "../../domain/elfProgramHeader.js"; import { readElfRawTableDeclarations } from "../../domain/elfRawTableDeclarations.js"; -import { createHash } from "node:crypto"; import { constants as bufferConstants } from "node:buffer"; import { parsePeResources, @@ -60,6 +59,7 @@ import { observeNodeSeaFuseMatches, type NodeSeaFuseObservation, } from "./NodeSeaBlob.js"; +import { sha256Hex } from "../../kernel/sha256Hex.js"; const PT_NOTE = 4; const SHT_NOTE = 7; @@ -691,7 +691,7 @@ const locatePeResources = async (carrier: Carrier): Promise => { bytes, { path: "", - sha256: createHash("sha256").update(bytes).digest("hex"), + sha256: sha256Hex(bytes), bytes: bytes.length, }, { diff --git a/src/browser/CdpCaptureStorageFingerprints.ts b/src/browser/CdpCaptureStorageFingerprints.ts index bfca80effd..780a7aae0b 100644 --- a/src/browser/CdpCaptureStorageFingerprints.ts +++ b/src/browser/CdpCaptureStorageFingerprints.ts @@ -1,5 +1,3 @@ -import { createHash } from "node:crypto"; - import canonicalize from "canonicalize"; import type { InspectWebPageInput } from "../domain/browserObservation.js"; @@ -13,6 +11,7 @@ import { recordsValue, cdpStringValue, } from "./CdpCaptureValues.js"; +import { sha256Hex } from "../kernel/sha256Hex.js"; type StorageFingerprint = WebPageInspection["storage"]["content_fingerprints"][number]; @@ -444,8 +443,7 @@ const addFingerprint = ( const STORAGE_ENTRY_PAGE_SIZE = 1_000; -const digest = (value: unknown): string => - createHash("sha256").update(encodedValue(value)).digest("hex"); +const digest = (value: unknown): string => sha256Hex(encodedValue(value)); const encodedValue = (value: unknown): Uint8Array | string => { if (value instanceof Uint8Array) return value; diff --git a/src/browser/CdpCaptureValues.ts b/src/browser/CdpCaptureValues.ts index 1c2ae66aad..cfe3b76100 100644 --- a/src/browser/CdpCaptureValues.ts +++ b/src/browser/CdpCaptureValues.ts @@ -4,7 +4,7 @@ import type { BrowserObservationOperation } from "../domain/browserObservationEr import { sanitizeBrowserUrl } from "../domain/browserObservation.js"; import { createWebTextArtifact } from "../domain/webContentArtifact.js"; import { err, ok, type Result } from "../domain/result.js"; -import { isRecord } from "../domain/isRecord.js"; +import { isRecord } from "../kernel/isRecord.js"; export type UnknownRecord = Readonly>; diff --git a/src/browser/CdpConnection.ts b/src/browser/CdpConnection.ts index 9808f2d922..042d121b9a 100644 --- a/src/browser/CdpConnection.ts +++ b/src/browser/CdpConnection.ts @@ -31,7 +31,7 @@ import { } from "../domain/browserDeadline.js"; import { safeParseJson } from "../domain/safeJson.js"; import { WEB_RUNTIME_LIMITS } from "../domain/webRuntime.js"; -import { isRecord } from "../domain/isRecord.js"; +import { isRecord } from "../kernel/isRecord.js"; // ws currently stores maxPayload as a signed 32-bit integer. Larger values can // wrap to a negative number, which disables its limit check. diff --git a/src/browser/CdpWebMcpDiscovery.ts b/src/browser/CdpWebMcpDiscovery.ts index 372aa45d65..cf5f63e717 100644 --- a/src/browser/CdpWebMcpDiscovery.ts +++ b/src/browser/CdpWebMcpDiscovery.ts @@ -1,6 +1,5 @@ import type { CdpFrameFacts } from "./CdpFrameIdentity.js"; import { cdpFrameEvent } from "./protocol/CdpEvents.js"; -import { createHash } from "node:crypto"; import type { ProgressReporter } from "../ports/ProgressReporter.js"; import type { @@ -46,6 +45,7 @@ import { cdpSourceCoordinates, topCallFrame, } from "./CdpCaptureEventHelpers.js"; +import { sha256Hex } from "../kernel/sha256Hex.js"; interface DiscoveryContext { readonly connection: CdpConnection; @@ -675,6 +675,4 @@ const toolKey = (frameUrl: string, frameId: string, name: string): string => // Registrations without a known admitted frame are excluded above, so the // frame ID here always distinguishes owners. Composite tuple keeps a NUL // inside one field from collapsing two registrations before hashing. - `webmcp_${createHash("sha256") - .update(compositeKey([frameUrl, frameId, name])) - .digest("hex")}`; + `webmcp_${sha256Hex(compositeKey([frameUrl, frameId, name]))}`; diff --git a/src/browser/ElectronFileScope.ts b/src/browser/ElectronFileScope.ts index 89820e6171..5385a85798 100644 --- a/src/browser/ElectronFileScope.ts +++ b/src/browser/ElectronFileScope.ts @@ -30,7 +30,7 @@ import { type AsarHeaderAdmission, } from "../config/asarHeaderAdmission.js"; import { decodeStrictUtf8 } from "../domain/strictUtf8.js"; -import { isRecord } from "../domain/isRecord.js"; +import { isRecord } from "../kernel/isRecord.js"; type ElectronFileOperation = | "inspect_electron_page" diff --git a/src/browser/PlaywrightElectronActiveProvider.ts b/src/browser/PlaywrightElectronActiveProvider.ts index 37e73dac00..a9bc128eda 100644 --- a/src/browser/PlaywrightElectronActiveProvider.ts +++ b/src/browser/PlaywrightElectronActiveProvider.ts @@ -14,7 +14,7 @@ import { ElectronCaptureCleanup } from "./ElectronCaptureCleanup.js"; import { analysisErrorWithCleanupFailure } from "../domain/analysisErrorCleanup.js"; import { analysisErrorWithCancellation } from "../domain/analysisErrorCancellation.js"; import { electronFuseFailure } from "../electron/ElectronFuseFailures.js"; -import { createHash, randomUUID } from "node:crypto"; +import { randomUUID } from "node:crypto"; import { fileURLToPath } from "node:url"; import type { _electron as electron } from "playwright-core"; @@ -65,6 +65,7 @@ const STARTUP_TIMEOUT_MS = 60_000; import { PLAYWRIGHT_ELECTRON_ACTIVE_PROVIDER_IDENTITY } from "./providerIdentities.js"; import { errorMessage } from "../kernel/errorMessage.js"; +import { sha256Hex } from "../kernel/sha256Hex.js"; const hookPath = fileURLToPath( new URL("../../scripts/electron-active-hook.cjs", import.meta.url), @@ -200,9 +201,7 @@ export class PlaywrightElectronActiveProvider implements ElectronActiveObservati ...safeElectronEnvironment(this.environment, runId, this.platform), REA_ELECTRON_CAPTURE_ARGV: JSON.stringify({ length: applicationArgs.length, - sha256: createHash("sha256") - .update(JSON.stringify(applicationArgs)) - .digest("hex"), + sha256: sha256Hex(JSON.stringify(applicationArgs)), }), }, args: applicationArgs, diff --git a/src/browser/PlaywrightScenarioArtifacts.ts b/src/browser/PlaywrightScenarioArtifacts.ts index 3f9eebff8b..50e27dcf03 100644 --- a/src/browser/PlaywrightScenarioArtifacts.ts +++ b/src/browser/PlaywrightScenarioArtifacts.ts @@ -1,5 +1,3 @@ -import { createHash } from "node:crypto"; - import { z } from "zod"; import type { BrowserContext, Page } from "playwright-core"; @@ -10,6 +8,7 @@ import { type BrowserStepArtifacts, } from "../domain/browserScenarioCaptureValues.js"; import type { BrowserScenarioSecrets } from "./BrowserScenarioSecrets.js"; +import { sha256Hex } from "../kernel/sha256Hex.js"; const historyValueSchema = z.strictObject({ length: z.int().min(0), @@ -36,7 +35,7 @@ const textArtifact = (text: string) => { return { state: "captured" as const, value: { - sha256: createHash("sha256").update(bytes).digest("hex"), + sha256: sha256Hex(bytes), bytes: bytes.byteLength, text, }, @@ -58,7 +57,7 @@ const captureScreenshot = async ( animations: "disabled", caret: "hide", }); - const sha256 = createHash("sha256").update(bytes).digest("hex"); + const sha256 = sha256Hex(bytes); return { state: "captured" as const, value: { diff --git a/src/browser/WebSourceMapFetcher.ts b/src/browser/WebSourceMapFetcher.ts index 60bb5e5826..60b6fae663 100644 --- a/src/browser/WebSourceMapFetcher.ts +++ b/src/browser/WebSourceMapFetcher.ts @@ -63,6 +63,7 @@ import { type SourceMapLimits, } from "../domain/sourceMapLimits.js"; import { errorMessage } from "../kernel/errorMessage.js"; +import { sha256Hex } from "../kernel/sha256Hex.js"; export interface WebSourceMapRequest { readonly scriptKey: string; @@ -911,7 +912,7 @@ const readBoundedText = async ( offset += chunk.byteLength; } const responseIdentity: ResponseIdentity = { - sha256: createHash("sha256").update(joined).digest("hex"), + sha256: sha256Hex(joined), bytes, representation: "fetch-response-body-bytes", }; diff --git a/src/browser/history/HarCapture.ts b/src/browser/history/HarCapture.ts index c8d29d8c87..e30b9d7354 100644 --- a/src/browser/history/HarCapture.ts +++ b/src/browser/history/HarCapture.ts @@ -1,5 +1,4 @@ import { captureBudgets } from "./CaptureBudgets.js"; -import { createHash } from "node:crypto"; import { LosslessNumber } from "lossless-json"; import { parseCaptureJson } from "./CaptureJson.js"; import type { JsonValue } from "../../domain/jsonValue.js"; @@ -16,6 +15,7 @@ import { } from "./CaptureRedaction.js"; import { createHarValidator } from "./HarSchema.js"; import { HAR_CAPTURE_PROVIDER_IDENTITY } from "./CaptureProviderIdentities.js"; +import { sha256Hex } from "../../kernel/sha256Hex.js"; type DecodedCapture = Omit< WebNetworkCapture, @@ -161,7 +161,7 @@ const projectHar = ( ) { const bytes = decodeHarBase64(item, pointer); const contentBase64 = bytes.toString("base64"); - const sha256 = createHash("sha256").update(bytes).digest("hex"); + const sha256 = sha256Hex(bytes); const hidden = redactor.sensitiveBytes(bytes) || sensitiveValues.some( diff --git a/src/browser/history/SazProjection.ts b/src/browser/history/SazProjection.ts index 3a75dbea3c..33b925434c 100644 --- a/src/browser/history/SazProjection.ts +++ b/src/browser/history/SazProjection.ts @@ -1,10 +1,10 @@ import { captureBudgets } from "./CaptureBudgets.js"; -import { createHash } from "node:crypto"; import { isUtf8 } from "node:buffer"; import type { JsonValue } from "../../domain/jsonValue.js"; import type { WebNetworkCaptureRecord } from "../../domain/webNetworkCapture.js"; import { CaptureRedaction, capturePointer } from "./CaptureRedaction.js"; import { CaptureFormatError } from "./CaptureFormatError.js"; +import { sha256Hex } from "../../kernel/sha256Hex.js"; export type SazValue = | JsonValue @@ -35,7 +35,7 @@ export const projectSazRecord = ( return redactor.credential(pointer); if (Buffer.isBuffer(value)) { const base64 = value.toString("base64"); - const sha256 = createHash("sha256").update(value).digest("hex"); + const sha256 = sha256Hex(value); const hidden = redactor.sensitiveBytes(value) || sensitiveValues.some( diff --git a/src/browser/history/protobuf/ProtobufCapture.ts b/src/browser/history/protobuf/ProtobufCapture.ts index 8c94af4788..66301325a8 100644 --- a/src/browser/history/protobuf/ProtobufCapture.ts +++ b/src/browser/history/protobuf/ProtobufCapture.ts @@ -6,7 +6,6 @@ import { CaptureRedaction, isCaptureCredentialHeaderBytes, } from "../CaptureRedaction.js"; -import { createHash } from "node:crypto"; import { readStableArtifact, completedStableArtifactObservation, @@ -40,6 +39,7 @@ import { type PreparedProtobufBody, } from "./ProtobufFraming.js"; import type { ProtobufDecoding } from "../../../domain/protobufWire.js"; +import { sha256Hex } from "../../../kernel/sha256Hex.js"; const object = ( value: JsonValue | undefined, @@ -427,10 +427,7 @@ export const prepareCaptureProtobuf = async ( `Protobuf body exceeds max_input_bytes (${String(captureBudgets().inputBytes)} bytes)`, ); const body = Buffer.from(field.content_base64, "base64"); - if ( - body.length !== field.bytes || - createHash("sha256").update(body).digest("hex") !== field.sha256 - ) + if (body.length !== field.bytes || sha256Hex(body) !== field.sha256) throw new AnalysisInputError("inspect_web_network_capture", undefined, [ { path: ["capture_path"], diff --git a/src/browser/network/PlaywrightNetworkContent.ts b/src/browser/network/PlaywrightNetworkContent.ts index 7d9930d412..71f42111d6 100644 --- a/src/browser/network/PlaywrightNetworkContent.ts +++ b/src/browser/network/PlaywrightNetworkContent.ts @@ -4,7 +4,6 @@ import { isJson, mediaTypeEssence, } from "../../domain/analysisView/recordedMediaType.js"; -import { createHash } from "node:crypto"; import { safeParseJson } from "../../domain/safeJson.js"; import { @@ -24,6 +23,7 @@ import type { ScenarioRedactionScope, } from "../BrowserScenarioSecrets.js"; import { withPlaywrightExecutionBoundary } from "../PlaywrightExecutionBoundary.js"; +import { sha256Hex } from "../../kernel/sha256Hex.js"; /** The producer seam for ordered, duplicate-preserving HTTP headers. */ export interface NetworkHeadersSource { @@ -256,7 +256,7 @@ export const captureNetworkBody = async ( encoding: "base64", content: retained.toString("base64"), bytes: retained.length, - sha256: createHash("sha256").update(retained).digest("hex"), + sha256: sha256Hex(retained), media_type: contentType === undefined ? null diff --git a/src/browser/protocol/CdpFrameTree.ts b/src/browser/protocol/CdpFrameTree.ts index 070fff2a08..6a4038e4d4 100644 --- a/src/browser/protocol/CdpFrameTree.ts +++ b/src/browser/protocol/CdpFrameTree.ts @@ -1,5 +1,5 @@ import { z } from "zod"; -import { isRecord } from "../../domain/isRecord.js"; +import { isRecord } from "../../kernel/isRecord.js"; import { observeCdpFrameUrl, diff --git a/src/cli/cliOutputFormatter.ts b/src/cli/cliOutputFormatter.ts index 0e354ddaad..378051aed0 100644 --- a/src/cli/cliOutputFormatter.ts +++ b/src/cli/cliOutputFormatter.ts @@ -25,6 +25,7 @@ import { Formatter } from "incur"; import { AnalysisInputError } from "../domain/analysisErrorCore.js"; import { projectAnalysisError } from "../domain/analysisErrorProjection.js"; import { err, ok, type Result } from "../domain/result.js"; +import { isRecord } from "../kernel/isRecord.js"; export interface CliDelimitedOutputOptions { readonly fields: readonly string[]; @@ -268,9 +269,7 @@ const isPlainObjectArray = ( Array.isArray(value) && value.every( (row: unknown) => - typeof row === "object" && - row !== null && - !Array.isArray(row) && + isRecord(row) && (Object.getPrototypeOf(row) === Object.prototype || Object.getPrototypeOf(row) === null), ); @@ -284,9 +283,7 @@ const isFlatObject = (value: Record): boolean => const isObjectArray = (value: unknown): value is Record[] => Array.isArray(value) && value.length > 0 && - value.every( - (item) => typeof item === "object" && item !== null && !Array.isArray(item), - ) && + value.every((item) => isRecord(item)) && value.some((item) => Object.keys(item).length > 0); const isWordCharacter = (character: string | undefined): boolean => @@ -467,11 +464,7 @@ const formatMarkdown = ( if (isScalar(child)) return `${heading}${escapeMarkdownText(String(child))}`; if (isObjectArray(child)) return `${heading}${formatObjectTable(child)}`; - if ( - typeof child === "object" && - child !== null && - !Array.isArray(child) - ) { + if (isRecord(child)) { const nested = child as Record; return isFlatObject(nested) ? `${heading}${formatKeyValueTable(nested)}` diff --git a/src/cli/contractCliDescription.ts b/src/cli/contractCliDescription.ts index a31621372e..2128fe78d7 100644 --- a/src/cli/contractCliDescription.ts +++ b/src/cli/contractCliDescription.ts @@ -9,7 +9,7 @@ import type { CallerInputPaths } from "../domain/evidence.js"; import { analysisInputErrorFromIssues } from "../domain/inputIssueProjection.js"; import { localPathStringSchema } from "../domain/localPath.js"; import { schemaAnnotations } from "../domain/schemaAnnotations.js"; -import { isRecord } from "../domain/isRecord.js"; +import { isRecord } from "../kernel/isRecord.js"; import { err, ok, type Result } from "../domain/result.js"; import { absoluteCallerPath } from "../filesystem/callerPath.js"; import { diff --git a/src/cli/contractCommand.ts b/src/cli/contractCommand.ts index c12538a3ee..cb2dfe67ab 100644 --- a/src/cli/contractCommand.ts +++ b/src/cli/contractCommand.ts @@ -59,6 +59,7 @@ import { projectCliInputFields, } from "./projectCliAnalysisResult.js"; import type { CliInstance } from "./types.js"; +import { isRecord } from "../kernel/isRecord.js"; /** * Incur adapter for contract commands. The command itself is described in @@ -1228,9 +1229,7 @@ const readJsonInputs = async ( /** A file failure names the selected path, and a cancellation is its own. */ const keepsOwnFailure = (error: JsonValue): boolean => - typeof error === "object" && - error !== null && - !Array.isArray(error) && + isRecord(error) && ("input_path" in error || (error as { readonly code?: unknown }).code === "cancelled"); diff --git a/src/cli/finishAnalysisCommand.ts b/src/cli/finishAnalysisCommand.ts index faa9a37f7d..db60353d7b 100644 --- a/src/cli/finishAnalysisCommand.ts +++ b/src/cli/finishAnalysisCommand.ts @@ -14,6 +14,7 @@ import { import { ProviderCleanupError } from "../domain/providerCleanupError.js"; import { err, ok, type Result } from "../domain/result.js"; import { dispatchQueuedInterrupts } from "../process/queuedInterrupts.js"; +import { isRecord } from "../kernel/isRecord.js"; /** Finish a one-shot CLI operation while retaining primary results through close. */ export const finishAnalysisCommand = async < @@ -133,11 +134,7 @@ export const finishAnalysisCommand = async < details: { ...failure.details, diagnostics: { - ...(typeof diagnostics === "object" && - diagnostics !== null && - !Array.isArray(diagnostics) - ? diagnostics - : {}), + ...(isRecord(diagnostics) ? diagnostics : {}), primary_error: initialDiagnosticFailure ?? initialFailure, }, }, diff --git a/src/cli/jsonLines.ts b/src/cli/jsonLines.ts index 4e7ca008ee..f0457b8cb4 100644 --- a/src/cli/jsonLines.ts +++ b/src/cli/jsonLines.ts @@ -4,7 +4,7 @@ import { err, ok, type Result } from "../domain/result.js"; import { AnalysisInputError } from "../domain/analysisErrorCore.js"; import { jsonParts } from "../domain/jsonSerialization.js"; -import { isRecord } from "../domain/isRecord.js"; +import { isRecord } from "../kernel/isRecord.js"; /** Reserved control-record marker, not an advertised external JSON Schema. */ export const JSON_LINES_PROTOCOL = "jsonl/v1"; diff --git a/src/cli/reverseEngineeringCommands.ts b/src/cli/reverseEngineeringCommands.ts index ea8c72ecd4..2798c0b8bf 100644 --- a/src/cli/reverseEngineeringCommands.ts +++ b/src/cli/reverseEngineeringCommands.ts @@ -48,6 +48,7 @@ import { import { finishAnalysisCommand } from "./finishAnalysisCommand.js"; import { projectCliAnalysisResult } from "./projectCliAnalysisResult.js"; import { errorMessage } from "../kernel/errorMessage.js"; +import { isRecord } from "../kernel/isRecord.js"; const executeWithCleanup = async ( service: ReverseEngineeringService, @@ -80,10 +81,7 @@ const cleanupOnlyCompleteEvidence = ( const parsed = recognizeEvidence(error.partialObservation); if (!parsed.ok || parsed.value === undefined) return undefined; const normalized = parsed.value.normalized_result; - return typeof normalized === "object" && - normalized !== null && - !Array.isArray(normalized) && - normalized.completion_status !== "unknown" + return isRecord(normalized) && normalized.completion_status !== "unknown" ? parsed.value : undefined; }; diff --git a/src/cliLogging.ts b/src/cliLogging.ts index e9ac96d3b7..bb7698b618 100644 --- a/src/cliLogging.ts +++ b/src/cliLogging.ts @@ -6,7 +6,7 @@ import { type AnalysisErrorProjection, } from "./domain/analysisErrorProjection.js"; import type { Logger } from "pino"; -import { isRecord } from "./domain/isRecord.js"; +import { isRecord } from "./kernel/isRecord.js"; type CliFailureIdentity = Pick< AnalysisErrorProjection, diff --git a/src/contracts/advertisedDialect.ts b/src/contracts/advertisedDialect.ts index 55508e7294..0612862197 100644 --- a/src/contracts/advertisedDialect.ts +++ b/src/contracts/advertisedDialect.ts @@ -3,7 +3,7 @@ import { schemaDepth, serializedBytes, } from "./compactJsonSchema.js"; -import { isRecord } from "../domain/isRecord.js"; +import { isRecord } from "../kernel/isRecord.js"; import { schemaArrays, schemaChildren, diff --git a/src/contracts/advertisedDialectProjection.ts b/src/contracts/advertisedDialectProjection.ts index 21836b2a12..c5f4d84195 100644 --- a/src/contracts/advertisedDialectProjection.ts +++ b/src/contracts/advertisedDialectProjection.ts @@ -1,6 +1,6 @@ import { isDeepStrictEqual } from "node:util"; -import { isRecord } from "../domain/isRecord.js"; +import { isRecord } from "../kernel/isRecord.js"; import { ADVERTISED_BOUND_LIMIT, ADVERTISED_DESCRIPTION_MAX_CHARACTERS, diff --git a/src/contracts/jsonSchemaKeywords.ts b/src/contracts/jsonSchemaKeywords.ts index 62319bb626..7c3f4afa4b 100644 --- a/src/contracts/jsonSchemaKeywords.ts +++ b/src/contracts/jsonSchemaKeywords.ts @@ -1,3 +1,4 @@ +import { isRecord } from "../kernel/isRecord.js"; export const schemaMaps = new Set([ "$defs", "definitions", @@ -28,12 +29,7 @@ export const schemaSubschemas = ( options: { readonly includeDefinitions: boolean }, ): unknown[] => Object.entries(schema).flatMap(([key, value]) => { - if ( - schemaMaps.has(key) && - typeof value === "object" && - value !== null && - !Array.isArray(value) - ) + if (schemaMaps.has(key) && isRecord(value)) return !options.includeDefinitions && (key === "$defs" || key === "definitions") ? [] diff --git a/src/contracts/outputSchemaDefinitions.test.ts b/src/contracts/outputSchemaDefinitions.test.ts index e783fcba94..bd3a0c3299 100644 --- a/src/contracts/outputSchemaDefinitions.test.ts +++ b/src/contracts/outputSchemaDefinitions.test.ts @@ -9,7 +9,7 @@ import { } from "./outputSchemaDefinitions.js"; import { ANALYSIS_VIEW_TOOL_CONTRACTS } from "./analysisViewToolContracts.js"; import { advertisedOutputJsonSchema } from "./toolSchemaMetadata.js"; -import { isRecord } from "../domain/isRecord.js"; +import { isRecord } from "../kernel/isRecord.js"; // An object alternative whose serialized size exceeds the inline bound. const largeAlternative = (kind: string, reference: string) => ({ diff --git a/src/contracts/outputSchemaDefinitions.ts b/src/contracts/outputSchemaDefinitions.ts index b7df03e43e..7a63cba14f 100644 --- a/src/contracts/outputSchemaDefinitions.ts +++ b/src/contracts/outputSchemaDefinitions.ts @@ -4,7 +4,7 @@ import { schemaMaps, schemaSubschemas, } from "./jsonSchemaKeywords.js"; -import { isRecord } from "../domain/isRecord.js"; +import { isRecord } from "../kernel/isRecord.js"; type Schema = Record; diff --git a/src/contracts/outputSchemaPresentation.ts b/src/contracts/outputSchemaPresentation.ts index ece6f19212..b635e5b34d 100644 --- a/src/contracts/outputSchemaPresentation.ts +++ b/src/contracts/outputSchemaPresentation.ts @@ -2,7 +2,7 @@ import { JsonSchemaReferences, type JsonSchemaScope, } from "./jsonSchemaReferences.js"; -import { isRecord as isObject } from "../domain/isRecord.js"; +import { isRecord as isObject } from "../kernel/isRecord.js"; import { advertisedSchemaPatterns } from "./advertisedDialect.js"; import { projectPortablePattern } from "./portablePattern.js"; import { diff --git a/src/contracts/toolSchemaMetadata.ts b/src/contracts/toolSchemaMetadata.ts index ba3582af97..5f2d479e8d 100644 --- a/src/contracts/toolSchemaMetadata.ts +++ b/src/contracts/toolSchemaMetadata.ts @@ -17,7 +17,7 @@ import { import { digestCanonicalValue } from "../domain/canonicalDigest.js"; import { shareOutputDefinitions } from "./outputSchemaDefinitions.js"; import { getEvidenceInputContract } from "../domain/evidenceInputContract.js"; -import { isRecord } from "../domain/isRecord.js"; +import { isRecord } from "../kernel/isRecord.js"; import { schemaAnnotations } from "../domain/schemaAnnotations.js"; const PROPERTY_DESCRIPTIONS: Readonly> = { diff --git a/src/cutter/CutterBridgeSource.ts b/src/cutter/CutterBridgeSource.ts index 4c3ad650db..4ba47877d5 100644 --- a/src/cutter/CutterBridgeSource.ts +++ b/src/cutter/CutterBridgeSource.ts @@ -1,9 +1,9 @@ -import { createHash } from "node:crypto"; import { readFileSync } from "node:fs"; import { fileURLToPath } from "node:url"; import { AnalysisCapabilityUnavailableError } from "../domain/analysisErrorCore.js"; import type { CutterBridgeSource } from "../domain/cutterDiscovery.js"; +import { sha256Hex } from "../kernel/sha256Hex.js"; const PACKAGED_PLUGIN = new URL( "../../bridge/cutter/rea_bridge.py", @@ -53,7 +53,7 @@ const packagedCutterPluginDigest = (operation: string, plugin: URL): string => { { cause, remediationAction: remediation, userMessage: remediation }, ); } - const digest = createHash("sha256").update(bytes).digest("hex"); + const digest = sha256Hex(bytes); packagedDigests.set(plugin.href, digest); return digest; }; diff --git a/src/desktop/AgentEnvComputer.ts b/src/desktop/AgentEnvComputer.ts index 8c3ee4dc64..c2c306957a 100644 --- a/src/desktop/AgentEnvComputer.ts +++ b/src/desktop/AgentEnvComputer.ts @@ -1,4 +1,4 @@ -import { createHash, randomUUID } from "node:crypto"; +import { randomUUID } from "node:crypto"; import { setTimeout as delay } from "node:timers/promises"; import { getHeapStatistics } from "node:v8"; @@ -26,6 +26,7 @@ import { DRAWN_WAIT_MS, drawnScreenshot } from "./DrawnScreenshot.js"; import { awaitHttpReply, type HttpReply } from "./HttpReply.js"; import { redactExplicitText } from "../domain/explicitSensitiveValues.js"; import { errorMessage } from "../kernel/errorMessage.js"; +import { sha256Hex } from "../kernel/sha256Hex.js"; const READY_TIMEOUT_MS = 180_000; const REQUEST_TIMEOUT_MS = 120_000; @@ -536,10 +537,7 @@ export class AgentEnvComputer implements ControlledComputer { )?.file?.bytes; const bytes = encoded === undefined ? undefined : Buffer.from(encoded, "base64"); - if ( - bytes?.length !== segment.bytes || - createHash("sha256").update(bytes).digest("hex") !== segment.sha256 - ) + if (bytes?.length !== segment.bytes || sha256Hex(bytes) !== segment.sha256) throw new Error( `Recording segment ${segment.path} is missing or differs from its manifest.`, ); diff --git a/src/desktop/BuildComputerController.ts b/src/desktop/BuildComputerController.ts index 8ecff91e1d..58238498ba 100644 --- a/src/desktop/BuildComputerController.ts +++ b/src/desktop/BuildComputerController.ts @@ -1,4 +1,3 @@ -import { createHash } from "node:crypto"; import { readFile } from "node:fs/promises"; import { fileURLToPath } from "node:url"; import { Buffer } from "node:buffer"; @@ -12,6 +11,7 @@ import { guestFileAnswerCeiling, guestFileAnswerWorkingBytes, } from "./AgentEnvComputer.js"; +import { sha256Hex } from "../kernel/sha256Hex.js"; import type { BuildControllerAnswer, ControlledComputer, @@ -343,10 +343,7 @@ export const fetchHomeFolder = async ( ); for (const file of batch) { const content = files.get(file.path); - const sha256 = - content === undefined - ? undefined - : createHash("sha256").update(content).digest("hex"); + const sha256 = content === undefined ? undefined : sha256Hex(content); if ( !file.path.startsWith(`${folder}/`) || content?.length !== file.size || diff --git a/src/desktop/DesktopContentStore.ts b/src/desktop/DesktopContentStore.ts index d8273e1b50..f84df30472 100644 --- a/src/desktop/DesktopContentStore.ts +++ b/src/desktop/DesktopContentStore.ts @@ -2,7 +2,6 @@ import { ArtifactReaderFailure, ArtifactResourceScope, } from "../resources/index.js"; -import { createHash } from "node:crypto"; import { mkdir, open, rename, rm, rmdir } from "node:fs/promises"; import { join } from "node:path"; @@ -25,6 +24,7 @@ import { RegularFileCapacityError, readStableFileBytes, } from "../filesystem/readStableFileBytes.js"; +import { sha256Hex } from "../kernel/sha256Hex.js"; type Omission = DesktopApplicationCapture["state"]["omitted_content"][number]; @@ -143,7 +143,7 @@ export class DesktopContentStore { /** Store bytes already read, such as a verified apt key; over the per-file limit or the remaining budget they are omitted. */ async retainBytes(bytes: Buffer): Promise { - const sha256 = createHash("sha256").update(bytes).digest("hex"); + const sha256 = sha256Hex(bytes); const size = bytes.byteLength; if (size > this.#maxFileBytes) return { kind: "omitted", reason: "too_large" }; diff --git a/src/desktop/GpgvKeyCheck.ts b/src/desktop/GpgvKeyCheck.ts index b905b38ceb..1ebe5bfa68 100644 --- a/src/desktop/GpgvKeyCheck.ts +++ b/src/desktop/GpgvKeyCheck.ts @@ -1,4 +1,3 @@ -import { createHash } from "node:crypto"; import { writeFile } from "node:fs/promises"; import { join } from "node:path"; @@ -16,6 +15,7 @@ import { verifyingKey } from "../domain/desktop/openPgpKeys.js"; import { PrivateRuntimeRoot } from "../process/PrivateRuntimeRoot.js"; import { readHostFile } from "./HostFileRead.js"; import type { QueryRunner } from "./HostQuery.js"; +import { sha256Hex } from "../kernel/sha256Hex.js"; const FILE_MAX_BYTES = 1024 * 1024; @@ -112,7 +112,7 @@ class GpgvKeyCheck { return { path: key.path, ...kept.value, - sha256: createHash("sha256").update(kept.value.bytes).digest("hex"), + sha256: sha256Hex(kept.value.bytes), fingerprint: signature.primary, }; } diff --git a/src/domain/analysisErrorProjection.ts b/src/domain/analysisErrorProjection.ts index 89241d2df1..a24ab41a2a 100644 --- a/src/domain/analysisErrorProjection.ts +++ b/src/domain/analysisErrorProjection.ts @@ -62,6 +62,7 @@ import { import { invocationLimit } from "./analysisSettingDefinitions.js"; import { analysisErrorRefusal } from "./analysisErrorRefusal.js"; import { analysisRefusalDetails } from "./analysisRefusal.js"; +import { isRecord } from "../kernel/isRecord.js"; /** * Project expected failures into exhaustive, secret-safe caller fields. The @@ -131,9 +132,7 @@ export function* unretainedEvidenceCandidates( ] as const) { const value = projected.details?.[field]; if ( - typeof value === "object" && - value !== null && - !Array.isArray(value) && + isRecord(value) && (value.kind === "unretained-evidence" || value.kind === "unretained-observation" || value.kind === "inline-evidence") @@ -214,12 +213,7 @@ export const omitUnretainedEvidenceFromError = ( } const { [field]: _partial, ...details } = projected.details!; const evidence = partial.evidence; - const evidenceId = - typeof evidence === "object" && - evidence !== null && - !Array.isArray(evidence) - ? evidence.evidence_id - : undefined; + const evidenceId = isRecord(evidence) ? evidence.evidence_id : undefined; const retention = partial.kind === "inline-evidence" ? typeof partial.retention === "string" diff --git a/src/domain/analysisView/commandObservationView.ts b/src/domain/analysisView/commandObservationView.ts index a9d37feddc..c7fc569354 100644 --- a/src/domain/analysisView/commandObservationView.ts +++ b/src/domain/analysisView/commandObservationView.ts @@ -20,6 +20,7 @@ import { } from "./analysisViewCoverage.js"; import { analysisViewInputError } from "./analysisViewErrors.js"; import { parseAnalysisViewResult } from "./analysisViewParent.js"; +import { isRecord } from "../../kernel/isRecord.js"; export const commandSummaryContext = { source_provider: providerSchema.nullable(), @@ -119,9 +120,7 @@ export const projectCommandObservationView = ( if (!parsed.ok) return parsed; const selection = parameters.data; if ( - typeof selection === "object" && - selection !== null && - !Array.isArray(selection) && + isRecord(selection) && typeof selection.command === "string" && selection.command !== parsed.value.command ) diff --git a/src/domain/analysisView/environmentStateCounters.ts b/src/domain/analysisView/environmentStateCounters.ts index e41f08aab4..51a8e919c9 100644 --- a/src/domain/analysisView/environmentStateCounters.ts +++ b/src/domain/analysisView/environmentStateCounters.ts @@ -1,6 +1,6 @@ import { jsonPointerTokens } from "../jsonPointer.js"; import type { JsonValue } from "../jsonValue.js"; -import { isRecord } from "../isRecord.js"; +import { isRecord } from "../../kernel/isRecord.js"; type JsonObject = { [key: string]: JsonValue }; diff --git a/src/domain/analysisView/recordedExchangeBody.ts b/src/domain/analysisView/recordedExchangeBody.ts index 6e12f16a1b..b7b5d60e05 100644 --- a/src/domain/analysisView/recordedExchangeBody.ts +++ b/src/domain/analysisView/recordedExchangeBody.ts @@ -1,3 +1,4 @@ +import { isRecord } from "../../kernel/isRecord.js"; /** Parsed declarations borrow source strings; they do not decode bodies or normalize media types. */ export type RecordedRequestBody = | { readonly kind: "request-unavailable" } @@ -19,9 +20,7 @@ export type RecordedRequestBody = }; const object = (value: unknown): Record | undefined => - typeof value === "object" && value !== null && !Array.isArray(value) - ? (value as Record) - : undefined; + isRecord(value) ? (value as Record) : undefined; /** Read HAR request body declarations once without turning omission or null into absence. */ export const readRecordedRequestBody = ( diff --git a/src/domain/apiContract/parseApiContract.ts b/src/domain/apiContract/parseApiContract.ts index a846d27108..05b76ae383 100644 --- a/src/domain/apiContract/parseApiContract.ts +++ b/src/domain/apiContract/parseApiContract.ts @@ -18,6 +18,7 @@ import { type ApiContractDiagnostic, type ApiContractOperation, } from "./apiContract.js"; +import { isRecord } from "../../kernel/isRecord.js"; const methods = [ "get", @@ -43,9 +44,7 @@ const pathMetadata = new Set([ // HTTP methods are case-sensitive tokens; additionalOperations preserves that spelling. const httpToken = /^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/u; const record = (value: unknown): Record | undefined => - typeof value === "object" && value !== null && !Array.isArray(value) - ? (value as Record) - : undefined; + isRecord(value) ? (value as Record) : undefined; const identity = (prefix: string, facts: unknown) => `${prefix}_${digestCanonicalValue(facts)}`; diff --git a/src/domain/browserScenarioNormalization.ts b/src/domain/browserScenarioNormalization.ts index f76d9ee201..8c979f07e6 100644 --- a/src/domain/browserScenarioNormalization.ts +++ b/src/domain/browserScenarioNormalization.ts @@ -8,7 +8,7 @@ import { type BrowserScenarioNormalization, type BrowserScenarioNormalizationRule, } from "./browserScenarioDiffValues.js"; -import { isRecord } from "./isRecord.js"; +import { isRecord } from "../kernel/isRecord.js"; /** Canonically order and commit a parsed browser scenario normalization policy. */ export const commitBrowserScenarioNormalization = ( diff --git a/src/domain/desktop/appTaskChecks.ts b/src/domain/desktop/appTaskChecks.ts index e3c48060cc..f15912ffb6 100644 --- a/src/domain/desktop/appTaskChecks.ts +++ b/src/domain/desktop/appTaskChecks.ts @@ -22,7 +22,7 @@ import { zipEntryAt, zipLeavesOutAt, } from "./zipView.js"; -import { isRecord } from "../isRecord.js"; +import { isRecord } from "../../kernel/isRecord.js"; /** One file as the app's data/get reports it: its view, or why it has none. An absent file has no entry. */ export interface TaskFileView { diff --git a/src/domain/desktop/appTaskDraft.ts b/src/domain/desktop/appTaskDraft.ts index f8d32d7232..63d398cb4b 100644 --- a/src/domain/desktop/appTaskDraft.ts +++ b/src/domain/desktop/appTaskDraft.ts @@ -36,7 +36,7 @@ import { import { diffNamedMembers, diffStateViews } from "./stateChanges.js"; import { DRAFT_VIEW_CHARS } from "./valueCuts.js"; import { resolvePointer } from "./viewPointer.js"; -import { isRecord } from "../isRecord.js"; +import { isRecord } from "../../kernel/isRecord.js"; type Version = DesktopStatePath["versions"][number]; type Suggestion = DesktopTaskCheckInput; diff --git a/src/domain/desktop/appTaskDraftAdded.ts b/src/domain/desktop/appTaskDraftAdded.ts index aead5a3931..b54d72b887 100644 --- a/src/domain/desktop/appTaskDraftAdded.ts +++ b/src/domain/desktop/appTaskDraftAdded.ts @@ -22,7 +22,7 @@ import { import { pairMembers } from "./memberPairing.js"; import { elementText, isXmlElement, resolvePointer } from "./viewPointer.js"; import { selectorOf } from "./viewSelector.js"; -import { isRecord } from "../isRecord.js"; +import { isRecord } from "../../kernel/isRecord.js"; type Suggestion = DesktopTaskCheckInput; diff --git a/src/domain/desktop/appTaskDraftGuards.ts b/src/domain/desktop/appTaskDraftGuards.ts index fad200ac0a..8cce48aab7 100644 --- a/src/domain/desktop/appTaskDraftGuards.ts +++ b/src/domain/desktop/appTaskDraftGuards.ts @@ -25,6 +25,7 @@ import { numberedInOrder } from "./positionalKeys.js"; import { elementText, isXmlElement, resolvePointer } from "./viewPointer.js"; import { selectorOf, spellCondition, type Condition } from "./viewSelector.js"; import { childConditions } from "./selectorCandidates.js"; +import { isRecord } from "../../kernel/isRecord.js"; type Suggestion = DesktopTaskCheckInput; @@ -215,11 +216,7 @@ const siblingsOf = ( }; const attributesOf = ({ attributes }: Record) => - typeof attributes === "object" && - attributes !== null && - !Array.isArray(attributes) - ? attributes - : {}; + isRecord(attributes) ? attributes : {}; /** The conditions a sibling's segment selects it by, `@` attributes and `>` children's text. */ const conditionsOf = (member: string) => diff --git a/src/domain/desktop/appTaskDraftJson.ts b/src/domain/desktop/appTaskDraftJson.ts index e4a8b57505..45d67029b9 100644 --- a/src/domain/desktop/appTaskDraftJson.ts +++ b/src/domain/desktop/appTaskDraftJson.ts @@ -31,7 +31,7 @@ const locatePointer = (view: JsonValue | null, pointer: string) => const resolvePointer = (view: JsonValue | null, pointer: string) => resolveView(view, pointer, "json"); import { selectorOf, spellCondition } from "./viewSelector.js"; -import { isRecord } from "../isRecord.js"; +import { isRecord } from "../../kernel/isRecord.js"; type Suggestion = DesktopTaskCheckInput; diff --git a/src/domain/desktop/appTaskDraftNamed.ts b/src/domain/desktop/appTaskDraftNamed.ts index 1e5495c633..bfcc380785 100644 --- a/src/domain/desktop/appTaskDraftNamed.ts +++ b/src/domain/desktop/appTaskDraftNamed.ts @@ -49,7 +49,7 @@ import { valueFormat, type CheckTree, } from "./appTaskDraftTree.js"; -import { isRecord } from "../isRecord.js"; +import { isRecord } from "../../kernel/isRecord.js"; type Suggestion = DesktopTaskCheckInput; diff --git a/src/domain/desktop/appTaskDraftNoise.ts b/src/domain/desktop/appTaskDraftNoise.ts index 1198219329..4118ab7695 100644 --- a/src/domain/desktop/appTaskDraftNoise.ts +++ b/src/domain/desktop/appTaskDraftNoise.ts @@ -13,7 +13,7 @@ import { idReferencesOf, mirrorsOf } from "./appTaskDraftMirrors.js"; import { isPositionalKey, positionalKeys } from "./positionalKeys.js"; import type { DesktopStateDifference } from "./stateChanges.js"; import { elementText, isXmlElement, resolvePointer } from "./viewPointer.js"; -import { isRecord } from "../isRecord.js"; +import { isRecord } from "../../kernel/isRecord.js"; /** Why a change is what an app writes as it saves or shows a document, rather than what its user made. */ export const NOISE_REASONS = [ diff --git a/src/domain/desktop/appTaskDraftRows.ts b/src/domain/desktop/appTaskDraftRows.ts index 3cc22ca10a..5427bd3f7c 100644 --- a/src/domain/desktop/appTaskDraftRows.ts +++ b/src/domain/desktop/appTaskDraftRows.ts @@ -4,7 +4,7 @@ import { countTaskRows } from "./appTaskChecks.js"; import type { DesktopStatePath } from "./desktopState.js"; import { sqliteRowIdentity } from "./stateChanges.js"; import { appendAll } from "../appendAll.js"; -import { isRecord } from "../isRecord.js"; +import { isRecord } from "../../kernel/isRecord.js"; type Version = DesktopStatePath["versions"][number]; type Suggestion = DesktopTaskCheckInput; diff --git a/src/domain/desktop/appTaskDraftText.ts b/src/domain/desktop/appTaskDraftText.ts index 5c942b3e21..36c2e0bdbf 100644 --- a/src/domain/desktop/appTaskDraftText.ts +++ b/src/domain/desktop/appTaskDraftText.ts @@ -12,7 +12,7 @@ import { valueEqualsCheck } from "./appTaskDraftScalars.js"; import { rankAttributes } from "./attributeRank.js"; import type { DesktopStateDifference } from "./stateChanges.js"; import { elementText, isXmlElement, resolvePointer } from "./viewPointer.js"; -import { isRecord } from "../isRecord.js"; +import { isRecord } from "../../kernel/isRecord.js"; /** The pointers a diff lists, of every kind. */ type Listed = Pick; diff --git a/src/domain/desktop/appTaskDraftTree.ts b/src/domain/desktop/appTaskDraftTree.ts index fc8fa1dffc..1b30087c9b 100644 --- a/src/domain/desktop/appTaskDraftTree.ts +++ b/src/domain/desktop/appTaskDraftTree.ts @@ -10,7 +10,7 @@ import { zipLeavesOutAt, zipView, } from "./zipView.js"; -import { isRecord } from "../isRecord.js"; +import { isRecord } from "../../kernel/isRecord.js"; /** * The entry a pointer into a zip view goes into, when it has a view and both diff --git a/src/domain/desktop/appTaskDraftValues.ts b/src/domain/desktop/appTaskDraftValues.ts index 951ce28684..3f4294c09a 100644 --- a/src/domain/desktop/appTaskDraftValues.ts +++ b/src/domain/desktop/appTaskDraftValues.ts @@ -16,7 +16,7 @@ import { holdsFields, isRecordAt } from "./appTaskDraftText.js"; import { attributesOf, compactValue, previewWriter } from "./compactValue.js"; import { pairMembers, pairedAtSeed } from "./memberPairing.js"; import { isXmlElement, locatePointer, resolvePointer } from "./viewPointer.js"; -import { isRecord } from "../isRecord.js"; +import { isRecord } from "../../kernel/isRecord.js"; /** Why a value's pointer cannot go into a check as it is, or why the value is noise. */ export const VALUE_NOTES = ["by_position", ...NOISE_REASONS] as const; diff --git a/src/domain/desktop/compactValue.ts b/src/domain/desktop/compactValue.ts index bb109c2a07..1573259d69 100644 --- a/src/domain/desktop/compactValue.ts +++ b/src/domain/desktop/compactValue.ts @@ -1,7 +1,7 @@ import { ellipsisExcerpt } from "../excerpt.js"; import type { JsonValue } from "../jsonValue.js"; import { isXmlElement } from "./viewPointer.js"; -import { isRecord } from "../isRecord.js"; +import { isRecord } from "../../kernel/isRecord.js"; /** An element's attributes; none for a value that holds none. */ export const attributesOf = (element: Record) => { diff --git a/src/domain/desktop/jsonRecordPairing.ts b/src/domain/desktop/jsonRecordPairing.ts index 6917e08a0f..ccb1086f77 100644 --- a/src/domain/desktop/jsonRecordPairing.ts +++ b/src/domain/desktop/jsonRecordPairing.ts @@ -6,7 +6,7 @@ import { isPlaceholder, } from "./attributeRank.js"; import { MAX_INSIDE_STEPS, spellCondition } from "./viewSelector.js"; -import { isRecord } from "../isRecord.js"; +import { isRecord } from "../../kernel/isRecord.js"; /** A field naming a JSON record, as TreeLine's `uid`: `id`, `uid`, `uuid`, `guid`, `key`, or a name ending in `_id`, `-id` or `Id`. */ const ID_FIELD = /^(?:_?id|uid|uuid|guid|key)$|[_-]id$|[a-z]Id$/u; diff --git a/src/domain/desktop/memberPairing.ts b/src/domain/desktop/memberPairing.ts index 2b15b7fd52..8528230b97 100644 --- a/src/domain/desktop/memberPairing.ts +++ b/src/domain/desktop/memberPairing.ts @@ -28,7 +28,7 @@ import { import { pairRecordsById } from "./jsonRecordPairing.js"; import { resolvePointer } from "./viewPointer.js"; import { selectorOf } from "./viewSelector.js"; -import { isRecord } from "../isRecord.js"; +import { isRecord } from "../../kernel/isRecord.js"; const own = (record: Record, key: string) => Object.hasOwn(record, key) ? record[key] : undefined; diff --git a/src/domain/desktop/positionalKeys.ts b/src/domain/desktop/positionalKeys.ts index 55435318be..d8df769086 100644 --- a/src/domain/desktop/positionalKeys.ts +++ b/src/domain/desktop/positionalKeys.ts @@ -1,6 +1,6 @@ import type { JsonValue } from "../jsonValue.js"; import { isIdentifyingAttribute } from "./attributeRank.js"; -import { isRecord } from "../isRecord.js"; +import { isRecord } from "../../kernel/isRecord.js"; /** An identifier of the members with one tag, as `tag` NUL `key`. */ const tagKey = (tag: string, key: string) => `${tag}\u0000${key}`; diff --git a/src/domain/desktop/seedScrub.ts b/src/domain/desktop/seedScrub.ts index bcaaaf0c6f..48f7ccdae3 100644 --- a/src/domain/desktop/seedScrub.ts +++ b/src/domain/desktop/seedScrub.ts @@ -17,7 +17,7 @@ import { textSyntaxFormat, } from "./stateFormats.js"; import { strictUtf8Decoder } from "../strictUtf8.js"; -import { isRecord } from "../isRecord.js"; +import { isRecord } from "../../kernel/isRecord.js"; /** What the export ships for one seed. */ export interface SeedScrub { diff --git a/src/domain/desktop/selectorCandidates.ts b/src/domain/desktop/selectorCandidates.ts index f0913d20e1..ebc0fb0e60 100644 --- a/src/domain/desktop/selectorCandidates.ts +++ b/src/domain/desktop/selectorCandidates.ts @@ -10,7 +10,7 @@ import { rankAttributes, } from "./attributeRank.js"; import { selectorOf, spellCondition, type Condition } from "./viewSelector.js"; -import { isRecord } from "../isRecord.js"; +import { isRecord } from "../../kernel/isRecord.js"; const own = (record: Record, key: string) => Object.hasOwn(record, key) ? record[key] : undefined; diff --git a/src/domain/desktop/stateChanges.ts b/src/domain/desktop/stateChanges.ts index 226924a8b6..4ba4f9e737 100644 --- a/src/domain/desktop/stateChanges.ts +++ b/src/domain/desktop/stateChanges.ts @@ -4,7 +4,7 @@ import type { DesktopStateFormat } from "./stateFormats.js"; import { holdsTagOnly, pairMembers } from "./memberPairing.js"; import { memberLookup } from "./viewPointer.js"; import { zipEntryAt, zipLeavesOut } from "./zipView.js"; -import { isRecord } from "../isRecord.js"; +import { isRecord } from "../../kernel/isRecord.js"; import { boundedList, type BoundedList } from "../boundedList.js"; const MAX_LISTED = 100; diff --git a/src/domain/desktop/viewPointer.ts b/src/domain/desktop/viewPointer.ts index 4ddcffce08..01b5b4c782 100644 --- a/src/domain/desktop/viewPointer.ts +++ b/src/domain/desktop/viewPointer.ts @@ -7,7 +7,7 @@ import { selectorOf, type Condition, } from "./viewSelector.js"; -import { isRecord } from "../isRecord.js"; +import { isRecord } from "../../kernel/isRecord.js"; /** The arrays a pointer stepped into, each as the pointer to it. */ interface ArraySteps { diff --git a/src/domain/desktop/zipView.ts b/src/domain/desktop/zipView.ts index dd2a827813..801233d3ed 100644 --- a/src/domain/desktop/zipView.ts +++ b/src/domain/desktop/zipView.ts @@ -12,7 +12,7 @@ import { desktopViewByteDisplay, type DesktopViewPolicy, } from "./desktopViewPolicy.js"; -import { isRecord } from "../isRecord.js"; +import { isRecord } from "../../kernel/isRecord.js"; import { sha256Hex } from "../../kernel/sha256Hex.js"; /** Why an archive has no view; the exported reader words it the same. */ diff --git a/src/domain/evidenceFormat.ts b/src/domain/evidenceFormat.ts index a76f7699d7..76167a6168 100644 --- a/src/domain/evidenceFormat.ts +++ b/src/domain/evidenceFormat.ts @@ -1,6 +1,6 @@ import { z } from "zod"; -import { isRecord } from "./isRecord.js"; +import { isRecord } from "../kernel/isRecord.js"; import { ParseFailureError, unsupportedInput } from "./parseFailure.js"; /** diff --git a/src/domain/inputIssueProjection.ts b/src/domain/inputIssueProjection.ts index 6d0f1bbd8d..ee7626eb3c 100644 --- a/src/domain/inputIssueProjection.ts +++ b/src/domain/inputIssueProjection.ts @@ -7,6 +7,7 @@ import { knownArgumentMistakeGuidance, knownViewMistakeGuidance, } from "./inputArgumentGuidance.js"; +import { isRecord } from "../kernel/isRecord.js"; const isRootArgument = (path: readonly unknown[]): boolean => path.length === 0 || (path.length === 1 && path[0] === "input"); @@ -532,11 +533,7 @@ const projectUnionIssue = ( const targetValue = valueAtPath(input, path); let activeErrors: readonly (readonly z.core.$ZodIssue[])[] = issue.errors; - if ( - typeof targetValue === "object" && - targetValue !== null && - !Array.isArray(targetValue) - ) { + if (isRecord(targetValue)) { const candidateKeys = candidateDiscriminatorKeys(targetValue, budget); let narrowed = narrowUnionBranches( issue.errors, diff --git a/src/domain/isRecord.ts b/src/domain/isRecord.ts deleted file mode 100644 index f6aa4c6022..0000000000 --- a/src/domain/isRecord.ts +++ /dev/null @@ -1,13 +0,0 @@ -import type { JsonValue } from "./jsonValue.js"; - -/** - * Whether a value is a non-null object other than an array. Its keys, - * prototype and property values are not inspected. - */ -export function isRecord( - value: JsonValue | null | undefined, -): value is { [key: string]: JsonValue }; -export function isRecord(value: unknown): value is Record; -export function isRecord(value: unknown): boolean { - return typeof value === "object" && value !== null && !Array.isArray(value); -} diff --git a/src/domain/jsonShape.ts b/src/domain/jsonShape.ts index b16af3cd74..9c16a16130 100644 --- a/src/domain/jsonShape.ts +++ b/src/domain/jsonShape.ts @@ -6,7 +6,7 @@ import { jsonStringByteLength } from "./jsonStringByteLength.js"; import { jsonValueByteLength } from "./jsonValueByteLength.js"; import { err, ok, type Result } from "./result.js"; import { strictUtf8Decoder } from "./strictUtf8.js"; -import { isRecord } from "./isRecord.js"; +import { isRecord } from "../kernel/isRecord.js"; const jsonValueTypeSchema = z.enum([ "object", diff --git a/src/domain/jsonValue.ts b/src/domain/jsonValue.ts index 2453c34155..2210e895c5 100644 --- a/src/domain/jsonValue.ts +++ b/src/domain/jsonValue.ts @@ -1,7 +1,7 @@ import { types } from "node:util"; import { z } from "zod"; import { isImmutableJsonSnapshot } from "./immutableJson.js"; -import { isRecord } from "./isRecord.js"; +import { isRecord } from "../kernel/isRecord.js"; /** Maximum JSON nesting accepted before recursive result cloning. */ export const MAX_JSON_DEPTH = 1000; diff --git a/src/domain/native/inventoryCoverage.ts b/src/domain/native/inventoryCoverage.ts index 63c02f356c..39b5ae6106 100644 --- a/src/domain/native/inventoryCoverage.ts +++ b/src/domain/native/inventoryCoverage.ts @@ -1,4 +1,5 @@ import { z } from "zod"; +import { isRecord } from "../../kernel/isRecord.js"; /** * Whether a provider inventory discovered every procedure, string or name in @@ -22,7 +23,7 @@ export const overviewInventoryCoverageSchema = z.strictObject({ * produced them. */ export const withOverviewInventoryCoverage = (overview: Value): Value => - typeof overview === "object" && overview !== null && !Array.isArray(overview) + isRecord(overview) ? { ...overview, inventory_coverage: { diff --git a/src/domain/pcap/tsharkJsonPackets.ts b/src/domain/pcap/tsharkJsonPackets.ts index 92c5cce21a..99b7934a93 100644 --- a/src/domain/pcap/tsharkJsonPackets.ts +++ b/src/domain/pcap/tsharkJsonPackets.ts @@ -1,5 +1,5 @@ import { setImmediate as yieldToEventLoop } from "node:timers/promises"; -import { isRecord } from "../isRecord.js"; +import { isRecord } from "../../kernel/isRecord.js"; import { err, ok, type Result } from "../result.js"; /** diff --git a/src/domain/process/processTraceSpecification.ts b/src/domain/process/processTraceSpecification.ts index 6fd37d6627..0818afde0d 100644 --- a/src/domain/process/processTraceSpecification.ts +++ b/src/domain/process/processTraceSpecification.ts @@ -8,6 +8,7 @@ import { comparableProcessObservationPayload, processObservationSourceSchema, } from "./processObservation.js"; +import { isRecord } from "../../kernel/isRecord.js"; /** * A declared trace, event or variant identifier. The specification owns this @@ -660,11 +661,7 @@ export const processTraceSpecificationSchema = ignoredFieldsBySource.set(event.source, ignoredKey); if ( ignoredFields.some( - (field) => - typeof event.exact === "object" && - event.exact !== null && - !Array.isArray(event.exact) && - field in event.exact, + (field) => isRecord(event.exact) && field in event.exact, ) ) context.addIssue({ diff --git a/src/domain/sourceMapEnvelope.ts b/src/domain/sourceMapEnvelope.ts index e2686d6c3d..fa37a823a8 100644 --- a/src/domain/sourceMapEnvelope.ts +++ b/src/domain/sourceMapEnvelope.ts @@ -1,5 +1,5 @@ import { z } from "zod"; -import { isRecord } from "./isRecord.js"; +import { isRecord } from "../kernel/isRecord.js"; /** Artifact source declarations do not require generated-position decoding. */ type SourceMapRecord = Readonly>; diff --git a/src/dotnet/ManagedSnapshot.ts b/src/dotnet/ManagedSnapshot.ts index 8c8a7b7d1c..f209378577 100644 --- a/src/dotnet/ManagedSnapshot.ts +++ b/src/dotnet/ManagedSnapshot.ts @@ -28,6 +28,7 @@ import { ProviderCleanupError } from "../domain/providerCleanupError.js"; import { RegularFileChangedError } from "../filesystem/RegularFile.js"; import { readBoundedFileBytes } from "../process/BoundedFileBytes.js"; import { classifyBinaryTargetFilesystemFailure } from "../domain/binaryTargetFilesystemFailure.js"; +import { sha256Hex } from "../kernel/sha256Hex.js"; interface ManagedSourceObservation { readonly byteLength: number; @@ -111,7 +112,7 @@ export const readManagedSnapshot = async ( signal?.throwIfAborted(); return { byteLength: bytes.length, - sha256: createHash("sha256").update(bytes).digest("hex"), + sha256: sha256Hex(bytes), bytes, }; }, diff --git a/src/erlang/BeamParser.ts b/src/erlang/BeamParser.ts index 85e3f907ee..11cf262e67 100644 --- a/src/erlang/BeamParser.ts +++ b/src/erlang/BeamParser.ts @@ -1,11 +1,11 @@ import { isUtf8 } from "node:buffer"; -import { createHash } from "node:crypto"; import { ArtifactReaderFailure } from "../resources/index.js"; import { MAX_INSPECT_ERLANG_BEAM_TABLE_ROWS, type ErlangBeam, type InspectErlangBeamInput, } from "../domain/erlang/beam.js"; +import { sha256Hex } from "../kernel/sha256Hex.js"; /** The producing parser names its count allowance independently of diagnostic text. */ export class BeamCapacityFailure extends ArtifactReaderFailure { @@ -23,9 +23,6 @@ const fail = (message: string): never => { throw new ArtifactReaderFailure("format", message); }; -const sha256 = (bytes: Buffer): string => - createHash("sha256").update(bytes).digest("hex"); - const LIMITATIONS = [ "This workflow does not execute BEAM bytecode, inflate LitT literals, or decode Attr/CInf external-term payloads.", "Atom names are structural table entries; they do not authenticate the originating compiler or module checksum.", @@ -258,7 +255,7 @@ export const parseErlangBeam = ( payload: { location: { offset: payloadOffset, bytes: size }, bytes: size, - sha256: sha256(payload), + sha256: sha256Hex(payload), }, }); // OTP's loader replaces the selected payload on each matching chunk. diff --git a/src/evm/EvmoleInterfaceProvider.ts b/src/evm/EvmoleInterfaceProvider.ts index 9bb417c002..41735e069b 100644 --- a/src/evm/EvmoleInterfaceProvider.ts +++ b/src/evm/EvmoleInterfaceProvider.ts @@ -8,7 +8,7 @@ import type { ProviderRejectionCode } from "../domain/providerSelection.js"; import { snapshotEnvironment } from "../process/snapshotEnvironment.js"; import type { JsonValue } from "../domain/jsonValue.js"; import { safeParseUtf8Json } from "../domain/safeJson.js"; -import { createHash, randomUUID } from "node:crypto"; +import { randomUUID } from "node:crypto"; import { access, readFile, stat, writeFile } from "node:fs/promises"; import { constants } from "node:fs"; import { isAbsolute, join } from "node:path"; @@ -90,6 +90,7 @@ import { type EvmWorkerLimits, } from "./EvmWorkerLimits.js"; import { errorMessage } from "../kernel/errorMessage.js"; +import { sha256Hex } from "../kernel/sha256Hex.js"; const OPERATION = "inspect_evm_interface"; @@ -785,9 +786,7 @@ export class EvmoleInterfaceProvider implements EvmInterfacePort { input.encoding, ); const selectedHex = Buffer.from(selectedBytes).toString("hex"); - const decodedHash = createHash("sha256") - .update(selectedBytes) - .digest("hex"); + const decodedHash = sha256Hex(selectedBytes); if ( decodedHash !== reply.bytecode.sha256 || selectedHex !== reply.bytecode.hex || diff --git a/src/evm/EvmoleInterfaceWorker.ts b/src/evm/EvmoleInterfaceWorker.ts index 19f5cba0e6..888feacc87 100644 --- a/src/evm/EvmoleInterfaceWorker.ts +++ b/src/evm/EvmoleInterfaceWorker.ts @@ -1,5 +1,4 @@ import { EvmAdmissionError } from "./EvmAdmissionError.js"; -import { createHash } from "node:crypto"; import { readFile, writeFile } from "node:fs/promises"; import { z } from "zod"; import { @@ -15,6 +14,7 @@ import { } from "../domain/evm/evmInterface.js"; import { readStableArtifact } from "../resources/index.js"; import { errorMessage } from "../kernel/errorMessage.js"; +import { sha256Hex } from "../kernel/sha256Hex.js"; const requestSchema = z.strictObject({ snapshot_path: z.string(), @@ -69,7 +69,7 @@ const main = async (): Promise => { ok: true, version: metadata.version, bytecode: { - sha256: createHash("sha256").update(bytes).digest("hex"), + sha256: sha256Hex(bytes), bytes: bytes.length, hex: Buffer.from(bytes).toString("hex"), metadata: inspectSolidityMetadata(bytes), diff --git a/src/firmware/FirmwarePublication.ts b/src/firmware/FirmwarePublication.ts index a0ae7e8c18..67d689f9e0 100644 --- a/src/firmware/FirmwarePublication.ts +++ b/src/firmware/FirmwarePublication.ts @@ -10,7 +10,6 @@ import { firmwareFailureDialect, firmwarePhaseInterruption, } from "./FirmwareFailures.js"; -import { createHash } from "node:crypto"; import { join } from "node:path"; import type { z } from "zod"; import { classifyProviderFailure } from "../providers/classifyProviderFailure.js"; @@ -50,6 +49,7 @@ const UNNAMED_DEPENDENCY_CONTINUATION = import { FIRMWARE_LIMITS } from "./FirmwareRelease.js"; import type { FirmwareDeadline } from "./FirmwareDeadline.js"; import { errorMessage } from "../kernel/errorMessage.js"; +import { sha256Hex } from "../kernel/sha256Hex.js"; const depthContinuation = ( maxDepth: number, @@ -383,7 +383,7 @@ const extractionGaps = ( const continuation = (instruction: string): string => { const known = instructions.get(instruction); if (known !== undefined) return known; - const id = createHash("sha256").update(instruction).digest("hex"); + const id = sha256Hex(instruction); instructions.set(instruction, id); return id; }; diff --git a/src/frida/FridaInstrumentationManager.ts b/src/frida/FridaInstrumentationManager.ts index 0d750cccf8..80dbfd7186 100644 --- a/src/frida/FridaInstrumentationManager.ts +++ b/src/frida/FridaInstrumentationManager.ts @@ -1,5 +1,5 @@ import { isUtf8 } from "node:buffer"; -import { createHash, randomUUID } from "node:crypto"; +import { randomUUID } from "node:crypto"; import { readFile } from "node:fs/promises"; import type { @@ -57,6 +57,7 @@ import { } from "../domain/fridaCapturePolicy.js"; import { analysisInputErrorFromIssues } from "../domain/inputIssueProjection.js"; import { errorMessage } from "../kernel/errorMessage.js"; +import { sha256Hex } from "../kernel/sha256Hex.js"; const DEVICE_LOOKUP_TIMEOUT_MS = 1_000; @@ -455,7 +456,7 @@ export class FridaInstrumentationManager implements FridaInstrumentationPort { source.sourceKind === "inline" ? source.source : await readFile(source.path); - sourceSha256 = createHash("sha256").update(selectedSource).digest("hex"); + sourceSha256 = sha256Hex(selectedSource); scriptSource = typeof selectedSource === "string" ? selectedSource @@ -464,9 +465,7 @@ export class FridaInstrumentationManager implements FridaInstrumentationPort { sourceRepresentation = { encoding: "utf8", decoding: "replacement", - loadedSourceSha256: createHash("sha256") - .update(scriptSource) - .digest("hex"), + loadedSourceSha256: sha256Hex(scriptSource), }; } catch (cause: unknown) { const sourcePath = source.sourceKind === "file" ? source.path : undefined; @@ -1309,9 +1308,7 @@ export class FridaInstrumentationManager implements FridaInstrumentationPort { remote: FridaRemoteConnection, ): Promise { return this.#withRemoteLock(remote.address, async () => { - const optionsDigest = createHash("sha256") - .update(JSON.stringify(remoteOptions(remote))) - .digest("hex"); + const optionsDigest = sha256Hex(JSON.stringify(remoteOptions(remote))); let reference = this.#remoteDevices.get(remote.address); if (reference !== undefined) { if (reference.optionsDigest !== optionsDigest) diff --git a/src/ghidra/GhidraAnalysisSeeds.ts b/src/ghidra/GhidraAnalysisSeeds.ts index c05d5157c6..2bdfc0d273 100644 --- a/src/ghidra/GhidraAnalysisSeeds.ts +++ b/src/ghidra/GhidraAnalysisSeeds.ts @@ -1,5 +1,4 @@ import { GhidraAdmissionError } from "./GhidraAdmissionError.js"; -import { createHash } from "node:crypto"; import { mkdir, realpath, stat } from "node:fs/promises"; import { isAbsolute, join } from "node:path"; import { z } from "zod"; @@ -24,6 +23,7 @@ import { ghidraSeedLineError, type GhidraSeedEntry, } from "../domain/native/ghidraSeedFile.js"; +import { sha256Hex } from "../kernel/sha256Hex.js"; /** Seed file format admitted by this adapter. */ export const GHIDRA_SEED_FORMAT = "rea-ghidra-seeds-v1"; @@ -71,9 +71,6 @@ export const ghidraSeedReportSchema = z ); export type GhidraSeedReport = z.infer; -const sha256 = (bytes: Buffer | string): string => - createHash("sha256").update(bytes).digest("hex"); - /** Parse seed facts before final close so later cleanup cannot replace invalid input. */ const readSeeds = ( path: string, @@ -137,7 +134,7 @@ export const resolveGhidraAnalysisSeeds = async ( format: GHIDRA_SEED_FORMAT, path, configured_path: configured, - sha256: sha256(normalized), + sha256: sha256Hex(normalized), entries: tally, }); }) @@ -165,7 +162,7 @@ export const snapshotGhidraAnalysisSeeds = async ( throw new GhidraAdmissionError("seed_path_differs"); const entries = await readSeeds(commitment.path, resources, signal); const normalized = normalizedGhidraSeeds(entries); - if (sha256(normalized) !== commitment.sha256) + if (sha256Hex(normalized) !== commitment.sha256) throw new GhidraAdmissionError("seed_changed", { path: commitment.path, }); diff --git a/src/ghidra/GhidraCheckpoint.ts b/src/ghidra/GhidraCheckpoint.ts index 501cb32ba7..bad74b6646 100644 --- a/src/ghidra/GhidraCheckpoint.ts +++ b/src/ghidra/GhidraCheckpoint.ts @@ -35,6 +35,7 @@ import { readGhidraProfileArtifact, } from "./GhidraFileArtifacts.js"; import { errorMessage } from "../kernel/errorMessage.js"; +import { sha256Hex } from "../kernel/sha256Hex.js"; const digest = z.string().regex(/^[a-f0-9]{64}$/); const sourceSchema = z @@ -185,9 +186,7 @@ export async function resolveGhidraCheckpoint( resources: ArtifactResourceScope, signal?: AbortSignal, ): Promise { - const key = createHash("sha256") - .update(JSON.stringify([targetSha256, profile.digest])) - .digest("hex"); + const key = sha256Hex(JSON.stringify([targetSha256, profile.digest])); const selection = { directory: appendCallerPath(root, key), key, diff --git a/src/ghidra/GhidraExecutableHeader.ts b/src/ghidra/GhidraExecutableHeader.ts index 567298e3aa..e3a0b79019 100644 --- a/src/ghidra/GhidraExecutableHeader.ts +++ b/src/ghidra/GhidraExecutableHeader.ts @@ -1,5 +1,4 @@ import { fixedAllowanceOptions } from "../domain/fixedAllowanceRemediation.js"; -import { createHash } from "node:crypto"; import type { GhidraExecutableHeaderProbe } from "./GhidraInstallation.js"; import type { GhidraInstallationFileOptions } from "./GhidraInstallationProperties.js"; import { err, ok, type Result } from "../domain/result.js"; @@ -8,6 +7,7 @@ import { AnalysisResourceConstraintError } from "../domain/analysisErrorCore.js" import { withArtifactRegularFile } from "../resources/index.js"; import { readStableFilePrefix } from "../filesystem/readStableFileBytes.js"; import { ghidraFileFailure } from "./GhidraFileArtifacts.js"; +import { sha256Hex } from "../kernel/sha256Hex.js"; /** Only this prefix is examined; the remainder is never retained or read. */ const GHIDRA_EXECUTABLE_HEADER_BYTES = 4096; @@ -82,9 +82,7 @@ export const readGhidraExecutableHeader = async ( completed_header: { file_bytes: completedHeader.size, examined_bytes: completedHeader.bytes.length, - prefix_sha256: createHash("sha256") - .update(completedHeader.bytes) - .digest("hex"), + prefix_sha256: sha256Hex(completedHeader.bytes), }, }), }), diff --git a/src/ghidra/GhidraInstallationProperties.ts b/src/ghidra/GhidraInstallationProperties.ts index d78ef919e7..7ca5887d16 100644 --- a/src/ghidra/GhidraInstallationProperties.ts +++ b/src/ghidra/GhidraInstallationProperties.ts @@ -1,4 +1,3 @@ -import { createHash } from "node:crypto"; import type { RetainedResourceScope } from "../ports/AnalysisProvider.js"; import { artifactFileCompletion, @@ -17,6 +16,7 @@ import { fixedProducerInputAllowance } from "../domain/fixedAllowanceRemediation import { NonRegularFileReadError } from "../filesystem/RegularFile.js"; import { ghidraApplicationProperties } from "./GhidraInstallationPolicy.js"; import { ghidraFileFailure } from "./GhidraFileArtifacts.js"; +import { sha256Hex } from "../kernel/sha256Hex.js"; /** Metadata admission budget, not a Java Properties format limit. */ const MAX_GHIDRA_INSTALLATION_PROPERTIES_BYTES = 1024 * 1024; @@ -82,9 +82,7 @@ export const readGhidraInstallationProperties = async ( : { completed_properties: { bytes: Buffer.byteLength(completed, "latin1"), - sha256: createHash("sha256") - .update(completed, "latin1") - .digest("hex"), + sha256: sha256Hex(completed, "latin1"), properties: jsonValueSchema.parse( ghidraApplicationProperties(completed), ), diff --git a/src/ghidra/GhidraLoadImageValues.ts b/src/ghidra/GhidraLoadImageValues.ts index b2c58a2ba5..6f49fcfe99 100644 --- a/src/ghidra/GhidraLoadImageValues.ts +++ b/src/ghidra/GhidraLoadImageValues.ts @@ -1,5 +1,4 @@ import { createLoadImageChecks } from "./GhidraLoadImageChecks.js"; -import { createHash } from "node:crypto"; import { nativeLoadImageSchema, type NativeLoadImage, @@ -10,9 +9,8 @@ import type { BinaryTarget } from "../domain/binaryTargetTypes.js"; import { validateDosComLength } from "../domain/dosCom.js"; import { err, ok, type Result } from "../domain/result.js"; import { ghidraRawBinaryLanguage } from "./GhidraRawBinaryLanguage.js"; +import { sha256Hex } from "../kernel/sha256Hex.js"; -const sha256 = (bytes: Buffer): string => - createHash("sha256").update(bytes).digest("hex"); const address = (offset: number): string => `0x${offset.toString(16)}`; const GHIDRA_DOS_LOAD_VERIFICATION_LIMITATION = "Verification covers original/modified FileBytes, every initialized target-backed header/module mapping, relocation records and the external entry point. Ghidra relocation symbol names are retained observations, not independently verified. Mapping ends are inclusive."; @@ -266,7 +264,7 @@ const checkMappings = ( check( `${at}.memory_sha256`, start !== null && end !== null && end <= modified.length - ? sha256(modified.subarray(start, end)) + ? sha256Hex(modified.subarray(start, end)) : null, mapping.sha256, start, @@ -290,7 +288,7 @@ export const attestGhidraDosComLoadImage = ( targetSha256: string, observations: NativeLoadImageObservation, ): Result => { - if (sha256(bytes) !== targetSha256) + if (sha256Hex(bytes) !== targetSha256) return err("Ghidra COM snapshot digest does not match the admitted target"); const length = validateDosComLength(bytes.length); if (!length.ok) return length; diff --git a/src/ghidra/GhidraProviderClient.ts b/src/ghidra/GhidraProviderClient.ts index e89e96a852..84f2feca31 100644 --- a/src/ghidra/GhidraProviderClient.ts +++ b/src/ghidra/GhidraProviderClient.ts @@ -170,6 +170,7 @@ import { import { ghidraRawBinaryLanguage } from "./GhidraRawBinaryLanguage.js"; import { ghidraDolLanguage, ghidraDolSectionFile } from "./GhidraDolProfile.js"; import { invalidRegexPatternError } from "../process/RegexMatcher.js"; +import { isRecord } from "../kernel/isRecord.js"; /** Production seam for exercising provider projection without a real process. */ export type GhidraProviderClientFactory = ( @@ -202,9 +203,7 @@ interface GhidraExecutionMetadata { const referenceObservationRecord = ( normalized: JsonValue, ): Readonly> | undefined => - typeof normalized === "object" && - normalized !== null && - !Array.isArray(normalized) + isRecord(normalized) ? (normalized as Readonly>) : undefined; diff --git a/src/ghidra/GhidraSessionValues.ts b/src/ghidra/GhidraSessionValues.ts index f0b7c031ac..35da4ce479 100644 --- a/src/ghidra/GhidraSessionValues.ts +++ b/src/ghidra/GhidraSessionValues.ts @@ -11,6 +11,7 @@ import { GHIDRA_FUNCTION_OPERATIONS } from "./GhidraFunctionOperations.js"; import { ghidraExtensionResultSchema } from "./extensions/GhidraExtensions.js"; import { GHIDRA_MIPS_SOFT_FLOAT_STORAGE } from "./GhidraMipsProfile.js"; import { GHIDRA_RISCV_CALLING_CONVENTION_IDS } from "./GhidraRiscvProfile.js"; +import { isRecord } from "../kernel/isRecord.js"; /** Exact methods proved by the selected Program bridge handshake. */ export const GHIDRA_SESSION_CAPABILITIES = [ @@ -205,8 +206,6 @@ export const parseGhidraSessionInfo = ( /** Require acknowledgement that the private bridge loop has ended. */ export const isGhidraShutdownAcknowledgement = (value: JsonValue): boolean => - typeof value === "object" && - value !== null && - !Array.isArray(value) && + isRecord(value) && value.shutdown === true && value.project_ephemeral === true; diff --git a/src/ghidra/extensions/GhidraExtensions.ts b/src/ghidra/extensions/GhidraExtensions.ts index 133c07e649..a62c01b09a 100644 --- a/src/ghidra/extensions/GhidraExtensions.ts +++ b/src/ghidra/extensions/GhidraExtensions.ts @@ -1,5 +1,4 @@ import { GhidraAdmissionError } from "../GhidraAdmissionError.js"; -import { createHash } from "node:crypto"; import { realpath, mkdir } from "node:fs/promises"; import { isAbsolute, join } from "node:path"; import { z } from "zod"; @@ -24,6 +23,7 @@ import type { AnalysisError } from "../../domain/analysisErrorBase.js"; import { jsonObjectSchema } from "../../domain/jsonValue.js"; import { err, ok, type Result } from "../../domain/result.js"; import { nativeAotAdapter } from "./nativeaot/NativeAotAdapter.js"; +import { sha256Hex } from "../../kernel/sha256Hex.js"; const digest = z.string().regex(/^[a-f0-9]{64}$/u); /** Exact executable extension artifact committed before the session starts. */ @@ -119,7 +119,7 @@ export const resolveGhidraExtensions = async ( id: adapter.id, path, configured_path: configured, - sha256: createHash("sha256").update(bytes).digest("hex"), + sha256: sha256Hex(bytes), entry_class: adapter.entryClass, integration_api: 1, }); @@ -223,9 +223,7 @@ export const snapshotGhidraExtensions = async ( const result: GhidraExtension[] = []; for (const extension of extensions) { const bytes = await readJar(extension.path, resources, signal); - if ( - createHash("sha256").update(bytes).digest("hex") !== extension.sha256 - ) + if (sha256Hex(bytes) !== extension.sha256) throw new GhidraAdmissionError("digest_differs", { id: extension.id, path: extension.path, diff --git a/src/gpu/AmdGpuMetadata.ts b/src/gpu/AmdGpuMetadata.ts index 8eaf4b2e97..a3772200a0 100644 --- a/src/gpu/AmdGpuMetadata.ts +++ b/src/gpu/AmdGpuMetadata.ts @@ -5,6 +5,7 @@ import { BinaryFormatFailure, } from "../domain/binaryContainer.js"; import { rejectGpu } from "./GpuSource.js"; +import { isRecord } from "../kernel/isRecord.js"; export const AMD_METADATA_BYTES = 8 * 1024 * 1024; const AMD_METADATA_DEPTH = 32; @@ -192,9 +193,7 @@ export const readAmdMetadata = (bytes: Buffer): unknown => { } }; export const amdRecord = (value: unknown): Record | null => - typeof value === "object" && value !== null && !Array.isArray(value) - ? (value as Record) - : null; + isRecord(value) ? (value as Record) : null; export const amdCount = (value: unknown): number | null => { if (typeof value === "bigint") return value >= 0n && value <= BigInt(Number.MAX_SAFE_INTEGER) diff --git a/src/gpu/GpuInventory.ts b/src/gpu/GpuInventory.ts index 6bf91dffa6..9d07805af4 100644 --- a/src/gpu/GpuInventory.ts +++ b/src/gpu/GpuInventory.ts @@ -40,11 +40,11 @@ import { GpuReportCapacityFailure, gpuCount, nextGpuContainerOffset, - gpuSha256, readGpuNativeDirectory, rejectGpu, type GpuSource, } from "./GpuSource.js"; +import { sha256Hex } from "../kernel/sha256Hex.js"; import { readGpuElfKernels, readAmdElfMetadata, @@ -353,7 +353,7 @@ export class GpuInventory { ); } } - this.#decoded(row, gpuSha256(bytes), bytes.length); + this.#decoded(row, sha256Hex(bytes), bytes.length); const decoded = new GpuBufferSource(bytes, row.id); if (row.kind === "ptx") { // NVIDIA appends NUL alignment padding to an uncompressed PTX entry. @@ -381,7 +381,7 @@ export class GpuInventory { const artifact = { id: `${row.id}/ptx`, object_id: row.id, - sha256: gpuSha256(content), + sha256: sha256Hex(content), media_type: "text/x-ptx" as const, encoding: "utf-8" as const, byte_length: content.length, @@ -680,7 +680,7 @@ export class GpuInventory { createHash("md5").update(data).digest().readBigUInt64LE(0) !== hash ) rejectGpu("CCOB truncated MD5 does not match decoded bytes"); - this.#decoded(row, gpuSha256(data), data.length); + this.#decoded(row, sha256Hex(data), data.length); await this.inspect(new GpuBufferSource(data, row.id), depth + 1); row.inspection = "complete"; } catch (cause) { diff --git a/src/gpu/GpuSource.ts b/src/gpu/GpuSource.ts index c3aecb31ae..d843500742 100644 --- a/src/gpu/GpuSource.ts +++ b/src/gpu/GpuSource.ts @@ -126,9 +126,6 @@ export const readGpuNativeDirectory = async ( } return next.value; }; -export const gpuSha256 = (bytes: Buffer): string => - createHash("sha256").update(bytes).digest("hex"); - export const nextGpuContainerOffset = async ( source: GpuSource, start: number, diff --git a/src/ida/IdaBusyHealth.ts b/src/ida/IdaBusyHealth.ts index daf69097d6..ef019eab70 100644 --- a/src/ida/IdaBusyHealth.ts +++ b/src/ida/IdaBusyHealth.ts @@ -7,6 +7,7 @@ import { idaRegistrationTimeoutGuidance } from "./IdaConfiguration.js"; import type { JsonValue } from "../domain/jsonValue.js"; import type { IdaMcpConnection } from "./IdaMcpConnection.js"; import { busyHealthSchema } from "./IdaProtocolValues.js"; +import { isRecord } from "../kernel/isRecord.js"; /** Pause between health reads while a freshly opened worker reports itself busy. */ const BUSY_HEALTH_RETRY_MS = 100; @@ -28,10 +29,7 @@ const busyToolName = (tool: string | undefined): string => tool !== undefined && BUSY_TOOL_NAME.test(tool) ? tool : "unknown"; const isBusyStatus = (raw: JsonValue): boolean => - typeof raw === "object" && - raw !== null && - !Array.isArray(raw) && - raw["status"] === "busy"; + isRecord(raw) && raw["status"] === "busy"; interface LastBusyHealth { readonly raw: JsonValue; diff --git a/src/inspector/JavaScriptRuntimeScope.cancellation.test.ts b/src/inspector/JavaScriptRuntimeScope.cancellation.test.ts index cf220c1748..d9ed23ae4d 100644 --- a/src/inspector/JavaScriptRuntimeScope.cancellation.test.ts +++ b/src/inspector/JavaScriptRuntimeScope.cancellation.test.ts @@ -83,13 +83,12 @@ import { V8InspectorProvider } from "./V8InspectorProvider.js"; import { startFakeCdpBrowser } from "../../tests/fixtures/fakeCdpBrowser.js"; import { startFakeV8Inspector } from "../../tests/fixtures/inspector/fakeV8Inspector.js"; import { createNodeDiscoveryTempDirectory } from "../../tests/fixtures/temporaryDirectory.js"; +import { isRecord } from "../kernel/isRecord.js"; const fixtures: { close(): Promise }[] = []; const record = (value: unknown): Record | undefined => - typeof value === "object" && value !== null && !Array.isArray(value) - ? (value as Record) - : undefined; + isRecord(value) ? (value as Record) : undefined; afterEach(async () => { fileAccess.path = undefined; diff --git a/src/inspector/V8InspectorCaptureProjection.ts b/src/inspector/V8InspectorCaptureProjection.ts index 979ec7ffd1..0d3f6fe2d9 100644 --- a/src/inspector/V8InspectorCaptureProjection.ts +++ b/src/inspector/V8InspectorCaptureProjection.ts @@ -1,5 +1,3 @@ -import { createHash } from "node:crypto"; - import type { JavaScriptRuntimeObservation, JavaScriptRuntimeTargetLocation, @@ -14,6 +12,7 @@ import { } from "./JavaScriptRuntimeScope.js"; import type { CaptureState, ScriptDraft } from "./V8InspectorProvider.js"; import type { AuthorizedV8InspectorTarget } from "./V8InspectorEndpoint.js"; +import { sha256Hex } from "../kernel/sha256Hex.js"; type ExclusionReason = "unsupported_location"; @@ -258,7 +257,7 @@ const scriptFromDraft = ( is_module: draft.isModule, }); return { - script_key: `v8_script_${createHash("sha256").update(stable).digest("hex")}`, + script_key: `v8_script_${sha256Hex(stable)}`, location, ...(location.kind === "file" ? { reported_url: draft.rawUrl } : {}), execution_context_key: draft.executionContextKey, diff --git a/src/javascript/analysis/JavaScriptAnalysisWorker.ts b/src/javascript/analysis/JavaScriptAnalysisWorker.ts index b70fbd9e64..10c30c8859 100644 --- a/src/javascript/analysis/JavaScriptAnalysisWorker.ts +++ b/src/javascript/analysis/JavaScriptAnalysisWorker.ts @@ -24,7 +24,7 @@ import type { JavaScriptSemanticProjectionCapacity, JavaScriptSemanticFileProjection, } from "../../domain/javascript/javascriptSemanticFileProjection.js"; -import { createHash, randomUUID } from "node:crypto"; +import { randomUUID } from "node:crypto"; import { readFile, rm, stat } from "node:fs/promises"; import { join } from "node:path"; import { writeJavaScriptAnalysisSourceTransfer } from "./JavaScriptAnalysisSourceTransfer.js"; @@ -100,6 +100,7 @@ import { type JavaScriptWorkerMessage, } from "./JavaScriptAnalysisWorkerProtocol.js"; import { errorMessage } from "../../kernel/errorMessage.js"; +import { sha256Hex } from "../../kernel/sha256Hex.js"; const OPERATION = "analyze_javascript_application"; const PROVIDER = "javascript-static-analysis"; @@ -392,7 +393,7 @@ export class JavaScriptAnalysisWorker { this.limits.memberMutationAllowance ?? DEFAULT_JAVASCRIPT_MEMBER_MUTATION_ALLOWANCE, ), - text_sha256: createHash("sha256").update(file.text.value).digest("hex"), + text_sha256: sha256Hex(file.text.value), file: metadata, package_type: packageType, purpose, @@ -866,10 +867,7 @@ export class JavaScriptAnalysisWorker { }, ); const checkpoint = await readFile(path); - if ( - expected !== undefined && - createHash("sha256").update(checkpoint).digest("hex") !== expected.sha256 - ) + if (expected !== undefined && sha256Hex(checkpoint) !== expected.sha256) throw new AnalysisOutputError( OPERATION, "JavaScript static checkpoint digest does not match", diff --git a/src/javascript/analysis/JavaScriptAnalysisWorkerServer.ts b/src/javascript/analysis/JavaScriptAnalysisWorkerServer.ts index 44779c9633..d4a364f4b0 100644 --- a/src/javascript/analysis/JavaScriptAnalysisWorkerServer.ts +++ b/src/javascript/analysis/JavaScriptAnalysisWorkerServer.ts @@ -10,7 +10,6 @@ import type { JavaScriptSemanticProjectionCapacity, JavaScriptSemanticFileProjection, } from "../../domain/javascript/javascriptSemanticFileProjection.js"; -import { createHash } from "node:crypto"; import { readFile, writeFile } from "node:fs/promises"; import { join } from "node:path"; import { getHeapStatistics } from "node:v8"; @@ -38,6 +37,7 @@ import { type JavaScriptWorkerMessage, } from "./JavaScriptAnalysisWorkerProtocol.js"; import { errorMessage } from "../../kernel/errorMessage.js"; +import { sha256Hex } from "../../kernel/sha256Hex.js"; /** Trusted composition callback; this provider owns framing and temporary I/O. */ export interface JavaScriptSourceWorkerAnalyzer { @@ -122,9 +122,7 @@ const analyzeJob = async ( try { let resultBudgetBytes = 0; const source = await readFile(join(root, `${request.id}.source`), "utf8"); - if ( - createHash("sha256").update(source).digest("hex") !== request.text_sha256 - ) + if (sha256Hex(source) !== request.text_sha256) throw new TypeError( "JavaScript worker source text digest does not match its request", ); @@ -180,7 +178,7 @@ const analyzeJob = async ( kind: "static", id: request.id, bytes, - sha256: createHash("sha256").update(text).digest("hex"), + sha256: sha256Hex(text), }); const next = await requests.next(); if (next.done || !next.value.ok) diff --git a/src/javascript/recovery/RecoveryFiles.ts b/src/javascript/recovery/RecoveryFiles.ts index 12f186d509..c4581becb0 100644 --- a/src/javascript/recovery/RecoveryFiles.ts +++ b/src/javascript/recovery/RecoveryFiles.ts @@ -37,13 +37,10 @@ import { import { RECOVERY_LIMITS, wakaruFixedLimitRecovery } from "./WakaruRelease.js"; import { isStrictUtf8 } from "../../domain/strictUtf8.js"; import { errorMessage } from "../../kernel/errorMessage.js"; +import { sha256Hex } from "../../kernel/sha256Hex.js"; const OPERATION = "recover_javascript_sources"; -/** Fingerprint exact selected or derived bytes. */ -export const recoveryDigest = (bytes: Uint8Array): string => - createHash("sha256").update(bytes).digest("hex"); - /** A file exceeded the byte bound its caller selected; the caller owns what that bound means. */ class RecoveryFileSizeError extends AnalysisOutputError { constructor( @@ -255,7 +252,7 @@ const snapshotRecoveryInput = async ( path, snapshot_path: snapshotPath, relative_path: relativePath, - sha256: recoveryDigest(bytes), + sha256: sha256Hex(bytes), bytes: bytes.length, }; }; diff --git a/src/javascript/recovery/WakaruPublication.ts b/src/javascript/recovery/WakaruPublication.ts index 9a99e6a91f..014250ded0 100644 --- a/src/javascript/recovery/WakaruPublication.ts +++ b/src/javascript/recovery/WakaruPublication.ts @@ -12,9 +12,9 @@ import { } from "../../domain/javascript/javascriptRecovery.js"; import { readRecoveryFile, - recoveryDigest, type RecoveryInputSnapshot, } from "./RecoveryFiles.js"; +import { sha256Hex } from "../../kernel/sha256Hex.js"; import { recoveryRanges, validateRecoverySourceMap, @@ -49,7 +49,7 @@ export const publishWakaruArtifacts = async ( ): Promise => { const { tree, sources, parsed, staging, signal, resources } = context; const write = async (path: string, bytes: Buffer) => { - const sha256 = recoveryDigest(bytes); + const sha256 = sha256Hex(bytes); const file = await tree.write( path, Readable.from([bytes]), @@ -71,7 +71,7 @@ export const publishWakaruArtifacts = async ( signal, resources, ); - if (recoveryDigest(snapshot) !== source.sha256) + if (sha256Hex(snapshot) !== source.sha256) throw new AnalysisOutputError( "recover_javascript_sources", `The input snapshot changed during recovery: ${source.path}`, diff --git a/src/javascript/sourceMaps/TraceSourceMap.ts b/src/javascript/sourceMaps/TraceSourceMap.ts index 7bcab30252..32dfd61c68 100644 --- a/src/javascript/sourceMaps/TraceSourceMap.ts +++ b/src/javascript/sourceMaps/TraceSourceMap.ts @@ -4,7 +4,6 @@ import { sourceMapLimitRecovery, type SourceMapLimits, } from "../../domain/sourceMapLimits.js"; -import { createHash } from "node:crypto"; import { createRequire } from "node:module"; import { getHeapStatistics } from "node:v8"; import { @@ -30,6 +29,7 @@ import { type SourceMapSourceDeclaration, } from "../../domain/sourceMapFormat.js"; import { decodeValidatedSourceMapLeaves } from "../../domain/decodedSourceMap.js"; +import { sha256Hex } from "../../kernel/sha256Hex.js"; /** Decode with the pinned upstream codec; preserve every equal-position candidate. */ export const traceSourceMap = ( @@ -94,7 +94,7 @@ export const traceSourceMap = ( .parse(metadata).version; const runtime = javaScriptRuntime(process.versions); return webSourceMapReportSchema.parse({ - source_map_sha256: createHash("sha256").update(text).digest("hex"), + source_map_sha256: sha256Hex(text), url_context: url, engine: { id: "jridgewell-trace-mapping", version }, // Bun reports V8-shaped heap statistics but ignores the codec's heap flags. @@ -201,9 +201,7 @@ const originalMatch = ( : { state: "embedded", text: declaration.content, - utf8_sha256: createHash("sha256") - .update(declaration.content) - .digest("hex"), + utf8_sha256: sha256Hex(declaration.content), utf8_bytes: Buffer.byteLength(declaration.content), representation: "UTF-8 encoding of decoded sourcesContent text", }, diff --git a/src/jeb/JebMcpConnection.ts b/src/jeb/JebMcpConnection.ts index d6445de67f..98ed56b2e1 100644 --- a/src/jeb/JebMcpConnection.ts +++ b/src/jeb/JebMcpConnection.ts @@ -23,6 +23,7 @@ import { AnalysisError } from "../domain/analysisErrorBase.js"; import { SharedStartupAttempt } from "../process/SharedStartupAttempt.js"; import { err, ok, type Result } from "../domain/result.js"; import { JebMcpDeadline, selectedJebMcpTimeout } from "./JebMcpDeadline.js"; +import { isRecord } from "../kernel/isRecord.js"; /** Upstream protocol names for the operations REA exposes. */ export const JEB_ENGINE_TOOLS = { @@ -87,10 +88,7 @@ export const decodeJebToolResult = (input: unknown): JsonValue => { }; const isJebFailureEnvelope = (value: JsonValue): boolean => - typeof value === "object" && - value !== null && - !Array.isArray(value) && - value.success === false; + isRecord(value) && value.success === false; export interface JebMcpConnectionTimeouts { /** Absolute catalog connection and pagination deadline. */ diff --git a/src/kernel/isRecord.test.ts b/src/kernel/isRecord.test.ts new file mode 100644 index 0000000000..6bc5f78cf0 --- /dev/null +++ b/src/kernel/isRecord.test.ts @@ -0,0 +1,31 @@ +import { expect, expectTypeOf, it } from "vitest"; + +import { isRecord } from "./isRecord.js"; + +type JsonValue = + | string + | number + | boolean + | null + | JsonValue[] + | { [key: string]: JsonValue }; + +it("accepts non-null objects other than arrays", () => { + expect(isRecord({})).toBe(true); + expect(isRecord(Object.create(null))).toBe(true); + expect(isRecord(new Error("x"))).toBe(true); + expect(isRecord([])).toBe(false); + expect(isRecord(null)).toBe(false); + expect(isRecord(undefined)).toBe(false); + expect(isRecord("text")).toBe(false); + expect(isRecord(() => undefined)).toBe(false); +}); + +it("narrows a JSON value to its object member and unknown to a string-keyed record", () => { + const json = JSON.parse('{"a":1}') as JsonValue; + if (isRecord(json)) + expectTypeOf(json.a).toEqualTypeOf(); + const value: unknown = json; + if (isRecord(value)) + expectTypeOf(value).toEqualTypeOf>(); +}); diff --git a/src/kernel/isRecord.ts b/src/kernel/isRecord.ts new file mode 100644 index 0000000000..d508597e84 --- /dev/null +++ b/src/kernel/isRecord.ts @@ -0,0 +1,16 @@ +/** The non-array object members of `T`. */ +type RecordMembers = Exclude, readonly unknown[]>; + +/** + * Whether a value is a non-null object other than an array. Its keys, + * prototype and property values are not inspected. A typed value narrows to + * its non-array object members (a `JsonValue` to its JSON object) with string + * keys; `unknown` narrows to `Record`. + */ +export function isRecord( + value: T, +): value is ([RecordMembers] extends [never] ? T : RecordMembers) & + Record; +export function isRecord(value: unknown): boolean { + return typeof value === "object" && value !== null && !Array.isArray(value); +} diff --git a/src/kuna/KunaProjectCache.ts b/src/kuna/KunaProjectCache.ts index 6661f3580b..7b48c08aa6 100644 --- a/src/kuna/KunaProjectCache.ts +++ b/src/kuna/KunaProjectCache.ts @@ -9,7 +9,7 @@ import { assertKunaProjectState, type KunaProjectFileStates, } from "./KunaProjectState.js"; -import { createHash, randomUUID } from "node:crypto"; +import { randomUUID } from "node:crypto"; import { mkdir, lstat, @@ -74,6 +74,7 @@ import type { import { KUNA_PROVIDER_ID } from "./KunaRelease.js"; import { releaseProducerIdentity } from "../filesystem/ProducerIdentity.js"; import { errorMessage } from "../kernel/errorMessage.js"; +import { sha256Hex } from "../kernel/sha256Hex.js"; /** A manifest names five files and their digests; anything larger is not ours. */ const MANIFEST_MAX_BYTES = 64 * 1024; @@ -99,22 +100,20 @@ export interface KunaProjectKeyInputs { /** Content address of one export: every input that can change its bytes. */ export const kunaProjectKey = (inputs: KunaProjectKeyInputs): string => - createHash("sha256") - .update( - canonicalize({ - // The entry layout and manifest meaning are REA's code: a new release - // keys new entries, and older ones are retired as foreign manifests. - producer: releaseProducerIdentity(), - target_sha256: inputs.targetSha256, - target_basename: inputs.targetBasename, - kuna_sha256: inputs.kunaSha256, - kuna_command: inputs.kunaCommand, - kuna_executable: inputs.kunaExecutable, - kuna_version: inputs.kunaVersion, - export: { command: "decompile-project", jobs: inputs.jobs }, - }) ?? "", - ) - .digest("hex"); + sha256Hex( + canonicalize({ + // The entry layout and manifest meaning are REA's code: a new release + // keys new entries, and older ones are retired as foreign manifests. + producer: releaseProducerIdentity(), + target_sha256: inputs.targetSha256, + target_basename: inputs.targetBasename, + kuna_sha256: inputs.kunaSha256, + kuna_command: inputs.kunaCommand, + kuna_executable: inputs.kunaExecutable, + kuna_version: inputs.kunaVersion, + export: { command: "decompile-project", jobs: inputs.jobs }, + }) ?? "", + ); const fileSchema = z.strictObject({ path: z.string().min(1), diff --git a/src/kuna/KunaProjectExport.ts b/src/kuna/KunaProjectExport.ts index ab19d48d85..9a2938a428 100644 --- a/src/kuna/KunaProjectExport.ts +++ b/src/kuna/KunaProjectExport.ts @@ -6,7 +6,6 @@ import { } from "../resources/index.js"; import { analysisErrorWithCleanupDependencies } from "../domain/analysisErrorCleanup.js"; import type { RegularFileState } from "../filesystem/RegularFile.js"; -import { createHash } from "node:crypto"; import { assertKunaProjectState, type KunaProjectFileStates, @@ -60,6 +59,7 @@ import { regularFileCancellation, } from "../filesystem/OwnedRegularFile.js"; import { errorMessage } from "../kernel/errorMessage.js"; +import { sha256Hex } from "../kernel/sha256Hex.js"; /** Operation name every export and cache failure reports. */ export const KUNA_EXPORT_OPERATION = "kuna:decompile-project"; @@ -391,10 +391,7 @@ export const exportKunaProject = async ( } const complete = files as KunaExportFiles; const states = fileStates as KunaProjectFileStates; - if ( - complete.inventory.sha256 !== - createHash("sha256").update(listed.snapshot.stdout.text).digest("hex") - ) + if (complete.inventory.sha256 !== sha256Hex(listed.snapshot.stdout.text)) return unusable("the retained inventory changed before export sealing"); await assertKunaProjectState(request.output, complete, states, signal); const functions = await readKunaExportSource( diff --git a/src/kuna/KunaReferenceFiles.ts b/src/kuna/KunaReferenceFiles.ts index 4464057071..705fb3a53d 100644 --- a/src/kuna/KunaReferenceFiles.ts +++ b/src/kuna/KunaReferenceFiles.ts @@ -1,5 +1,3 @@ -import { createHash } from "node:crypto"; - import { z } from "zod"; import type { AnalysisError } from "../domain/analysisErrorBase.js"; @@ -9,6 +7,7 @@ import { KunaDocumentError } from "./KunaDocumentError.js"; import { parseKunaJson } from "./KunaJson.js"; import { KunaJsonDocumentReader, parseKunaRow } from "./KunaJsonStream.js"; import { errorMessage } from "../kernel/errorMessage.js"; +import { sha256Hex } from "../kernel/sha256Hex.js"; /** The raw xref budget also bounds its materialized rows. */ export const KUNA_XREF_OUTPUT_BYTES = 16 * 1024 * 1024; @@ -376,7 +375,7 @@ export const parseKunaIncomingReferences = ( pointer, ) ?? null, bytes: Buffer.byteLength(text), - sha256: createHash("sha256").update(text).digest("hex"), + sha256: sha256Hex(text), }); } catch (cause: unknown) { if (cause instanceof KunaDocumentError) { diff --git a/src/main/deferredRuntime.ts b/src/main/deferredRuntime.ts index f890010c95..df7ca78d25 100644 --- a/src/main/deferredRuntime.ts +++ b/src/main/deferredRuntime.ts @@ -1,4 +1,3 @@ -import { createHash } from "node:crypto"; import { readFileSync } from "node:fs"; import { STDIO_DEFAULT_MAX_BUFFER_SIZE, @@ -20,14 +19,12 @@ import { reportMcpTransportError } from "./reportMcpTransportError.js"; import { OwnedMcpServers } from "./OwnedMcpServers.js"; import { COMPACT_INPUT_SCHEMA_PRESENTATION } from "../contracts/mcpSchemaPresentation.js"; import { errorMessage } from "../kernel/errorMessage.js"; +import { sha256Hex } from "../kernel/sha256Hex.js"; /** Verify the build-owned artifact before trusting its exact typed projection. */ const readCatalog = (): RecordedMcpCatalog => { const bytes = readFileSync(new URL("../mcp-catalog.json", import.meta.url)); - if ( - createHash("sha256").update(bytes).digest("hex") !== - RECORDED_MCP_CATALOG_SHA256 - ) + if (sha256Hex(bytes) !== RECORDED_MCP_CATALOG_SHA256) throw new Error(SERVER_START_FAILED); // The digest binds these bytes to the same compiled producer and SDK converter. const catalog: unknown = JSON.parse(bytes.toString("utf8")); diff --git a/src/mcpDoctor.ts b/src/mcpDoctor.ts index c30a578831..6b8f0fdbd2 100644 --- a/src/mcpDoctor.ts +++ b/src/mcpDoctor.ts @@ -37,7 +37,7 @@ import { } from "./config/mcpStartupPolicy.js"; import { MCP_DOCTOR_ALIAS, MCP_DOCTOR_OPTIONS } from "./mcpDoctorOptions.js"; import { OwnedMcpStdioTransport } from "./process/OwnedMcpStdioTransport.js"; -import { isRecord } from "./domain/isRecord.js"; +import { isRecord } from "./kernel/isRecord.js"; import { resolveMcpOutputSchemaProfile } from "./contracts/mcpSchemaPresentation.js"; import { errorMessage } from "./kernel/errorMessage.js"; diff --git a/src/native/AppleDispatchMetadata.ts b/src/native/AppleDispatchMetadata.ts index 4e4b1d04f1..2edf007ee9 100644 --- a/src/native/AppleDispatchMetadata.ts +++ b/src/native/AppleDispatchMetadata.ts @@ -15,7 +15,6 @@ import { parseFailureFromCause, } from "../domain/parseFailure.js"; import { setImmediate as immediate } from "node:timers/promises"; -import { createHash } from "node:crypto"; import { isSelectedRegularFileError } from "../filesystem/RegularFile.js"; import { DEFAULT_DISPATCH_METADATA_INPUT_BYTES, @@ -69,6 +68,7 @@ import { import { inspectObjcClassImportBindings } from "./AppleObjcClassImportBindings.js"; import { invariantViolation } from "../domain/internalInvariant.js"; import { errorMessage } from "../kernel/errorMessage.js"; +import { sha256Hex } from "../kernel/sha256Hex.js"; /** Decode validated little-endian 64-bit Apple Objective-C metadata without loading target code. */ export function* decodeAppleDispatchMetadataSteps( @@ -427,7 +427,7 @@ export const inspectAppleDispatchMetadata = async ( cancellationFailure: () => cancelled(), }); if (read === undefined) throw inputBudgetExceeded(admission, null); - const sha256 = createHash("sha256").update(read).digest("hex"); + const sha256 = sha256Hex(read); if (sha256 !== target.sha256) throw new EvidenceIntegrityError( "Apple metadata target digest changed after session binding", diff --git a/src/native/elf/ElfNoteParser.ts b/src/native/elf/ElfNoteParser.ts index 95ec07fd7c..4a0a1ad6d8 100644 --- a/src/native/elf/ElfNoteParser.ts +++ b/src/native/elf/ElfNoteParser.ts @@ -6,7 +6,6 @@ import { readElfSectionHeader } from "../../domain/elfSectionHeader.js"; import { readElfProgramHeader } from "../../domain/elfProgramHeader.js"; import { validateElfSectionTablePresence } from "../../domain/elfDeclaredRanges.js"; import { readElfRawTableDeclarations } from "../../domain/elfRawTableDeclarations.js"; -import { createHash } from "node:crypto"; import { ArtifactReaderFailure, assertArtifactReadActive, @@ -33,6 +32,7 @@ import { import { BinaryFormatFailure } from "../../domain/binaryContainer.js"; import { decodeLimit, ParseFailureError } from "../../domain/parseFailure.js"; import { decodeElfSectionNameTable } from "../../domain/native/elfSectionNameTable.js"; +import { sha256Hex } from "../../kernel/sha256Hex.js"; const PT_NOTE = 4; const SHT_NOTE = 7; @@ -118,9 +118,6 @@ const chargeText = ( budget[field] += bytes; }; -const sha256 = (bytes: Buffer): string => - createHash("sha256").update(bytes).digest("hex"); - const GNU_OS_NAMES: Readonly> = { 0: "linux", 1: "hurd", @@ -978,7 +975,7 @@ const toEntry = ( let digest = text.hashes.get(range); if (digest === undefined) { chargeText(text, note.descriptor.length, "hashed"); - digest = sha256(note.descriptor); + digest = sha256Hex(note.descriptor); text.hashes.set(range, digest); } return { diff --git a/src/native/elf/KernelModuleParser.ts b/src/native/elf/KernelModuleParser.ts index 70cf8577b5..a7233ea294 100644 --- a/src/native/elf/KernelModuleParser.ts +++ b/src/native/elf/KernelModuleParser.ts @@ -1,5 +1,3 @@ -import { createHash } from "node:crypto"; - import { ArtifactReaderFailure } from "../../resources/index.js"; import { allKeyed, firstKeyed, keyedBy } from "../../domain/keyedCollection.js"; import { elfObjectTypeName } from "../../domain/native/elfNotes.js"; @@ -21,6 +19,7 @@ import type { } from "../../domain/binaryContainer.js"; import { readElfImage } from "../../domain/native/elfImage.js"; import { kernelCompressionCodecAt } from "./KernelCompressionCodec.js"; +import { sha256Hex } from "../../kernel/sha256Hex.js"; type ElfSection = Extract; type Report = KernelModule; @@ -29,9 +28,6 @@ type Limitations = string[]; const MAGIC = Buffer.from(MODULE_SIGNATURE_MAGIC, "latin1"); const MODULE_CODECS = ["gzip", "xz", "zstd"] as const; -const sha256 = (bytes: Buffer): string => - createHash("sha256").update(bytes).digest("hex"); - const exceeds = (examined: number, maxEntries: number): void => { if (examined > maxEntries) throw new ArtifactReaderFailure( @@ -187,7 +183,7 @@ const parseModinfo = ( return { status: "unsupported", location, - sha256: sha256(stored), + sha256: sha256Hex(stored), entries: [], reason: "modinfo_section_compressed", }; @@ -237,7 +233,7 @@ const parseModinfo = ( }, key, value, - raw_sha256: sha256(raw), + raw_sha256: sha256Hex(raw), raw_hex: rawHex(raw), status: reason === null ? "observed" : "malformed", reason, @@ -261,7 +257,7 @@ const parseModinfo = ( return { status: "present", location, - sha256: sha256(stored), + sha256: sha256Hex(stored), entries, reason: null, ...(omissionLimits.length === 0 ? {} : { omission_limits: omissionLimits }), @@ -311,7 +307,7 @@ const parseVersions = ( layout, entry_bytes: entryBytes, location, - sha256: sha256(stored), + sha256: sha256Hex(stored), entries: [], reason: "versions_section_compressed", }; @@ -321,7 +317,7 @@ const parseVersions = ( layout, entry_bytes: entryBytes, location, - sha256: sha256(stored), + sha256: sha256Hex(stored), entries: [], reason: "versions_size_not_multiple", }; @@ -356,7 +352,7 @@ const parseVersions = ( layout, entry_bytes: entryBytes, location, - sha256: sha256(stored), + sha256: sha256Hex(stored), entries, reason: null, }; @@ -493,7 +489,7 @@ const parseSignature = (bytes: Buffer): Report["signature"] => { info, pkcs7: { location: { offset: infoOffset - info.sig_len, bytes: info.sig_len }, - sha256: sha256(pkcs7), + sha256: sha256Hex(pkcs7), }, reason: null, }; diff --git a/src/native/pe/PeCertificateParser.ts b/src/native/pe/PeCertificateParser.ts index 2f59c15087..e0463f1a98 100644 --- a/src/native/pe/PeCertificateParser.ts +++ b/src/native/pe/PeCertificateParser.ts @@ -1,4 +1,3 @@ -import { createHash } from "node:crypto"; import { ArtifactReaderFailure, artifactParseFailure, @@ -15,6 +14,7 @@ import { readAsn1, } from "./PeCertificateAsn1.js"; import { readPeHeaders } from "../../domain/pe/peResourceLayout.js"; +import { sha256Hex } from "../../kernel/sha256Hex.js"; const fail = (message: string): never => { throw new ArtifactReaderFailure("format", message); @@ -44,9 +44,6 @@ const requireRange = (bytes: Buffer, offset: number, length: number): void => { const align8 = (value: number): number => Math.ceil(value / 8) * 8; -const sha256 = (bytes: Buffer): string => - createHash("sha256").update(bytes).digest("hex"); - const LIMITATIONS = [ "This workflow does not verify signatures, certificate chains, timestamps, or Authenticode digest coverage of image bytes.", "PKCS#7 fields are decoded structurally; cryptographic validity remains unobserved.", @@ -153,7 +150,7 @@ export const parsePeCertificates = ( offset: tableOffset + at + 8 + certificate.start, bytes: certificate.end - certificate.start, }, - der_sha256: sha256( + der_sha256: sha256Hex( payload.subarray(certificate.start, certificate.end), ), serial_hex: certificate.serial_hex, @@ -214,7 +211,7 @@ export const parsePeCertificates = ( payload: { location: { offset: tableOffset + at + 8, bytes: payload.length }, bytes: payload.length, - sha256: sha256(payload), + sha256: sha256Hex(payload), }, pkcs7, }); diff --git a/src/native/windows/WindowsShortcutParser.ts b/src/native/windows/WindowsShortcutParser.ts index d3b3b82307..1b487b4fcc 100644 --- a/src/native/windows/WindowsShortcutParser.ts +++ b/src/native/windows/WindowsShortcutParser.ts @@ -1,4 +1,3 @@ -import { createHash } from "node:crypto"; import { setImmediate } from "node:timers/promises"; import { assertArtifactReadActive } from "../../resources/index.js"; @@ -14,6 +13,7 @@ import type { import { WindowsShortcutResourceFailure } from "./WindowsShortcut.errors.js"; import { malformedInput } from "../../domain/parseFailure.js"; import { byteToHex } from "../../kernel/byteToHex.js"; +import { sha256Hex } from "../../kernel/sha256Hex.js"; type Artifact = WindowsShortcut["artifact"]; @@ -130,9 +130,6 @@ const LIMITATIONS = [ "Volume serial, NetBIOS machine id, and Tracker droid values are recorded as stored. Host identity is not verified.", ]; -const sha256 = (bytes: Buffer): string => - createHash("sha256").update(bytes).digest("hex"); - const namedBits = ( raw: number, names: ReadonlyArray, @@ -471,7 +468,7 @@ const decodeIdListItem = ( offset, size, type_byte: typeByte, - sha256: sha256(data), + sha256: sha256Hex(data), }); if (typeByte === 0x1f && data.length >= 18) { return { @@ -891,7 +888,7 @@ const decodeExtra = ( offset, "Environment ExtraData payload is shorter than 780 bytes", ); - return { kind: "raw", bytes: payload.length, sha256: sha256(payload) }; + return { kind: "raw", bytes: payload.length, sha256: sha256Hex(payload) }; } charge( walk, @@ -911,7 +908,7 @@ const decodeExtra = ( offset, "TrackerDataBlock payload is shorter than 0x58 bytes", ); - return { kind: "raw", bytes: payload.length, sha256: sha256(payload) }; + return { kind: "raw", bytes: payload.length, sha256: sha256Hex(payload) }; } const length = payload.readUInt32LE(0); const version = payload.readUInt32LE(4); @@ -922,7 +919,7 @@ const decodeExtra = ( offset, `TrackerDataBlock header is unsupported (Length 0x${length.toString(16)}, Version ${String(version)})`, ); - return { kind: "raw", bytes: payload.length, sha256: sha256(payload) }; + return { kind: "raw", bytes: payload.length, sha256: sha256Hex(payload) }; } const machine = latin1Z(payload.subarray(8, 24)); charge(walk, machine.length); @@ -942,14 +939,14 @@ const decodeExtra = ( if (signature === 0xa0000004) { if (payload.length < 4) { note(walk, "truncated", offset, "ConsoleFEDataBlock is truncated"); - return { kind: "raw", bytes: payload.length, sha256: sha256(payload) }; + return { kind: "raw", bytes: payload.length, sha256: sha256Hex(payload) }; } return { kind: "console_fe", code_page: payload.readUInt32LE(0) }; } if (signature === 0xa0000005) { if (payload.length < 8) { note(walk, "truncated", offset, "SpecialFolderDataBlock is truncated"); - return { kind: "raw", bytes: payload.length, sha256: sha256(payload) }; + return { kind: "raw", bytes: payload.length, sha256: sha256Hex(payload) }; } return { kind: "special_folder", @@ -960,7 +957,7 @@ const decodeExtra = ( if (signature === 0xa000000b) { if (payload.length < 20) { note(walk, "truncated", offset, "KnownFolderDataBlock is truncated"); - return { kind: "raw", bytes: payload.length, sha256: sha256(payload) }; + return { kind: "raw", bytes: payload.length, sha256: sha256Hex(payload) }; } return { kind: "known_folder", @@ -972,9 +969,9 @@ const decodeExtra = ( return { kind: "property_store", bytes: payload.length, - sha256: sha256(payload), + sha256: sha256Hex(payload), }; - return { kind: "raw", bytes: payload.length, sha256: sha256(payload) }; + return { kind: "raw", bytes: payload.length, sha256: sha256Hex(payload) }; }; const parseIdList = async ( diff --git a/src/python/PythonPycParser.ts b/src/python/PythonPycParser.ts index 22d15f0dd7..a045b7a2f2 100644 --- a/src/python/PythonPycParser.ts +++ b/src/python/PythonPycParser.ts @@ -1,5 +1,4 @@ import { observePythonBytecodePrefix } from "../domain/python/pythonBytecodeIdentity.js"; -import { createHash } from "node:crypto"; import { MarshalReader, smallBitLength, @@ -33,6 +32,7 @@ import { PythonPycResourceFailure, } from "./PythonPyc.errors.js"; import { pythonPycBytecodeIdentity } from "./PythonPycBytecodeEquality.js"; +import { sha256Hex } from "../kernel/sha256Hex.js"; const TYPE_NULL = 0x30; const TYPE_NONE = 0x4e; @@ -225,7 +225,7 @@ const sha256 = (bytes: Buffer, work: PythonPycWork): string => { const cached = digests.get(bytes); if (cached !== undefined) return cached; work.digestedBytes += bytes.length; - const digest = createHash("sha256").update(bytes).digest("hex"); + const digest = sha256Hex(bytes); digests.set(bytes, digest); return digest; }; diff --git a/src/server/EvidenceMcpServerCore.ts b/src/server/EvidenceMcpServerCore.ts index b1bbf253b3..5f63788d0a 100644 --- a/src/server/EvidenceMcpServerCore.ts +++ b/src/server/EvidenceMcpServerCore.ts @@ -274,7 +274,7 @@ export const forgetPendingMcpRequest = ( pendingCompletions.delete(id); }; import type { PromptCompletionSource } from "./promptCompletion.js"; -import { isRecord } from "../domain/isRecord.js"; +import { isRecord } from "../kernel/isRecord.js"; import { advertisedToolPresentation, resolveMcpOutputSchemaProfile, diff --git a/src/server/ToolResultDelivery.ts b/src/server/ToolResultDelivery.ts index f46a52e1d9..55b148d991 100644 --- a/src/server/ToolResultDelivery.ts +++ b/src/server/ToolResultDelivery.ts @@ -36,6 +36,7 @@ import { TARGET_CONTENT_RESULT_META, type ToolResultEncoding, } from "./toolResultEncoding.js"; +import { isRecord } from "../kernel/isRecord.js"; /** Project a response-budget refusal without labeling REA's reserved string limit as Node's ceiling. */ export const mcpResponseOverflowProjection = (input: { @@ -74,18 +75,8 @@ export const mcpResponseOverflowProjection = (input: { * Each projection owns a different next step when it exceeds one MCP frame. */ const evidenceBundleProjection = (value: JsonValue): JsonValue | undefined => { - const payload = - typeof value === "object" && - value !== null && - !Array.isArray(value) && - "result" in value - ? value.result - : value; - return typeof payload === "object" && - payload !== null && - !Array.isArray(payload) - ? payload.kind - : undefined; + const payload = isRecord(value) && "result" in value ? value.result : value; + return isRecord(payload) ? payload.kind : undefined; }; /** @@ -122,14 +113,8 @@ const evidenceBundleOverflowStep = (value: JsonValue): OverflowNextStep => { * `{ result }` envelope; a smaller limit only helps above one. */ const unknownPageItems = (value: JsonValue): number => { - const page = - typeof value === "object" && value !== null && !Array.isArray(value) - ? value.result - : undefined; - return typeof page === "object" && - page !== null && - !Array.isArray(page) && - Array.isArray(page.items) + const page = isRecord(value) ? value.result : undefined; + return isRecord(page) && Array.isArray(page.items) ? page.items.length : Number.POSITIVE_INFINITY; }; diff --git a/src/server/environment/environmentDataPlane.ts b/src/server/environment/environmentDataPlane.ts index 509b85aff8..18354a04cd 100644 --- a/src/server/environment/environmentDataPlane.ts +++ b/src/server/environment/environmentDataPlane.ts @@ -11,7 +11,7 @@ import { type RpcError, type StateIntake, } from "./stateIntake.js"; -import { isRecord } from "../../domain/isRecord.js"; +import { isRecord } from "../../kernel/isRecord.js"; /** One data-plane method's outcome; undefined from a method table means the method is not served. */ export type RpcOutcome = diff --git a/src/server/environment/serveEnvironment.ts b/src/server/environment/serveEnvironment.ts index 267b9c5da0..66aa08d845 100644 --- a/src/server/environment/serveEnvironment.ts +++ b/src/server/environment/serveEnvironment.ts @@ -65,7 +65,7 @@ import { bufferedJsonParts, jsonParts, } from "../../domain/jsonSerialization.js"; -import { isRecord } from "../../domain/isRecord.js"; +import { isRecord } from "../../kernel/isRecord.js"; /** Where the environment card is served. */ export const ENVIRONMENT_CARD_PATH = "/.well-known/agent-env.json"; diff --git a/src/server/environment/stateIntake.ts b/src/server/environment/stateIntake.ts index 8c6edd3d9f..865e9af5ac 100644 --- a/src/server/environment/stateIntake.ts +++ b/src/server/environment/stateIntake.ts @@ -20,7 +20,7 @@ import { withOwnedRegularFile, } from "../../filesystem/OwnedRegularFile.js"; import { decodeStrictUtf8 } from "../../domain/strictUtf8.js"; -import { isRecord } from "../../domain/isRecord.js"; +import { isRecord } from "../../kernel/isRecord.js"; /** Why a named file or download could not be read, or a call was cancelled: a category naming neither the uri nor the content. */ export type IntakeFailure = diff --git a/src/server/mcpClientMetadata.ts b/src/server/mcpClientMetadata.ts index 83ece1a20c..8d4eeb9d7d 100644 --- a/src/server/mcpClientMetadata.ts +++ b/src/server/mcpClientMetadata.ts @@ -8,7 +8,7 @@ import { import type { ClientFeatureAvailability } from "../contracts/toolOutputSchemaPrimitives.js"; import type { ConnectedClientIdentity } from "../process/ServerIdentity.js"; -import { isRecord } from "../domain/isRecord.js"; +import { isRecord } from "../kernel/isRecord.js"; /** Initialize-scoped client metadata the SDK keeps for a 2025-era connection. */ export type McpConnectionClientMetadata = Pick< diff --git a/src/v8/V8CodeCacheParser.ts b/src/v8/V8CodeCacheParser.ts index 1044d3685a..ae353b4539 100644 --- a/src/v8/V8CodeCacheParser.ts +++ b/src/v8/V8CodeCacheParser.ts @@ -1,4 +1,3 @@ -import { createHash } from "node:crypto"; import { MAX_INSPECT_V8_CODE_CACHE_STRING_BYTES, V8_CODE_CACHE_COMPILE_FUNCTION_BIT, @@ -12,6 +11,7 @@ import { import type { V8CodeCacheInputBudget } from "../domain/v8/v8CodeCacheBudget.js"; import { V8CodeCacheBudgetFailure } from "../v8/V8CodeCache.errors.js"; import { malformedInput, unsupportedInput } from "../domain/parseFailure.js"; +import { sha256Hex } from "../kernel/sha256Hex.js"; const unsupported = (message: string): never => { throw unsupportedInput("v8-code-cache", message); @@ -54,9 +54,6 @@ const MODULE_BITS = V8_CODE_CACHE_MODULE_BIT | V8_CODE_CACHE_LEGACY_MODULE_BIT; const isPrintable = (byte: number): boolean => (byte >= 0x20 && byte <= 0x7e) || byte === 0x09; -const payloadSha256 = (bytes: Buffer): string => - createHash("sha256").update(bytes).digest("hex"); - /** * Read one V8 code cache container without executing it. * @@ -175,7 +172,7 @@ export const parseV8CodeCache = ( payload: { offset: payloadOffset, bytes: payload.length, - sha256: payloadSha256(payload), + sha256: sha256Hex(payload), trailing_bytes: 0, }, embedded_strings: observations, diff --git a/src/wasm/WabtArtifactProvider.ts b/src/wasm/WabtArtifactProvider.ts index 3ba42125a0..6161220334 100644 --- a/src/wasm/WabtArtifactProvider.ts +++ b/src/wasm/WabtArtifactProvider.ts @@ -3,7 +3,7 @@ import { capturedProviderOutput } from "../process/capturedProviderOutput.js"; import { decodeStrictUtf8 } from "../domain/strictUtf8.js"; import { WabtAdmissionError } from "./WabtAdmissionError.js"; import { HOST_PLATFORM } from "../platform/HostPlatform.js"; -import { randomUUID, createHash } from "node:crypto"; +import { randomUUID } from "node:crypto"; import { access, writeFile } from "node:fs/promises"; import { constants } from "node:fs"; import { isAbsolute, join } from "node:path"; @@ -76,6 +76,7 @@ import { parseWabtOutput } from "./WabtOutput.js"; import { parseWabtWat } from "./WabtWat.js"; import { associateWasmGlue } from "./WasmGlueAdapter.js"; import { errorMessage } from "../kernel/errorMessage.js"; +import { sha256Hex } from "../kernel/sha256Hex.js"; type Launcher = NonNullable[2]>["launcher"]; type AcquiredGlue = @@ -86,8 +87,6 @@ type AcquiredGlue = readonly references: []; }; const OPERATION = "inspect_wasm_artifact"; -const digest = (text: string) => - createHash("sha256").update(text).digest("hex"); const warningOutput = (text: string): readonly string[] | null => { if (text === "") return []; const lines = text.trimEnd().split("\n"); @@ -694,7 +693,7 @@ export class WabtArtifactProvider implements WasmArtifactPort { details, wat: { text: wat.stdout.text, - sha256: digest(wat.stdout.text), + sha256: sha256Hex(wat.stdout.text), representation: "decoded-wat", }, tool_profile: toolProfile, diff --git a/src/windows/WindowsNativeLoader.ts b/src/windows/WindowsNativeLoader.ts index fae44c1b29..937bbd69b4 100644 --- a/src/windows/WindowsNativeLoader.ts +++ b/src/windows/WindowsNativeLoader.ts @@ -13,11 +13,11 @@ import { } from "../domain/windowsNativeArtifact.js"; import { RuntimeControlUnavailableError } from "../domain/runtimeControlUnavailableError.js"; import { errorMessage } from "../kernel/errorMessage.js"; +import { isRecord } from "../kernel/isRecord.js"; /** A native resource remains opaque until the addon validates its object tag. */ -export const windowsHandleSchema = z.custom( - (value): value is object => - typeof value === "object" && value !== null && !Array.isArray(value), +export const windowsHandleSchema = z.custom((value): value is object => + isRecord(value), ); /** Observed identity of an opened local NTFS or ReFS object. */