Files
Reims-Go/internal/macos/autoinstall/ocr/fetch.go
T
球球 7fd1947bef feat(plugin,host,macos,ui): 实现 Agent 受控接管、受保护阶段确认、离线预配置与自动装机基础 (#103, #105, #129) (#134)
* feat(plugin,host,ui): add agent session takeover, protected-phase confirmation, and autoinstall host foundation

* feat(macos,ui,cli): add offline REIMSPROV first-boot provisioning to skip Setup Assistant (#129)

Builds a per-VM read-only REIMSPROV disk image containing a pure-Go XAR Distribution flat package (provision.pkg) and an offline Recovery fallback script (provision-offline.sh). Passwords are hashed in memory to Apple SALTED-SHA512-PBKDF2 bplist00 ShadowHashData (never persisted in plaintext, no auto-login or NOPASSWD sudo). Uses native OpenDirectory.framework (JXA NSData) + dseditgroup under SIP-enabled live bootinstalld and dslocal plist + PlistBuddy under offline Recovery, skips Setup Assistant and Keyboard Setup Assistant, pre-stages Guest Tools, integrates with CreateWizard / VMPage / vm provision CLI / StartAutoInstall, and zero-wipes on finish_install, normal cold start, or DeleteVM.

* feat(autoinstall,host,ui): add input-locked session shield, recovery-only mode, and restart grace cap

Adds the real-machine end-to-end verified baseline for automatic macOS installation: (1) takeover_policy 'lock' with transparent Win32 VM client-area input shield, low-level key/mouse lock preserving host escape shortcuts (Alt+Tab/Alt+Esc/Win), HUD & UI Pause/Resume controls, and write guards while paused; (2) decoupled recovery_only vs full (REIMSPROV) modes in StartAutoInstall, CreateWizard, and VMAutoInstallPanel; (3) graceful_timeout_sec cap (default 10s) on automated built-in macOS host/vm.restart so Setup Assistant/Login Window restarts do not stall 90s on ACPI; (4) additional modifier aliases in console manager and agent-session/telemetry cleanup on VM deletion.

* feat(autoinstall,overlay,plugin): add built-in macOS auto-install plugin, dynamic island overlay, and review fixes

* fix(app,host,macos,ui): address PR #134 automated review findings

- Frontend & i18n:
  - Fix UTF-8/GBK mojibake in VMPage.tsx.
  - Emit reims:confirm-resolved on timeout/cancel/resolve so frontend modals auto-close and surface errors cleanly; stop submitCreate from continuing after PrepareVMProvision failure.
  - Gate AutoInstallPanel RapidOCR download button on preflight can_download_ocr when pinned default assets are unavailable.
- App / Sessions / Confirm / Lifecycle:
  - Add 30s denial cooldown for protected-phase confirmation prompts and revoke (pluginID, vmKey) grants on non-completed session exits.
  - Fix sessionOverlay / activeAgentSessions data race, remove duplicate permission-denied invocation, guard against clobbering other sessions or completed overlays, and unify VM key normalization.
  - Grant protected-phase confirmation and attach lock-mode session + watcher when resuming auto-install without an active session.
  - Unify FinishInstall and host/vm.finishInstall result handling and persist .reims-go-provision-ready across restarts.
  - Preserve non-timeout stop errors in restartMacOSVMLocked instead of force-killing.
- Host Takeover Hooks:
  - Require both keyboard and mouse WH_*_LL hooks (rolling back partial installs), initialize thread message queue before ready, reset started state on error/exit for retry, and report hook failures.
- macOS Provisioning & Autoinstall Engine:
  - Track REIMSPROV staged/wipe-pending/ready lifecycle markers, exclude "restore" recovery marker from re-attaching REIMSPROV, fail explicitly on offline admin plist creation failure, and report wipe failures.
  - Serialize per-VM Start/Stop/Resume with stop generation tokens, guard ROI fast-path against maxDim overflow, switch hostclient early-event buffer to FIFO eviction, fix untyped nil Engine return, tighten negation & high-risk fuzzy matching, preserve ackedQemuErrors across RebootWindow resets, and re-orient/expire stale inherited running checkpoints.
  - Document verified Windows SDK IDL vtable slots for WinOCR (live-tested on Windows) and add regression tests across app, host, macosdriver, startprep, installer, and autoinstall packages.

* fix(app,cli,host,macos,ui): address PR #134 second automated review findings

- CLI & Desktop Control Channel:
  - Add __reims_host__ / autoinstall desktop control channel with data_root verification so CLI status, resume, and stop talk directly to the live desktop runner instead of splitting checkpoint state or launching doomed short-lived CLI runners.
  - Merge live runners with on-disk checkpoints when listing status without a VM argument.
- App Sessions, Confirmations, Downloads & Telemetry:
  - Scope single-VM not_authorized errors to the target VM in handleSessionBegin and resolveComputerUseVM so active sessions on other VMs are not aborted.
  - Exclude stopped and suspended VMs from hasUnboundAgentSession fast-polling.
  - Revoke protected-phase grants when a VM disappears from poll results.
  - Require manifest Secret:true validation before storing auto-install passwords and remove the unsafe default account_password fallback.
  - Reject userinfo URLs in allow_custom_mirror, gate custom-mirror exemption strictly on plugin.ErrNetOriginNotDeclared, and keep redirect SSRF checks enabled on loopback custom mirrors.
  - Preserve VM telemetry milestones across suspend-resume and Win10 cold-reboot restarts while still resetting on fresh cold boots.
  - Log a warning when Guest Tools bridge is unavailable while preparing REIMSPROV.
  - Clarify CallHostAPI authorization/audit contract and add regression test proving built-in plugins enforce catalog permissions and audit logging.
- Host Takeover & Guest Tools:
  - Track locked mouse button presses via a 5-button bitmask so ButtonUp events from drags started outside the VM window are never swallowed.
  - Align active-window-reporter.js permissions to 0o100755 across ToolsDiskFiles, ToolsProvisionFiles, and postinstall.
- macOS Provisioning & Autoinstall Engine (OCR / Vision / Rules / Runner):
  - Never delete an unwiped REIMSPROV image on OpenFile/Write/Sync failure; persist wipe-pending marker and return error for retry.
  - Harden live postinstall preference writes with chmod 600, plutil -lint, chown, and cfprefsd flush.
  - Rewrite Windows RapidOCR C ABI structs and result extraction to match RapidAI/RapidOcrOnnx@675e73fe4c include/OcrLiteCApi.h:27-70 and src/OcrLiteCApi.cpp:12-160 (5-arg OcrInit verified).
  - Inspect PE32/PE32+ IMAGE_DIRECTORY_ENTRY_IMPORT directly to require onnxruntime.dll only for dynamically linked RapidOcrOnnx.dll builds.
  - Validate cfg.VM and use collision-free SHA-256-suffixed checkpoint paths with read fallback; redact PII/paths/UUIDs/MACs/IPs/tokens in diagnostic summaries; snapshot checkpoints before releasing r.mu for serialized disk I/O.
  - Add contrast/border/focus-ring ok return to DetectInputFieldNearLabel, enforce mask-dots verification in fillAccountForm and login screens, refuse blind password typing on clock-only lock screens, confirm shell readiness before typing install.sh, and prefer isolated button lines over modal prose in FindHit.
- Frontend:
  - Require explicit Apple SLA confirmation in both recovery_only and full modes across AutoInstallPanel and CreateWizard, with unit tests in frontend/scripts/test-autoinstall.mjs.

* fix(app,cli,host,macos,ui): address PR #134 third automated review findings

Addresses all confirmed findings from Review #6204465334 (commit d516350)
with targeted regression tests and hardens verified COM vtable bindings:

- App & Session Lifecycle:
  - Track hostPaused separately in agentSession so plugin host/session.update
    (paused_for_user=false) cannot clear physical user takeover or explicit
    PauseAgentSession holds; only host ResumeAgentSession or timed takeover
    expiry clears them.
  - Give each auto-install session watcher a monotonic watchGen + cancelable
    child context so restarting/resuming auto-install on the same VM cancels
    any superseded watcher and prevents stale timeout or secret cleanup.
  - Bound fast 500ms unbound-PID discovery for running VMs to
    sessionDiscoverGraceWindow via unboundSince (refreshed on restart/rebind).
  - Keep non-blocking buffered confirm resolution send inside confirmMu for
    clear mutual exclusion with cancelPendingConfirmations.
  - Clear cold-reboot telemetry preserveNextBoot via defer on all early-return
    and StartVM-failure paths in watchColdReboot.
  - Rebuild REIMSPROV with current StartAutoInstall credentials (preserving
    install_guest_tools) whenever VM is stopped instead of reusing stale images.
- CLI & macOS Provisioning / StartPrep:
  - Refuse `vm provision --clear` and overwriting existing REIMSPROV while the
    VM is running or paused.
  - Guard live "/" root in postinstall against macOS Recovery/Installer
    (/System/Installation/CDIS), forbid "/" in provision-offline.sh, and scope
    chmod 644 strictly to com.apple.keyboardtype.plist.
  - Reject unknown -* options in REIMSHELP/install.sh (including after --erase).
  - Defer clearing the one-shot REIMSPROV staged marker until after
    setExtraArgs (startprep) and StartWithCompat (macosdriver) succeed.
  - Preserve pending RestartFrom guards in AdvancePostInstallHandoff when
    checkpoint is already at StepDesktop.
- Host Input & Session Overlay:
  - Filter injected keyboard events (LLKHF_INJECTED / LLKHF_LOWER_IL_INJECTED)
    in locked-input mode consistently with the mouse hook.
  - Clean up exited overlay entries in entry.run() and recreate dead entries on
    Manager.Upsert when CreateWindowExW fails or exits early.
  - Cache the static island base surface (shell + icons + DirectWrite text) and
    measured text metrics across breathing frames, raising timerBreathMs to 100ms.
  - Replace magic Direct2D/DirectWrite vtable indices with named d2d1.h /
    dwrite.h constants, check EndDraw HRESULT, and add a live Windows DirectWrite
    rendering smoke test.
- Autoinstall OCR, Rules, Watchdog & Runner:
  - Persist and verify a per-file SHA-256 manifest.json in <dataDir>/ocr/
    before loading RapidOcrOnnx.dll / onnxruntime.dll; reject duplicate
    whitelisted basenames in offline zip imports.
  - Signal WinOCREngine.Close() before acquiring e.mu and add bounded wait +
    channel wakeup in Recognize so Close() immediately cancels in-flight OCR.
  - Fall back to installed RapidOCR when WinOCR initialization fails in Open(),
    and distinguish needs_rapidocr_import from needs_rapidocr_download in Probe.
  - Pause instead of pressing Return when post-TypeSecret login screenshot fails.
  - Re-baseline ColdRebootCount in Watchdog.ResetRebootWindow / ResetAfterResume.
  - Tighten recovery.main specificity (drop bare "Disk Utility"), guard 4-5 char
    pure-ASCII needles from sliding-window fuzzy collisions, use Unicode word
    boundaries for short names (<4 runes) in RedactDiagnosticText, and honor
    rule verify.wait_change_ms with early exit on visual frame diff.

* fix(autoinstall): handle CJK short-name redaction, sh-3.2 prompt bound, and OCR re-import pruning
2026-12-06 15:46:39 +08:00

463 lines
15 KiB
Go

package ocr
import (
"archive/zip"
"context"
"crypto/sha256"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"io"
"net/url"
"os"
"path"
"path/filepath"
"strings"
)
func isSafeAssetFilename(name string) bool {
trimmed := strings.TrimSpace(name)
if trimmed == "" || trimmed == "." || trimmed == ".." {
return false
}
if strings.ContainsAny(trimmed, `/\`) || filepath.Base(trimmed) != trimmed {
return false
}
return true
}
// AssetSpec describes one pinned Apache-2.0 RapidOCR ONNX file or bundle with
// ordered HTTPS mirrors (China-first fallback to GitHub) and a fixed SHA-256.
type AssetSpec struct {
Name string `json:"name"`
SHA256 string `json:"sha256"`
Size int64 `json:"size,omitempty"`
Mirrors []string `json:"mirrors"`
}
// DownloadOptions controls fast mirror failover and custom mirror approval.
type DownloadOptions struct {
URL string
SHA256 string
Dest string
Size int64
Label string
ConnectTimeoutMS int
StallTimeoutMS int
AllowCustomMirror bool
}
// HostDownloader abstracts `host/download.start` so failover logic is unit-tested
// without external network access.
type HostDownloader interface {
DownloadAndWait(ctx context.Context, opts DownloadOptions) (string, error)
}
// DefaultRapidOCRAssets returns the ordered Apache-2.0 upstream PP-OCRv4 mobile
// + RapidOcrOnnx release specs. Custom mirrors or an offline zip bundle override
// or bypass these URLs while enforcing the same SHA-256 verification discipline.
func DefaultRapidOCRAssets() []AssetSpec {
return []AssetSpec{
{
Name: "ch_PP-OCRv4_det_infer.onnx",
Mirrors: []string{
"https://modelscope.cn/models/RapidAI/RapidOCR/resolve/master/onnx/PP-OCRv4/det/ch_PP-OCRv4_det_infer.onnx",
"https://hf-mirror.com/SWHL/RapidOCR/resolve/main/PP-OCRv4/ch_PP-OCRv4_det_infer.onnx",
"https://github.com/RapidAI/RapidOCR/releases/download/v1.1.0/ch_PP-OCRv4_det_infer.onnx",
},
},
{
Name: "ch_ppocr_mobile_v2.0_cls_infer.onnx",
Mirrors: []string{
"https://modelscope.cn/models/RapidAI/RapidOCR/resolve/master/onnx/PP-OCRv4/cls/ch_ppocr_mobile_v2.0_cls_infer.onnx",
"https://hf-mirror.com/SWHL/RapidOCR/resolve/main/PP-OCRv4/ch_ppocr_mobile_v2.0_cls_infer.onnx",
"https://github.com/RapidAI/RapidOCR/releases/download/v1.1.0/ch_ppocr_mobile_v2.0_cls_infer.onnx",
},
},
{
Name: "ch_PP-OCRv4_rec_infer.onnx",
Mirrors: []string{
"https://modelscope.cn/models/RapidAI/RapidOCR/resolve/master/onnx/PP-OCRv4/rec/ch_PP-OCRv4_rec_infer.onnx",
"https://hf-mirror.com/SWHL/RapidOCR/resolve/main/PP-OCRv4/ch_PP-OCRv4_rec_infer.onnx",
"https://github.com/RapidAI/RapidOCR/releases/download/v1.1.0/ch_PP-OCRv4_rec_infer.onnx",
},
},
{
Name: "ppocr_keys_v1.txt",
Mirrors: []string{
"https://modelscope.cn/models/RapidAI/RapidOCR/resolve/master/paddle/PP-OCRv4/rec/ch_PP-OCRv4_rec_infer/ppocr_keys_v1.txt",
"https://hf-mirror.com/SWHL/RapidOCR/resolve/main/PP-OCRv4/ppocr_keys_v1.txt",
"https://github.com/RapidAI/RapidOcrOnnx/raw/main/models/ppocr_keys_v1.txt",
},
},
}
}
// HasPinnedDefaultRapidOCRAssets reports whether DefaultRapidOCRAssets contains
// a complete runnable RapidOCR bundle (including RapidOcrOnnx.dll) with pinned
// SHA-256 digests so one-click online download can succeed safely.
func HasPinnedDefaultRapidOCRAssets() bool {
assets := DefaultRapidOCRAssets()
if len(assets) == 0 {
return false
}
hasDLL := false
for _, spec := range assets {
if strings.TrimSpace(spec.Name) == "" || strings.TrimSpace(spec.SHA256) == "" || len(spec.Mirrors) == 0 {
return false
}
if spec.Name == "RapidOcrOnnx.dll" {
hasDLL = true
}
}
return hasDLL
}
// FetchAssetWithFallback downloads spec into destDir/spec.Name trying mirrors in
// order with fast failover timeouts (5s connect, 15s idle read). If customMirror
// is set, it is tried first with AllowCustomMirror=true (host requires user confirmation).
// Every candidate is verified against spec.SHA256 before moving into place.
func FetchAssetWithFallback(ctx context.Context, dl HostDownloader, destDir string, spec AssetSpec, customMirror string) (string, error) {
if dl == nil {
return "", errors.New("host downloader is unavailable")
}
spec.Name = strings.TrimSpace(spec.Name)
if !isSafeAssetFilename(spec.Name) {
return "", fmt.Errorf("invalid asset name %q", spec.Name)
}
if strings.TrimSpace(destDir) == "" {
return "", errors.New("destination directory is required")
}
wantHash := strings.ToLower(strings.TrimSpace(spec.SHA256))
if wantHash == "" {
return "", fmt.Errorf("asset %s is missing a pinned SHA-256 digest", spec.Name)
}
type candidate struct {
url string
custom bool
}
var candidates []candidate
if prefix := strings.TrimSpace(customMirror); prefix != "" {
u, err := url.Parse(prefix)
if err != nil || (u.Scheme != "https" && !isLoopback(u.Hostname())) || u.Host == "" {
return "", fmt.Errorf("invalid custom HTTPS mirror %q", customMirror)
}
candidates = append(candidates, candidate{
url: strings.TrimRight(prefix, "/") + "/" + spec.Name,
custom: true,
})
}
for _, m := range spec.Mirrors {
if trimmed := strings.TrimSpace(m); trimmed != "" {
candidates = append(candidates, candidate{url: trimmed, custom: false})
}
}
if len(candidates) == 0 {
return "", fmt.Errorf("no download mirrors configured for %s", spec.Name)
}
if err := os.MkdirAll(destDir, 0o755); err != nil {
return "", err
}
finalDest := filepath.Join(destDir, spec.Name)
if ok, _ := VerifyFileSHA256(finalDest, wantHash); ok {
if err := recordRapidOCRManifestEntry(destDir, spec.Name, wantHash); err != nil {
return "", err
}
return finalDest, nil
}
var errs []string
for _, cand := range candidates {
if err := ctx.Err(); err != nil {
return "", err
}
partDest := filepath.Join(destDir, spec.Name+".dl")
_ = os.Remove(partDest)
gotPath, err := dl.DownloadAndWait(ctx, DownloadOptions{
URL: cand.url,
SHA256: wantHash,
Dest: partDest,
Size: spec.Size,
Label: "RapidOCR: " + spec.Name,
ConnectTimeoutMS: 5000,
StallTimeoutMS: 15000,
AllowCustomMirror: cand.custom,
})
if err != nil {
_ = os.Remove(partDest)
errs = append(errs, fmt.Sprintf("%s: %v", cand.url, err))
continue
}
if gotPath == "" {
gotPath = partDest
}
ok, actual := VerifyFileSHA256(gotPath, wantHash)
if !ok {
_ = os.Remove(gotPath)
errs = append(errs, fmt.Sprintf("%s: sha256 mismatch (got %s, want %s)", cand.url, actual, wantHash))
continue
}
if err := os.Rename(gotPath, finalDest); err != nil {
_ = os.Remove(gotPath)
return "", err
}
if err := recordRapidOCRManifestEntry(destDir, spec.Name, wantHash); err != nil {
return "", err
}
return finalDest, nil
}
return "", fmt.Errorf("all RapidOCR mirrors failed for %s: %s", spec.Name, strings.Join(errs, "; "))
}
// ImportOfflineBundle verifies a locally downloaded RapidOCR .zip archive against
// expectedSHA256 (required), extracts the required DLL/ONNX model files safely
// with zip-slip protection, and atomically places them into <dataDir>/ocr/.
func ImportOfflineBundle(zipPath, dataDir, expectedSHA256 string) (string, error) {
dataDir = strings.TrimSpace(dataDir)
if dataDir == "" {
return "", errors.New("plugin data directory is required for offline OCR bundle import")
}
want := strings.ToLower(strings.TrimSpace(expectedSHA256))
if want == "" {
return "", errors.New("expected SHA-256 digest is required for offline OCR bundle import")
}
ok, actual := VerifyFileSHA256(zipPath, want)
if !ok {
return "", fmt.Errorf("offline bundle SHA-256 mismatch: got %s, want %s", actual, want)
}
zr, err := zip.OpenReader(zipPath)
if err != nil {
return "", fmt.Errorf("open zip bundle: %w", err)
}
defer zr.Close()
ocrDir := filepath.Join(strings.TrimSpace(dataDir), "ocr")
stageDir := ocrDir + ".staging"
_ = os.RemoveAll(stageDir)
if err := os.MkdirAll(stageDir, 0o755); err != nil {
return "", err
}
defer os.RemoveAll(stageDir)
allowedFiles := map[string]bool{
"RapidOcrOnnx.dll": true,
"onnxruntime.dll": true,
"ch_PP-OCRv4_det_infer.onnx": true,
"ch_ppocr_mobile_v2.0_cls_infer.onnx": true,
"ch_PP-OCRv4_rec_infer.onnx": true,
"ppocr_keys_v1.txt": true,
"LICENSE": true,
"NOTICE": true,
}
const maxUncompressed = 128 << 20
var totalBytes int64
seen := make(map[string]string, len(allowedFiles))
extractedHashes := make(map[string]string, len(allowedFiles))
for _, f := range zr.File {
if f.FileInfo().IsDir() {
continue
}
if f.Mode()&os.ModeSymlink != 0 {
return "", fmt.Errorf("zip symlink entry is not allowed: %s", f.Name)
}
if filepath.IsAbs(f.Name) || strings.Contains(f.Name, ":") {
return "", fmt.Errorf("zip entry uses absolute path: %s", f.Name)
}
normalized := strings.ReplaceAll(f.Name, "\\", "/")
clean := path.Clean(normalized)
if clean == ".." || strings.HasPrefix(clean, "../") || strings.HasPrefix(clean, "/") || strings.Contains(clean, "/../") {
return "", fmt.Errorf("zip entry escapes target directory: %s", f.Name)
}
base := path.Base(clean)
if !allowedFiles[base] {
continue
}
if prev, dup := seen[base]; dup {
return "", fmt.Errorf("offline bundle contains duplicate entry for %s (%s and %s)", base, prev, f.Name)
}
seen[base] = f.Name
rc, err := f.Open()
if err != nil {
return "", err
}
outPath := filepath.Join(stageDir, base)
outFile, err := os.OpenFile(outPath, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0o644)
if err != nil {
_ = rc.Close()
return "", err
}
fileHash := sha256.New()
n, copyErr := io.Copy(io.MultiWriter(outFile, fileHash), io.LimitReader(rc, maxUncompressed-totalBytes+1))
closeErr := outFile.Close()
_ = rc.Close()
totalBytes += n
if copyErr != nil {
return "", copyErr
}
if closeErr != nil {
return "", closeErr
}
if totalBytes > maxUncompressed {
return "", errors.New("offline OCR bundle exceeds maximum uncompressed size")
}
extractedHashes[base] = strings.ToLower(hex.EncodeToString(fileHash.Sum(nil)))
}
for _, req := range []string{"RapidOcrOnnx.dll", "ch_PP-OCRv4_det_infer.onnx", "ch_PP-OCRv4_rec_infer.onnx", "ppocr_keys_v1.txt"} {
if st, err := os.Stat(filepath.Join(stageDir, req)); err != nil || st.Size() == 0 {
return "", fmt.Errorf("offline bundle missing required file %s", req)
}
}
if dllImportsLibrary(filepath.Join(stageDir, "RapidOcrOnnx.dll"), "onnxruntime.dll") {
if st, err := os.Stat(filepath.Join(stageDir, "onnxruntime.dll")); err != nil || st.Size() == 0 {
return "", errors.New("offline bundle missing required dependency onnxruntime.dll for RapidOcrOnnx.dll")
}
}
if err := os.MkdirAll(ocrDir, 0o755); err != nil {
return "", err
}
entries, err := os.ReadDir(stageDir)
if err != nil {
return "", err
}
for _, e := range entries {
src := filepath.Join(stageDir, e.Name())
dst := filepath.Join(ocrDir, e.Name())
_ = os.Remove(dst)
if err := os.Rename(src, dst); err != nil {
return "", err
}
}
// Remove any stale previously imported optional files (e.g. onnxruntime.dll or
// cls model from an earlier bundle) not present in this replacement bundle so
// manifest verification stays consistent across re-imports.
for name := range allowedFiles {
if _, kept := extractedHashes[name]; !kept {
_ = os.Remove(filepath.Join(ocrDir, name))
}
}
if err := writeRapidOCRManifest(ocrDir, extractedHashes); err != nil {
return "", err
}
return ocrDir, nil
}
const rapidOCRManifestFilename = "manifest.json"
type rapidOCRManifest struct {
Files map[string]string `json:"files"`
}
func loadRapidOCRManifest(dir string) (rapidOCRManifest, error) {
raw, err := os.ReadFile(filepath.Join(dir, rapidOCRManifestFilename))
if err != nil {
return rapidOCRManifest{}, err
}
var m rapidOCRManifest
if err := json.Unmarshal(raw, &m); err != nil {
return rapidOCRManifest{}, err
}
if len(m.Files) == 0 {
return rapidOCRManifest{}, errors.New("empty RapidOCR integrity manifest")
}
return m, nil
}
func writeRapidOCRManifest(dir string, files map[string]string) error {
if err := os.MkdirAll(dir, 0o755); err != nil {
return err
}
normalized := make(map[string]string, len(files))
for k, v := range files {
if isSafeAssetFilename(k) && strings.TrimSpace(v) != "" {
normalized[k] = strings.ToLower(strings.TrimSpace(v))
}
}
raw, err := json.MarshalIndent(rapidOCRManifest{Files: normalized}, "", " ")
if err != nil {
return err
}
tmpPath := filepath.Join(dir, rapidOCRManifestFilename+".tmp")
finalPath := filepath.Join(dir, rapidOCRManifestFilename)
if err := os.WriteFile(tmpPath, raw, 0o644); err != nil {
return err
}
_ = os.Remove(finalPath)
if err := os.Rename(tmpPath, finalPath); err != nil {
_ = os.Remove(tmpPath)
return err
}
return nil
}
func recordRapidOCRManifestEntry(dir, name, sha256Hex string) error {
if !isSafeAssetFilename(name) || strings.TrimSpace(sha256Hex) == "" {
return nil
}
m, err := loadRapidOCRManifest(dir)
if err != nil || m.Files == nil {
m.Files = map[string]string{}
}
m.Files[name] = strings.ToLower(strings.TrimSpace(sha256Hex))
return writeRapidOCRManifest(dir, m.Files)
}
// verifyRapidOCRManifest verifies that every required RapidOCR file (and any
// present optional DLL/model file) matches the SHA-256 recorded at import or
// verified download time before loading RapidOcrOnnx.dll into the host process.
func verifyRapidOCRManifest(dir string, requiredFiles, optionalFiles []string) error {
m, err := loadRapidOCRManifest(dir)
if err != nil {
return fmt.Errorf("RapidOCR integrity manifest missing or invalid (re-import bundle): %w", err)
}
checkFile := func(name string) error {
want := strings.ToLower(strings.TrimSpace(m.Files[name]))
if want == "" {
return fmt.Errorf("RapidOCR file %s is not attested in %s (re-import bundle)", name, rapidOCRManifestFilename)
}
if ok, actual := VerifyFileSHA256(filepath.Join(dir, name), want); !ok {
return fmt.Errorf("RapidOCR file %s failed SHA-256 verification before load (got %s, want %s)", name, actual, want)
}
return nil
}
for _, name := range requiredFiles {
if err := checkFile(name); err != nil {
return err
}
}
for _, name := range optionalFiles {
if st, err := os.Stat(filepath.Join(dir, name)); err == nil && !st.IsDir() {
if err := checkFile(name); err != nil {
return err
}
}
}
return nil
}
// VerifyFileSHA256 computes the SHA-256 of path and compares it with wantHex.
func VerifyFileSHA256(path, wantHex string) (bool, string) {
f, err := os.Open(path)
if err != nil {
return false, ""
}
defer f.Close()
h := sha256.New()
if _, err := io.Copy(h, f); err != nil {
return false, ""
}
actual := strings.ToLower(hex.EncodeToString(h.Sum(nil)))
return actual == strings.ToLower(strings.TrimSpace(wantHex)), actual
}
func isLoopback(host string) bool {
h := strings.ToLower(strings.TrimSpace(host))
return h == "localhost" || h == "127.0.0.1" || h == "::1"
}